Sam MacPherson

Flash, Haxe, Game Dev and more…

iOS Safari Mobile Absolute Position Bug

This bug has gotten me twice with two separate HTML5 games so I figured I’d share. Seeing as most cross-platform HTML5 games have to run on a bunch of different screen resolutions it’s fairly common to see games resize a canvas to fit the screen. It’s for this reason that we need to be able to accurately determine the width and height available to us.

If you are just using a canvas element then you should be fine, but a lot of the time I’m seeing absolutely positioned elements above the canvas (such as for text display). The problem comes in when you move an absolutely positioned element off the screen – even partially. Most browsers respect that absolutely positioned elements should not affect the dimensions of the parent element, but for iOS Mobile Safari this is not the case. Off screen absolute elements will change the dimensions of the page and cause width and height measurements to be wrong which in turn causes the canvas to resize to an amount larger than the screen.

Until they fix this it seems the only solution I could find was to change position: absolute to position: fixed for these elements. As long as the page doesn’t move it will produce the same effect. Cheers.


Web 2.0 with Haxe

When it comes to modern web infrastructure there are three main things you need to worry about when programming: Front-end development (JS, DOM, CSS, etc), stateless http(s) service and within recent years stateful push services. I’ve been building a website over the past year and a half, and I must say that Haxe has been a great asset for this project. Traditional web development would have required me to write in php, javascript, html, css and perhaps java for the stateful service (modulo some other similar languages). But NO! With the exception of css everything is written in Haxe. The client, the http server and the stateful push server are all using the same code base.

To demonstrate how awesome Haxe (and the community) is I will explain how the chat on my site works. Below is an example of some client sending a message to two different people. All 3 of which are on completely different devices and browsers.

As you can see all 3 clients have the capability to communicate with the http server. I hope you can agree that it is a reasonable assumption that all browsers are able to communicate via http. 😀 On the other hand Client 3 is unable to communicate with the push server because of lack of support for web sockets and flash.

The first message that Client 1 sends is addressed to Client 2. The message gets sent to the http server which notices this is a chat message and immediately forwards it to the push server that Client 2 is connected to. It might make sense for Client 1 to send the message directly to the push server, but this may have issues if Client 1 and Client 2 are not connected to the same push server. Anyways, Client 2’s push server then forwards the message to Client 2. Behold instant messaging!

In the second scenario Client 1 sends another message to Client 3 who is browsing the site with his Android device. Unfortunately as of the time of this writing Android’s native browser does not support web sockets (nor flash), so we are stuck with http polling. What happens here is even though Client 3 is not connected to a designated push server we can still agree on a stateful server to hold the message until Client 3 requests it. The http server can’t hold the message because it is stateless. If the user won’t be requesting the message for a while, long term database storage is a good idea.

Now if we were doing this with 2 different languages for both the http and push servers things would be a little nightmareish. Duplicate code would pop up all the time with interpreting protocols and backwards compatibility for users who need to rely on http polling. Not to mention duplication in the client code as well. Haxe unites all 3 essential programming components of websites into a largely overlapping code base.

I want to say also that is a great library for Haxe-based modern web design. It allows for setting up a Haxe push server which can communicate with web socket enabled browsers as well as a client implementation for server-server communication. If the client’s browser doesn’t support web sockets or flash then the http server can act on behalf of the client to communicate with the push server.

Preventing Cheating in Multiplayer Games

So it’s been a while since my last post. Almost a year actually. The reason behind this is largely due to school. I just finished my last year at the University of Waterloo and suffice to say I have a lot more free time now. Another reason for my lack of posting is because I have been hard at work implementing a gaming portal for html5 games. The gaming portal has been going on for over a year now and there isn’t really anything too interesting going on there besides the features of the portal itself. 😛

In the past month I have been getting back into finishing up my game Zed – a multiplayer zombie shooter. This of course makes for some more relevant and interesting posts! In particular I have been implementing the multiplayer portion of Zed and I wanted to go over how I will be making the game more or less cheat proof without the need for expensive server validation or relying too heavily on obfuscation.

First I will go over what is normally done for “complete” cheat prevention in multiplayer games. That is to basically run the game on a server and have the server perform arbitration over everything. The only thing that the client can decide on is keyboard/mouse input. The good thing about this method is it prevents most if not all ways to cheat depending on the game. Auto aim is a good example of a cheat that can still happen on first person shooters with this setup. The problem with the server-arbitrates-everything setup is that running the game simulation on the server is extremely demanding CPU-wise especially if you have a lot of complicated physics in your game. It is for this reason that a lot of smaller companies (such as mine) choose different solutions to handle cheating.

