Category Archives: Haxe

Unity, Flambe & OpenFL Skeletal animation libraries performance

Hey guys, I concluded my AS3 performances test saying that AS3 math performances are still a bit low and that with other technology, we should have better performances. So here we go!

Again I remember that it’s really hard to compare different Skeletal animation engines using different models (and so an engine/a tech). I would really enjoy to have the same model available for each soft…

Flambe
Using Flump with AS3 implementation I had very good performances 30 mascots for 54 FPS. Since Haxe optimized AS3 code, we could imagine that we would win a bit more fps. However using Flambe (which is awesome) and its own Flump runtime I didn’t save FPS. Worst, I lost many! I had 30 mascots at 30FPS. Bad surprise.

OpenFL
OpenFL still use Haxe for coding however it may export native code! On mobile we could suppose that we would win some fps too. I tried several libararies, but the only one I succeed to make working was this one from Lugludum studio. They didn’t try it a lot on mobile, they focus on desktop, but for a first mobile run it wasn’t bad at all: 34 FPS for 30 animated characters.

Unity
For Unity I searched a free library, and I was really glad to see there is an implementation (no official, there was missing an eye with my model) of DragonBones. I put 30 dragons, damn I had 60 FPS! And finally 40 dragons at 46 FPS.

So what to conclude? I was sad to see that OpenFL didn’t save me some FPS relatively to my AS3 benchmark. But we can’t judge a technology on this test. Unity math performances seems to be really good. Is it the best tool for making 2D game? Maybe, without any doubt they are on the good road.

Download sources.

P.S. Gaming for change? Have a look on A Blind Legend! A really nice mobile project using binaural tones! Oh and my colleague and me will work on it. So stay tuned ;)

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 ;)

Citrus Engine on Nape and physics performance improvement

Hi folks! Since my studies are over and my new portfolio online, I have time to focus on personal projects. Yep, it was time to contribute again to the Citrus Engine. I’ve worked 3 days at full time focusing on its big issue : mobile performances. I’m glad to say that now they are just an old memories!

6 months ago, I’ve made the CE compatible with Stage3D thanks to Starling and added some cool stuff. CitrusEngineV3 BETA 1 has been downloaded 3047 in 6 months, that’s not bad! However it didn’t see lots of Stage3D game, because it was missing the point : people wants to make mobile games.

You will find all the sources at the end.

Nape
Nape is Luca Deltodesco‘s open-source physics engine written in haXe with the help of his preprocessor caXe. It is written with AVM2 in mind for performance, and utilising another part of his build chain provides a seamless API between AS3 and haXe though it does compile with hxcpp with other targets unknown. The idea behind Nape is to provide a high-performance, powerful and moreover friendly and safe physics engine.

Nape is faster than Box2D, and easier to handle. Adding it in the CE wasn’t hard, and we use it the same way than Box2D. Using Box2D (Alchemy version) & Stage3D with Starling in the CE you must take a look on Adobe Flash Player Premium announcement if you are targetting Browser games. With Nape, you are no more related to the “premium features license” from Adobe.

A NapeStarlingGameState Class exemple :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package  
{
	import com.citrusengine.core.StarlingState;
	import com.citrusengine.objects.NapePhysicsObject;
	import com.citrusengine.objects.platformer.nape.Platform;
	import com.citrusengine.physics.Nape;
 
	import starling.display.Image;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;
	import starling.textures.Texture;
 
	/**
	 * ...
	 * @author Aymeric
	 */
	public class NapeStarlingGameState extends StarlingState 
	{
		[Embed(source="../bin/small_crate.png")]
		private var _cratePng:Class;
 
		public function NapeStarlingGameState() 
		{
			super();
		}
 
		override public function initialize():void {
 
			super.initialize();
 
			var nape:Nape = new Nape("nape");
			//nape.visible = true; -> to see the debug view!
			add(nape);
 
			add(new Platform("borderBottom", { x:0, y:stage.stageHeight - 10, width:stage.stageWidth, height:10 } ));
			add(new Platform("borderLeft", { x:0, y:0, width:10, height:stage.stageHeight } ));
			add(new Platform("borderRight", { x:stage.stageWidth - 10, y:0, width:10, height:stage.stageHeight } ));
 
			stage.addEventListener(TouchEvent.TOUCH, _addObject);
		}
 
		private function _addObject(tEvt:TouchEvent):void {
 
			var touch:Touch = tEvt.getTouch(stage, TouchPhase.BEGAN);
 
			if (touch) {
 
				var image:Image = new Image(Texture.fromBitmap(new _cratePng()));
 
				var physicObject:NapePhysicsObject = new NapePhysicsObject("physicobject", { x:touch.getLocation(this).x, y:touch.getLocation(this).y, width:35, height:38, view:image} );
				add(physicObject);
			}
 
		}
 
	}
 
}

