Category Archives: Flash

Planète Liège, ANEs, QRCode, Camera and Videos

I’m happy to introduce you a new app: Planète Liège (cork planet) for iOS & Android. The application (in french only) gives lots of information about winemaking. Sometimes making institutional apps reveals many challenges as we will see below.

Camescreen568x568ra
In the corkstagram part (I’m sure you get the joke), we take a cork in photo and can customize it with several objects. We needed something integrated into the application, so we couldn’t use the CameraUI class. We used the Camera class, create the object and use the Video object to display it. Our app is forced into portrait mode whereas the Camera object expect a landscape mode on mobile. So we’d to rotate ourselves the Video object. For iOS it works great but for Android on some devices it’s flipped at 180. Unfortunately we can’t have this information, so we’d to put a button on Android for flipping the camera. That’s really a feature that AIR should handle directly.

Change orientation
As I said the application is in portrait mode, but the main part use landscape mode. With AIR you can easily rotate the main content using this snippet:

stage.setOrientation(StageOrientation.ROTATED_RIGHT);

Be careful, on Android (if you’re using Stage3D & Starling) you will lost the context and so it will take time to see the full content of the new part!

StageVideo
Needing StageVideo with Starling? Just set visible false to stage3d! Be careful, it won’t remove touch interactivity etc.

QRCode
We’re in 2014 and it’s complicated to scan a QR Code with AS3. Firstly, I looked for ANEs and the only one I found had several issues: really hard to recompile it due to its IntelliJ integration, managing all the camera stuff which is great but unfortunately we can’t put something on top of Objective-C / Java code, bugs with Android…
Ok so no ANE. But finally I just need to check a bitmap data and there are plenty of AS3 libs making it. So time for a small benchmark? After several test, I was so frustrated… what are those shitty performances? 7 seconds for a QR Code scan, seriously?
Crazy that it’s complicated to scan a QR Code with AS3 nowadays. So I made my first (public) ANE using ZXing library. I included the AS3 lib for the default platform, so it means this ANE works for iOS & Android (using native code) and on all other targets supported by Flash using the AS3 code. Once I made it, I discovered an other one which did the same thing using ZBar lib. However since it isn’t packaged with a default platform, I forked it.

Instagram
We needed to be able to share the corckstagram picture on Instagram. I discovered those ANEs but I wasn’t happy with their structure. I really needed the same API between iOS & Android, and everything into the same ANE. So I forked it and changed its structure.

AIR is a very powerful tool, and ANEs make it so strong.
iOS & Android.

Sophie the Girafe 2

I’m glad to present you a new app with the famous girafe: The Safari of Sophie la Girafe!

screen568x568A fun and educational puzzle game for children between 2 and 6 years old! This adventure contains 18 original puzzles for you to enjoy with your child!
Travel to the great plains of Africa with the famous Sophie la Girafe! Introduce your child to lions and giraffes! Soar alongside eagles and pink flamingos and fly over herds of zebra and groups of crocodiles as you explore the mythical world of Sophie la Girafe.

All the scenery and environments have been especially designed with your child in mind. Your child will find it easy to move the puzzle pieces around by dragging them on-screen. The howls and roars of the savannah have been used to bring each animal to life.
Your child will be captivated by the clear, interactive interface, especially designed for younger children.

Thomas, in a previous blog post, related our issues using Adobe AIR GPU mode for a large project & how we switched to Starling. The Safari of Sophie la Girafe, is made with the GPU mode. As usual I made it with the Citrus Engine. Due to the complexity of some animations and finally because of bones/layer number I used DragonBones for running lots of them at full speed. The app works great but you may encounter some performance issue on iPhone4 due to this Adobe’s bug.

Is it my latest project with the GPU mode? Not certain, however for future apps I will focus on performances (even if on all my GPU apps there were pretty acceptables) rather than loading time. Obviously it depends primarily of the app content ;)

Silly Family available on the Mac App Store

Hey, I’m glad to share with you that Silly Family is now available on the Mac App Store! Don’t hear anything about Silly Family? Have a look there.

Thanks to Adobe AIR technology, with exactly the same code base we released the game on iOS, Mac, Android & Amazon. We could also release it to PC, but not sure where to sell it… I hope AIR would work on Windows 8 modern UI mode and so sell it via Windows store, but that’s an other story.

The first time you’re looking for putting your AS3/AIR game on the iOS store, you will find lots of tuts. However for the Mac App Store, that’s an other story. This one is the most concrete that I found.

Here is my bash script, FromAirAppToMacAppStore, working for AIR 13:

#!/bin/sh
#!/usr/bin/env bash
#$ -N $2
 
DIR="$( cd "$( dirname "$0" )" && pwd )"
 
cp $DIR/Info.plist $DIR/"$1".app/Contents
cp $DIR/Icon.icns $DIR/"$1".app/Contents/Resources
 
rm $DIR/"$1".app/Contents/Frameworks/Adobe\ AIR.framework/Versions/Current/Resources/WebKit.dylib
rm -rf $DIR/"$1".app/Contents/Frameworks/Adobe\ AIR.framework/Versions/1.0/Resources/AdobeCP15.plugin
rm -rf $DIR/"$1".app/Contents/Frameworks/Adobe\ AIR.framework/Versions/1.0/Resources/Flash\ Player.plugin
rm -rf $DIR/"$1".app/Contents/Frameworks/Adobe\ AIR.framework/Versions/1.0/Resources/adobecp.plugin
 
chmod -R 777 $DIR/"$1".app/
 
