Skip to content

Blog moved to a new location!

This Blog has moved: http://blog.pixelpracht.net/

I have a domain, webspace… there is no good reason beyond lazyness to not host my own blog but forward to wordpress.com. Finally I found the time and bravery to make the move!🙂 I hope everything still works. In the days to come I’ll explore the new customization options that I now have.

Thanks to Barry from GameCharts.com for the nudge!🙂

An asset pipeline in Flash. How we do it!

Here’s a real-world example of how we handle the assets in our current flash game project at my company. It’s a rather big browser game that uses several megabytes of resources (XML meta-data, PNG & JPEG Images, Sounds and Movieclips) that we have to deploy to the serves and load into the client when needed. In such a scenario managing the dependancies between the code and the assets can be quite challenging and timeconsuming.

This post is a little advanced and you should be allready familiar with embedding and dynamically loading resources in Flash.

The Challenge

The content creators create assets file by file and save them to a folder structure. Thanks to the magics of version control systems (SVN in our case) these ever growing amount of assets is synced between all collaborators. But someone has to make sure everything is available at runtime when the application needs it.

To embedd all resources using the [Embed] tag in the game’s source code would cause several problems: The size of the SWF would be huge as all assets that are potentially needed would have to be included. Each embedded resource has to be added when you build your project so compile times would explode. And as we’re using FlashBuilder we would have to write some lines of code for each embedd asset. But who’s going to maintain that? Gamedesigners and artists change, add and delete files to the repository but they don’t have the means (and inclination) to edit source code, so who’s keeping it synced?
A contrary approach is to put all resource files on server and load them at run time. But different types of resources require different code to load, if you require many resources at once you have to open one connection for each resource (adding a lot of overhead) and you have to keep track of multiple loaders. Lastly many resource files are compressed efficiently when embedded into a SWF and it’s sad to miss out on that kind of optimization.

Our Solution

So we’ve decided to setup an asset pipeline that converts our assets into a format that is more optimized to the needs of the runtime environment. Such a system is a common thing in “real” game development but unusual for flash game development – maybe because traditionally Flash applications are authored in an IDE that has build in functionality for asset management.

Flash Builder doesn’t have anything like that but luckily it’s based on Eclipse, a software development environment with an extensible plugin system. One plugin (part of the “Eclipse Java Development Tools”) adds support for “Apache Ant” build scripts to Flash Builder. Ant is a tool for automating software build processes. What to build with it? SWF’s that contain only assets as embedded resources, get uploaded to the server alongside our game SWF and when resource are needed the appropriate resource-packs are loaded at runtime to make the embedded assets available to Flash.

But our Ant script does a lot more then just invoke a compiler to build some AS3 files. It also generates these files on the fly. So the manual work required to embedd all our assets into some dozens of resource packs reduces to clicking a button.

The Details

So, what happens when we click?

  1. The Script will go to the root directory where our assets are stored and browse the subdirectories recursively. Finally when a directory is reached that contains files a resource pack is created.
  2. To do that we first generate create a temporary AS3 source file. We just concatenate templates that contain a mix of actual source code and temporary portions of text, marked with @-symbols, that are replaced by the Ant script when it builds the source file.First we include the header…
    package @PACKAGE@
    {
      import flash.display.Sprite;
      public class @PACK_NAME@ extends Sprite
      {
    

    …then we add souce code for each asset in the folder based on it’s file extension…

      [Embed(source="@ASSET_PATH@/@ASSET_NAME@.@ASSET_EXTENSION@", mimeType="image/png", compression="true", quality="@IMAGE_COMPRESSION@")]
      public static var @ASSET_NAME@:Class;
    

    …finally we add a footer to close the class and package declartion.

      }
    }
  3. Now we kindly ask the mxmlc compiler to compile the generated class into a SWF. The Flex SDK contains Ant tasks for that purpose so it’s pretty easy to invoke the mxmlc compiler from an Ant script.
    
      false
    
  4. We also copy a manifest XML that describes game objects and links them with certain embedded Resources in the ResourcePacks we generated.
    A gameobject’s definition might look like this:There’s one special manifest that tells our application what other manifests to load and where to look for the resource packs. When a player starts the game this main manifest is loaded. Now that we know what resourcepacks and manifests exists on the server we can ask the ResourceManager to load them when neaded.
    
    
  5. The manifests and the compiled SWFs are uploaded to the server.

I can has Resources, please?