There wouldn’t be any CE’s API difference if you used Box2D (except for package/class names).

Bad mobile performances’ end
So Nape was amazing powerful in the CE? Yes and no. The performance was better than Box2D, but not as good as I’d like. Troubled, I started thinking there was a bad “architecture” in the Citrus Engine… and there was one. The solution came from my Haxe NME port, or more precisely a simple Box2D’s Haxe NME project on my desktop. This one had better performance than my port, on very simple test. The Box2D’s debug view changed object’s color after some time ; not on mine! Sleeping object… something prevented objects to sleep. After some investigations, it was the way how gravity was settled : no gravity in World/Space but one applied on each dynamic objects :

/**
 * You should override this method to extend the functionality of your physics object. This is where you will 
 * want to do any velocity/force logic. By default, this method also updates the gravitatonal effect on the object.
 * I have chosen to implement gravity in each individual object instead of globally via Box2D so that it is easy
 * to create objects that defy gravity (like birds or bullets). This is difficult to do naturally in Box2D. Instead,
 * you can simply set your PhysicsObject's gravity property to 0, and baddabing: no gravity. 
 */		
override public function update(timeDelta:Number):void
{
	if (_bodyDef.type == b2Body.b2_dynamicBody)
	{
		var velocity:V2 = _body.GetLinearVelocity();
		velocity.y += gravity;
		_body.SetLinearVelocity(velocity);
	}
}

Easier to manage different objects’ gravity, but no sleeping objects. Now the gravity is set in the World/Space creation and this update function is empty. That was it!

Performance tests
Ok now everything is correct, it’s time to give some numbers! Don’t hesitate to give yours! The tests are based on the code above and use an iPhone 4S.
Citrus Engine with Starling & Box2D : 50 dynamic objects = 50FPS.
CitruxEngine with Box2D : 67 dynamic objects = 50FPS.
Citrus Engine with Starling & Nape : 80 dynamic objects = 50FPS.
I’ve not implemented Nape on the CitruxEngine yet.
Note that I was compiling for 60FPS, targetting 50 FPS just to be sure that performance decrease. Important, the 50FPS is stable when objects are sleeping. Since they are all in contact each other, the framerate drop fast.

Physics engines cohabitation
The Citrus Engine is built with a “platformer” starter-kit using Box2D, which you can use to easily make awesome 2D sidescrolling games. I’ve started to port some platformer objects on Nape. That would be really stupid to delete Box2D support since Nape is more powerful. Remember the Citrus Engine with Box2D is performing very well on Desktop & Browser games. So it’s time for a cohabitation! There is a (little) file size difference using 2 physics engines instead of one (250 Ko for a SWF, 700 Ko for an IPA), but primarily I didn’t detect a performance drop! For the final release, you may remove the other engine stuff, it takes less than 2 minutes.
At the moment, Nape class name have “Nape” in front of them or are in a Nape package (platformer objects). I will do the same with Box2D objects.

Future
I will port some Box2D platformer objects into Nape, and later offer the Citrus Engine V3 BETA 2. The idea is to have the same behavior with both physics engines. Community help is always greatly appreciated ;)
The CitruxEngine will drop Box2D support to use only Nape since I had an endless bug with it. Remember, this Haxe NME port is not ready for production but don’t be shy, get involved :D
An optional entity/component system is always something jumping in my head, I hope to be able to offer one soon.

Sources & demo
Citrus Engine with Nape & Starling ; Browser live demo
Citrus Engine with Box2D & Starling ; Browser live demo
CitruxEngine with Box2D ; Browser live demo

Grab the last Citrus Engine update on its Google Code!

The Citrus Engine goes on Haxe NME, welcome to the CitruxEngine

