Tag Archive for 'as3'

Page 2 of 3

Speedcoding

It is really fun to watch speedpainting videos. Why did nobody do the same thing using Flash? Here is my contribution. A particle explosion in one and a half minute. The video has been speeded up by a factor of ten. The result is not very interesting but maybe someone will pick it up and do something a little bit more beautiful to watch.

Update: Original source is available here. Remember that this was written in 15 minutes total so it is not very clean or optimized. For instance the Explosion object will stay in memory all the time.

Jens’ AS3 workflow special

If you understand German I would strongly recommend you to read the article series about AS3 development at the blog of Jens Franke. Jens is about to release around 10 to 15 posts in the next two weeks in his special.

And reading is not only worthwhile for your own knowledge. There will be a raffle at the end. Prices include a full copy of FDT3.0, four FDT3.0 discount keys and five books from O’Rielly. All in all a very nice idea from Jens.

Converting a Number to 4 bytes and vice versa

For the hell of it I wanted to implement the fast inverse square-root that has been flying around in the Quake3 source-code for instance. Fantastic game by the way. There has been quiet a lot of talk about this algorithm. So can we do that with Flash? No we can not. It would be nice but it is simply not possible because you can not just map a Number into an int. With languages like C++ you can. So first of all: I found already an approach that is very fast but not as nearly as good as the original algorithm. It is also not the same “magic”. It is just some newton iterations and faster but worse then 1/Math.sqrt(x).

So what do you need to implement the original inverse square root algorithm? A way to convert any number to its four byte representation aka the way it is stored in memory. The original algorithm is freakin fast because it does not have to calculate the four bytes. It can just juggle with them. Since we have to insert some heavy math here our approach will always be slower but it helped me understanding IEEE single precision numbers a lot. Maybe anyone has a use for this?

Remember the isqrt function is WAY slower than doing 1/Math.sqrt(x)!

[as]private function isqrt( x: Number ): Number
{
var xhalf: Number = x * 0.5;
var i: int = toFloat( x );
i = 0x5f3759df – ( i >> 1 ); // the magic first guess
x = toNumber( uint(i) );
x = x * ( 1.5 – xhalf * x * x );
return x;
}

private function toNumber( x: uint ): Number
{
//– precheck here
if ( 0xffc00000 == x )
{
return NaN;
}
else
if ( 0x7f800000 == x )
{
return Number.POSITIVE_INFINITY;
}
else
if ( 0xff800000 == x )
{
return Number.NEGATIVE_INFINITY;
}

//– can not shift because flash doesnt like it…
var v: Boolean = uint( x & uint(0×80000000) ) == uint(0×80000000);
var e: int = ( uint( x >> uint(23) ) & 0xff ) – 127;
var m: int = x & 0x7fffff;
var n: Number;

//– if e > 0 we can do 2^e very easy by shifting it
//– otherwise we do 1/(2^e) and 2^e can be achieved by shifting it
if ( e > 0 )
{
n = ( 1 + m / ( 1 << 23 ) ) * ( 1 << e );
}
else
{
n = ( 1 + m / ( 1 << 23 ) ) * ( 1 / ( 1 << -e ) );
}

if ( v )
{
return -n;
}

return n;
}

private function toFloat( x: Number ): uint
{
//-- do a quick precheck
if ( Number.POSITIVE_INFINITY == x )
{
return 0x7f800000;
}
else
if ( Number.NEGATIVE_INFINITY == x )
{
return 0xff800000;
}
else
if ( isNaN( x ) )
{
return 0xffc00000;
}

//-- calculate ieee single precision
var v: Boolean, e0: int, e1: int, m: int;
var f: Boolean = x > 0;

if ( x > 0 )
{
e0 = int( Math.log( x ) / Math.LN2 );
m = ( ( x / ( 1 << e0 ) ) - 1 ) * ( 1 << 23 );
}
else
{
v = true;
e0 = int( Math.log( -x ) / Math.LN2 );
m = ( ( -x / ( 1 << e0 ) ) - 1 ) * ( 1 << 23 );
}

e1 = e0 + 127;

//-- usually here would go the test for e1 = 0x00 or e1 = 0xff
//-- BUT we tested already and that's why we do not do it here

//-- be save
e1 &= 0xff;
m &= 0x7fffff;

//-- merge into 4bytes
var float: uint;

if ( v )
{
float = 0x80000000;
}

float |= e1 << 23;
float |= m;

return float;
}[/as]

Flash Strandbeest

Some weeks ago Marc Thiele showed me a link that was about the kinetic sculptures from Theo Jansen. If you do not know about him yet check out strandbeest.com. There are a couple of videos on YouTube describing the technique behind those sculptures (click me).