#codesign -f -v -s "$2" $DIR/"$1".app/Contents/Frameworks/Adobe\ AIR.framework/Versions/1.0/Resources/AdobeCP15.plugin
#codesign -f -v -s "$2" $DIR/"$1".app/Contents/Frameworks/Adobe\ AIR.framework/Versions/1.0/Resources/Flash\ Player.plugin
#codesign -f -v -s "$2" $DIR/"$1".app/Contents/Frameworks/Adobe\ AIR.framework/Versions/1.0/Resources/adobecp.plugin
codesign -f -v -s "$2" $DIR/"$1".app/Contents/Frameworks/Adobe\ AIR.framework/Versions/1.0
codesign -f -v -s "$2" $DIR/"$1".app/Contents/Frameworks/Adobe\ AIR.framework
codesign -f -v -s "$2" --entitlements $DIR/entitlements.plist $DIR/"$1".app
 
codesign --display --entitlements - $DIR/"$1".app
 
productbuild --component $DIR/"$1".app /Applications $DIR/"$1".pkg --sign "$3"
 
codesign -v --verify $DIR/"$1".app
 
exit 0
 
#sh FromAirToMacAppStore.sh "SillyFamilyDesktop" "3rd Party Mac Developer Application: DaVikingCode (XXXXXXXXXX)" "3rd Party Mac Developer Installer: DaVikingCode (XXXXXXXXXX)"

For more instructions (and latest update) have a look on my Github’s repository. Note that I’m moving some repositories to Da Viking Code‘s Github account, the Citrus will move too ;)

GPU render mode hell, and how we barely got out of it alive.

Hello everyone, Thomas here!

I’m going to recount the story of one of the projects I’ve been working on in the past few months, and how it all went downhill from the very beginning.
Oh don’t worry though. This is not a fancy post-mortem for the biggest game of the year, but its my first so I’ve got at least something to smile about.
In fact in order to be able to write this article let me pull up a happy image just for you and me, and then let’s jump right in.

Friends-With-You_Happy_Rainbow-01

 

 

Part I : Making Decisions (that are going to put you knee deep in it) :

I.1 Intro :
The project is a fairly simple (no offense to the designers) kids game with a dress-up section and two mini games, each themed on a country of the world.
Each mini-game would be accessed via a 3D spinning planet – a variant of the ‘cube menu’ everyone wanted to create with flash dozens of years ago.
Move the planet with a swipe, zoom in or out with a pinch, click on a country , you’ll be sent to the corresponding mini-game. Sounds simple enough (and in fact this happened to be the easiest part.)

The first mini game is a ‘point and click’ game, where you have to find objects in a landscape drawing rich with objects.
The second is just a card memory game with the infamous card flip effect.

I.2 Making decisions….
First note, the 3D spinning planet didn’t require any special effect, lighting or flare, only a sphere and a skybox, so this could even be done with away3D lite (we tried) and run nicely enough – so going stage3D was not necessary.

As we took a closer look at the design documents, we thought that we should decide on which technology/framework or combo of any of these to use by looking at the biggest part of the game, and this was the dress up game. And even then we were convinced this was going to be over in a couple of weeks at worst.
I played my fair share of dress up games on newgrounds back in the day (DON’T JUDGE ME) – and made one myself. A couple of shapes put together in a timeline, two buttons to go back and forth in that timeline to display different types of hair, shoes … and a way to color skin, hair, with a ColorMatrixFilter for example.
We knew there was going to be a lot of coloring going on : the artist included shadows or different shades of the skin color on all parts of the character (even in parts you would not see on small devices) so this had to be taken care of. The hair color also would need to color the eyelashes ! this was the level of precision I agreed to go for even though the final result didn’t reflect that level of detail so much because of the dimensions.

I.3 Digging our graves…

This was not the first mobile project I worked on, but the first I would as Aymeric’s employee. I was already worried about my tendency to code more than is needed, trying to prevent problems before they even arose, that tendency you also may have to just pre-optimize everything or simply expect that your project will evolve so much in the future (who knows) that you need everything to be as modular as possible. That doesn’t help when it comes to deadlines, but it does when a client doesn’t really know what he wants. In this context, the client did know what he wanted… but what he wanted, we would realize later, could’ve been made a bit much better (I mean this iterative process is normal) and you’ll understand how important it was for me to have my code as object oriented and parametric as it could’ve been.

Ok so anyway, we went for the GPU render mode as we were expecting a fair amount of vector assets, and decision was made that the dress-up section and the simple mini-games could be visually assembled in the good old flash pro, and simply instantiated and connected to the code at runtime, no loading screens, and we would leave everything to flash. As for the 3D planet, we would use away3Dlite. Aymeric pushed this idea given his experience and the fact that he had successfully released lots of simple mobile apps using this renderMode, vector intensive but not necessarily complex in terms of ‘moving parts’ on screen. I agreed because I saw no reason not to use this render mode + it made sense specially if you’re experience with the flash editor and you don’t want to waste time re-building layouts in code.

I.4 Being knee deep in it.

Everything was good at first.
I decided to build myself a little framework for multi-resolution support in the native flash display list context – we already have our multi-res support when using starling, but nothing like it for flash itself.
Our multi-resolution system is built of four major “coordinate spaces” :
1.the inevitable flash native stage
2.the viewport (it’s usually sync’d with the previous because it would stay at 0,0 and be of the same size but not in Letterbox mode so we have to consider this)
3. the starling stage which can be scaled on the X or Y axis – though we scale to keep the original aspect ratio
4. The “camera space”. a game world in citrus engine is contained within a ‘viewRoot’ which is moved by the camera object, with zoom, pan and rotate effect this is totally different.

In this game, the camera has not been used, we have ‘static’ screens for all parts of the games.
Anyway, to project a point from the starling stage to the native flash stage, we have to use the right transformation and it is made up of the viewport position, the starling stage scale and the camera transformation matrix.
Anyway, This is not available to us in a normal CitrusEngine + State scenario.
So I created a custom State class that would emulate what happens when we use StarlingCitrusEngine and a StarlingState.
This state would require us to define a baseWidth and baseHeight (the graphic designer having created assets for the biggest resolution we were targetting) and would, on native stage resize events, do the same as StarlingCitrusEngine does to the starling stage : The entire state would be scaled up or down, assets would be loaded in the right size from specific folders… overall this worked fine, but you’ll see, was not that necessary in the end.