One month ago I started to work on the CitruxEngine. I was very confident with Haxe performance on mobile and NME cross platform opportunities. And now, I can say those are awesome!

In April 14-15th, I was in Paris to assist to the Haxe conf 2012. It was really cool, Silex Labs has made a good job! Conferences were very interested and the community greatly friendly. And I had the opportunity to make a lightning talk concerning my contribution to the Citrus Engine 2D game framework and its port on Haxe NME. The presentation was a bit from scratch, but that was a good experience! I’m very happy to be the first to start the lightning talk, since there were very serious projects :D

CitruxEngine Github.
CitruxEngine Demo. Simple demo which have been tested on Flash & CPP (using left/right key and spacebar) and iOS (touch & accelerometer). There are sound, animations (idle, walk and jump) and physics.
The port is currently not finished!

I will not present some code here. If you are already familiar with the Citrus Engine, there will be no problem. Take a look on the example on Github.

HTML5
When I started the port, I would the CitruxEngine be as cross platform as possible. HTML5 is promising, and Niel Drummond the man behind Jeash has made an incredible job! However I found that the Haxe NME Box2D port has not very good performance with HTML5. So I’ve dropped the HTML5 target at the moment, but I keep an eye on Jeash!

Box2D
Thanks to Haxe NME, Box2D runs very well on mobile! This is mostly the reason why I’ve started the CitruxEngine. The Citrus Engine uses the AS3 Alchemy version of Box2D which has some differences with the original. It seems there is a bug with the Haxe NME Box2D port : the beginContact & endContact listeners are fired all the time if a dynamic body is on a static body (like a hero on a platform), whereas it fires only once if there are 2 dynamics bodies. This behavior is blocking me.

SpriteSheets
I made my test with the spritesheet haxelib which uses SpriteLoq. At the moment it works well. I’ve not made serious test with animations.

Level Editor
I love how the Citrus Engine handles Flash Pro as a Level Editor. I would like the Haxe NME version handles it as well. But at the moment we can’t read AS3 code in a SWF file (it is the way that class and properties are defined), so I need to think to an external way. Maybe it’s time to reconsider the Level Architect!

Console
The console is really a cool feature of the Citrus Engine, it will be available in the CitruxEngine too. I’ve started to implement it, but it’s not ready yet.

I will continue to work on the CitruxEngine, but now I’ve to focus on my school project using Objective-C, it’s really hard to get back when you have tested Haxe power ! In less than two months I will be graduate and looking for a job, future is exciting.

Thanks to postite & elsassph for their help!

JavaScript slider made with haXe and JQuery

After playing with haXe and Php, it was time to try haXe and JavaScript! I used the JQuery library included in haXe. For more information on haXe JS take a look on its website.

Click here to see the slider in action. It uses keyboards and a timer. The slider centers a picture with a 50px margin, there is also a red or green filter.

The html part :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8"/>
	<title>Slider</title>
	<meta name="description" content="" />
	<link rel="stylesheet" href="style.css" type="text/css" />
 
	<script type="text/javascript" src="slider.js"></script>
</head>
 
<body>
 
	<div id="haxe:trace"></div>
 
	<div id="slider">
 
		<div id="animate">
			<ul>
				<li><img src="img/pic1.jpg" alt="img1"/></li>
				<li><img src="img/pic2.jpg" alt="img2"/></li>
				<li><img src="img/pic3.jpg" alt="img3"/></li>
				<li><img src="img/pic1.jpg" alt="img4"/></li>
			</ul>
		</div>
 
	</div>
 
</body>
</html>

A part of the CSS :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#slider {
  position: absolute;
  left: 50px;
  right: 50px;
  overflow: hidden;
}
 
#animate {
  position: relative;
  z-index: 5;
}
 
#animate ul {
 
  position:absolute;
  left: 1px;
 
  list-style: none;
  overflow: hidden;
  margin: 0; padding: 0;
}
 
#animate li {
  float: left;
  text-align: center;
  background-color: red;
  overflow: hidden;
}
 
#animate li:nth-child(odd) {
  background-color: green;
}
 
#animate li img {
  opacity: 0.7;
}
 
.carousel-previous {
  position: relative;
  z-index: 100;
}
 
.carousel-next {
  position: relative;
  z-index: 100;
}

And finally the haXe part :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package;
 
import haxe.Timer;
 