Now I just saw a demo from APE which has that model built in Flash using their engine. So lovely!

Lists faster than Array

Since we are planing to release a detailed paper about AS3 optimizations and techniques I was thinking about another optimization for one of the daily problems. Looping through an array that contains objects. The fastest code to do this is

[as]for (;i {
v0 = array[i];
l = v0.length;
}[/as]

v0 is a local variable for my custom class which looks like this

[as]class Vector3D
{
public var x: Number;
public var y: Number;
public var z: Number;

public function Vector3D( x: Number, y: Number, z: Number )
{
this.x = x;
this.y = y;
this.z = z;
}

public function get length(): Number
{
return Math.sqrt( x * x + y * y + z * z );
}
}[/as]

Looks like from a real scenario. You can replace the vector class also with a particle class or whatever. It does not matter. The point is this loop takes 272ms for 1000000 iterations. It is pretty good already but if you add one more parameter to the Vector3D class you can get even faster. This is my modified Vector3D called LVector3D

[as]class LVector3D
{
public var x: Number;
public var y: Number;
public var z: Number;

public var next: LVector3D;

public function LVector3D( x: Number, y: Number, z: Number )
{
this.x = x;
this.y = y;
this.z = z;
}

public function get length(): Number
{
return Math.sqrt( x * x + y * y + z * z );
}
}[/as]

There is a public variable now called next. This variable will always point to the next LVector3D object. The exact same loop takes about 260ms.

[as]var v0: LVector3D = start;
for (;i {
l = v0.length;
v0 = v0.next;
}[/as]

You see how nice this looks? No ugly [] etc. Our variable is directly typed. And we can speed it up even more! If we replace the for(...) part with while( v0 ) it goes down to 249ms. What is also nice about a linked list is that you could add an easy splice functionality or functions to remove elemts from a list. You just have to change the next reference. If you also add a prev variable it becomes even more easy and you could loop backwards.

Building that list of vectors is also very easy. And it looks beautiful. Compare this

[as]for ( var i: int = 0; i < n; ++i )
array[ i ] = new Vector3D( i, i, i );

var v3d: LVector3D = start;

for ( var j: int = 1; j < n; j++ )
v3d = v3d.next = new LVector3D( j, j, j );[/as]

The start variable is defined in the class as private const vector3d: LVector3D = new LVector3D( 0, 0, 0 );. Very nice. Of course not useful in every case but sometimes if you have to squeeze out what is possible here is another method. So stay tuned for our paper.

Run-time file uploads

Very useful. Including source-code for real file uploads with run-time generated content.

AS3 Proxy Example

Some people have problems with the migration from AS2 to AS3. First of all. This post will not help you to migrate. Also using the stuff here is bad. I just thought I can share some idea I had and make nice use of the Proxy class you have with AS3. Why is it bad? It will make your project run slower.

First of all. What can you do with Proxy? The proxy is defined as a dynamic class and it allows you to override any method and also the “delete” operator for instance. Back to the problem: Someone said “why can I not use clip0.clip1.clip2” any longer. Another friend told me it took him some time to figure out he has to use getChildByName( 'clip0' ).getChildByName( 'clip1' ).getChildByName( 'clip2' ). By making use of the Proxy class we can give this possibility back to the users.

Since I am a nice guy I added also _x, _y, _xscale and _yscale. Now how to do that? You define a proxy that holds a Sprite object (actually… not really. More on that later). Then you have to override a lot of methods like this:

[as]flash_proxy override function getProperty( name: * ): *
{
if ( sprite.hasOwnProperty( name.toString() ) )
{
return sprite[ name.toString() ];
}
else
{
var displayObject: DisplayObject = sprite.getChildByName( name.toString() );
return ( displayObject is AS2SpriteHandle ) ? ( displayObject as AS2SpriteHandle ).handler : displayObject;
}
}[/as]

This may look a little bit fancy for the first time but what do we do? We check if the Sprite object already has that property. If so we return it. Otherwise we return the child of that sprite. Now you see that I check if the DisplayObject is a AS2SpriteHandle. That is the instance the AS2Sprite (our Proxy) stores. Because it keeps a reference back to its AS2Sprite object we can return the AS2Sprite object. If we return only Sprite we could do a.b but not a.b.c because for b we would return just Sprite and lose therefore the ability to add c just as a property.

This is important. The class AS2Sprite extends Proxy and not Sprite. Therefore I added some functions like toSprite() etc. Have a look. Examples help me often the most. And if you are a lazy guy that does not really want to bother with the AS3 syntax you might find this helpful as well.

Some example code what you can do with it:
[as]var sprite: AS2Sprite = new AS2Sprite;
addChild( sprite.toSprite() );//doh! default app is still sprite :(

sprite.clip = new AS2Sprite;

sprite.graphics.beginFill( 0xff0000, 1 );
sprite.graphics.drawCircle( 0, 0, 10 );
sprite.graphics.endFill();
sprite._x = 10;
sprite._y = 10;

sprite.clip.graphics.beginFill( 0x00ff00, 1 );
sprite.clip.graphics.drawCircle( 0, 0, 10 );
sprite.clip.graphics.endFill();
sprite.clip._x = 50;
sprite.clip._y = 50;

sprite.clip.clip2 = new AS2Sprite;
sprite.clip.clip2.graphics.beginFill( 0x0000ff, 1 );
sprite.clip.clip2.graphics.drawCircle( 0, 0, 10 );
sprite.clip.clip2.graphics.endFill();
sprite.clip.clip2._x = 50;
sprite.clip.clip2._y = 50;

delete sprite.clip.clip2;//remove the blue one[/as]

A hint of true overloading

This morning I came across some strange sort-of overload workaround that can cast your class to any type. Imagine you want to have a reference to a boolean. You have to “box” it then. It look like this:

[as]class BoxedBoolean
{
private var value: Boolean;

public function BoxedBoolean( value: Boolean )
{
this.value = value;
}
}[/as]

Now doing something like if ( boxedBoolean == true ) is not possible since boxedBoolean is type BoxedBoolean. Even though the value we want to use is a boolean value. So here is the workaround:

[as]class BoxedBoolean
{
private var value: Boolean;

public function BoxedBoolean( value: Boolean )
{
this.value = value;
}

public function toString(): Boolean
{
return value;
}
}[/as]

Do not ask me what strange nature toString() has but it works. Now the only problem with this is that if ( a == true ) works fine but if ( a ) is always true.

Here is an example

[as]var b0: BoxedBoolean = new BoxedBoolean( true );
var b1: BoxedBoolean = new BoxedBoolean( false );

trace( b0 is Boolean );
trace( b1 is Boolean );

trace( b0 );
trace( b1 );

if ( b0 == true )
trace( ‘b0 = true’ );
else
trace( ‘b0 = false’ );

if ( b1 == true )
trace( ‘b1 = true’ );
else
trace( ‘b1 = false’ );[/as]

The trace output is then

false
false
true
false
b0 = true
b1 = false

If you remove the == true you will get that both b0 and b1 are true. I do not think that there is much use for it but it is interesting what you can do. toString() can also return an integer and it works as well.

How high can you get?

:o)Actually this frame-rate is not faked. It is not the actual screen refresh rate. This means you do not have 65.000 new screens during one second, but, and that is the funny thing: you have 65.000 executions of a function in one second. This is an evil hack and slows down the whole display stuff of Flash. So you can not use this in any of your projects but it is funny to watch. I think you can get higher, I was just lazy and got tired searching for the best settings.

So there is no use for this. Just fun to watch :)