There was a big misunderstanding between the graphic designer and us very early on, as vector format would obviously be the prefered and/or logical choice, we ended up getting lots of .png files – and I didn’t object to it. It appeared that the original assets were either not drawn in vector format or couldn’t be easily transfered to a flash friendly vector format on his side so we decided that this wouldn’t matter much in the final product, pngs would do fine. Being overconfident on this project already started to smell bad, We felt the game would be lightweight enough, but later, we were asked to add some features that were not totally explicitly present in the design documents. I came prepared with my expert overly optimized and parametric code, but didn’t expect the issues I would face with the actual render mode we were using – the basis of everything , doesn’t matter how sexy your code looks.

Part II : The GPU render mode, blackbox.

unnamed2

So the first mini game is a “where’s waldo” type of game. Just pan/zoom in a landscape illustration and find the right object. Simple enough.
Keep in mind throughout this article that the multi-resolution system has scaled the root container in which all objects are the same way a starling stage would be scaled to fit different screens.
Each time one object is clicked and found, that object would be highlighted by being overlayed with an image (an outline of the object was the first thing we did).
But as objects were further to the right and to the bottom, these outlines were displaced and even squashed … even though both were in the same container and had the exact same location.

With days if not weeks of testing (and developping other parts of the game) I couldn’t figure out what went wrong. Since everything was created through the flash editor visually, I assumed I was doing things wrong, so I wasted time re-creating things over and over again, double checking… trying other systems, making sure my multi-resolution system was working ok… I made Aymeric test it out… And I built a very simple project to see that issue happen (or not) out of context. It would still happen. For some reason both objects even though being at the exact same location and in the same container would not visually match and the one on top of the other would be distorted. I could only blame myself before blaming anything else, I left out all of my transformation matrix manipulations (who knows) and still, same issue.
This would happen only on some devices…
So the outlines of my objects were distorted and displaced, based on a certain position in space.
I tried any combination of factor (based on screen size) to displace these objects in the other direction and no solution was found, only time was spent for nothing.
I Then told our client that we had to find another solution, and we went for an explosion of stars happening roughly around the found object instead of a perfectly aligned outline. This feedback would work just as well for the player, and we would be hiding the fact that the center of that explosion was displaced… and I would place that object on the location of the touch so to get closer to the finger as possible (not the center of the object) .

During this time spent analyzing my possible mistakes, I tried every and any suggestions found , of course cache as transform matrix was turned on and off , nothing did the trick or changed the results (apart from actually displacing the object itself from the location it was supposed to be in) .

My conclusion is:
The GPU render mode is a blackbox system supposed to ease your life, and it does in most cases, but in edge cases you will have issues dependent on devices/os – something we don’t want/expect when using flash, and you have absolutely no control over what’s going on in the GPU (you can only give some kind of hints as to what is what with the cache as matrix functionality) . When you come from a lot of starling development, just stick with it, at least you control your texture’s quality and what goes on with it. If I may suggest an analogy, giving your project to the gpu render mode (when everything is in the normal display list) is like giving flash the freedom to make one asset jump from gpu to cpu at any time with you just watching helplessly – if you didn’t do things correctly or if you are in edge cases.

I would very much like to hear some feedback on this. Perhaps I have misunderstood everything there is about the gpu mode – But with stage3D now, I don’t see the point in using it – On top of that, the misunderstandings we’ve had with the graphics designer made me work with bitmaps instead of at least having some simple assets (like outlines) be vectors which could’ve helped but as we already were late, I just took what I was sent and ran with it , thinking It was the best solution possible.

Part III : The GPU render mode, bitmap decompression.

 

unnamed3

The dress up game was very hard to create with the flash editor.
Actually Aymeric created a skeleton project for me to work on this part and it worked fine, with all the assets we had for it (we received assets progressively during the developement).

Coloring my characters should’ve been straightforward. just grab one image, apply a color filter and boom.
of course everything was separated in a lot of layers (in the end we actually can go over 200 , depends on what you dress up with.)

First mistake is thinking the color filter would be fine (I’m talking about the same color filter you have in photoshop.) when multiply worked just as well for the purposes of this project and the graphic designed agreed that the multiply blend mode would work. A color filter doesn’t exist in flash, you can only go through a shader filter to use it (created with pixel bender which refused to run on my windows 7) . There’s a set of .pbx files out there that would create a shader filter behaving like a photoshop filter. so trying out coloring on retinas or skin worked fine with the multiply blend mode and, you can actually create a ColorMatrixFilter that will, once applied to a greyscale image at least, work the same as a multiply blend mode. Just use the Color class ( in the fl.motion package) ,create a white color, tint it. use its properties to create a ColorMatrixFilter and apply it. that’s all really.

I would load up the skeleton project with default assets, but I could not grab bitmaps from it. This can in fact only be done if your bitmaps are exported for actionscript in your .fla (otherwise, they are represented as bitmap filled Shapes). Not a problem in theory as you can get the bitmapData associated with that bitmap fill but you’ll obviously loose the original version… so you have to redraw the shape, with a different bitmap data copy and so on.

With a working solution in hand , I started testing on devices. A massive fail even on the most performant ones we have.

Everytime a bitmap was moved, flash would decompress it completely (regardless of whether or not I was caching it.) . Spikes of 500Mb allocated memory were seen in the ScoutCC profiler and crashes were happenning when you started to change your character too fast (obviously garbage collector was overwhelmed or too slow) . The character needed to appear during the game, and I couldn’t bare thinking that I would have to re-instantiate and color it everytime so I drew him on a bitmap once, saved it in external storage.