import js.Dom;
import js.JQuery;
import js.Lib;
 
class Slider {
 
	private var _timer:Timer;
	private var _timerSpeed:Int;
	private var _countTimer:Int;
	private var _timerIsRunning:Bool;
 
	private var _jqSlider:JQuery;
	private var _jqAnimate:JQuery;
	private var _jqAnimateUlLi:JQuery;
 
	private var _nbrElements:Int;
	private var _elementWidth:Int;
	private var _sliderWidth:Int;
	private var _animateWidth:Int;
	private var _margin:Int;
 
	static function main () {
 
		new JQuery (Lib.document).ready(function(evt) {
 
			new Slider();
		});
	}
 
	public function new() {
 
		_jqSlider = new JQuery('#slider');
		_jqAnimate = new JQuery('#animate');
		_jqAnimateUlLi = new JQuery('#animate ul li');
 
		// required by Chrome for the width() function
		Lib.window.onload = _onload;
 
		Lib.window.onresize = _onresize;
	}
 
	private function _onload(evt:Event):Void {
 
		_nbrElements = _jqAnimateUlLi.length;
 
		_jqSlider.css("height", Std.string(new JQuery('#slider ul li').height()) + "px");
 
		_elementWidth = _jqAnimateUlLi.width();
		_animateWidth = _elementWidth * _nbrElements;
		new JQuery("#animate ul").width(_animateWidth);
 
		_onresize();
 
		_timerSpeed = 5000;
		_countTimer = 0;
		_timer = new Timer(_timerSpeed);
		_timer.run = _tick;
		_timerIsRunning = true;
 
		Lib.document.onkeyup = _onkeypress;
 
		_jqSlider.prepend('<input class="carousel-previous" type="button" value="Previous">');
		_jqSlider.append('<input class="carousel-next" type="button" value="Next">');
 
		new JQuery('.carousel-previous').click(function(evt) {
 
			_moveLeft();
 
			if (_timerIsRunning)
				_timerIsRunning = false;
		});
 
		new JQuery('.carousel-next').click(function(evt) {
 
			_moveRight();
 
			if (_timerIsRunning)
				_timerIsRunning = false;
		});
	}
 
	private function _onresize(?evt:Event):Void {
 
		_sliderWidth = _jqSlider.width();
 
		// bitwise operator FTW !
		_margin = Std.int(_sliderWidth - _elementWidth >> 1);
 
		_jqAnimateUlLi.css("margin-left", Std.string(_margin) + "px");
	}
 
	private function _tick():Void {
 
		if (_timerIsRunning)
			_moveRight();
	}
 
	private function _onkeypress(evt:Event):Void {
 
		if (evt.keyCode == 39)
			_moveRight();
 
		if (evt.keyCode == 37)
			_moveLeft();
	}
 
	private function _moveRight():Void {
 
		//pre incrementation FTW !
		if (++_countTimer == _nbrElements) {
 
			_jqAnimate.animate({left: 0});
 
			_countTimer = 0;
 
		} else {
			_jqAnimate.animate({left: '-=' + Std.string(_elementWidth + _margin) + "px"});
		}
	}
 
	private function _moveLeft():Void {
 
		//post incrementation FTW !
		if (_countTimer-- != 0) {
 
			_jqAnimate.animate({left: '+=' + Std.string(_elementWidth + _margin) + "px"});
 
		} else {
 
			_jqAnimate.animate({left: '-=' + Std.string((_elementWidth + _margin) * (_nbrElements - 1)) + "px"});
 
			_countTimer = _nbrElements - 1;
		}
	}
}

Handle JS with haXe is easy, managing JQuery too. Once again the haXe api is your friend. Like for Php you can use external libraries and wrap them, see the documentation. Also take a look on the haXe magic.

My zip.

That’s it for the haXe experimentation to replace native languages, now I will focus on NME, Flash Stage3D, and my school project using Sparrow & Chipmunk in Objective-C. More information later !

Using native Php with haXe Php

Recently I had some time to dig more with haXe Php. The major question was how does it integrate with existing native Php ? I’m glad to say that it works fine!
Let’s start a quick overview of our native Php file test (Simple.class.php) :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
function makeSimple($text) {
    return new Simple($text);
}
 
function affichText($text) {
    echo $text;
}
 
