How to transfer your Wattbike workout to Garmin Connect / Strava

Short Version

  • Record your Wattbike session on to a USB stick
  • Install the Wattbike Expert Software and import the session from the USB stick
  • Select “Analyse” / “Export analysis modules” to export a DAT file
  • Go to wattbike2garmin to convert your DAT file to a TCX
  • Import the TCX into Garmin Connect / Strava etc

WatttbikeGraph10

Long Version

Introduction

You can plug a USB stick into a Wattbike and get some WSE files with loads of information about your workout, however those files are not recognised by Garmin or Strava etc. Garmin/Strava require TCX files. In order to convert the WSE files to TCX we need to import the WSE files into the “Wattbike Expert Software”, which allows us to export to a DAT file. We can then use a web-site to convert the DAT files to TCX – then we can upload the workout to Garmin/ Strava.

This blog post explains how to do this…

Recording your workout

Before you start your training session on the wattbike, simply plug a USB stick into the bike – The USB port is on the back of the computer/display at the front of the bike. Note: Make sure there is nothing on the USB stick that you want to keep because the Wattbike will first format the USB stick.
Select ‘Just ride’ and complete your work-out as normal. Pressing ESC at the end of the session will display a status bar showing ‘transferring files to USB’. This may scroll through a couple of times but will eventually complete. You may then take the USB stick out.

Wattbike Exert Software

Once back at home you’ll need to install the Wattbike Expert Software – Go to Wattbike and click on the “Expert Software” download button.

WattbikeExpertInstall1

This will download the installer executable which you’ll need to run to install the software.
Once installed and running you should have a screen like below…

WattbikeExpertRunning2

Plug your USB stick into the computer and click on “Device” / “Transfer Data from Logger”. Then click on the ‘USB Stick’ option when the below screen is presented.

WattbikeSessionTransfer3

Select the appropriate drive. (There will probably be just one shown).

WattbikeUsbList4

You are then presented with the following screen…

WattbikeSession5

You probably want to click on “Import all sessions”, or you can select “Session Details” and pick individual sessions to import.
If you do decide to import just some sessions then they are listed with the most recent first. (Note: The date and time is taken from the Wattbike, so if it is wrong on the Wattbike then it’ll be wrong on the screen below).

WattbikeSession6

You’ll next be prompted to create a user. You’ll need to populate the names, height, weight and birth-year in order to proceed. (In future this screen will show your existing user at the bottom of the screen thus meaning you won’t need to enter your details again.)

WattbikePersonal7

You are then taken back to the initial ‘transfer sessions from USB’ screen. Just wait – It might take a few seconds – but eventually you’ll be presented with the following screen.

WattbikeTransfer8

At this point I selected the ‘open file’ option and the software locked up! So, I killed the process via task manager, re-opened the application, clicked on Exit on the splash screen and selected “File” / “Open personal file from database”. I selected myself on the below screen…

WattbikePerson9

Once I’d clicked on myself then the list of sessions were displayed. From here you can export each session. Simply double click on the session and wait for it to load up. You’ll be presented with a screen something like below…

WatttbikeGraph10

At this point we can select the “Analyse” menu and then select “Export analysis modules”.

WattbikeExport11

I left everything ticked as it was and just pressed the “Export” button. You’ll be prompted for a location to save the file and then it will export the data for you. (Note: You will hopefully see some feedback in the bar to the left of the ‘Export’ button to show that it has exported, however if your computer is quick and/or the session is short then you might not see this!)

At this point we have the DAT file.

Converting the DAT file to a TCX file

We must now convert this to a TCX to upload to Garmin. This is the easy bit! Browse to wattbike2garmin and select the “Choose File” button. Select the DAT file you just exported, fill in the date and time and then select “Convert File Now”.

Wattbikeconvert12

The conversion is pretty quick and you should receive a TCX file in no time at all.

WattbikeconvertResult13

You should now be able to connect to Garmin, Strava or wherever and select to manually upload the TCX file, whereupon you’ll see your speed, power and cadence (and heart rate if you paired a heart rate monitor with the Wattbike).

WattbikeStrave14

Trouble Shooting

If you find that the Wattbike Expert software does not recognise your USB stick then it may be that the Wattbike did not format the USB stick properly and thus all the files are in the wrong location.
The correct file structure is as below, with a single folder in the root called “WATTBIKE Expert”. Under that there will be a “SessionFiles” folder with an “UnknownUser” folder and then all the WSE files (one for each work out).

WattbikeCorrectStructure15

However, I have seen one instance (Rob’s comment below) where it appears that the Wattbike did not format the USB stick correctly and we ended up with a structure like below…

WattbikeBadStructure16

You can see that instead of there being a “WATTBIKE Expert” folder, there is a file with that name! Then all the WSE files are in the root. Trying to import these into the Wattbike Expert Software won’t work – the USB stick won’t be listed. If this happens to you then you’ll need to manually create the correct structure (right-click, new-folder etc) and then move all the XML files into the “WATTBIKE Expert\XMLFiles\UnknownUser” folder and move all the WSE files into the “WATTBIKE Expert\SessionFiles\UnknownUser”. You should then be able to import the data into the Wattbike Expert Software application.
It will be interesting to see, now that the folder/file structure is correct, whether future workouts transfer to the correct location on the USB stick.

Running an AngularJS App in the Windows Store

My previous blog entry talked about my experiences writing an ‘AngularJS + HTML5 canvas’ game without a game engine. Now I’m not going to pretend that this was the greatest code of all time – it was very much a way of learning AngularJS – however I am pleased that I managed to complete the game.

For those interested you can play the game here and access the source code on GitHub.

However, I wanted to see if I could convert this to run as a Windows Store App…

By default it is not possible to run AngularJS code in a Windows Store App. If you try then you get the following error…

WinStoreJSUnsafeError

The problem is that various restrictions are put in place to stop malicious code from running – which unfortunately causes problems to anyone who wants to use many of the popular third party JavaScript frameworks out there – e.g. AngularJS.

As it happens there are actually a few different methods for overcoming this. Originally I found this blog post which used a custom version of jQuery. This worked fine, however I didn’t really want to have to include jQuery, so recently I found the winstore-jscompat library, on GitHub, which also solves the problem.

So, to convert our game to run as a Windows Store App we just add all our code to a new empty ‘Win Store App Visual Studio project’ and then make sure we include the winstore-jscompat library before the reference to the AngularJS script like so.

IncludeWinStoreJsCompat

Simples!

If you want to see the code to run the game as a Windows Store App then you can take a look at the WinStoreApp branch of my GitHub repository.

Note: You will not find this running in the Windows Store. It really isn’t good enough for that!🙂

Writing an HTML5 game with no game engine – Just AngularJS and the HTML5 Canvas!

TL;DR

I wrote a version of the Arcade classic Centipede using AngularJS and the HTML5 canvas. You can play the game here and view the source code on GitHub.