That was inacceptable… and I ran a bit late… but Aymeric trusted me even though I thought I completely failed.

Of course in hindsight, a lot of decisions I made were wrong. In fact when all went to hell and the weekend came, I just thought … well hell. How hard could it be to port everything to starling – were I do have control (at least more than I have now ) ?

Part IV : Moving over to starling.

Trying to force the idea that starling was the solution was not easy – since we were already late and my problem is never finishing my personal projects because I would try to rethink and rebuild parts of it, then get bored or do something else. That was not a personal project, all the problems came from the mode we were rendering in, and the horrible amount of details and images we had to keep, so this definitely had to be done.
I Started thinking about all different parts of the game. The 3D planet. The memory mini game with flipping cards (an effect that you cannot create with starling because fake 3D transforms are not included yet or it would simply be a burden to starling if it was made an option) , the ‘find an object’ game… oh and the video transitions we had to display, I forgot to tell you about that.

I would first start from scratch a character dress-up system that I would base on render texture and the fact that all starling images can be multiplied with a color simply by using the color property.

Each eyes, mouth, hair could be composed of more than one layer of graphics, a hair element could have two sub elements, the front hair and the hair that fell on the back of the character. So by hand I listed all possible elements, each with indices for draw order, and indices for the kind of coloration they required if any.
The character object would collect all those elements, sort them by indices and loop through each of them to see if they were active or not, color them if they needed coloring , and draw that to a render texture.

Where previously that would take at least 2 seconds on an Ipad, this was pretty much instantaneous even with all elements activated (+200 elements).

Then I went on to create the ‘find an object’ game which had no displacement problem but we kept the ‘star explosion’ as an indicator for the fact that the object was found anyway.

patacards

For lack of time, the memory game was kept in the display list – so we could keep the card flipping effect.

By the way, to flip a card on its own center in the flash display list, you have to first set its perspective projection to its center (in world coordinates, not local) then just rotate the matrix3D as you would with a normal matrix to transform something around an anchor or pivot point :

private var currX:Number ;
private    var currY:Number ;
private    var centerX:Number ;
private    var centerY:Number ;
 
protected var _rotZ:Number = 0;
 
public function setPos():void
{
currX = this.x;
currY = this.y;
centerX = this.width / 2;
centerY = this.height / 2;
 
z = 0;
transform.perspectiveProjection = new PerspectiveProjection();
transform.perspectiveProjection.projectionCenter = new Point(currX + centerX, currY + centerY);
}
public function get rotZ():Number
{
return _rotZ;
}
 
public function set rotZ(value:Number):void
{
if (_rotZ == value)
return;
 
var m3D:Matrix3D = transform.matrix3D;
m3D.identity();
transform.matrix3D.appendTranslation(-centerX,-centerY,0);
transform.matrix3D.appendRotation(value, Vector3D.Y_AXIS);
transform.matrix3D.appendTranslation(centerX + currX,centerY + currY, 0);
transform.matrix3D = m3D;
_rotZ = value;
}

I would call setPos() once the card is created (so that I know its width and height).
The card is not transformed by its parents so we can consider its parent’s coordinates system to be ‘parallel’ to the stage so the perspective projection is easy to setup.

Part V : The 3D Planet and starling/Away3D interoperation with CitrusEngine

unnamed

Alright we’re getting to the good stuff. So far I didn’t have much code to share, some was lost as I was desperately struggling to find solutions so I could only tell you about my experience, hoping that you won’t go through the same and simply not choose GPU at all.

V.1 : starling and away3D.

I suppose you can mix starling and away3D in a couple of ways, our example from the CitrusEngine examples repo shows how to use Away3DCitrusEngine so that starling sits on top of away3D… I didn’t want to use Away3DCitrusEngine… Specially because it doesn’t handle multi-resolution like StarlingCitrusEngine does and would brake almost everything.

So here’s how we add (in a hack’ish manner) away3D to StarlingCitrusEngine so that it would run only when we want it to :

public static var A3DView:View3D;
public var stage3DManager:Stage3DManager;
public var stage3DProxy:Stage3DProxy;
 
override public function initialize():void
{
	stage3DManager = Stage3DManager.getInstance(stage);	
	stage3DProxy = stage3DManager.getFreeStage3DProxy();
	stage3DProxy.color = 0x00000000;
	stage3DProxy.addEventListener(Stage3DEvent.CONTEXT3D_CREATED, onContextCreated);
	stage3DProxy.antiAlias = 1;
 
	//...
}
 
private function onContextCreated(evt:flash.events.Event):void
{
	stage3DProxy.removeEventListener(Stage3DEvent.CONTEXT3D_CREATED, onContextCreated);
	Starling.handleLostContext = true;
	setUpStarling(false, 1, null, "baselineExtended", stage3DProxy.stage3D);
}
 
override public function handleStarlingReady():void
{
	_starling.simulateMultitouch = true;
	_starling.shareContext = true;
	//...
}
 
override protected function resetViewport():Rectangle
{
	var vp:Rectangle = _viewport = _starling.viewPort = super.resetViewport();
		trace("Current Viewport :", _viewport, "found nearest scale factor :", scaleFactor, "starling scale factor :", _starling.contentScaleFactor);
	if (stage3DProxy.configureBackBuffer.length == 2)
		stage3DProxy.configureBackBuffer.apply(null, [_viewport.width, _viewport.height]);
	else if (stage3DProxy.configureBackBuffer.length == 3)
		stage3DProxy.configureBackBuffer.apply(null, [_viewport.width, _viewport.height, _starling.antiAliasing]);
	else if (stage3DProxy.configureBackBuffer.length == 4)
		stage3DProxy.configureBackBuffer.apply(null, [_viewport.width, _viewport.height, _starling.antiAliasing, true]);
 
	return vp;
}
 