class Simple {
 
    public $text;
    public $tab;
 
    public function __construct($text) {
        $this->text = $text;
        $this->tab[0] = "index 0";
        $this->tab[1] = "index 1";
    }
 
    public function doPrint() {
        echo $this->text;
    }
 
    protected function changeText($text) {
        $this->text = $text;
    }
}
 
class Simple2 extends Simple {
 
    public function __construct($text) {
        parent::__construct($text);
    }
 
    public function makeChange($text) {
        $this->changeText($text);
    }
 
    public function associativeArray() {
 
        $tab["num1"] = "number 1";
        $tab["num2"] = "number 2";
        return $tab;
    }
}
?>

There are a simple function, some inheritance stuff and an associative array which is very common in Php.

Now the haXe part :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package;
 
import php.Lib;
 
class Test {
 
    static function main() {
 
    	new Test();
    }
 
    public function new() {
 
        // import php file
    	untyped __call__("require_once", "Simple.class.php");
 
        // call a php function with an arg
    	untyped __call__("affichText", "first msg </br>");
 
        // create a php object with an arg
    	var myPhpObject:Dynamic = untyped __call__('new Simple2', 'second msg </br>');
 
        // manipulate the object
    	myPhpObject.doPrint();
    	myPhpObject.makeChange("some new text </br>");
    	myPhpObject.doPrint();
 
        // print an array
        Lib.print(myPhpObject.tab);
 
        // trace the index 0 value
        trace(myPhpObject.tab[0]);
 
        // make some native php
        untyped __php__("echo '</br>php native from haXe !</br>'");
 
        // we need a Hashtable to parse an associative array from php :
        var phpAssociativeArray:Hash<String> = Lib.hashOfAssociativeArray(myPhpObject.associativeArray());
 
        // trace the key value num2
        trace(phpAssociativeArray.get("num2"));
    }
 
}

The output log :

first msg
second msg
some new text
["index 0", "index 1"]Test.hx:32: index 0
php native from haXe !
Test.hx:41: number 2

If you are using everyday libraries/tools written in Php, you may wrap them with haXe for more comfort. Take a look there : Wrapping External PHP Libraries & the haXe Magic.

Unfortunately, there isn’t lots of ressources/tutorials for haXe Php on the website, I will update this post if I go deeper in haXe Php development. It is very pleasant to write Php this way. Give it a try!
haXe API.

And because memes are fashion :

haXe workflow with Sublime Text 2, Php & nme examples

A good IDE is the developer’s best friend. FDT is my favorite one to code AS3 stuff, however I’m not very satisfied with haXe integration… it could be better. A good source code editor is also an amazing tool. I’ve found Sublime Text 2 some months ago, and it sounds always awesome to me. There is an extension which add Package control management to ST2 for adding new plugin, like haXe one.

Come on, download Sublime Text 2, install the Package control and haXe plugins!

That’s ok ? Now we can create a simple Php project.
Create a new file, save it as Test.hx and add this code :

package;
 
class Test {
 
    static function main() {
 
    	new Test();
    }
 
    public function new() {
 
    	var number:Float = 4;
 
        trace(number + 5);
    }
}

Then press ctrl (even if you use a mac) + shift + b. A new file called build.hxml is opened with some code generated to compile. You should just need that :

# Autogenerated build.hxml

# www
-php www
-main Test

Then press ctrl + enter. Your php files are generated. Pretty easy!

Now let’s make more stuff, a PDO connection with a simple query.

var cnx:Connection = PDO.open('mysql:host=localhost;dbname=igobelins', 'myUsr', 'myPwd');

If you press ctrl + space you have some greats auto-completion features! ctrl + i and the class is imported. If you make some mistake your code is highlighted in pink.

Our php stuff :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package;
 
import php.db.Connection;
import php.db.Mysql;
import php.db.Object;
import php.db.PDO;
import php.db.ResultSet;
 
class Test {
 
	public var cnx:Connection
 
    static function main() {
 
    	new Test();
    }
 
    public function new() {
 
      cnx = PDO.open('mysql:host=localhost;dbname=igobelins', 'myUsr', 'myPWd');
 
      var sql:String = "SELECT * FROM configs";
 
      var results:ResultSet = cnx.request(sql);
 
      for (result in results) {
       	trace(result.user);
       }
 
       cnx.close();
    }
}