To get the assets when you need them you have to add code to your main application that will load the resourcepacks and manifests and extract the required resources. Our ResourceManager turned out rather complex but at its core it’s pretty straight-forward. This is how you’d load a XML-based manifest file.

private function loadManifest (url:String):void
{
  var xmlLoader:URLLoader = new URLLoader();
  xmlLoader.addEventListener(Event.COMPLETE, onManifestLoaded);
  xmlLoader.load(new URLRequest(url));
}
private function onManifestLoaded(e:Event):void
{
  var xml:XML = new XML(e.target.data);
  app.processManifest(xml);
}

And provided you know the URL to the resource pack an asset can be retrieved like this:

private function loadAssets(url:String):void
{
var loader:Loader = new Loader();
loaders[url] = loader;
loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaded);
resourcesToLoad[url] = loader;
loader.load(new URLRequest(url));
}

When the loader completes it contains the class that we generated and compiled with our Ant script. We can look for the embedded resources if we know their name. To access a specific image asset you’d do this:

var resourcePack:Class = loader.contentLoaderInfo.applicationDomain.getDefinition(resourcePackClassName) as Class;
var resource:Class = resourcePack[imageName];
var bitmapData:BitmapData = (new resource() as Bitmap).bitmapData;

Final Words

I do realize that (unlike ours) many Flash applications need to be deployable as a single SWF that contains all the code and assets. Also, in smaller projects the effort of setting up system like ours might be bigger then just embedding the assets manually. But for us Ant has made deployment much easier and it allows the coders and artists to work on the same project mostly independ from each other.

I’d be curios to learn how other developers manage the assets in their projects! Feel free to comment!🙂

Matrix Magic

For a flash game project at work I needed to setup a flash.geom.Matrix instance to transform points from cartesian space into an isometric perspective.

To get it working I had to answer three questions:

1. How do the properties a, b, c, d, tx and ty map to the coefficients of the matrix?

Mapping of coefficeints in the Flash Matrix class

2. How to use the matrix to transform a Point?

The Matrix class provides two methods to transform a point.

  • deltaTransformPoint transforms a point without applying the translation.
x' = a * x + c * y;
y' = b * x + d * y;
  • transformPoint transforms a point including the translation.
x' = a * x + c * y + tx;
y' = b * x + d * y + ty;

If you know the mapping of coefficients and a bit of computer graphics that’s the expected behavior. To be able to multiply a 2D vector with a 3D matrix you introduce an extra 1 as 3rd component. Then perform a matrix multiplication. That way the transformation is added to x and y after the rotation/sheering is done.

3. How to setup the matrix to get the desired transformation?

If none of the provided methods fits your need (like in my case) you can set the correct values for the coefficients directly. That’s easier then it sounds. Look at the basis vectors of your source coordinate system and imagine (or calculate) how they look like after the transformation. Assign coefficients a the x and b the y value of the transformed x-axis. Assign the x and y value of the transformed y-axis to c and d.
If you need it you can set tx and ty to move the transformed points relative to the new origin.

And why do I blog about math, now?

Adobe managed to have a incorrect illustration of the layout of the coefficients in the german doc (english docs happen to be correct!) and the inscrutable description of the transformPoint and deltaTransformPoint methods lacked the specifics I needed. Let’s hope this post and the power of google will help those, that seek the same kind of knowledge!

Simulating Fluids in Flash

A thread in the FGL forums got me interested in the simulation of fluids. Of course this topic has seen quite extensive coverage in academic papers but getting it to work in the limitted environment of Flash provides some intersting challenges. Interesting enough for me to give it a try over my christmas break.

I loosely followed a paper Particle-based Viscoelastic Fluid Simulation to implement a sandbox application that simulates and renders a small blob of fluid and allows you to tinker with various parameters. Click the image below and give it a try!

The fluid is represented as a set of ~400 particles that interact with their neighbours and such seem to form a coherent entity.

For rendering I use an oldschool approach: Each particle is represented as a metaball. For a given pixel the force function of every metaball is evaluated, summed up and the final sum is compared with a threshold value to decide whether the pixel is inside or outside of the fluid.

To be able to do that in realtime I precalculate the values that a forcefunction yields for pixels within a relevant range of the particles center as a Bitmap.
Fluid Rendering - Illustration #1
These tiny images (about 40×40 pixels) are rendered at the position of the particle with additive blendmode.
Fluid Rendering - Illustration #2
Now I can decide with a single lookup in the resulting Bitmap if a pixel belongs to the surface or not. That evaluation step is done by a pixel bender shader and instead of just working with a boolean state (inside or outside) I sample a gradient based on the accumulated force value.
Fluid Rendering - Illustration #3
This approach allows me to achieve a variety of styles in the visual appearance of the simulated fluid by just using different gradients.

