Converting Float/Single To Network Order And Back In C#

I’ve seen a few posts & threads around the Internet about network order (aka big-endian) and floating point values in C#. First – all binary values are affected by the underlying architecture – this includes floating point values. It’s akin to Hebrew – all the words are written right-to-left, not just some. Now that we’ve cleared that up, I’m sure you’re wondering just how we reverse the ‘endianness’ of floats given that IPAddress only lets you convert ints.

A 32bit int is merely 32 bits of data. We just label it as an ‘int’ and always interpret it thus. What we need to do, is take a 32bit float and pretend it’s an int, get C# to convert it, then send it down the network pipe. The receiver can then fix the endianness and read it as a float. I’ve written some code that does just that:

/// <summary>
/// Convert a float to network order
/// </summary>
/// <param name="host">Float to convert</param>
/// <returns>Float in network order</returns>
public static byte[] HostToNetworkOrder(float host)
{
    byte[] bytes = BitConverter.GetBytes(host);

    if (BitConverter.IsLittleEndian)
        Array.Reverse(bytes);

    return bytes;
}

/// <summary>
/// Convert a float to host order
/// </summary>
/// <param name="network">Float to convert</param>
/// <returns>Float in host order</returns>
public static float NetworkToHostOrder(int network)
{
    byte[] bytes = BitConverter.GetBytes(network);

    if (BitConverter.IsLittleEndian)
        Array.Reverse(bytes);

    return BitConverter.ToSingle(bytes, 0);
}

Remember Network Order is always big-endian. .NET itself can be big-endian or little-endian depending on the underlying architecture. For this reason we always check if we even need to perform a conversion by checking if we’re running on a little-endian system. As an aside Java is always big-endian, regardless of the underlying architecture it’s running on.

Posted by Dan in C#, Guides, 1 comment

Notify Property Weaver

I’ve found MVVM to require somewhat excessive amounts of boilerplate code, and as far as I’m concerned if you have a lot of boilerplate (aka. repeated) code then you’re doing it wrong. There’s a few articles out there on using a little IL weaving to automatically provide notifications for the INotifyPropertyChanged interface. This dramatically reduces the amount of boilerplate you have to write, and dramatically increases readability. Simon Cropp has released the best solution by far – a NuGet package that you can integrate into your app and forget about.

The solution works with Silverlight 3.5 and .NET 3.5 onwards. Most importantly it works well with Windows Phone 7 – something many other solutions don’t always work particularly well with. The solution even works automatically with dependencies – so if one property changes as a result of another changing, the notifications will automatically be fired for both properties. Very, very clever.

Go give it a go!

Posted by Dan in C#, Windows Phone, 1 comment

Cocos2D Sound in Android Tutorial

Update: This code is using an outdated version of the Cocos2D port. It’ll still work if you use the sample download linked at the end – but it’s using outdated API calls. Unfortunately I don’t have time to update the tutorial to the new release of Cocos2D. Sorry guys 🙁

Cocos2D for Android provides a very rudimentary sound system for playing background music, and simple sound effects. For the vast majority of games, this is plenty. However, if you have more advanced requirements you may need to look into either rolling out your own sound engine or sourcing something more complete elsewhere.

Overview

The Cocos2D ‘SoundEngine’ class provides all of the functionality you’ll need. It groups audio into two main groups: ‘Sound’ and ‘Effect’. Effects are the explosions, jump sounds, and other general effects you have within games. Sound is the background music and is the only audio type that can be paused and resumed. Sound effects should be kept under 5 seconds long, and ideally they should be under 3 seconds.

Android supports a wide range of different audio formats, you can view a complete list here. However, I’ve found that the SoundEngine doesn’t necessarily support all of these formats – so please do test your audio on a real device, preferably a few.

Let’s start coding!

Create a new Android project in your IDE of choice, IntelliJ Idea is my favourite, but Eclipse is very good also. You also need to download the latest source code for cocos2d-android-1, the downloadable jar doesn’t include the SoundEngine code. Include the source into your project – this also has the added advantage that you can poke around the code to see how everything works.

Also you need to add the two audio files in this zip, and put them in the ‘raw’ folder within the ‘resources’ folder. If you don’t have a raw folder, create it.

Before we get into any real coding, we’ll need to create a very rudimentary GUI to allow us to interact with the sound system. We’ll add two buttons to the main layout, one to play some background music and another to play a single sound effect:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:text="BG Music Toggle"
        android:onClick="bgMusicClicked" />

    <Button
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:text="Play Sound Effect"
        android:onClick="sfxClicked" />
</LinearLayout>

Using SoundEngine

The SoundEngine offers functionality to pre-load audio, this is critical to ensure sound effects are played instantly. It also means we can use compressed audio formats such as mp3, without slowing down our game. Add the following field to the top of the main activity:

private Context _cocos2dContext;

Next add the following code to the onCreate() method:

_cocos2dContext = this;

// Preload background music
SoundEngine.sharedEngine().preloadSound(_cocos2dContext, R.raw.background_music_aac);

// Preload sound effect
SoundEngine.sharedEngine().preloadEffect(_cocos2dContext, R.raw.pew_pew_lei);

This code sets the context we’ll use for playing audio, and preloads the background audio, and the sound effect. We set the context to the current activity; this is because we’re not actually using Cocos2D in this demo. In your actual games you would use CCDirector.sharedDirector().getActivity() instead of this.
Now, create the event handlers for the two buttons we created:

public void bgMusicClicked(View button)
{
    // Play the background music
    SoundEngine.sharedEngine().playSound(_cocos2dContext, R.raw.background_music_aac, true);
}

public void sfxClicked(View button)
{
    // Play the sound effect
    SoundEngine.sharedEngine().playEffect(_cocos2dContext, R.raw.pew_pew_lei);
}

Give it a test!

It won’t stop playing!

OK I may have let you walk into this one – the background music plays even when the activity is ‘closed’ or otherwise not being used by the user. This is very handy if you’re making an mp3 player, but not so useful when making a game. Fortunately we can fix this problem by hooking into a few events Android offers. As a refresher, here is the Activity Lifecycle in Android:

We need to cater for the activity being obscured by another activity, being hidden, and being closed down. The onResume, onPause, and onDestroy methods should be plenty for our needs. In onResume we’ll need to resume playback of the background sound if it was playing. onPause will pause the sound (if any) ready for resuming. When onDestroy is called we’ll close everything down and free up any applicable resources.

First, add the following fields to the activity class:

private boolean _soundPlaying = false;
private boolean _soundPaused = false;
private boolean _resumeSound = false;

We need to populate these fields as necessary when the user wants to play / pause the background music. Replace the bgMusicClicked method with:

public void bgMusicClicked(View button)
{
    // If we haven't started playing the sound - play it!
    if (!_soundPlaying)
    {
        SoundEngine.sharedEngine().playSound(_cocos2dContext, R.raw.background_music_aac, true);
        _soundPlaying = true;
    }
    else
    {
        // We've loaded the sound, now it's just a case of pausing / resuming
        if (!_soundPaused)
        {
            SoundEngine.sharedEngine().pauseSound();
            _soundPaused = true;
        }
        else
        {
            SoundEngine.sharedEngine().resumeSound();
            _soundPaused = false;
        }
    }
}

Now we only play the sound once, rather than starting fresh each time. We pause / resume the sound depending on whether it’s currently playing or not – your typical toggle pattern.
Now we’ll create the onPause handler:

@Override
public void onPause()
{
    super.onPause();

    // If the sound is loaded and not paused, pause it - but flag that we want it resumed
    if (_soundPlaying && !_soundPaused)
    {
        SoundEngine.sharedEngine().pauseSound();
        _soundPaused = true;
        _resumeSound = true;
    }
    else
        _resumeSound = false; // No sound playing, don't resume
}

In this method we check if the sound is playing, and if it is – whether it’s paused or not. If the sound is playing but it’s not paused, we pause it and request that it’s resumed at the earliest opportunity. If the sound isn’t playing or it’s paused, then we request that the sound isn’t resumed when the activity is.

Now it’s time for the onResume method:

@Override
public void onResume()
{
    super.onResume();

    // Resume playing sound only if it's loaded, paused and we want to resume it
    if (_soundPlaying && _soundPaused && _resumeSound)
    {
        SoundEngine.sharedEngine().resumeSound();
        _soundPaused = false;
    }
}

We check if the sound is playing, it’s paused, and a request is pending to resume the sound. If all of this is true (phew, that’s a lot of checking!) we resume the sound.

At this point we can run the app, and the audio will be handled properly. The user won’t be irritated by music playing when it shouldn’t, and our game can resume seamlessly when the user comes back. However, we haven’t yet implemented the onDestroy method – we never clean everything up.

Cleaning up our mess

Strictly speaking, cleaning up isn’t necessary in this app. Android will automatically reclaim the consumed resources when the app is destroyed. However, it’s always good to clean everything up anyway, if only so you know how to do it when it really is important. Add the following destroy method:

@Override
public void onDestroy()
{
    super.onDestroy();

    // Clean everything up
    SoundEngine.sharedEngine().realesAllSounds();
    SoundEngine.sharedEngine().realesAllEffects();

    // Completely shut down the sound system
    SoundEngine.purgeSharedEngine();
}

First we release all of the preloaded sounds and effects. You can selectively release individual sounds and effects if you need to. If your game is made up of multiple scenes with different audio in each, it’s a very good idea to release the audio you’re not using to save on memory.