The most common approach with flash games is to use “security through obscurity”. The idea behind this approach is to make it hard to understand the underlying game mechanics given the binary swf file. Techniques such as monitoring important variables, bytecode manipulation (SWFEncrypt) and packet encryption are all methods of obfuscation. The good thing about security through obscurity is it is usually relatively easy to implement and it will deter most of the people who want to hack your game if you do it well. But for those 1% of hackers who are knowledgeable and determined it is not enough.

For these 1% of people you need guaranteed security and, if you don’t want to spend thousands of dollars on server infrastructure, you will need to verify actions on the client. So if we don’t have a central authority verifying what is correct game play and what is incorrect then what can we do? The idea rests on the assumption that given any particular game instance you can assume that the majority of the players are not cheating. This may or may not be a good assumption, but in general there are more legitimate players than illegitimate.

So what you do is make sure every player has access to all information at every game tick. IE where every other player is, what keyboard buttons are down, where the mouse is, etc. With this knowledge every player’s own version of the game should behave identically provided there is no randomness. If someone’s game is not behaving identically then the other players will be able to gang up on the player and boot him out. Hold on though, this is a multiplayer game and packets do not travel instantly. If I am player A and I am running game tick 1500 then what if I haven’t received player B’s keyboard state for tick 1500? Well I could just pause the game and wait until I get the required information, but this will be problematic because even with a very low latency system you are still looking at 50ms or so round trip time for the packet. This will cause the game to operate at 20 FPS max in IDEAL situations. Not to mention that also requires you sending 20 packets per second which for flash with a TCP socket that may be too fast.

All that being said there is a simple solution to these problems. Look into the future. No, I’m not talking about the latest and greatest in quantum technology. Obviously we cannot look into the physical future, but what we can do is make the game run in the past so that our present time is the game’s future. Confused? Let me explain. A game evolves according to the player input (keyboard, mouse, etc). Normally the input is applied during the game’s next frame. To make the game run in the past we put a delay on the input and buffer it for X number of ticks. After X game ticks have gone by we then actually apply the input. Doing this in a multiplayer game allows for input from other players to be processed in real time as we have a nice delay of X ticks to receive incoming data as illustrated below.

Mutliplayer Synchronization

In the above example X = 3 ticks. This means that as long as it doesn’t take longer than 3 game ticks to receive packets from all players then the game will run smoothly. For a game at 30 FPS this means 100ms which may or may not be reasonable. You can always increase X to keep the game running smooth! If you have played StarCraft before you should notice this is the exact system they use. The X variable is controlled by the network latency setting in the game options. If you’ve seen “Player John Doe set the network for extra high latency” what they are doing is increasing X to allow for smooth gameplay. Of course if you set this to the maximum setting the delay from you telling a unit where to move and it actually moving is increased which can be annoying. For a game like StarCraft this delay may be tolerable; on the other hand, if you are building a fast paced shooter then the input delay can feel very unnatural.

To get around this unnatural control feeling we use a bit of a cheat in Zed. Due to the fact that Zed is not PvP we don’t need millisecond accuracy for the other player’s characters. We run the player’s own character as the keyboard/mouse input is received and all other players X frames behind. This seems like a bit of a paradox, and there definitely are some paradoxical time issues that come up; however, Zed’s game mechanics allow us to do this safely.

Keep in mind this particular network implementation will not work for everything. When considering a game infrastructure you will need to carefully consider your game mechanics before decided on which path to take. Another thing to keep in mind is that this setup will only prevent cheating under the assumption that the majority of players are legitimate. Do not rely on this method as a silver bullet. Layered security is always a good approach for software running on the client.

Lighting and Particle Demo

Here is a demo of the effects that I have been working on in my upcoming game – Zed. The video is intended for the gamers, but you can also get a glimpse at the tech side of things.

To Batch or not to Batch

Once again I’ve revisited my rendering system. This time with the intention of switching over to a batched setup instead of a one-draw-call-per-sprite setup. Overall the switch was relatively painless, but I did learn some lessons along the way. I wanted to share some of the pitfalls that I experienced.