This technique would unfold it’s real potential if you could use hardware acceleration to accumulate the field functions because that’s a bottle neck in the current implementation.

Not sure if that stuff has any practical relevance, anyway. But the SWF is only 32kb big so people that are into demos (32k, 64k) could maybe make something fancy out of it.🙂 Here’s the source code released under the MIT license.

Developing and Selling Rune Hunt

I started experimenting with real time shadows in Flash in fall 2009. At the same time I took notice of the Flixel framework and all the cool retro games that people made with it. Why not make a game of my own that combines pixel graphics with dynamic light and shadows?

At the 14th December 2009 I created a thread in the Flixel forums with a mission statement:

The setup is classic: a hero in a dungeon full of treasure, traps and NPC of questionable attitude. The twist is that I’m limiting the player’s view to what his avatar is seeing. Top-down-ego-perspective so to speak. I hope it’s making exploring the dungeon more interesting and the enemies more scary if you don’t see all the stuff long before it becomes relevant/dangerous.

Read more…

Rune Hunt Released

Hungry eyes watch from the shadows. The flickering light of a butterfly is all that keeps them at bay. Run for your live – and sanity!

Finally, after almost a year of working on it, I have finished Rune Hunt!

Well, technically it’s been finished a couple of weeks ago. But I tried to find a portal that would sponsor the game. The basic idea of sponsorship is that you include links and logos of a flash game portal in your game before you spread it. The branding means traffic for the sponsor and that traffic is what they essentially pay you for. The other great thing besides money is that the sponsoring portal has an interest in getting your game played and will help spreading it – for example by featuring it on the front page. So you get money, exposure and retain full creative control. Cool stuff!

So in the last weeks I’ve spend quite a while on flashgamelicense.com and learned a great deal about how the market around free flash games works. The website is basically an agent that brings developers and sponsors together. Sponsors can bid on your games, after a while you pick the best offer and pay a comission to FGL. The process of trying to license my own game was nerve-wrecking but fun and in the end pretty successful. Huge thanks to ArmorGames for the generous sponsorship!

But enough of that for now. Go and play the game allready!😉

Drawing API Memory-Leak in Flash 10.1

When trying Rune Hunt in the new 10.1 version of the Flash Player I noticed a HUGE performance drop. In the old player it would take about 27ms on my system (debug build) to update the game’s state and render the next frame. In Flash Player 10.1 this changed: The time it took to calculate a frame started fluctuating and increased to 48ms on average.

A member of the Flash Player Engineering team the new player replied to my inquiry about known performance issues:

General actionscript performance is not any slower in 10.1 than 10.0 from our testing, it must be something particular in your code which exhibits the problem. Do you have a reproducable test code or a url you can point us at?

So I tried to isolate and reproduce my problems. It seems that my problems are caused by a Memory Leak in the Drawing API. I wrote a simple test application to illustrate the issue and hopefully find a work-around.

//... there`s a buffer as rendertarget and a flare
private var _flare:BitmapData = null;
private var _buffer:BitmapData = null;

//each frame I render the flare 100 times into the buffer 
for(var i:int = 0; i < 100; i++)
    _buffer.draw(_flare, null, null, BlendMode.ADD);

In the 10.0 player there is no memory fluctuation caused by this code. But in the 10.1 player each draw-call allocates new memory. The total memory is increasing linearily until the garbage collector kicks in. This of course effects the performance.

In all browsers and on all systems that I tested the memory leak was present in the new player – but the way the garbage collector handled it varied so the graph isn’t always as clear. You can test it for yourself. And here’s the source for the test application.

My guess at what happens: BitmapData.draw() method accepts IBitmapDrawable an interface that is implemented by all DisplayObjects and BitmapData objects. If you pass a BitmapData object however it seems like memory gets allocated based on the size of the render target. This memory is not reused or instantly freed but has to be collected by the garbage collector.

Knowing this there’s a neat workaround: If you wrap the BitmapData in a Bitmap before you draw it you can avoid the bugged code and the memory keeps steady!

//wrap _flare in a Bitmap (do this only once!)
_flareBmp = new Bitmap(_flare);

//now instead of _flare render _flareBmp
for(var i:int = 0; i < 100; i++)
    _buffer.draw(_flareBmp, null, null, BlendMode.ADD);