1GameScreenShot

Introduction

Normally I’m coding in c# and evangelising about MonoGame, however in recent times I’ve had to start using JavaScript, in particular AngularJS. As always when learning a new programming language I like to write a game – and so it was no different this time around. Back in 2002, learning c#, I wrote a version of Centipede. I still had this code and the ‘programmer art’ graphics I produced back then so decided to recreate it with AngularJS.

This blog post is about my experiences writing this game using AngularJS. The problems I overcame, lessons I learnt and the fun I had.

Note that all of the code for the game is available on GitHub for you to take a look at.

Code Structure

The first thing we’ll look at is the index.html – the only page in the game. It is pretty simple and looks as per below…

2IndexHtml

..with various other script tags following on from this for each code file in the game.

I’m not going to go into too much detail about AngularJS as there are lots of other resources on the web that already cover that, so we’ll just go with a quick summary of the above.
As per most AngularJS pages I have defined my ng-app at the top (gameApp). I also have one ng-controller (appController) and one directive (centipede-game).

The appController code (shown below) very simply handles the transition from the introduction (instructions) screen to the main game. As soon as the user presses a key then we set the $scope.instructionsDisplayed to true. Any further keypresses are then passed off to the keyPressHandlerService – More on this later!

3AppController

Once the instructions have been displayed, and dismissed via the key-press, then the centipede-game directive is displayed on screen.
This directive is the gateway into the game.

4GameDirective

You can see that the template just adds an instance of the HTML5 canvas element to the page, however the link function is the main area of interest as this handles our ‘game loop’. There are various (no doubt better) ways to program the game loop, however I have kept this implementation quite simple. Every 50 milliseconds the gameLoop method is invoked and the ‘animation’ variable incremented, continuously looping from zero to three. This animation value is then passed into our gameService and renderService to handle all the game logic and screen rendering respectively. (More on this later.)

One final point to note about this directive is I’m being a good boy, ensuring the promise created by the $interval service is correctly disposed of when the scope is destroyed.🙂

I don’t intend to go through every line of code in the code base – you’d soon get bored – So I’ll just go over some of the key parts to the code and let you browse the GitHub code at your leisure.

The full code base is shown below…

5ProjectStructure

The gameApp.js you have already seen. This defined the gameApp angular module along with the sole directive and controller in the app.
The constants folder contains all the ‘constant services’ in the game. Generally speaking these are pretty simple areas of the code, for example the characterDirection constant service defines each direction the character can move in. As is the nature of an AngularJS constant service, there isn’t really any logic to see!

6ConstantsCharacterDirection

The sprite.js file is worth a mention though – This contains a reference to every sprite in our sprite sheet. The first sprite is a ‘red mushroom’ at 100% health, then one at 75% health etc.

7ConstantsSprite 7SpriteSheet

Whenever we want to render a particular sprite to the screen we reference it as defined in sprite.js. For example, if we wanted to render the full strength purple mushroom at screen co-ordinates 100, 200 then we would use the below code.

8GraphicsEngineDrawImageCall

This leads us nicely on to our graphicsEngineService which is the first of the ‘Angular factory services’ we will look at.
The graphicsEngineService holds a reference to our HTML5 canvas and handles all the rendering to that canvas – any text that needs to be displayed and/or sprites from our sprite sheet.

Let’s take a look at the drawImage function. A function that allows us to render a particular image at a specific location (x and y co-ordinate).

9GraphicsEngineDrawImageImplementation

The first thing to note is we check whether the caller is passing us ‘screen’ or ‘world’ co-ordinates. This is a common concept in games development. If working in ‘screen’ co-ordinates then we are working on a pixel by pixel basis, however if working in ‘world’ co-ordinates then we are working on the basis of each mushroom/player/enemy taking up one space on the board. As we need to work in pixels when accessing the HTML5 canvas then we convert any world co-ordinates to screen co-ordinates.

Finally we just need to render the chosen image (sprite) on to the canvas. The canvas drawImage function handles this for us – all we have to do is pass in the following parameters…

  • [1] A reference to our sprite sheet
  • [2, 3] The location of the sprite, within the sprite sheet
  • [4, 5] The sprite width and height as defined in the sprite sheet
  • [6, 7] The location on screen we wish to render the sprite
  • [8, 9] The size to render the sprite as on screen (In this case the same size as defined in our sprite sheet, however we could alter these values to stretch or shrink the image).

For those that don’t know about sprite sheets I refer you to the following video by Code And Web (The makers of TexturePacker)…

SpriteSheets – TheMovie – Part 1 by CodeAndWeb

Animation

So, assuming you are still reading this, I’m guessing you have already tried playing the game? As such you will notice the various characters on screen ‘animate’ as they move around – for example the centipede’s legs move back and forth. Also you may have noticed that the characters transition (relatively) smoothly from one location to the next as opposed to suddenly jumping to the next location. This is where the ‘animation’ variable in our centipedeGame directive (mentioned earlier) plays its part…

Every iteration of the game loop (every 50 milliseconds), we increment our animation count by one – looping from zero to three and then back to zero again. Think of this as the ‘frame count’ for each movement sequence – where there are four frames for each movement. So, if the spider moves left one space then this is handled over 4 frames – each frame the spider will move an extra quarter of the distance to the desired location. Combine this with displaying a slightly different graphic for each of the frames ensures that the movement is smooth and the spider looks like it is walking. Although this has simplified the explanation, this is pretty much what is happening!
Similarly the other moving entities in the game (the player, bullets fired, centipede, flea and snail) are handled in the same way – The only difference might be the speed they travel. The player moves twice as fast as the spider, moving to its new location within 2 frames, whereas the bullets travel an entire space each frame.

Let’s take a look at how this works…

Earlier we saw our game loop within the directive.

10GameLoop

This passes the animation into the gameService.update() function. If you take a look at that code then you’ll see there is a check on the current state of the game – e.g. are we handling the ‘player death sequence’ or a ‘transition to the next level’. Assuming we are in ‘normal game mode’ then we ultimately call the moveCharacters() function, which in turn calls update() on each ‘moving character’ service…

11MoveCharacters

Thus each service can handle the logic for updating its own state itself – e.g. the bulletService will move all the bullets and check for collisions, the centipedeService will move all the centipedes, the fleaService will move the flea down, or if the flea doesn’t exist then perform a check to see if it should be created.

At this stage we are not rendering anything to the screen, however this is immediately handled after all services have handled their above movement phase. Taking a look at the gameLoop you can see the call to the renderService.draw() function…

10GameLoop

…which simply offloads the rendering to each service…

12DrawFunction

Again you’ll notice that the ‘animation’ value is passed into the draw method. This is so that each service can determine how far the character(s) have moved in this animation sequence and thus position the correct sprite at the appropriate location. For example the snailService will use a different sprite depending on the animation value – and increase the x co-ordinate more for each animation, thus animating the snail across the screen.