First, I will briefly explain what a batched sprite rendering system is. The basic idea behind batched sprite rendering is that everytime you call drawTriangles() you incur some overhead. If you are using a naive setup (Like I was) you are probably calling drawTriangles() once for every sprite. This is okay for a few sprites, but once you get a couple thousand it becomes extremely inefficient. Basically the name of the game is to minimize the number of drawTriangles() calls. To do this, we don’t immediately render the sprite when render is called. Instead we batch the sprite’s verticies onto a global vertex buffer with the intent of rendering everything at the end with one drawTriangles() call. Simple. Well not really. Using this method has some implications:

1. We can no longer use the GPU to apply sprite-specific transforms.
2. A batch of sprites must share the same texture.

The implications of (1) mean that we must do the coordinate transforms on the CPU. This not the best, but it is unavoidable. If you have a reasonable amount of sprites (Say a couple thousand) then this should be fine.

Because of (2) we must make seperate drawTriangles() calls everytime we need to switch textures. But wait hang on. If we need to make another call everytime we switch textures then doesn’t that leave us where we started seeing as different sprites will likely have different images? The answer is yes — and no. First and foremost you can group sprites of the same image into the same draw call. However, you can even go one step further.Instead of allocating a texture for every image we allocate a global store of massive textures (2048×2048 pixels). We then stamp in all the smaller textures and give the render jobs appropriate U,V coordinates. Very nice! If your game has a lot of small sprites this will be lightning fast. Probably under 3 draw calls.

Ok so we go ahead and do this and oops we have another problem. Because we are grouping the sprites by texture they will no longer necessarily be sorted by depth. Ok, so this is a set-back, but perhaps we could just batch the sprites until we encounter a texture change then flush the buffer and start again. This will of course work, but it is only efficient if sprites of similar depth also share the same texture which may not be true. For example when testing this with my game I went from 3 draw calls to about 300. This is unacceptable.

Well we are rendering on a 3D graphics card so why not use the depth buffer to do the sorting for us! Every frame update we assign a global depth value to each sprite accordingly and enable the depth buffer. This may appear to be the best solution possible, but it does have one major flaw. You can’t use translucent textures. The reason behind this is the depth buffer does not understand alpha compositing. All it understands is geometry. Either a triangle is blocking something behind it or it is not. This is where we have to make a decision. There are four equally valid solutions that I have come up with.

General Purpose Solutions

1. Fall back to the render on texture switch method and do some optimizations to try and group depth-locality with texture-locality. (Could be optimal depending on setup)

2. Render all opaque images first entirely on the GPU. Then do transparent images after using method (1). (Works very well if there isn’t many transparent images)

Specific Solutions

3. Only use opaque textures. (Optimal)

4. Only use textures with quantized alpha values of either 0 or 1. (Optimal, but requires an extra instruction in the shader)

All of these methods have there strengths and weaknesses. Personally I decided to go with method (4) for my game. Method (4) is very similar to method (3). They only differ by one instruction in the shader. For (4) you include a KIL opcode (kill() in hxsl) which when the alpha channel is less than one will abort the pixel and depth buffer writes.

There are definitely other solutions out there, but these were the best ones I could come up with after working on this for several hours. Hope this helps.

Asset Management

Here is a quick overview of how we (My game designer and I) deal with managing assets for flash development. Due to our small team size of just 2 people we historically had a very programmer-centric setup which put a lot of pressure on me, the programmer, to hard code things into the game as they were developed. This worked fine for our previous projects which were relatively simple, but our latest project requires much more content. So naturally I had to start developing tools for my designer. Specifically an asset management tool.

Starting last November I began work on an Asset Management tool written in Java. Eight months later this is what we have come up with.

The above image is a screen shot of the asset manager with our latest game’s asset file open. Let me go over each of the sections briefly. But first some terminology:

  • A directory is basically a grouping of attributes with a (potentially empty) asset attached to it. I may use the word object or game object interchangeably with directory.
  • Assets are binary data which can be images/animations/sounds/fonts/etc.
  • Attributes are just simply key/value pairs. I will sometimes call these properties.

1. Directory Explorer

Displays the logical structure of the game elements. For example I have highlighted a directory called “regular0” which is inside the zombie directory so even with no knowledge of the game internals you can probably tell it is a common zombie.

2. Directory Preview

This is somewhat preliminary. As of now only images will display. Everything else will just display text to let the designer know there is an asset attached to this directory.

3. Directory Properties