According that you have a field user in your database, it will show the names.

Ok that was pretty cool, what about nme ? Go on this page and download the haXe project. In ST2 go in File/Open Folder… and select the Folder you have just unzipped. It should show the different folders & files in a left panel. Browse the Source and open SimpleBox2DExample.hx and then press ctrl + enter. It is compiled for flash and open quickly the result in the Flash Player. Ok but with NME I would like to target cpp. No problem press ctrl + shift + b then select cpp and compile. This way you can quickly change the target.
He wait, there isn’t html5 target !? I don’t know the reason but it is not offered. But you can add it (thanks to Julien Roche for the tips) : on Mac open the file Users/YourUserName/Library/Application Support/Sublime Text 2/Packages/HaXe/HaxeComplete.py and add html5 to nme_targets on line 124. Restart ST2, press ctrl + shift + b select html5 then compile. You have a new target ;-)

Sublime Text 2 and the haXe plugin are awesome, but so far it can not be as powerful as an IDE for debugging. No breakpoint for example, anyway it is already a great tool for a simple code editor!

Recently, JetBrains has released a haXe plugin for IntelliJ. We should keep an eye on it!

Air NativeProcess and bash file to compile haXe nme project

Last week I’ve made some test with haXe nme and box2d. The result is awesome : beautiful perf and a quick export on the target required! When I tried to run box2d from flash on a iPhone there was really bad performance : 10 dynamics objects – 5 fps. With haXe nme, more than 80 dynamics objects and 30 fps… that the power of native app. And for the fun I had an html5 box2d export, but not running smoothly.
At the moment, what I’m really missing is a powerful IDE for writing code and don’t use the console (even if it works great). FlashDevelop is the best one, but runs only on windows. Sadly, FDT supports haXe but not the nme. However it seems that JetBrains are working on a plugin for haXe and nme! But right now, I use Sublime Text 2 with the haXe plugin.

Anyway, I thought it would be cool to have a simple utilitarian app to create nmml files and compile projects with options (targets, mode, …). An Air application seemed to be an elegant way. Let’s go for a proof of concept on this last part :

The problem was how to run terminal command line with Air? The NativeProcess class provides command line integration and general launching capabilities. The NativeProcess class lets an AIR application execute native processes on the host operating system.
So it means that if I write a simple bash file, I’m able to run it with AIR!

Here we go for a simple version, my file name is nme.sh :

#!/bin/bash
nme test \"SimpleBox2DExample.nmml\" flash

Make sure to save the file with a chmod which allows you to execute it.
The Flex code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
					   xmlns:s="library://ns.adobe.com/flex/spark" 
					   xmlns:mx="library://ns.adobe.com/flex/mx">
	<fx:Declarations>
		<!-- Place non-visual elements (e.g., services, value objects) here -->	
	</fx:Declarations>
 
 
	<fx:Script>
		<![CDATA[
 
			public var process:NativeProcess;
 
			protected function compile(mEvt:MouseEvent):void
			{
				trace(NativeProcess.isSupported);
 
				var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
				nativeProcessStartupInfo.workingDirectory = new File("/Users/Aymeric/Desktop/Simple Box2D Example/"); 
				nativeProcessStartupInfo.executable = new File("/Users/Aymeric/Desktop/Simple Box2D Example/nme.sh");
 
				process = new NativeProcess();
				process.start(nativeProcessStartupInfo);
				process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
				process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
				process.addEventListener(NativeProcessExitEvent.EXIT, onExit);
				process.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError);
				process.addEventListener(IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError);
			}
 
			public function onOutputData(event:ProgressEvent):void {
				trace("Got: ", process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable)); 
			}
 
			public function onErrorData(event:ProgressEvent):void {
				trace("ERROR -", process.standardError.readUTFBytes(process.standardError.bytesAvailable)); 
			}
 
			public function onExit(event:NativeProcessExitEvent):void {
				trace("Process exited with ", event.exitCode);
			}
 
			public function onIOError(event:IOErrorEvent):void {
				trace(event.toString());
			}
 
		]]>
	</fx:Script>
 
	<s:Button label="Compile" click="compile(event)" />
 
</s:WindowedApplication>