public static function startAway3D():View3D
{
	var ce:Main = (CitrusEngine.getInstance() as Main);
	A3DView = new View3D();
	A3DView.antiAlias = ce.starling.antiAliasing;
	A3DView.shareContext = true;
	A3DView.stage3DProxy = ce.stage3DProxy;
	ce.stage.addChild(A3DView);
 
	return A3DView;
}
 
public static function stopAway3D():void
{
	if (A3DView)
	{
		var ce:Main = (CitrusEngine.getInstance() as Main);
		A3DView.dispose();
		ce.stage.removeChild(A3DView);
	}
}

 

In the StarlingState where I need to create my 3D planet…. I need a View3D which I simply get by calling Main.startAway3D();

And that’s it, I call Main.stopAway3D() when I get out of the state.

 

V.2 Clicking on countries on a 3D sphere.

Again, running out of time, this was yet amazingly simple to do… I mean once you decided that a little hack and display list magic is ok.

I load in a .swf with a map of the world (the same image texture that I would use for the planet sphere) and in the .fla I drew over the countries I needed with some shapes which I put in MovieClips with names.
So if I were to click on any of these and the .swf would be on screen, I would just be clicking on those MC’s with names (the bitmap itself is not an interactive object yet for debugging purposes, I kept it.) so yes, those are simple targets in 2D space. The idea obviously is to transform the 3D point that I click on the sphere, into 2D and “hit test” that point on the MC to find if I clicked on an actual country.

unamed88

What I really want is the uv coordinates of my click on the 3D sphere.
I first get the vector3D of my click with

var pos3D : Vector3D = e.localPosition;

Then I normalize it (my sphere happens to have a radius of 100 and be placed at 0,0)

pos3D.scaleBy(1 / 100);

Here’s my magic 3D normalized position to UV coordinates converter.
Now this was the result of simply adding, removing, multiplying and dividing values at pseudo-random , trying to make sense over my debug view where I drew a red circle where that position should’ve been on the flat map as I hovered the 3D sphere.

var u : Number = (1 - ( (Math.atan2(pos3D.x, pos3D.z) - Math.PI / 2) / (2 * Math.PI)) ) % 1 ;
var v : Number = 1 - ( Math.asin(pos3D.y) / Math.PI + .5 ) ;