By the way the initial idea came from André Michelle. The competition is open, ha! How high can you get?

Looking up the calling function

Ralf Bokelberk had a nice idea about how to get dynamically to the function name of the calling function. This may sound a little bit wired, but if you do debugging it is nice to do something like Logger.add( 'log this infomration', ... ); and then have the output with the calling function (and maybe line number).
For instance something like com.test.package::Class/function(): log this information.

Now the solution Ralf had is throwing an error and get to the whole stuff by using the stack trace. This works pretty well. In debug mode you can also send line-numbers and file information to your log output which is very nice.

[as]var stackTrace: String;

try { throw new Error(); }
catch ( e: Error ) { stackTrace = e.getStackTrace(); }

var lines: Array = stackTrace.split( “\n” );
var isDebug: Boolean = ( lines[ int( 1 ) ] as String ).indexOf( ‘[' ) != int( -1 );

var path: String;
var line: int = -1;

if ( isDebug )
{
var regex: RegExp = /at\x20(.+?)\[(.+?)\]/i;
var matches: Array = regex.exec( lines[ int( 2 ) ] );

path = matches[ int( 1 ) ];

//file:line = matches[2]
line = matches[ int( 2 ) ].split( ‘:’ )[ int( 2 ) ];//windows == 2 because of drive:\
}
else
{
path = ( lines[ int( 2 ) ] as String ).substring( 4 );
}

msg = path + ( line != -1 ? ‘[' + line.toString() + ']‘ : ” ) + ‘: ‘ + msg;[/as]