If you run that script, your haXe nme project will compile from Air and open the flash player!
However this is not very dynamic… we can do better, let’s use some parameters :

#!/bin/bash
 
if [ $2 = "html5" ]
	then
	nme $1 \"SimpleBox2DExample.nmml\" $2
fi
 
nme test \"SimpleBox2DExample.nmml\" flash

That was our new bash file. $1 is the first argument given by our nativeProcessStartupInfo. The Air code :

var processArgs:Vector.<String> = new Vector.<String>();
processArgs[0] = "test";
processArgs[1] = "html5";
nativeProcessStartupInfo.arguments = processArgs;

Now if you run your app and click on the compile button, it will run your code in the browser thanks to html5 and open the flash player. You should be able to use all the nme’s Command-Line Tools.

If you’re familiar with bash script, you may be able to create a good dynamic script. I’m not.

Does it mean that we need to create ourselves the bash file? No, the app can generate one :

var file:File = File.desktopDirectory.resolvePath("test.sh");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);
stream.writeUTFBytes("#!/bin/bash\nnme test \"SimpleBox2DExample.nmml\" flash");
stream.close();

Thanks to the File API we are able to create a file, and later update it.
So everything is running fine, and I’m able to run my generated bash script? Well, there is one last problem : you can’t execute this file, so you get an error : Error #3219: The NativeProcess could not be started. ‘launch path not accessible’.

Google, my friend, show me this thread : http://forums.adobe.com/thread/721724 but it doesn’t work for me. And I can’t find other result. As far as I know, it seems to be not possible to create a file from air and change its chmod.
Anyway, if your file is already created, you could update it through Air.

That’s it for this proof of concept, an other thing for the todo list ? Maybe.

Ho! And since I was blasted by box2d mobile perf with the nme, we started to work with Dav Kert for a Citrus Engine haXe nme release : stay tuned on the github.

My thoughts on Flash and its recent events

Update : Unity3D has set up an exporter to target Flash which works very well! Without doubt they are working on an exporter for HTML5 too. This technology seems to be promising, I’ve added it on my to learn list!

I wouldn’t come back on the Adobe announcements, everyone know what’s happened and it has already been discussed everywhere. I just would like to share my student point of view about the future.

I started to develop and learn programming with AS3 5 years ago. It was in 2007, AS3 was just out. AS3 is really a cool language to learn programming. I know that purist doesn’t like it and say that it’s shit… but most of them have never taken a look on it. AS3 is OOP programming language, it’s easy to manage picture/shape, memory too (yeah the GC isn’t perfect, and you have to learn good practice but for the best), no pointer, simple listener on events, work with diversified media : video/sound/3D/game… and finally we can use frameworks which are available in other languages such as Box2D.

So yeah, flash as3 is a good language to have good programming skills, but you can’t stop on it. During my first 2 years training, I have also learned xHTML/CSS/JavaScript/Php/SQL. One year later, when I was in a computer science school I have learned “decent” programming language : C/C++/Java, some VHDL & VBA & Ruby too… and certainly I forget some of them. I can’t say that I remember each of them, at this moment I’m not able to write a “Hello World” in Ruby, but when we learn a new language its not only our specific language skill which is improved, but our skills as a developer. A mathematician does not work only on trigonometry for example, but on many other things too, even if he is specialized in trigonometry. Because everything is just ONE simple box. And finally when you have good programming skills, and know the concept behind the programming language that you want to learn, it isn’t really hard : it’s about one week to be operational.

I loved learning C: managing memory, C++ :writing complex OOP (multi-heritage, operator overloading…), Java which has a syntax close to AS3 (yeah, I know its just the opposite ;-) ) and its difference on constructor, listeners…
Since last year, I’m back in the web and works essentially with AS3, and I feel really stronger than before because I learned newest things form other languages.

So what’s up now? Flash isn’t dead yet, and probably not in the next five years. But we couldn’t say that it’s always popular, don’t lie to yourself HTML5/CSS3/JS is the new elected. And now you have to think about what you love, here are mine :
– working in a web agency (I have sandwich course) with a small team (not like on a big game with 300 people).
– diversity : video/sounds/3D…
– games.
– desktop/mobile applications.
Finally I consider myself as an interactive developer. Here is what I don’t like :
– “back development” such as php, I don’t feel really comfortable with database.
– CSS/JS it’s not a troll… I will explain after.
– working on CMS website.