I’m pretty sure one of you is going to simplify that u calculation fast. I don’t even remember what that %1 was there for (probably when the point was actually not looking right on the X axis , I would do %1 to ‘loop around’ the position so it stayed within the 0-1 range as I tried debugging things. Just remember, this definitely depends on the way the 3D software would map the texture out, how the sphere would unfold etc… I’m pretty lucky this works (and its definitely accurate.)

The final X/Y positions on the map would be the uv coordinates (that are normalized) taken to the dimensions of the actual map movie clip :

var testX : Number = u * (map.width / map.scaleX);
var testY : Number = v * (map.height / map.scaleY);

here I’ll project that local point to global because hitTestPoint requires global coordinates (_p and _resultP are helper points)

_p.setTo(testX, testY);
_resultP = map.localToGlobal(_p);

Then What I did was just test my targets one by one – I’m sure you could find other less expansive ways to do that but we have only 2 countries for the moment :

if(map.target_brasil.hitTestPoint(_resultP.x, _resultP.y, true))
{
trace("you clicked brasil !");
}

 

V.3 Sidenote about Skyboxes.

With this projects, my “planet” state used away3Dlite (when in gpu mode) away3D 2, 3.6, 3.7, 4, 4.1… well I think I’ve went over a looot of versions of away3D for dumb reasons I can’t explain… but it wasn’t very hard to update/upgrade (just know that I never ever seriously touched away3D before that) . The skyboxes changed and so did the accepted format. The graphic designer did manage to give me the right format from the very beginning but as I started exploring version , the required format changed… Anyway, this tool from nicoptere was incredibly handy to cut the skybox cube map from the flat png I was given.

http://en.nicoptere.net/?p=1955

This returns a CubeMap, which is like a BitmapCubeTexture. Away3D creators did change the naming convention quite a lot, but then again, who is actually going to try out all version over the course of a day like I did.

Part VI : StageVideo killed the adobe star

 

vlcsnap-2014-05-18-22h36m39s224

Yes this title is cliché. But the idea is there. So far I never felt so helpless and even started to question the legitimacy of me being a developer.

Remember those video transition between states I told you about? maybe not.
Well between mini games and profile creation/ dress up screen, we have video transitions.

I started off with moving the stage3D away, putting a very simple and lightweight class to hold an url to a video and a callback to be called once the video is done. I’d trigger it, it would self destruct and usually the callback simply creates the next state I want to have.
Fine.

But once you add a listener for a StageVideoAvailabilityEvent, everything crashes or at least no longer renders.

We found no solution to that. And again, this might sound like I’m just putting stuff together and don’t know what I’m doing but we had no time to find a solution to assemble the entire project in other ways as we could prove that it was linked to the use of starling + away3D in combo .

So we ended up using a normal flash Video object – HD quality was not a requirement anyway.

Part VII : Conclusion

I’ll stop there. VII is a nice number (specially if there’s two F’s before it) .
There was further issues when trying to use expansion files on Android, it seems some android version have trouble mounting the .obb file correctly , or corrupt files are found. The solution to that was to completely unzip a zip formatted .obb file into external storage and just load stuff through there, because enough is enough.

And StageText issues : briefly, strings got doubled when the restrict property was true on certain devices so I had to leave it out. Thanfully these days, StageText is being looked at, I hear.

The game was shown in time at the expected realease date for a press conference and even Apple decided that I went through too much so the very morning of the conference reviewed positively the full version of the app. Or maybe that’s just coincidence?

That’s my first experience as an employee so I’ll keep all the mistakes , misunderstandings and bad choices in mind. Obviously as I think about it, there was a lot of mistakes on my part – or things I should’ve talked about earlier during the production process.

 

If you are really curious, here are the links to the app in question :

 

pata33

Android , Free/Full :

Free : https://play.google.com/store/apps/details?id=air.com.kbstudio.PataTrottersLite
Full: https://play.google.com/store/apps/details?id=air.com.kbstudio.PataTrotters

IOS

Free : https://itunes.apple.com/us/app/id880622460
Full : https://itunes.apple.com/us/app/id879475182

AS3 Skeletal animation libraries performance test

Update: part2.

Right after Silly Family (the Android & multiplayer version will be out at the end of the month!), we are already planning our next game. It will be more for gamer, a bit less family, it will be a tower defense kind of game (I enjoyed so much Bardbarian). We’ve already some fresh ideas, so it’s already time for making test implementation!

On Silly Family we used DragonBones for animations. The graphic designer enjoyed to be able to make them right in Flash, and for me the .dbswf exported file is really optimized (less than 1Mb for 6 * 5 * 16 animations and multi resolutions friendly)! However in our future game, we will have at least 30 animated characters at the same time, and in my quick prototype DragonBones wasn’t able to handle them. So it’s time for a benchmark!

Benchmark
Ok, first thing to consider: since I’m not a graphic designer (nor an animator) I wasn’t able to use the same graphics for each library. So I used their default model. Some may be more complex than others and so impact performances. The goal was to see if I can reach 60 FPS on my iPhone 4S (using iOS 7.1.1) in release mode obviously with AIR 13 using ASC 2.0 compiler and Starling framwork.
If you want to have a quick look on what the benchmark looks like, go there.

DragonBones
DragonBones has the easiest workflow since it is used directly into Flash. This is the library with which I’m the most familiar. For 30 Dragons on screen, I reached 34 Fps using version 3.0 beta and its new cacheFrameRate feature!

Flump
Flump is an other library using Flash for making animations. I found it harder to use (in Flash editor) than DragonBones when making Witchcraft Works (I used Flump with Haxe and Flambe). Making this simple performances test was a bit complicated since they don’t provide external libraries (fzip, react) directly, or I missed something. Anyway, I had 30 of their mascot running at 54 Fps!

Spine
Spine has its own software for making animations. It also has its official runtime for AS3/Starling. I had 30 orcs at 25 Fps.

Spriter
Spriter also has its own software for making animations, it also has its official AS3 implementation but when I tested it performances was really, really bad. I didn’t have 30 objects at 60 FPS on my computer! Lucky me, since Spriter is very popular (it was one of the first Skeletal animation software on KickStarter) there are several implementations. And the one made by TreeFortress is pretty solid concerning performances. Have a look on Shawn’s article. I reached 45 fighters at 52 Fps!

Conclusion
After this benchmark, I already know that I won’t use Spine. It’s the most expensive software and concerning performances point of view, there aren’t very good. Spriter Shawn’s implementation sounds very performant however sadly it doesn’t sound to be updated and supported with latest Spriter update. We enjoyed working with DragonBones for our previous game, however for this new one it may be a bad deal. Performances aren’t enough good, but since the graphic designer and me are very familiar with it, it may worth spending time on the library to optimize it (and damn I love this .dbswf format). And finally Flump sounds like a way to gve a serious try, performances seem to be pretty good and for the graphic designer he should feel at home using Flash!

Download sources & Scout reports.

Using an other technology?:
As you can see in the Scout reports, this is really the AS3 code which is limiting performances. It reminds me Philippe Elsass blog post about the fail of AS3/AIR. For my game I won’t need 100 characters à 60 FPS, but it isn’t a reason to have a look on other tech:
– I enjoyed using Flambe, however it’s using AIR on mobile. Thanks to Haxe optimization, it should be more optimized than AS3 directly, however I doubt having so much different performances.
OpenFL may be the solution concerning performances. However I’m a bit afraid of its constant evolution.
– And finally, why not Unity? Related to my old article, here I’m facing Unity’s bad side: all Skeleton animation libraries aren’t free even for testing their runtime. It’s really sad… Smooth Moves doesn’t sound bad at all.

And you what do you think?

Silly Family, being an indie dev

The game.

Hey guys, this blog post is very special for me :
– it’s my hundredth article!
– my first game as an indie dev is out!

100 blog articles
When I started blogging 4 years (already!) ago, I didn’t imagine that someday I’ll reach the hundredth article. I started mostly as an exercice in style, improving my english communication skills and coding different things for sharing (unpretentious). I continued and now when I give a look in the past I’m smiling : I can see my evolution, how I’m better as a programmer, and all the different things I did in 4 years.
Also thanks to this blog I had my first client as a freelancer! I would recommand to any programmer to have a blog and post each month an article (that’s what I’m doing since 3 years) on what he is doing.

Apptoonomy
With some friends we created a new company, Apptoonomy. So does it mean that I’m not anymore a freelancer at Da Viking Code? No way! What does a programmer on his spare time? He is programming. With Apptoonomy we mainly focus on making our own games. Let me introduce the first one!

Silly Family
silly1Silly Family is a familly-fun Puzzle Game! Do you know Suzan? Of course you do! Suzan is my father’s son’s sister’s mother’s mother! Suzan is my grandma!!!

In Silly Family, you train your logic by resolving more and more complicated enigmas about increasingly crazier families! You’ll have to find the family relationship or run through the family tree.

We offer 3 different gameplays, 5 families (maybe more) and crazy designs… not to mention the animations! Also a multiplayer mode to defeat your friend!

Obviously questions are generated dynamically, I wrote the algorithm using (family) trees and recursivity. That was funny especially managing the different languages (the application is currently available in English, French, Spanish and Italian). We’re waiting a little bit for German, it won’t be easy ;)