13DrawFunction

(Note: You will also see that two images are drawn because the snail is bigger and takes up 2 sprites.)

Now, I’m not saying this is the ‘best way’ to implement basic animation within a game, but it’s relatively simple and works for me🙂. If you want to delve deeper into this sort of thing then I’d suggest reading this article which goes into depth about implementing movement logic within 2D platform games. And if you want to read about how a game loop should be implemented then I definitely recommend reading the game loop article at Code inComplete. In fact anyone interested in writing their own JavaScript games without a game engine should take a look at the games on the Code inComplete Games site as they are pretty amazing!

Of course, you could use a game engine like Phaser and write a lot less code and produce something much quicker – it depends what your goals are – for me this was about playing with AngularJS and seeing what I could do with it and the HTML5 canvas element.

Player Interaction

Now, one thing we haven’t talked about yet is how to control the player. Interestingly this is an area where I encountered a few problems!
To control the player I decided to keep it simple – arrow keys for moving and the space-bar for firing. If we take a look at the index.html then you’ll see I am using the AngularJS ng-keydown and ng-keyup built in directives to capture the keyboard interaction.

14KeyDown

And, looking in the controller, you may recall from earlier, we are simply handing this information off to a specific service (keyPressHandlerService) to handle the keyboard interaction. That same service can then be queried by the playerService to determine which direction the player should move.

3AppController

I haven’t included the code from the keyPressHandler service here because it is actually quite long and more complex than one would have hoped! When I first started implementing the game I just monitored the keydown event and moved the character whenever it fired, however this meant a very ‘user unfriendly experience’ because holding down the left arrow (for example) would move the character to the left once, then pause, and then continually move the player left. This is because there is a delay between the first keydown event and the second, but then all others come in quick succession. Try it now for yourself in any input box or word processing app etc – you will experience the same behaviour. What I wanted was for the character to continually move all the time the key was pressed. I therefore took a slightly different approach of tracking all the keys currently being pressed, and then on each game loop, we could check which keys are being pressed.

That almost gave me the final solution – I just had one more issue – If the user quickly pressed and released a button then the keydown and keyup would fire before the playerService had a chance to check what key was being pressed, so I had to also track whether the key press had been handled. If on keyup it had not been handled by the playerService then the keyPressHandlerService would keep track of that keypress until it had been handled by the playerService.

One good thing about this though is that I took the opportunity to learn a bit about AngularJS unit testing using Jasmine! You’ll see I have a Tests folder in the solution with a SpecRunner.html page which runs all the tests in my KeyPressHandlerSpec.js file.

15KeyPressHandlerProjectList

16KeyPressHandlerSpecTests

Now, if I was using a game engine like Phaser, then this is the sort of thing that is completely handled for us – However my intention was to write this purely in AngularJS without any game engines – and that I achieved!🙂

Conclusion

In terms of what I set out to do, I am happy. I have successfully written a simple game using AngularJS and the HTML5 canvas. Before I started on this project I had never written anything in JavaScript let alone AngularJS before. Looking back at the commit history I started working on this in July 2013, doing a bit here and there as time allowed, took a break in August (summer holiday time) and then ‘finished’ it in September. However, at that stage the code was a complete mess! Some of the code was AngularJS but a lot of it was pure JavaScript – and as such there were loads of messy callbacks all over the place. Coming from a c# background I probably made every mistake listed on the numerous “Top 10 mistakes made by .net developers when programming in JavaScript” web-sites.
With more experience, and the determination to write this blog post, I revisited the repository in October 2014 and converted it to be 100% AngularJS – and although the repository is by no means a master class in AngularJS, it is certainly a lot neater than it was – which I believe is a testament to how great AngularJS is!

So, would I recommend writing a game in AngularJS with no game engine?
Answer: It depends on your goal!

If you want to produce a HTML5 game quickly (e.g. you are entering a Ludum Dare type game jam) then I’d probably recommend using a game engine like Phaser. Phaser would let you concentrate on the game without worrying about handling keypresses – You wouldn’t even have to worry about things like collision detection as there are built in physics engines within Phaser.

However if you want to get involved in every low level aspect of the game then, as this blog post shows, it is possible to complete a game using just AngularJS and no games engine.

In the future I see myself using Phaser when time is of the essence (e.g Game Jam Event) – However I certainly see myself taking a similar approach to this blog post again, as you ultimately have more power over the mechanics of the game – and indeed I could reuse some of the logic from this game for future games anyway.

Something Extra

My next blog post talks about an extra direction I went with this project – Still using AngularJS, but converting the game to run as a Windows Store App.

Links

  • If you want to learn how to do HTML5 games from scratch properly then I would highly recommend Jake Gordons web site Code inComplete
  • If you want to read about HTML5 game development in general then I’d recommend signing up to the GameDevJSWeekly mailing list.
  • If you want to learn about AngularJS then there are loads of resources out there now, however my favourite is the Dan Wahlin weekly newsletter.

Animation made easy in MonoGame with TexturePacker

Hello! It’s been far too long since my last blog post, however I’ve had nothing interesting to say – that is until now! Today I will talk about the latest version of TexturePacker, which has a new export option specifically for MonoGame – thus allowing you to easily create animations within your MonoGame apps.

For those who just want to see the results straight away, here is a video of the iOS simulator running a MonoGame animation produced with the help of TexturePacker…

Below I will walk you through how to produce the above application. Also a link will be provided to the source code.

TexturePacker

I’ve mentioned TexturePacker in a previous blog post however, for those that haven’t used it before, it is a very easy to use application for creating Texture Atlases / Sprite Sheets. The idea is that you draw the individual frames of animation for your game characters as separate image files – and then drag and drop them into TexturePacker – whereupon you end up with a single image file and accompanying data file ready to load into your game. Using a single sprite sheet is much more efficient than loading lots of individual images in game development. (See this fun video from the makers of TexturePacker that explains it better than I can)

SpriteSheets – TheMovie – Part 1 by CodeAndWeb

Now the above maybe nothing new to a lot of people, however what you might not know, is that the latest version of TexturePacker has an option for exporting the sprite sheet and data file in a format targeted at MonoGame – along with access to source code for loading and handling the resultant data files within your MonoGame app. This means that all the hard work of loading the sprite sheet and rendering the correct frame is taken care of for you – as described further below…

So, let’s get started…

First step – Download a copy of TexturePacker from here and load it up. You’ll be presented with a screen like below…

TexturePacker-NewProject

Select the MonoGame option and then ‘Create Project’ to move forward…

TexturePacker-CreateProject

Next gather your individual images together into a logical folder structure. E.g. folder name based on the animation type. Then drag and drop the parent folder into TexturePacker. (For the purposes of this tutorial I am using a set of images from my demonstration project on GitHub here).

Immediately you’ll see that TexturePacker has grouped all the images together, as below…