Every directory can be assigned as many properties as it needs. As you can see in the above image this is useful for attaching game-specific meta data to the object.

4. Asset Library

The asset library stores references to all external binary data. By keeping the asset library and the directories separate we are able to separate the game logic from the raw data. This is useful if for example you want to make two different enemies but don’t want to duplicate the animation data.

5. Asset Preview

Similar to the directory preview except for the asset library.

Now for some technical details on the file structure. Everything in the above image is stored into a GigaBlast Asset Package file format (.gap extension). On the flash side I can then load everything in using an in-house resource management class. The file format is as follows:

-- GigaBlast Asset Package Format Specification V2.00 --

-- Data Types --
String - 2 byte length followed by 'length' 1 byte ascii characters  
Integer - 4 byte integer  

-- Overall structure --
[Binary Data]  

-- Header --
"GAP" (3 byte file format identifier)  
Major Version (2 bytes)  
Minor Version (2 bytes)  
Flags (1 byte) {  
	1 - Compressed (All non-header data is compressed with zlib)  
	2 - Signed (All non-header data is signed with RSA after compression and signature is appended to file)  
ABSOLUTE Library offset (Integer) (Does not include header)  
ABSOLUTE Directory offset (Integer) (Does not include header)  
ABSOLUTE Binary Data offset (Integer) (Does not include header)  

-- Library --
Asset Count (Integer)  
Assets {  
	Name (String)  
	Data Type (Integer) [0 = Any, 1 = Image, 2 = Animation, 3 = Sound, 4 = Font)  
	RELATIVE Binary Data offset (Integer)  

-- Directory --
Name (String)  
Library ID (Integer)  
Meta Data Count (Integer)  
Meta Data {  
	Name (String)  
	Value (String)  
Directory Count (Integer)  
Directories {  
	Dir (Directory)  

-- Binary Data --
Data Size in bytes (Integer)  
Data (Binary Data)

-- Formats Supported by GigaBlast Asset Manager --
Binary Data (Anything -- even empty data)
Images (PNG, GIF, JPEG)
Animations (SWF)
Sound (MP3)
Fonts (TTF)

Once I have a GAP, say ‘’ from above, I can then load this into flash by doing this:


function onAssetsLoaded ():void {
	var asset:Asset = Assets.get('zombies.regular0');
	trace(asset.getProperty('speed'));                    //Will print '5:10'
	var displayObject:FlashDisplayObject = asset.get();   //Get the attached asset on the directory
	canvas.add(displayObject.newInstance());              //This will create a new instance of the animation and attach it to the canvas

As I was designing this, the terminology between the Java and Flash counterparts became a little fuzzy. What I am in fact calling an asset in flash is actually equivalent to a directory in the Java manager.

You are able to load as many GAP files as you want. They will all be gracefully merged into the Assets class.

But wait! There’s more!

You may have noticed in the file format structure there is the allowance for compression and package signing. The compression is completely transparent. The package signing is useful if you don’t want people tampering with the GAP file (Messing with enemy stats and bad stuff like that). I’ve also included a key generation tool.

When the keys are set (As seen in the above image) then the file will include an RSA signature at the end of the GAP file. You then hardcode the public key somewhere very hidden inside your swf file. When loading the file you do this:

var publicKey:BigInteger = BigInteger.ofString("30819F300D06092A864886F70D010101050003818D0030818902818100B79E8D7D9B538BDCBFF4EDD0E4BB0AB3031D49FFD8759F7FEDF5D171BF9969EBC148325F3FF9246A2E489F6FE7506329B72DD3477134FB6D7098487261B8F9A6E96DDF21DCB0062C9931737C9924A6CFC64DAC06A8F6DB1F363F54FBA763330EB2A8DBEB52D9DD62AB998D2C7BC63CAE2D8D4E2A5A8A13E0B362F44410134DFB0203010001", 16);
Assets.load('path/to/', publicKey);

What does this do? Without going into details it will disallow anyone but the person who knows the private key to edit the GAP file. The BigInteger class you see is provided by caffine-hx which is a haxe library.

But wait! There’s even MORE!

Included in the asset manager is a generic map editor which is capable of drawing in directories onto a map.

The map editor is in its infancy, but as of now it is capable of drawing three distinct types of images: surfaces (grass, dirt), wall-like things (walls, railings, roads) and doodads (chairs, tables). The nice thing about combining this with the asset manager is that for example as long as you add in a ‘type’ property on your directory and the directory is an image anything can be drawn onto the map.

To make things more specific to a particular game you can add in any property onto the drawn directory. For example Zed (Our zombie game) has collision areas which I’m sure is fairly common. To make any object collidable you simply add the property ‘inteact’=’collidable’ to the directory and begin drawing it in.

My flash-side library is capable of loading maps in a WYSIWYG fashion. More complicated constructs such as lighting and localized sound is achieved by having game logic pull out specific drawn-in objects instead of rendering them. You can see an example of this in the above example with all the faint blue/green/red areas. Those areas are in fact markers for lighting and event based actions.

There is a bunch more features but I won’t get into them right now. As of now our asset manager is not open to the public, but I hope to release it into the open source community soon. I am not particularly skilled at GUI design so perhaps someone out there would be willing to help out with that aspect.

Why Haxe is Just Awesome Pt 2

Ok, so as always I end up doing way more work then I need to due to my lack of knowledge. After some development, the javascript interface I was explaining in my previous post ended up getting a little sloppy. Turns out for more AJAX intensive parts of my site resolving html elements was getting harder and harder. A lot of the time I ended up just navigating the dom by relative parent/child pointers which of course is terrible if you want to have a manageable long-term code-base. Having the static event handlers just wasn’t cutting it. So I did some looking around and it turns out Haxe already has a solution!

Serialization is the answer and the haxe.Serializer and haxe.Unserializer classes provide just the solution. Now instead of transmitting the html (

tags, etc) from the server I just send the client a serialized version of the dom representation and the javascript on the client can recreate the exact same structure on the client! A webpage ends up looking like this:

<html><head><title>Home</title><link type='text/css' href='/style.css' rel='stylesheet'></link><script type='text/javascript' src='/client.js'></script><meta name='data' content='cy12:www.dom.HTMLy8:childrenlcy12:www.dom.Heady6:parentr0R1lcy13:www.dom.Titley4:texty4:HomeR3r2R1lhy3:tagy5:titley7:attribsbhgcy18:www.dom.StyleSheetR3r2R1lhR7y4:linkR9by4:typey10:text%2Fcssy4:hrefy12:%2Fstyle.cssy3:rely10:stylesheethgcy18:www.dom.JavascriptR3r2R1lhR7y6:scriptR9bR12y17:text%2Fjavascripty3:srcy12:%2Fclient.jshghR7y4:headR9bhgcy12:www.dom.BodyR3r0R1lcy11:www.dom.DivR3r14R1lcy12:www.dom.LogoR3r16R1lcy11:www.dom.ImgR3r18R1lhR7y3:imgR9bR21y20:%2Fimages%2Flogo.pnghghR7y3:divR9by5:classy4:logohgcy13:www.dom.LoginR3r16R1lcy17:www.dom.form.FormR3r24R1lcy19:www.dom.form.HiddenR3r26R1lhR7y5:inputR9by4:namey1:aR12y6:hiddeny5:valuey5:loginhgcR35R3r26R1lhR7R36R9bR37y4:hashR12R39R40y32:2h4i27uutas7l02dild8t8hzbi0489f7hgcy18:www.dom.form.InputR3r26R1lhR7R36R9bR37y4:userR12R5y2:idy2:e1R31y72:input-empty%20__clswww.dom.form.Input%20__ed.e1.onfocus%20__ed.e1.onblurR40y8:Usernamehgcy21:www.dom.form.PasswordR3r26R1lhR7R36R9bR37y4:passR12R5R46y2:e2R31y75:input-empty%20__clswww.dom.form.Password%20__ed.e2.onfocus%20__ed.e2.onblurR40y8:Passwordhgcy21:www.dom.form.CheckboxR5y16:Remember%20Me%3FR3r26R1lhR7R36R9bR37y8:rememberR12y8:checkboxR40y4:truehgcy19:www.dom.form.SubmitR3r26R1lhR7R36R9bR12y6:submitR31y15:__ed.e3.onclickR40y5:LoginhghR7y4:formR9by6:actiony0:y6:methody4:posty7:enctypey35:application%2Fx-www-form-urlencodedR46y2:e3R31y18:__clswww.dom.Loginhgcy9:www.dom.AR5y24:Register%20an%20account.R3r24R1lhR7R38R9bR14y11:%2FregisterhghR7R30R9bR31y7:accounthgcR25R3r16R1lcy15:www.dom.NavListR3r51R1lcy10:www.dom.LIR3r53R1lcR73R5R6R3r55R1lhR7R38R9bR14y3:%2FhghR7y2:liR9bhgcR78R3r53R1lcR73R5y5:GamesR3r61R1lhR7R38R9bR14y8:%2FgameshghR7R80R9bhgcR78R3r53R1lcR73R5y7:ProfileR3r67R1lhR7R38R9bR14y10:%2FprofilehghR7R80R9bhgcR78R3r53R1lcR73R5y6:GroupsR3r73R1lhR7R38R9bR14y9:%2FgroupshghR7R80R9bhgcR78R3r53R1lcR73R5y5:ForumR3r79R1lhR7R38R9bR14y8:%2FforumhghR7R80R9bhghR7y2:ulR9bhghR7R30R9bR31y10:navigationhghR7R30R9bR31y6:headerhgcR25R3r14R1lcR25R3r88R1lcR25R3r90R1lhR7R30R9bR31y5:errorhgcR25R3r90R1lcy22:www.dom.home.GameSmallR3r95R1lcR25R3r97R1lcy10:www.dom.H1R5y3:ZedR3r99R1lhR7y2:h1R9bhghR7R30R9bR31y16:game-small-titlehgcR25R3r97R1lcy19:www.dom.AnchorImageR5R66R3r105R1lcR27R3r107R1lhR7R28R9bR21y25:%2Fimages%2Fgames-zed.pnghghR7R38R9bR14y3:%23hghR7R30R9bR31y34:game-small-image%20__ed.e0.onclickhgcR25R3r97R1lcy9:www.dom.PR5y229:Pick%20a%20class%2C%20kill%20zombies%20and%20level%20up%20your%20character.%20Features%20will%20include%20an%20extensive%20item%20system%2C%20very%20customizable%20skill-sets%2C%20large%20re-playable%20worlds%20and%20much%20more.R3r114R1lhR7y1:pR9bhghR7R30R9bR31y15:game-small-deschghR7R30R9bR46y2:e0R31y33:game-small%20__clswww.dom.GameDOMhghR7R30R9bhghR7R30R9bR31y7:contenthghR7R30R9bR31y29:content-wrapper%20columns-onehgcR25R3r14R1lcR102R5y6:FooterR3r124R1lhR7R104R9bhghR7R30R9bR31y6:footerhgcy13:www.dom.CoverR3r14R1lhR7R30R9bR37y5:coverhgcy15:www.dom.GameDOMR3r14R1lhR7R30R9bR37y4:gamehgcy12:www.dom.DockR3r14R1lcy19:www.dom.FriendsListR3r136R1lcR73R5y7:FriendsR3r138R1lhR7R38R9bR14R100R31y15:__ed.e4.onclickhghR7R30R9bR46y2:e4R31y43:dock-friend-list%20__clswww.dom.FriendsListhghR7R30R9bR37y4:dockR31R122hghR7y4:bodyR9bR46R123hghR7y4:htmlR9bhg' id='__DATA__'></meta></head></html>

As you can see the html is fairly boiler-plate save for the massive meta tag. The meta tag contains the entire webpage along with the back-end to make AJAX stuff a LOT easier. I can then run this on the client:

ROOT ="__DATA__").getAttribute("content"));

What does all of this give me? Very intuitive code that seamlessly integrates the server and the client. For example I can write this:

var body:Body = new Body();
var button = new Submit("MyButton");
button.addEventListener(Event.CLICK, onClick);

function onClick (e) {

Amazingly this code will add a button to the body of an html document then (when clicked) will remove itself. How does this work? The body and button tags are generated on the server and transmitted through the serialized data meta tag then unserialized and javascript sets up the listeners on the client. Once the button is pressed the function onClick() is called (In javascript) and the body element removes the button child. Of course some code is missing but you get the idea. Very cool stuff!

Why Haxe is Just Awesome

Recently I’ve switched gears and am working on a website. For this website I had originally decided to use the Drupal CMS as the backend. This was before I actually started working with Drupal on another unrelated site. Drupal to me seems like a fine choice for certain kinds of websites, but in the end it just seems to rigid for my needs. It’s also built to minimize the amount of programming you need to do. The thing is that programming is one of my strengths, and I don’t want to ignore that when choosing a backend. However, I am not very knowledgeable in scripting languages — PHP/Javascript in particular. So I decided to give Haxe a try and so far I am loving it.

The fact that Haxe can compile to both javascript and php allows me to merge the server and client logic into the same codebase. Very nice for event driven behavior. For example, if I want to do client-side form validation, traditionally I would have to design the form in php and have some sort of javascript validation function loaded in somewhere. This is okay for small projects, but I am aiming big and want everything to be as nice as possible.

My solution was to abstract all the HTML nodes into an Element class and use that as the base for everything. The element class has a lot of fancy functionality for attaching and detaching classes and such, but at the core everything would operate through the getAttribute and setAttribute methods which (using conditional compile flags) compile differently depending on whether I was targeting javascript or php. Here are the methods:

public function setAttribute (key:String, value:String):Void {
	#if js
	domNode.setAttribute(key, value);
	attribs.set(key, value);

public function getAttribute (key:String):String {
	#if js
	return domNode.getAttribute(key);
	return attribs.get(key);

What the php version does is prepare the attributes for printing to the html response while the javascript version will access the properties directly on the html nodes. I then have a special bootstrap function in javascript (Idea taken from the Distill Haxe library) which will prepare the html into a tree of Element’s on load. If you want to do something similar then have a look at the Distill library for reference.

What does this allow me to do? Things like this.

class DivWithClickListener extends Element {
	public function new () {
		add(new P("Some text produced in PHP"));
		addEventListener(Element.EVENT_CLICK, this);

	public static function event (e:Event):Bool {
		Lib.alert("This is a javascript click event!");
		return true;

For technical reasons the event handler must be static, but I do include several useful properties.

Event.source:Element – The source object.
Event.handler:Element – The handler object.
Event.type:String – The event type.
Event.jsEvent:Dynamic – The original javascript event. (Browser dependant so should be used with care)

Accessing and changing the html elements is very simple. As I’ve made sure the Element class is completely functional from both php and javascript. So for example if you want to add/remove a class from an element then all you have to do is:


This code will do the exact same thing no matter if it’s run from the server or the client. Very cool!

Compiling Formulas at Runtime

During development of my newest game I ran into a bit of a barrier with the recently implemented lighting system. I wanted to give my level designer a large degree of control over the lighting in the game. My first thought was to associate predefined values with each of the lights. For example if you wanted a flickering light you could attach a “light-type” property with a value set to “flickering” or something similar. At first this seemed like a good idea, but we quickly found out that there is just too much variation to have to rely on the programmer to implement a new light everytime one is needed. The solution? Allow the level designer to specify time-evolution formulas for each of the properties of the light.

I decided to generalize this approach to arbitrary formulas of n input variables. Given a valid formula string this class will compile it and allow you to pass input variables. The answer will be returned as if the programmer had wrote it in the language. Here is an example equation that one might use:

(x0 + x1) / 5 – sin(r)

What this will do is add input variable 0 to variable 1 then divide that by 5 and subtract sin of a random value. As you can see I have included some common functions that you may want to use. Valid functions include:


Most of these functions are self-explanatory except for perhaps the hs() one. hs() is just the Heaviside step function ( which is useful for converting continuous functions into discrete ON/OFF style functions.

Also included are a couple of useful identifiers. The constant PI which can be written as “pi” anywhere in the formula. Also you can specify a random value by writing “r” as seen in the above formula. The random value is always 0 <= r < 1).

So what can you do with this? Make cool lights!

Given that the variable x0 will always contain a value from 0 to 1 which will increment by a delta time value every frame we can basically do anything. Want to make a random flickering light that is on 95% of the time? Easy.

on = r – 0.05

Just a side note, "on" is a predefined light value which is either on (>= 0) or not (< 0).

Want to create the tv light from the video in the last post?

red = hs(sin(x0*11*pi)) + 0.5
blue = hs(sin(x0*5*pi)) + 0.5
green = 0
period = 50seconds

What the above formulas do is cycle through 4 distinct possibilities (RED off, BLUE off), (RED on, BLUE off), (RED off, BLUE on) and (RED on, BLUE on). We put the sin function through the Heaviside step function to make these shifts abrupt. If we left the hs() function out we would have more of a gradual color change (which doesn't look very good for a tv).

The compiler is fairly straight forward. First the string is lexed into tokens and stored in an array. After that calls to compute() will return the appropriate value.

public inline function compute (input:Array):Float {
	_index = 0;
	return _expr(input);

private inline function _err (token:Token):Void {
	throw new Error("Syntax error at token '" + token.str + "'.");

private inline function _eoi ():Bool {
	return _index >= _tokens.length;

private function _expr (input:Array):Float {
	var token:Token = _tokens[_index];
	if (, ValueTerminalToken) ||, FunctionToken)) {
		return _term(input);
	} else {
		return Mathematics.NaN;

private function _term (input:Array):Float {
	var token:Token = _tokens[_index];
	if (, ValueTerminalToken) ||, FunctionToken)) {
		return _moreTerm(_factor(input), input);
	} else {
		return Mathematics.NaN;

private function _moreTerm (left:Float, input:Array):Float {
	var token:Token = _tokens[_index];
	if (, AddToken)) {
		return left + _term(input);
	} else if (, SubtractToken)) {
		return left - _term(input);
	} else if (, RightParenToken) || _eoi()) {
		return left;
	} else {
		return Mathematics.NaN;

private function _factor (input:Array):Float {
	var token:Token = _tokens[_index];
	if (, ValueTerminalToken)) {
		return _moreFactor(_val(input), input);
	} else if (, LeftParenToken)) {
		var v:Float = _expr(input);
		if (![_index++], RightParenToken)) {
			return Mathematics.NaN;
		return _moreFactor(v, input);
	} else if (, SinToken)) {
		var v:Float = Math.sin(_expr(input));
		if (![_index++], RightParenToken)) {
			return Mathematics.NaN;
		return _moreFactor(v, input);
	} else if (, CosToken)) {
		var v:Float = Math.cos(_expr(input));
		if (![_index++], RightParenToken)) {
			return Mathematics.NaN;
		return _moreFactor(v, input);
	} else if (, TanToken)) {
		var v:Float = Math.tan(_expr(input));
		if (![_index++], RightParenToken)) {
			return Mathematics.NaN;
		return _moreFactor(v, input);
	} else if (, SqrtToken)) {
		var v:Float = Math.sqrt(_expr(input));
		if (![_index++], RightParenToken)) {
			return Mathematics.NaN;
		return _moreFactor(v, input);
	} else if (, HeavisideToken)) {
		var v:Float = if (_expr(input) >= 0) 1 else 0;
		if (![_index++], RightParenToken)) {
			return Mathematics.NaN;
		return _moreFactor(v, input);
	} else {
		return Mathematics.NaN;

private function _moreFactor (left:Float, input:Array):Float {
	var token:Token = _tokens[_index];
	if (, MultiplyToken)) {
		return left * _factor(input);
	} else if (, DivideToken)) {
		return left / _factor(input);
	} else if (, AddToken) ||, SubtractToken) ||, RightParenToken) || _eoi()) {
		return left;
	} else {
		return Mathematics.NaN;

private function _val (input:Array):Float {
	var token:Token = _tokens[_index];
	if (, VariableToken)) {
		return input[, VariableToken).val)];
	} else if (, NumberToken)) {
		return cast(token, NumberToken).val;
	} else if (, RandomToken)) {
		return Math.random();
	} else {
		return Mathematics.NaN;

I want to note that this is not the most efficient way to do this since you have to essentially recompile every time you want to compute a value. A better solution is to compile the formula into actionscript bytecode (ABC). I will likely switch over to that method soon.

This class can be used like this:

var eqn:Equation = Equation.compile("x0 + 5");

The above piece of code should print 7.

2D Dynamic Lighting Demo

In my previous post I went over how to implement 2d dynamic lighting on the GPU. After some tweaking I finally came up with a suitable solution for general purpose dynamic lighting. Here is a video demonstration of this in action in a game I am currently developing – codename Zed.

Currently the lighting only works with static objects as light blockers, but it’s not very hard to extend this to moving objects as well.

To get the effect right I had to modify my previous code and split the rendering into 2 separate tasks. First I do an additive light pass which fills in the glowing light you can see in the video. Next I had to do a subtractive shadow pass which worked by just starting with a black texture and subtracting off the alpha component as necessary. After each of these runs I do a 5x Gaussian blur effect to make things look nice and smooth and voila you have general purpose lighting that runs reasonably fast.

Depending on the quality of the light and your graphics card there are some limitations. I still plan on doing some more optimizations and benchmarking, but it seems that you are stuck with ~40 lights max on screen at any given moment. Possible optimizations could be caching of light textures that are static which would allow for a lot more stationary lights like what you saw in the game.