Being an indie dev
Silly Family is the first (finished and published) game that I made as an indie dev. It’s really a longest process than programming games for clients. A client has to be sure (or at least should) that his game design is strong and developer implementation won’t show design flaws. Otherwise programmer’s bill may be painful. I started to develop Silly Family in October 2013 so six months ago. And obviously we already had a game design document. But so many things changed during its developement. Also you can add the fact that you must be satisfied with your game’s direction, and to still have the will to work on. Anyway, it’s a very interesting experience and it improved my skills as a game designer. We’re already looking forward for the next game!

Technology
Obviously I used my beloved Citrus Engine for making this game and Starling framework. The IPA size (before submitting to Apple) is less than 17Mo! How did we achieve this size? It’s thanks to DragonBones and its awesome .dbswf format. AS3/AIR technology was perfect for making this game!

Flambe versus the World!

The game.

The (HTML5) engines war
You probably didn’t miss the engines war of the previous month: Unity announced Unity5 with WebGL support (which I already pre-ordered hurrah!) and Unreal Engine 4 did the same with an incredible price. That was for the big guys.
From a more indie friendly point of view, PixiJS continue to kick ass with awesome new features (cacheAsBitmap, blend mode for canvas, SpriteBatch…). Phaser using PixiJS as its rendering engine, is becoming much more popular every day and obviously more stable. PixiJS has really the wind in its sails because OpenFL switched to it for its HTML5 rendering engine!

Witchcraft Works
wwI had to make a new HTML5 game, Witchcraft Works, available through (iOS, Android wasn’t required) devices browser. Since Unity5 isn’t available yet and even if they will support WebGL it can’t be used on a mobile game browser while WebGL isn’t available on mobile yet (iOS I’m looking at you!). So I needed an engine working with Canvas.
In my latest HTML5 project, I summarized my first experience with PixiJS and the issue with performances (certainly not the engine’s fault). Since StarlingJS sounds like abandonned to me, and I wanted to test something new, CreateJS just has WebGL support, I didn’t feel confident with that engine (and add JavaScript coding…). It was finally time to give a try to Flambe, and I fell in love! I heard about it some years ago when I was most active in the Haxe community with a Citrus Engine‘s port.

With the same code base, coded in Haxe, Flambe enables to export Flash/AIR (web, mobile applications), Canvas (old browser, device mobile browser) & WebGL (web) builds!

Haxe
As you probably know, I hate coding in JavaScript. With my previous project I found TypeScript not bad at all, but I’d to make a TypeScript definition file for feeling comfortable with PixiJS. Using external libraries in the project, I didn’t have TypeScript support for them, that was a mess… Using Flambe I’m able to benefit from lots of Haxe’s libraries, and yeah coding in Haxe is lovely!

When I played with NME, 2 years ago we were fighting with the lack of IDE support. There is an excellent plugin for Sublime Text, but I can’t feel enough comfortable, I needed an IDE. But now even if you’re not on Windows (and its awesome Flash Develop), you have cross platform Haxe IDE support with FDT which isn’t bad at all and IntelliJ (I prefered FDT).
Flambe works with a command line interface, but you can also have easily a .hxml file for your IDE ;)

Flambe
Getting started with Flambe might be a bit complicated. Be sure to read its installation guide, have a look on the examples and on its official Cookbook. Holy crap we’re seriously missing documentation here! Don’t panic have a look on Mark Knol‘s one and you can already be grateful! Also be sure that Flambe will match with your project requirements (add no video support).

Entity component system
The first thing you will notice with Flambe is its entity component system. Unlike many frameworks which cloned Flash display list, Flambe works with an entity component system even for rendering stuff! Basically that means if you create a Sprite object, you can’t addChild children directly. You have to create a new Entity, add it a display object, and addChild this entity to a parent entity! It’s really troubling at first, but once you get it it works like a charm.
It’s sad that you can’t extend an Entity, it will be very useful for creating lots of custom objects, instead of that we are creating many Components for a project. I understand the design choice, but I find it too restrictive for making frameworks on top of Flambe. Also it would be cool to have getEntityAt method & I didn’t find an easy way to identify Entity/Component like we do with their name in Flash.
Anyway it’s very pleasant to use its entity component model once you get it.

Animations
With Flambe you will have to use Flump for your animations. Seems it sounds like a correct way for manipulating animations (you will write some JSFL for speeding your workflow), it’s crazy that Flambe can’t load SpriteSheet in any format provided by TexturePacker! I may have missed something but that means even for making a SpriteSheet of images you will have to import them in Flash and export them with Flump. What the fuck?

Performances
Ok here we go. On my latest HTML5 games I fought a lot with bad performances on mobile… Here it just works… like a charm! I didn’t have to fight with anything. I have a strong 60 fps on my iPhone4S and iPad3. Nothing to add. So kudo Bruno!!

I don’t need at all a Flash target, so why bother with Flambe?
Me neither, but having a Flash support will help you a lot with debugging your code!

Still not convinced by Flambe? Have a look on its showcase and see games made by big firms (Disney, Nickelodeon)!

Finally I’m back in the Haxe world and that’s very pleasant! Using Flambe at Da Viking Code gives me without any doubt a strong weapon for future HTML5 project! Feeling even more like a Viking ;)

Finally I made a serious game

After several years in the gaming industry making mostly casual games, it was about time to give a try to serious game, right?

mef-gameMon Exploitation Forestière, only available in French at the moment, offers to the player to grow a forest. He will have to manage different tree species having their own properties (life duration, units collected, …) and cope with natural elements (fire, storm, …). The client wanted to responsibility players about the fact that a forest need to be maintain.
As cool features to develop there were saving players game in database, facebook connect and tiles’ OOP management.