TexturePacker-Sprites

Now, the final steps, before hitting the ‘publish’ button to create your sprite sheet data, is to alter a few settings depending on your requirements. I will explain the few that we will use in this tutorial, however an extensive set of documentation can be found here.

TexturePacker-Settings

Scaling Variants

In a later section within this tutorial I will walk you through creating a MonoGame app, targeting iOS, using Xamarin Studio. Those who have done iOS development before will know that you should create two versions of your graphics – a high resolution version for retina screens and a ‘normal resolution’ graphics file for non-retina screens – and by appending @2x to the end of the retina file, iOS will take care of ensuring the appropriate graphics file is used at run-time.
If you are targeting iOS with MonoGame then this is no different. MonoGame will automatically load the @2x version when run on a retina device.
This is where the ‘Scaling Variants’ feature comes in useful. Rather than having to produce two versions of your graphics files and use TexturePacker twice to export separate sprite sheets for retina and non-retina, you are able to tell TexturePacker to do all of this for you.

So, let’s do that now! Click on the ‘Scaling Variants’ cog and you’ll be presented with the following screen.

TexturePacker-ScalingVariants

Change the Preset option to be generic @2x and then click on the ‘Add’ button to get a second box. Fill in the details as below.

TexturePacker-ScalingVariantsPopulated

Click Apply and then Close.

Hopefully the above screen shot was pretty self-explanatory, however in summary we are telling TexturePacker to produce two versions of the sprite sheet – one with a scale of 1 (retina version) and one with a scale of 0.5 (non retina version) – and the Variant Name is @2x. (The variant name is used later when we specify the filenames for export).

Of course, if you are targeting a platform (or device) that only has support for a single resolution then you won’t need to use the ‘Scaling Variants’ option – however for iOS, for example, this option makes it very easy.

Trim Mode

If you scroll down the TexturePacker options you’ll see a Sprites section…

TexturePacker-SettingsTrimMode

The first option is the ‘trim mode’ option. Already set to ‘trim’, this will remove any transparent borders around each individual frame, thus reducing the overall size of the sprite sheet. I would therefore suggest keeping this set to ‘trim’ rather than ‘none’. Also, handling the trimming of the frames at runtime is taken care of for us by the TexturePacker MonoGame Loader code – as described later!

Pivot Points

This option serves two purposes…

  • Firstly it dictates which point on each frame should be positioned at the location that we choose to render that frame. For example, if you choose a pivot point of centre and you choose to render a frame at location 100, 100 then it is the centre of the frame that is positioned at 100, 100. However if you choose a pivot point of top left then it is the top left hand corner of the frame that is positioned at location 100, 100. Generally speaking I would choose centre as my pivot point.
  • The pivot point also dictates where the point of rotation should be if we rotated a frame at runtime. Should it be the Top-Left corner of the frame or the centre etc. If you don’t need to rotate a frame at runtime then it doesn’t matter.

Export Files

Next let’s take a look at the three different files that are produced by TexturePacker when we create our sprite sheet…

TexturePacker-SettingsExportFiles

Initially blank, these fields need to be populated as per the screenshot and explanation below…

TexturePacker-SettingsExportFilesPopulated

The Texture file is the graphics / sprite sheet file. Above you can see I have set the name of this file to be CapGuyDemo{v}.png. The main point of interest here is the {v} – this will be replaced at the time of export by the variant name as configured in the Scaling Variants optjon above. Thus, we will end up with two PNG files – one called CapGuyDemo@2x.png and the other called CapGupDemo.png. Just by configuring the Scaling Variants option and placing the {v} in the filename, this is handled for us.

The Data file is the accompanying file that contains the location, trim, rotation and pivot point information for each individual frame/sprite within the sprite sheet. As, in this example, there are two different sprite sheets produced by TexturePacker – retina and non-retina – then so we will need two different data files. Therefore again we include the {v} in the filename.

Finally the Class file is a file containing a c# class which simply contains a series of constants referring to each individual frame. Later you will see that within our MonoGame app we need to reference each frame by its ‘string name’ however a runtime error would occur if we had a typo, or if we specified the name of a frame that we accidentally forgot to drag into TexturePacker. Therefore we use the const strings defined in the below file to reference a particular frame – thus if we refer to a const string that does not exist then we’ll get a compile time error which can be resolved straight away as opposed to a run time error that would not occur until deployed and running on the target device(s).
This will become clearer when we build the MonoGame app later.

Code-ClassFile

One point worth noting at this stage is to give some thought to the location of the above three files. You might want to specify the appropriate location within the source code to avoid an extra step of copying them later. i.e. the Data file and the Texture file ultimately need to end up in the Content folder – and the class file needs to go ‘somewhere’ in your app source tree.

As I stated above, there are more options within TexturePacker, however for the purposes of this tutorial we will leave it at that for now and proceed to the next step. Therefore save your TexturePacker project and then hit publish to export all you sprite sheet(s) and data files(s) and the class file.

TexturePacker Loader

Before we delve into writing our demo MonoGame app it is worth first talking about the TexturePacker Loader source code. The TexturePacker Loader is free to use and can be obtained either from Nuget or direct from Github (or, in the future, the Xamarin component store). If installing from Nuget or cloning direct from Github you’ll get the source code.

Most Nuget packages are a library DLL that just gets referenced into your project, however this Nuget package actually brings in the complete TexturePackerLoader source code – It’s only 4 source files so it’s quite easy to follow and understand – and, as such, advanced users have the option of making their own changes should they wish.

TexturePackerLoader-ProjectFiles

Now, I’m not going to delve deeply into the TexturePacker Loader explaining every single line of code – instead I will give an overview of how to use the loader.

Sprite Sheet Loader

The first step you’ll want to take when creating a new MonoGame application is to load your sprite sheet(s) along with any other assets. As such this is likely to be done in the LoadContent method of your main Game class.
Simply instantiate a new instance of the SpriteSheetLoader class and call the Load method passing in the name of your sprite sheet (as produced by TexturePacker), something like below…

Code-SpriteSheetLoader

You will now have a reference to a SpriteSheet. I’d suggest this is a class level variable as it will be required in your draw method as described below…

Sprite Render

The other main class that the TexturePacker Loader gives us is the SpriteRender class. This class handles the positioning and drawing of our sprites on screen. In its simplest form all you have to do is specify which frame / image to draw and at what position – however you also have the power, if you so desire, to specify the colour, rotation, scale and whether the image should be flipped.
Again I would recommend instantiating the one instance of this class in your LoadContent method like below…

Code-SpriteBatchAndRender

…and then in your draw method you simply render frames on screen something like this…

Code-Draw

In the above example we are drawing the frame / image labeled Capguy_turn_0002 to location 350, 530.
You may recall that one of the files exported by TexturePacker was the class definition file which simply defined a constant value for each individual frame within the sprite sheet. This is where we use that constant. We could have just passed in the string value of the frame, however this approach is better as it ensures a compile time error is generated if we update the sprite sheet and forget to include this individual image file. The alternative is a run time error which might not occur until we have deployed to the device which could be a pain.