So this last day, I said to myself : “You must learn newest things, it’s time”. In july, I will work at full time and I’m not sure to find easily some works with my flash skills. So it’s time to start learning newest things. If you are a hero flash developer it may not be a big problem for you, you have enough experienced to work on amazing project (if you are up to date!), for people like me, I’m not sure. So here are my reflexions about what new skills I should pick up or not :

– HTML/CSS/JS, I will follow their updates as a web developer, but it’s not my priority at the moment. I’m not trolling : I don’t like CSS tricks, and JS is definitely not a better language than AS3 for lots of reasons. Obviously, we can make amazing things with framework like ThreeJS, WebGL, and the flash community has started to make amazing tools like this one for example : HTML5 Canvas API implementation of the AS3 BitmapData class. But JS with Jquery… is not something which interest me a lot, I’m not sure it will increase my programming skills as much as other languages.

– AIR & FP, I must keep my skills up to date. There are always lots of things to learn, and some cool stuff is coming (stage 3d on mobile). And AIR is really useful to create apps for desktop/ios/android.

– haXe, I’m following strongly haXe & nme activities. haXe may be the next programming language that we should learn, but the market isn’t ready : I can’t find any jobs which request strong haXe skills. And it’s not a junior developer who will impose his method.

Hiddenwwod, like haXe HiddenWood sounds very interesting… but the same doubts here.

Unity3D, I’m very interesting in Unity… but what will happen if in 2 years a good 3D game editors made with HTML5/CSS/JS is out? And I’m sure that there will be one.

– Java & Android, today was my last training day on this, it was great & fun to work (fight? ;-) ) again with Java. However I don’t feel really comfortable with it, and I’ve just bought an iPhone 4S, so…

– Objective-C & iOS, finally I will learn Objective-C. I know it’s really not the most beautiful programming language, but it’s an old one. I know it isn’t request for simple apps (air or html apps are great), but I’m interested in games. So after some days on this language, I will learn Sparrow Game Framework or Cocos 2D Game Framework, maybe Cocos 2D because it doesn’t simulate the flash displaylist/API like the other one. Even if it will be harder, I think it is better to learn a new language : start from scratch and learn language specificity.

To conclude here is my roadmap for 2012 :
– keep playing with flash (hey I’m an CitrusEngine’s official contributor now, cool stuff in preparation) & air.
– keep an eye on HTML/CSS/JS… my point of view might change (keep an opened mind!).
– learn Objective-C and made some cool apps & games!
– keep an eye on haXe and HiddenWood.

AIR is ready for AS3 developers and some new cool stuff is arriving (stage 3d), but it could not be as good as native apps. However haXe & HiddenWood seems to be, but it’s not easy to find a job with those skills.
So continue to improve your skills on what you love, keep an eye on your “old” job, learn strong language like Objective-C / Java, and be ready for cross platform compilation framework / language.
Finally future is really exciting!

And you, what do you think ?

Rugby game, AS3 – CE – haXe versions

Two weeks ago at school we made a simple rugby game with graphics provided.
I take this opportunity to compare how I develop the game if I use different framewok :

– in AS3 with linked list and object pooling (refers to this previous tutorial). Obviously it is a little game, and we don’t need complex optimization, but that was a good implementation exercice. Moreover I’ve updated my class ;-)

– with the Citrus Engine, managing Box2D. It was not easy to handle physics to have the same result that the basic AS3 version, and actually it is not the same (there is some inertia), but I really like how Box2d handle collision. We can manage before collision, the beginning and the ending. It is really more precise than a hitTestObject. Moreover we can separate art from physic body, and so change easily the “collision box”.

– last night, with lbineau we made a programming evening around haXe (and some beers :) ). The idea was really simple : make the same game, using existing AS3 classes with haXe. I have already given a chance to haXe previously and saw how powerful it is. This time, I see how easy it is to use previous AS3 code. I didn’t rewrite my Opponent and Player class! And I used the fla to link graphics without any trouble! However I’m a bit disappointed : I used most of the time original AS3 objects instead of haXe primary objects. What I need right now is FDT5 with its full haXe support! Can’t wait for it… Oh! If you’re interesting by haXe, you should take a look on NME, it seems to be amazing.

The zip with the three versions.