Let’s start for some explanations with the latest one:
Each tile is designed into Flash Pro and inherit from a class with its properties (tree or empty tile for example). This way it’s very easy to modify it in real time, switch or even save it!
For saving the game, I’ve basically create a JSON with each tiles informations (+ score etc.), since everything is OOP it’s very easy to read its data and save it. For loading a save game it’s the same process. Load the JSON with all tiles informations and create objects.
Concerning the Facebook connect, I didn’t use at all the AS3 SDK but the php one. It’s very useful since you may use it for UI combined with JavaScript SDK. And using the php one in the backend is very safe ;)

AIR ANEs

Hey guys! Time flies, February is already finished.

It’s time for a very short blog post! I made many AIR Native Extensions this last months, playing with ads, analytics, sounds… it’s awesome the number of amazing SDKs you find on mobile. Unfortunately all my ANEs are private due to NDAs.

Here are some links to learn how to write your own:
– never played with ANEs? Get started with an Adobe tutorial.
– before coding your first ANE, have a look on the ones provided by StickSports. Richard Lord’s made an excellent work! He provides the best template ;)
– developing your ANE, be sure to read his tips!
– and yes, obviously you can add an Objective-C view on top of your Flash View but you unfortunately you can’t do the reverse.
– for a long run have a look on this Adobe’s PDF.

Hope this links will help!

Working with multi-resolutions assets

When we’re making mobile apps we have to support lots of resolution from 480 x 320 to 2048 x 1536 if you only target iOS. Adding Android support you have to extend it to 2560 x 1600 (for the Nexus 10)!

If your graphic designer made its design into a vector format, it will be easy to fit exactly to your screen size, and you will only fight with the different ratios format.
However if your design is made with bitmaps, you have to, firstly, be sure they have been made for the highest resolution you would like to support! When this is done, you will use a SpriteSheet to have all of your assets in one (or a little more) place.

In this blog post we will see how to manage multi-resolutions assets based on a Starling app.

When you’re building a game with Starling you have several way to handle the multi-resolution management and the Citrus Engine offers more. In this example, we will just fit Starling’ stage to always have the size of the device. And we will use our own scale factor!

I will override the CitrusEngine findScaleFactor with my custom one. Note it should be more or less the same even if you don’t use the Citrus Engine.

override protected function findScaleFactor(assetSizes:Array):Number {
 
	var minValue:Number = Math.min(screenWidth, screenHeight);
 
	if (minValue < 400) // iPhone3GS
		return 1; // 0.25 in TexturePacker
	else if (minValue < 640) // Lots of Android devices
		return 1.5; // 0.375 in TexturePacker
	else if (minValue < 1536) // iPhone4, iPhone5, iPad non retina
		return 2; // 0.5 in TexturePacker
	else  // iPad retina
		return 4; // 1 in TexturePacker
}

In my app I will support 4 sets of texture, we don’t want to create a lots more because it will request extra space. Also I don’t extend it to the Nexus 10, since the one provided by the iPad retina should be ok.

Now that I’ve my scaleFactor, I will load the correct set using Starling’s AssetManager:

Assets.assets.enqueue(File.applicationDirectory.resolvePath(formatString("assets/{0}x", scaleFactor)));
 
Assets.assets.loadQueue(function(ratio:Number):void {
	if (ratio == 1) {
		state = new GameState();
	}
});

Bonus: you can easily combine it with DragonBones! Here you should export your design into the awesome .dbswf format, it will save you lots of space! Also if you’ve designed your DragonBones assets at the maximum resolution you will supported, it’s perfect you can easily resize the future spritesheet:

Assets.factoryDB = new StarlingFactory();
Assets.factoryDB.scaleForTexture = scaleFactor / 4; // models designed for 4X.
 
Assets.factoryDB.parseData(new Assets.DragonBonesAssets());

Ok, so this is great but how could I automate my way to generate SpriteSheets?
Firstly, you have to use the best SpriteSheets generator on the market: TexturePacker. Put all your bitmap assets at one place, and drag and drop them in TexturePacker. When you’ve selected the different options save it as a .tps file!
You could manually generate SpriteSheets one by one just changing the scale and it will do the job. But it will be very annoying to do it each time you change one asset.
TexturePacker provides a command line tool, so let’s use it with a bash script:

#!/bin/sh
#!/usr/bin/env bash
 
DIR="$( cd "$( dirname "$0" )" && pwd )"
 
for i in 1 1.5 2 4
do
        TexturePacker --sheet "$DIR"/../bin/assets/"$i"x/assets.png --data "$DIR"/../bin/assets/"$i"x/assets.xml --scale $(echo "scale=3; $i/4" | bc) --format sparrow "$DIR"/assets.tps
        echo "pngquant image" "$i"x
        pngquant -f --ext .png "$DIR"/../bin/assets/"$i"x/assets.png
done
 
echo "TexturePacker and pngquant tasks done."
 
exit 0

Latest script version and instruction to run it.

It will generate you all the resolutions needed and applied the awesome pngquant! So it will greatly improve your final SpriteSheets weight!

Bonus: you will probably also use BitmapFonts into your game. I used to deal with the great GlyphDesigner, however I’m facing a strong issue: I’m not able to export a downscale BitmapFonts spritesheets (updated: in fact it’s only available via the command line). They all have characters to a different place. And I would enjoy to add this png generated to my main SpriteSheets… so how could I do that?

I switched to bmGlyph, and it enables me to downscale a BitmapFonts SpriteSheets. So thanks to this downscale, I generate them all (you will certainly don’t have to update this bitmap fonts often), add the 4x sizes to my bitmap assets folder, and remove all the others generated pngs. And then in the same repository than the future global SpriteSheet, I add the .fnt file. Now when Starling parse the SpriteSheet, it will also add the bitmap font. Powerful, isn’t it?