And that is pretty much all that you need in order to start rendering individual frames to the screen. It doesn’t matter if TexturePacker rotated these frames when the sprite sheet was produced or if the frames were trimmed etc – The code within the TexturePacker Loader takes care of all of this logic for us – We just need to specify (1) which frame we want to render and (2) where we want to position it!

So, now you know how to use TexturePacker, and you have an understanding of the TexturePacker Loader, you are now free to start integrating it with MonoGame!
However if you feel you aren’t quite ready to delve in yet, or maybe you want to see a more in depth example, then the next part of this tutorial is for you. Under the MonoGame heading below there are two sections – one for creating an iOS MonoGame application using Xamarin Studio – and one for creating a Windows 8 Store App using Visual Studio. They are quite similar – just choose the one that is appropriate for you. Or alternatively download an example MonoGame solution from Github showing how it is all put together.

MonoGame

For those that don’t know…

“…MonoGame is an Open Source implementation of the Microsoft XNA 4 Framework. The goal is to allow XNA developers on Xbox 360, Windows & Windows Phone to port their games to the iOS, Android, Mac OS X, Linux and Windows 8 Metro. PlayStation Mobile, Raspberry PI, and PlayStation 4 platforms are currently in progress…”

The above is pinched straight from the MonoGame website. Basically, it’s all about making cross platform game development easier. No need to learn different languages/APIs for different platforms. Instead just develop in c# for one platform – and then make (hopefully just minor) adjustments to run on other platforms.

In this tutorial I am going to show you how to create a simple demo Windows 8 Store app using the above sprite sheet to animate the ‘cap guy’ across the screen. This will be done using Visual Studio. I am then going to show you how to do exactly the same thing, using Xamarin Studio on a Mac, to create the same demo running on an iPad.

However, if you want to skip the below instructions and jump straight to the code then you can do so by grabbing the entire solution (Xamarin and VS solutions plus the TexturePacker sprites) from Github.

So, first up, Visual Studio…

MonoGame Windows Store Example with Visual Studio

Now, there are a couple of different approaches to getting MonoGame working with Visual Studio. Both are extremely easy – it just depends what your preference is….

One option is to download the windows installer for the latest release from MonoGame

This gives you a ‘MonoGame’ option in the list of templates presented when selecting to create a new project. As such you can choose the ‘MonoGame Windows Store Project’ and you’ll be up and running straight away…

Windows-MonoGame-CreateProject

An alternative approach (which I prefer as it is easier to update as new versions/updates of MonoGame become available) is to start a new standard windows store project and then install the monogame nuget package. The choice is yours!

Windows-MonoGame-Nuget

At this stage you should be able to build and run the solution and be presented with a ‘cornflower blue’ screen. If so then all is working!

The next step is to add our three TexturePacker files to the solution…

First, place the texture file and the data file into the Content folder of your solution and mark their ‘build action’ as ‘Content’.

Windows-MonoGame-DataFileProperties

This ensures that we can access these data files at run-time.

With regards to the SpriteNames.cs file (or whatever you decided to call it) this can go anywhere you like within your solution.

Next we need to bring in the TexturePackerLoader code that knows how to handle the TexturePacker data files – and render our sprites to the screen. This code is available in Nuget – so, right click on ‘references’ in your ‘solution explorer’ and select ‘Manage NuGet Packages’.

Windows-MonoGame-Loader-Nuget

Search for TexturePacker and install the package…

Windows-MonoGame-Loader-Nuget-Search

Most Nuget packages are a library DLL that just gets referenced into your project however, as described above, this Nuget package actually brings in the complete TexturePacker Loader source code.

TexturePackerLoader-ProjectFiles

Once we have our TexturePacker sprite sheet, data file, class file and the TexturePacker Loader source; we just need to start using it. So, at this stage I would suggest downloading the Demo package from Github.

Load up the solution and it should look something like below…

Windows-MonoGame-VisualStudio

Hit F5 and you should see the ‘Cap Guy’ walking backwards and forwards across the screen, which considering how little code there is, I think is pretty cool!

The next section explains how to create the same project using Xamarin Studio and targeting iOS. Then, for those who want to take a deeper look at this demo, there is a further section explaining a bit more about the Demo app.

MonoGame iPad Example with Xamarin Studio

There are probably a few different ways to get yourself setup to use MonoGame with Xamarin Studio, but my preference is to use the Nuget package. I prefer this as it is easier to update as new versions/updates of MonoGame become available.

So, load up Xamarin Studio and create a new iPad empty project as shown below…

Xamarin NewProject

From here select the Project \ Add Packages option…

Xamarin AboutToAddPackage

…and then search for MonoGame once the Nuget window appears…

Xamarin NugetPackageList

You will notice various different packages are available, including a couple of ‘official’ MonoGame ones. I would recommend installing the one highlighted – the ‘MonoGame’ package as this not only contains the binaries required to build against MonoGame, but also some sample code to get us up and running quickly.

Once installed then you’ll see a new ‘Packages’ folder appear in your solution with the MonoGame packages installed, as well as a couple of new source files – a Game1.cs and a GameMain.cs.

Xamarin AfterNugetAdded

Now there are two important steps that you need to take in order to run the solution at this stage.

First you must delete the AppDelegate.cs and Main.cs files, as these are replaced by the new Game1.cs and GameMain.cs files.

Secondly you must add a reference to the newly downloaded Nuget package. This is a little different to how it works in Visual Studio. So, right click on ‘references’ and select ‘edit references’ – you will be presented with a screen similar to below…

Xamarin AddReference

Select the ‘.Net Assembly’ tab and then browse to the MonoTouch folder within the MonoGame.Binares package – Click the MonoGame.Framework.dll – Click ‘Add’ – and then finally click ‘OK’.

You should now be able to run the solution and be presented with a ‘cornflower blue’ screen.

The next step is to add our TexturePacker files to the solution…

First, create a ‘Content’ folder and place inside it the texture and data files. Add them to the solution and ensure that the ‘build action’ for all of them is ‘BundleResource’ – This ensures that we can access these data files at run-time. The png files automatically get set this way, however the txt files may not.

Notice how we have two sets of similarly named files in the Content folder – one with the @2x extension which will be used for Retina tablets – and one without which will be used for non-retina tablets. This is handled for you – you do not need to do anything special within the code.

Xamarin ContentProperties

With regards to the SpriteNames.cs file (or whatever you decided to call it) this can go anywhere you like within your solution.

Next we need to bring in the TexturePackerLoader code that knows how to handle the TexturePacker data files – and render our sprites to the screen. This code is available in Nuget – so, select Project / Add Packages and this time search for TexturePacker and install the package…