Finally we shut down the sound engine itself. This isn’t really necessary, but it’s here for you to see how it can be done. If you have completely different areas in your game, you could feasibly want to have no trace of the SoundEngine between those scenes since the SoundEngine is a singleton by design.

And we’re done!

And that’s it; you now know everything you need to add basic audio to your Android Cocos2D games.

You can download the sample project here.

If you want more Cocos2D, don’t forget to check out the basic tutorial series starting here.

Posted by Dan in Android, Java, Tutorials, 3 comments

I LOVEFiLM Launched

I’ve been holding off talking about my app until I had the free version available on the marketplace… and now it is!

I LOVEFiLM Screenshot

I hope you like it, it’s the product of much work, sweat, blood and tears with a little drop of pixie dust. Obviously you’ll need to have a LOVEFiLM account for the app to actually work for you, but if you do have a LOVEFiLM account I feel this app is the best on the market… because I made it!

No, but seriously this app is fully-featured and should offer everything you need, including:

  • New releases
  • Coming soon
  • Lists (genre, famous actors, famous directors, format, 100 best, language, production year, etc.)
  • Search by keyword
  • Add to default rental list or a specific list
  • Remove from rental list
  • Change title priority
  • Rating
  • Find all of the films / TV shows by your favourite actor, actress, or director
  • Find similar titles to the one you’re currently viewing
  • Play trailer for the title you’re viewing
  • Actor/Director information

But don’t take my word for it, download the free version and see for yourself! If you’re totally confident in my abilities (and who isn’t?!), then use the big banner below to get the full paid version:

Download for Windows Phone 7

Posted by Dan in Windows Phone, 0 comments

Enum in Java with int conversion

If you’ve found this post, chances are you want to convert from an enum to an int, or alternatively from an int to an enum in Java. Well… you can’t. Java has the most robust implementation of the ‘enum pattern’ of any language, in essence enums are a class that can only be instantiated once. This makes them ideal as singletons by the way…

Anyway, since enums are a class, you need to provide the int functionality yourself. For my example, I’m going to be making a ‘difficulty’ enum which should be very familiar with anyone making games for Android. First declare your enum:

public enum Difficulty
{
    EASY(0),
    MEDIUM(1),
    HARD(2);

    /**
     * Value for this difficulty
     */
    public final int Value;

    private Difficulty(int value)
    {
        Value = value;
    }
}

This should be fairly familiar to you if you’ve worked with Java enums for any length of time. Each enum is effectively an instance of itself, so we can pass values to the constructor. We store the value in a final field (enums are by definition immutable – don’t go breaking this without good reason!) for future retrieval. Ideally the value should be accessed by a getter rather than directly, but I think in this case it makes more sense to making it a public field. The user can’t change it, and we don’t need any code to run on access; so I think a getter would just reduce performance and make consumption that little bit more tedious.

Now we need to add the important part, the conversion from int to the enum itself:

// Mapping difficulty to difficulty id
private static final Map<Integer, Difficulty> _map = new HashMap<Integer, Difficulty>();
static
{
    for (Difficulty difficulty : Difficulty.values())
        _map.put(difficulty.Value, difficulty);
}

/**
 * Get difficulty from value
 * @param value Value
 * @return Difficulty
 */
public static Difficulty from(int value)
{
    return _map.get(value);
}

So what are we doing here, exactly? Well we create a map that will be our lookup table, we do this rather than a switch statement to minimise long-term maintenance. If someone added an extra enumeration in the future, they may forget to update the switch statement – and this error won’t be picked up until runtime, and even then it may appear as incorrect behaviour rather than throwing an exception. After we’ve created the map, we populate it automatically by looping through all of the enums and adding them and their value to the map.

So there you have it, the proper pattern for adding int values to an enumeration. The code in full is below:

public enum Difficulty
{
    EASY(0),
    MEDIUM(1),
    HARD(2);

    /**
     * Value for this difficulty
     */
    public final int Value;

    private Difficulty(int value)
    {
        Value = value;
    }

    // Mapping difficulty to difficulty id
    private static final Map<Integer, Difficulty> _map = new HashMap<Integer, Difficulty>();
    static
    {
        for (Difficulty difficulty : Difficulty.values())
            _map.put(difficulty.Value, difficulty);
    }

    /**
     * Get difficulty from value
     * @param value Value
     * @return Difficulty
     */
    public static Difficulty from(int value)
    {
        return _map.get(value);
    }
}

Bonus

OK I can’t leave you with just this without providing a little ‘from here’ info. Switching on an enum in Java isn’t ideal since you can add all sorts of information to the enum to minimise the necessity for a glorified if..elseif statement. For this difficulty example, we could add a ‘multiplier’ field that allows code to automatically modify state values based on the selected difficulty. See below:

public enum Difficulty
{
    EASY(0, 0.5f),
    MEDIUM(1, 1.0f),
    HARD(2, 2.0f);

    /**
     * Value for this difficulty
     */
    public final int Value;

    /**
     * Multiplier for difficulty
     */
    public final float DifficultyMultiplier;

    private Difficulty(int value, float multiplier)
    {
        Value = value;
        DifficultyMultiplier = multiplier;
    }
}

So now we’ve added the multiplier to the difficulty, we could use it like so:

enemy.speed = baseSpeed * difficulty.DifficultyMultiplier;
player.speed = baseSpeed / difficulty.DifficultyMultiplier;

This has the added advantage that you can manipulate the global difficulty in a single central place.

Posted by Dan in Guides, Java, 7 comments

Network Game Synchronisation

This is going to be a slightly more ‘abstract’ post compared to what I normally do, but I think it’ll be useful for anyone making multi-player games. The biggest problem with multi-player games is network latency & bandwidth. This is something you just have to design for with your game mechanics, for example many MMOs have ‘cast times’ for most actions to cover the latency between the various clients and the server.

In this post I’m going to show clock synchronisation, a kind of synchronisation where you can ensure your various clients are all sharing the same timestamp as the host, give or take a few ms. For my game, having the same clock on all clients means I can time actions to occur simultaneously across all users. The code below is Java for Android, but it can be ported across to other platforms easily enough.

First you need to request the host’s current timestamp:

_timeRequest = System.currentTimeMillis();
_networkDroid.sendMessage(address, GameMessage.REQUEST_TIME);

_timeRequest in this case is a long field, while _networkDroid is my networking layer. Next when you get a response, you need to get the offset between the host’s timestamp and the client’s:

long currentTime = System.currentTimeMillis();
long travelTime = (currentTime - _timeRequest) / 2;

_timeDifference = (int)(currentTime - (remoteTimestamp + travelTime));
_timeRequest = 0;

In this code we first get the client’s current time, we get this as early as possible to minimise the error margin. Next we work out how long it took the packet to arrive from the host – we do this by dividing the total transit time by 2 (the first half was sending the request). Next we work out the difference between the hosts timestamp (with transit time taken into account) and the client’s timestamp.

Finally to get the synchronised timestamp is simple:

return System.currentTimeMillis() - _timeDifference;

And there you have it, synchronised clocks!

Posted by Dan in Game, Guides, Programming, 0 comments

Isolated Storage and Multithreading

The documentation is a little weak on thread safety when it comes to Isolated Storage, with just a little message on the subject: “Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.”.

What I’ve found is this: Reading files from Isolated Storage is fine from multiple threads at the same time – obviously if a thread is saving the file then things are a little murkier.

However, writing files is not thread safe. Do not attempt to write two different files at the same time to Isolated Storage, you’ll get an exception sooner or later.

My fix is a little messy, I have a global lock object I use whenever I want to write to Isolated Storage; this means I can only ever save one file at a time.

Posted by Dan in Windows Phone, 0 comments

Deployment Failed – The parameter is incorrect

In your output window you may find something like:

Deploying C:\Users\Username\Documents\Visual Studio 2010\Projects\MyApp\MyApp\Bin\Debug\MyApp.xap…
Deployment of application to device failed.
The parameter is incorrect.

The problem is probably due to the ApplicationIcon.png or Background.png files. These files must be actual files within the project – they can’t be linked to.

Another problem can be an incorrectly formatted WMAppManifest.xml file. Create a dummy project so you can compare your manifest file to the freshly created correct manifest. Pay particular attention to the Genre (must be ‘apps.normal’) and the IconPath and BackgroundImageURI values. Also make sure the DefaultTask’s ‘NavigationPage’ is set correctly.

Posted by Dan in Windows Phone, 1 comment

ID_CAP_LOCATION ‘Location Services’ Incorrectly Detected With WP7Contrib

I had an issue where my app would incorrectly report ‘location services’ when attempting to submit for certification. The problem turned out to be two classes in WP7Contrib using the Microsoft.Phone.Controls.Maps and System.Device.Location namespaces. When the capability detection tool runs, it checks for any use of a namespace, not just methods that actually check the user’s location. Unfortunately you can’t override it in the WMAppManifest.xml file – which begs the question of why even have the flags there if all they do is increase the chances of an exception.

Anyway, to fix the problem you need to comment out two classes in WP7Contrib.Common. In ‘Serialization’ are ‘SerializeGeoCoordinate’ and ‘SerializeLocationRect’. Comment out these classes in their entirety and re-build both WP7Contrib.Common and your app. Your app should no longer be incorrectly detected as using location services.

Posted by Dan in Windows Phone, 0 comments