Xamarin NugetTexturePacker

Most Nuget packages are a library DLL that just gets referenced into your project however, as described above, this Nuget package actually brings in the complete TexturePacker Loader source code.

Xamarin TexturePackerReferences

Once we have our TexturePacker sprite sheets, data files, class file and the TexturePacker Loader source; we just need to start using it. So, at this stage I would suggest downloading the Demo package from here.

Load up the solution and it should look something like below…

Xamarin FullSolution

Click the ‘run triangle’ and you should see the ‘Cap Guy’ walking backwards and forwards across the screen.

If you want a deeper look at this demo code then the following section goes into a bit more depth.

DemoGame

Well done for getting this far. I hope the above has been useful!
This final section isn’t really about TexturePacker or MonoGame – It is just a brief overview of some of the other classes in the demo app which you might find useful for your own projects – and if so then are free to use.

Hopefully most, if not all, of the code in the DemoGame class is self explanatory. The interaction with the TexturePacker Loader code has already been explained above. However you may notice the InitialiseAnimationManager() method. This method defines how the ‘Cap Guy’ should be animated within the demo.

The first part of this method defines where he should first be positioned on screen and the speed at which he should move (and if running under iOS then this can be effected by the scale of the device (i.e. is it a retina device or not).

Code-DemoGame-Position

Next you’ll see two local variables created which are simply arrays of frame names. These simply define which frames make up an individual sequence of movement. i.e. turnSprites is an ordered array of all the frames required to animate Cap Guy turning, whilst walkSprites is an ordered array of all the frames required to animate Cap Guy walking.

Code-DemoGame-TurnSprites

Along with the above sequence of frames, we can state the velocity of the Cap Guy, time before switching frames and whether the frames should be flipped (e.g. walking left as opposed to walking right). Together this information is enough to define an individual animation – as declared in code like so…

Code-DemoGame-Animations

Now that we have defined each animation type – walking left, walking right, turning left to right and turning right to left; we can join these animations together to make our entire looping animation of the Cap Guy walking backwards and forwards across the screen.

Code-DemoGame-Animations2

i.e. He will complete the ‘walk right’ animation six times, turn around, complete the ‘walk left’ animation six times and then turn around again.

Finally we create an instance of the AnimationManager class passing in all of this information.

Code-DemoGame-AnimationManager

Once this is defined, all we need to do is call the AnimationManager’s update method each game loop.

Code-DemoGame-Update

…and then ensure we use the information from the AnimationManager class to ensure the correct image, with the correct sprite effects (whether flipped or not) is rendered to the correct position in our Draw method…

Code-DemoGame-Draw

For your own games you may want to implement your own way of handling the animation – but, if not, then you are more than welcome to use the code from above!

The End

I hope this tutorial has been useful. Let me know how you get on!

For those who’ve skipped straight to the end without building the demo, here is a video of our demo running in the iOS simulator via Xamarin Studio.

At some point in the future the intension is to also publish the TexturePacker Loader to the Xamarin Component Store. Once that is done then I’ll post an update to the blog!

Links related to this tutorial

MonoGame
TexturePacker
Github Demo Source Code

DDD East Anglia

Yesterday I presented at the DDDEA conference in Cambridge. I talked about MonoGame and presented a couple of demos – one a live port of an iPad demo to Windows8 – and one including an example of how to create animation in MonoGame with the help of Spine by Esoteric Software.

I hope everyone who attended enjoyed the presentation!

At the end of the presentation I had a slide with a load of links to the various things I talked about. As promised in the talk I have put those links here for peoples reference….

MonoGame: http://www.monogame.net/
MonoGame Source: https://github.com/mono/MonoGame
Xamarin: http://www.xamarin.com/
Spine: http://esotericsoftware.com
Dancing Crab Demo Source: https://github.com/RandolphBurt/SpineMonoGameDancingCrabDemo
Chase Camera Demo Source: https://github.com/RandolphBurt/ChaseCameraMonoGamePortingDemo
My Paint Replay App: https://itunes.apple.com/us/app/paint-replay/id596118428?ls=1&mt=8

Dragons and Dancing Crabs [An update]

Just a quick blog post to update the situation with the Esoteric Software runtimes. As of today the official Generic C# and XNA runtimes have been made available by Esoteric Software. As such there is no need for my runtime anymore. This is good news as it means that any new features added by Esoteric Software will be automatically fed through to the official run-times. I have therefore updated my GitHub Repository to use the official runtimes. As such there is a lot less code to see! If you still want to get hold of ‘my old cobbled together code’ – converted from the corona and java runtimes – then I’ve tagged the tree on the master branch at the point before I removed the runtime – Tag name is PreOfficialRuntime.

One thing to note is that the format of the atlas (Sprite Sheet) files have changed (compared to my runtime) as a result of moving to the official run-times. If using TexturePacker then you should export the “LibGDX” format rather than the Json formats.

I found one small issue with the runtime when importing skeleton Json files with slot changes in the animation, however by the time you read this it’ll be fixed because I can see my pull request has already been accepted! Fast work from the team at Esoteric!

I did find one more issue, that is not yet resolved, where the graphics are distorted when the iPad is rotated. I haven’t yet found where this issue lies. I wonder if it is with the custom SpriteBatcher code in the XNA runtime, however it may just as likely (more likely) be something I’ve done wrong! I’ll see if I can look into this over the next few days and fix it up.

[Edit: 12-04-2013 – The rotation distortion is now fixed. Esoteric Software fixed an issue in the XNA runtime] 🙂

Dragons and Dancing Crabs

Creating smooth animations in MonoGame using Spine

For those of you who don’t want to read the entire blog post (shame on you), here’s a slightly slowed down video of some animation in MonoGame using Spine to create the animation. In summary, this can be achieved with just a few lines of code in MonoGame.

Introduction

This blog post is a guide to producing smooth animation in MonoGame using Inkscape, TexturePacker and Spine. Below is a ‘short and simple beginner level’ introduction to each of these apps and then a slightly more detailed step by step tutorial for getting an animation up and running in MonoGame.

Inkscape


Inkscape is an Open Source scalable vector graphics editor – similar to Illustrator or CorelDraw, but completely free of charge. You don’t need to be pay loads of money to produce good vector graphics, but you do need to be able to draw. If you can’t draw then it doesn’t matter how much money you spend on an app, it won’t make you suddenly produce better graphics.
I hadn’t used any vector graphics editing software before so Inkscape seemed a good choice – it was free so if I didn’t get on with vector graphics editing then I hadn’t wasted any money.

TexturePacker


TexturePacker is a neat tool for producing ‘sprite sheets’. Once you’ve created all your separate image files for your game (e.g. using Inkscape), you simply drag and drop them into TexturePacker which then exports one large image file along with a data file describing where each individual image is within the larger image. Using sprite sheet is more efficient than loading lots of individual images in game development. (See Wikipedia for more info).

Spine


Approximately a month ago I heard about a Kickstarter project from Esoteric Software to make Spine – an application that allows you to make 2D skeletal animation for games. Taken from their web-site…

“…Spine replaces traditional raster animation in games, providing smoother animations that are easier to produce. Animations can be created without needing more art and are so tiny that games can make extensive use of them…

So I backed the project and now have a working copy of the Spine app running on my mac – and it is pretty good! In my opinion anyone who needs to animate any kind of character (or title screen for that matter) should buy it. It will save you so much time! Note: Spine is also available for windows.

MonoGame


MonoGame is an Open Source implementation of the Microsoft XNA 4 Framework. As a MonoGame Evangelist’ I will be biased of course, however even so, it is awesome!🙂 Develop an app using MonoGame and with a few device specific changes you can target lots of different platforms with a huge percentage of shared code.

Tutorial

That’s the introduction out the way, so let’s start creating our animation!
Note: All the code and graphics are available on github.

Step 1 – Inkscape – Creating our graphics


I decided to try out a vector based graphics application for my next game so that it would be easier to produce graphics for various screen sizes (e.g. iPad v iPad retina). i.e. I could just draw one set of graphics and then scale the vector diagram appropriately before exporting the png/jpg file.

Note: You don’t have to use a vector graphics editor for producing your images to use in Spine or MonoGame. Any graphics tool that produces images is fine. I simply wanted to try out a vector graphics editor, as I hadn’t used one before.

If you haven’t used Inkscape before then I’d recommend you follow the tutorials in the first few chapters here. It’s fair to say that Inkscape is pretty powerful, but if creating vector graphics is new to you then you will have to put some effort in to avoid frustration. I also found that the 2D Game Art for Programmers site was a useful learning resource.

So traditionally when creating graphics you might have an image of your character in one position and then another image in the next position and so on – e.g. one image with both feet together – another with left foot forward and then one with the right foot forward. This is fine, however it would be nice to make animations where each limb moved smoothly – hence this tutorial.

One of the main characters in my next game is going to be a crab, so I’ve drawn a simple crab, as below, using Inkscape.

InkscapeCrab

Now, rather than exporting this entire picture as a single image, I have exported each ‘movable part’ as separate images – The intention being that we want to animate each body part separately to create realistic motion – hence we need separate body part images. Fortunately Inkscape allows you to export individual shapes/paths of an image to a bitmap/png/etc file – as shown below.

InkscapeExportSelectionCrab

The only problem however is that it actually exports the square selection surrounding all selected images rather than the actual selection – therefore you need to move the selected body part to a blank section of the page, then export the selection and then undo the move so that it goes back to the correct location. Repeat this for each body part and you will end up with a series of images files – one for each movable body part.
Note, it is worth giving some thought to how you name your images files to make it easier to identify them later – e.g. BackUpperLegLeft.

Step 2 – TexturePacker

Now we have all our individual images files we need to load them into TexturePacker to create our Sprite Sheet. This part is very easy.

  • Open TexturePacker
  • Drag and drop each individual image file into TexturePacker
  • Ensure the Data Format is set to “JSON (Array)”
  • Ensure “Trim Mode” is set to ‘none’
  • Press Publish to create a Json data file and a PNG Sprite Sheet

You should now end up with a Json file looking something like this…

{"frames": [

{
	"filename": "BackLowerLegLeft.png",
	"frame": {"x":294,"y":335,"w":36,"h":69},
	"rotated": false,
	"trimmed": false,
	"spriteSourceSize": {"x":0,"y":0,"w":36,"h":69},
	"sourceSize": {"w":36,"h":69}
},
{
	"filename": "BackLowerLegRight.png",
	"frame": {"x":285,"y":407,"w":36,"h":69},
	"rotated": false,
	"trimmed": false,
	"spriteSourceSize": {"x":0,"y":0,"w":36,"h":69},
	"sourceSize": {"w":36,"h":69}
},

…and a SpriteSheet looking something like this…

TexturePackerCrabSpriteSheet

Step 3 – Spine

Right, we’ve done the easy bit – now for the fun part! Creating our animation…

At this point I would suggest you go to the Esoteric Software web-site and watch the “Quick Overview Part 1” and “Quick Overview Part 2” videos. They are both approximately 10 minutes in length. They will tell you enough for you to create an animation in Spine. But in summary, you will need to export a copy of the entire crab from Inkscape and import this as your template image in Spine so you can line everything up – then draw the ‘bone structure’ on top of this template – then apply the individual images to each bone – delete the original template file and then you can start creating an animation by rotating each bone/image on various frames of the timeline. Spine will then take care of ensuring a smooth animation between each frame. Below we can see the ‘bone structure’ I have created for the crab.

SpineCrabBoneStructure

One thing you may notice is that there are ‘bones’ for the two eyes and eye-lids. The reason for this is that I am going to make the eye and eye-lid jump up in the air in a cartoon style. So, don’t necessarily think of ‘bones’ as having to mirror where real bones are – instead it is all about what parts of the animation need to move. Further to this, if I had wanted the teeth to move about then one approach would be to create separate teeth images instead of them being part of the head image – then I could have created ‘bones’ to attach them to and animated them.

Something else you may have noticed earlier is the additional eyes in the Sprite Sheet exported by TexturePacker. We have one set for looking forwards, where the pupil is in the middle of the eye – and another set for looking to the side where the pupil is on the side of the eye. The reason for this is because we can still use ‘old fashioned style’ animation where required – i.e. When creating our crab skeleton in Spine we can attach both types of eye images to the ‘eye bone’ but choose on a per frame basis which one we want to use. Thus, when the crab walks to the side he can look to the side, but when he is stood still he can look forwards.

Once you’ve completed your animation within Spine you’ll need to export a Json file of your work. (Select the ‘export’ menu option – ensure Json is the selected data format – select a destination – and press ‘Export’. This will create a Json file containing the basic skeleton structure of your character and all the animations.

Step 4 – Putting it all together

At this stage we have the following…

  • Our Sprite Sheet [produced by TexturePacker]
  • A Json file describing the details of the individual images within the Sprite Sheet [produced by TexturePacker]
  • A Json skeleton file [produced by Spine]

We now need to work out how to put this all together to create animations within MonoGame…

On the face of it this may sound quite tricky. Although writing code to import the Sprite Sheet and parse the Sprite Sheet Json data file is relatively simple, writing code to import the Spine animation data and then understand that data to perform the animation is quite complex. Fortunately Spine offers more than creating the animation – The guys at Esoteric Software have also created some run-times for different platforms which you can plug into your own code. They have a runtime for LIBGDX (in java) and another for Corona (in LUA).

But wait, how does that help us? We need a c# MonoGame runtime.

Now, one of the stretch goals for the Spine Kickstarter was to develop a generic c# runtime. The good news is that this stretch goal has been reached and is due to be developed within the next few weeks, however I couldn’t wait that long so I decided to try writing my own runtime specifically for MonoGame. 🙂
Now, I must point out that although I do indeed have a runtime which is available for anyone to use, I don’t really feel I can take a huge amount of credit for it because it is entirely based upon the work already done by the guys at Esoteric Software – i.e. heavily based on the LIBGDX and Corona runtimes.

So, the source code for the MonoGame runtime can be found on GitHub. Grab a copy of this and you will see a ‘runtime project’ and an iOS ‘demo project’. Add a reference to MonoGame and it will build and you’ll see an animated crab.
Note: If you want to run this on a different platform than iOS then just create a new runtime project (for your platform) and add all the source files. Then implement an equivalent demo project.

If we look at the code needed to create an animation then it is pretty simple! Below is our entire Game class for rendering a smooth animation. The key parts are…

  • The LoadContent method where we (a) load our TexturePacker SpriteSheet and (b) load our Spine skeleton Json file.
  • The Draw method where we move the animation along based on the time and then simply call ‘Draw’ on the skeleton passing in our SpriteBatch and letting the Spine runtime take care of the rendering.

Simples!

/// <summary>
/// Animation demo.
/// 2013-March
/// </summary>
namespace Demo
{
	using Microsoft.Xna.Framework;
	using Microsoft.Xna.Framework.Graphics;
	using Microsoft.Xna.Framework.Input.Touch;
	using Spine.Runtime.MonoGame;
	using Spine.Runtime.MonoGame.Attachments;
	using Spine.Runtime.MonoGame.Graphics;
	using Spine.Runtime.MonoGame.Json;

	public class AnimationDemo : Game
	{
		private readonly GraphicsDeviceManager graphicsDeviceManager;
		private SpriteBatch spriteBatch;
		private Texture2D crabTextureMap;
		private Skeleton crabSkeleton;
		private Animation crabAnimationWalk;
		private float timer = 0;

		public AnimationDemo ()
		{
			this.graphicsDeviceManager = new GraphicsDeviceManager (this);
			this.graphicsDeviceManager.IsFullScreen = true;
			
			this.graphicsDeviceManager.SupportedOrientations = 
				DisplayOrientation.LandscapeLeft | 
					DisplayOrientation.LandscapeRight |
					DisplayOrientation.PortraitDown | 
					DisplayOrientation.Portrait;
			
			this.Content.RootDirectory = "Content";
		}
		
		protected override void Initialize ()
		{
			TouchPanel.EnabledGestures = GestureType.Tap;
			
			base.Initialize ();
		}

		protected override void LoadContent ()
		{
			// Load our sprite sheet
			this.crabTextureMap = Content.Load<Texture2D>("crab.png");
			var texturePackerReader = new TextureMapJsonReader ();			
			var spriteSheet = texturePackerReader.ReadTextureJsonFile("Content/crab.json", this.crabTextureMap);

			// Load our basic skeleton
			var skeletonReader = new SkeletonJsonReader(new TextureAtlasAttachmentLoader( spriteSheet));
			this.crabSkeleton = skeletonReader.ReadSkeletonJsonFile("Content/crab-skeleton.json");
			this.crabSkeleton.FlipY = true; // MonoGame origin is top left so we need to flip the y axis

			this.crabAnimationWalk = crabSkeleton.Data.FindAnimation ("WalkLeft");

			// Finally set the initial state/position of our crab
			crabSkeleton.SetToBindPose();
			
			var root = crabSkeleton.GetRootBone();
			root.X = 500;
			root.Y = 750;
			
			this.crabSkeleton.UpdateWorldTransform();

			this.spriteBatch = new SpriteBatch (this.graphicsDeviceManager.GraphicsDevice);

			base.LoadContent ();
		}

		protected override void Draw (GameTime gameTime)
		{
			this.spriteBatch.Begin ();

			this.GraphicsDevice.Clear (Color.CornflowerBlue);

			// In reality you'd probably pass in some time related variable to this rather than
			// my crude timer variable for demonstration purposes.
			// Also you'd probably want to perform the UpdateWorldTransform outside of the draw method
			// Should probably be in the Update method
			this.crabAnimationWalk.Apply(crabSkeleton, timer++ / 100, true);
			this.crabSkeleton.UpdateWorldTransform();
			this.crabSkeleton.Draw(this.spriteBatch);

			this.spriteBatch.End ();

			base.Draw (gameTime);
		}

		protected override void Dispose (bool disposing)
		{
			this.crabTextureMap.Dispose ();

			base.Dispose (disposing);
		}
	}
}

If you want to see this running on your machine then you can grab the source code from GitHub.

Where do we go from here…

Currently the structure of the MonoGame runtime code needs a bit of work. As stated, I cobbled it together by looking at the existing Corona and LIBGDX runtimes and just concentrated on getting something working. The code could do with a bit of refactoring in terms of encapsulation and general c# structure, however it works so it will do for now. There are probably a couple of features not yet implemented (colour blending for example) and I haven’t tried the mixing of animations or different skins yet. Also I believe you can export binary data, rather than Json, from Spine which will probably load quicker – however I haven’t written a binary importer yet.
I suspect I will actually wait until the official generic c# runtime is released and then fork that to create the next version of the MonoGame runtime. The advantage of this is that the core of the code will then be provided by Esoteric Software so any new features or bug fixes can just be taken from their fork – and I would imagine my MonoGame part of the code will be much smaller. However, it is a bit of an unknown at this stage – until the generic c# runtime is available we won’t know how well a MonoGame implementation might fit in – so worse case scenario is that I decide to keep my existing MonoGame runtime and maintain it. Either way, we can be sure that Spine animations will work with MonoGame!

At this point I feel I should also point out another option available to people. Trugnt has taken a fork of MonoGame and implemented loads of LIBGDX features within it. Their source is available on GitHub so gives people another option when it comes to implementing Spine and MonoGame together.

Enough with this crazy crab! Where’s the dragon?

Yes, there is a rather cool dragon in the video at the top of the page. If you want to see the graphics and Json files for that then you’ll need to download Spine from Esoteric Software and try them out yourself🙂 Those graphics aren’t mine so I didn’t feel it was appropriate to include them in my demo project on GitHub. Consider it an exercise for the reader🙂

Summary

So, in summary, if you want to create smooth animations for your games then I’d strongly recommend taking a look at Spine. I love it!
And if you use MonoGame to create your games then you now have the ability to use those animations in your MonoGame apps!

I hope this has been useful to you. Let me know how you get on.
Good luck and have fun!

EDIT: 04/04/2013 – Updated blog entry slightly to reflect recent change to the runtime as a result of a data format change in the latest version of Spine. The animation data is now included in the main skeleton Json file.

EDIT: 11/04/2013 – This is slightly out of date now because the official c# runtime has been produced by EsotericSoftware. See later blog post for more information.