Showing posts with label haxe. Show all posts
Showing posts with label haxe. Show all posts

Tuesday, August 3, 2010

kit-kat-toe: mochiads with haxe

I recently tried out Viktor Hesselbom Haxe Instructions for MochiAds and they work just fine.

Something like this...

% wget https://www.mochimedia.com/dl/MochiAPI_v3_8.zip
% unzip MochiAPI_v3_8.zip
% cd MochiAPI_v3_8
% mkdir -p foo/mochi
% cp -r mochi/as3 foo/mochi
% cd foo
% compc -source-path . -output mochi.swc -include-sources .
% unzip mochi.swc library.swf
% haxe --gen-hx-classes library.swf


Then just get the game id from the nice folks over at mochi and jam in the little bit of ad code.

One problem I had was that I found I needed to add a new MovieClip to the flash.Lib.current, use that for the ad and remove it in the ad_finished callback.

I had some mixed luck with swfmill... The old version I had (0.2.12) didn't complain about the mp3 I having the wrong bitrate... But when I linked against the -swf-lib from the new version it produced a blank swf!

So... I have no sound...

LOL... it is a very silly proof of concept... check it out

I call it kit-tac-toe

gory swfmill detail



To compile swfmill under Hardy Heron (I know... it's old)... I had to modify swfmill.c and add: extern char *xslt_simple;

And it still didn't work... I may try to use a newer box to see if my horked environment is why it didn't work right....

Here is the handy message I got from it...

Sampling rate: 32000
Error: Flash only supports sampling rates of 44100, 22050 and 11025 Hz
WARNING: MP3 file sounds/cats/meow.mp3 has a wrong sampling rate

Monday, March 23, 2009

feelin' randy!

Shuffle! Chaos! Randomness! Surprise me! How many times... have you wanted to:
  • shuffle a list of mp3 to pass to mplayer
  • randomize a list of background images to eog
  • pick a random file from a directory
Once or twice? OK! These can all be boiled down to reading in lines from stdout, mixing 'em up and spewing them back out in a random order.

Check out this tiny haxe program called randy. It's self compiling:
% wget http://brianin3d-misc.googlecode.com/svn/trunk/random/haxe/Randy.hx
% chmod 755 Randy.hx
% ./Randy.hx
% echo -e "1\n2\n3" | ./randy
1
3
2

I wrote it just 4u!

Sunday, March 8, 2009

UpperCamel: compiling haxe to a native executable

UpperCamel is a little program for going back and forth between
camel case and underlined uppercase.

Typically camel case is used for class names, variables, and method names.

Whereas underlined uppercase is used for constants, statics, etc.
     Sample Input     | Sample Output
------------------+-------------------
UpperCamel | UPPER_CAMEL
ThisIsNeatoEh | THIS_IS_NEATO_EH
UPPER_CAMEL | upperCamel
MIX-and-Match | mixAndMatch

Somewhat useful... The main point is to show how to compile haxe to create a native executable:
% haxe -main UpperCamel -neko upperCamel.n
% nekotools boot upperCamel.n
% echo hello_world | ./upperCamel
helloWorld

Neat, huh?
% file upperCamel
upperCamel: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.6.8, dynamically linked (uses shared libs), stripped
% ldd upperCamel
linux-gate.so.1 => (0x4001a000)
libneko.so => /usr/lib/libneko.so (0x4002e000)
libpthread.so.0 => /lib/libpthread.so.0 (0x4004d000)
libc.so.6 => /lib/libc.so.6 (0x40065000)
libdl.so.2 => /lib/libdl.so.2 (0x401a8000)
libgc.so.1 => /usr/lib/libgc.so.1 (0x401ad000)
libm.so.6 => /lib/libm.so.6 (0x401e1000)
/lib/ld-linux.so.2 (0x40000000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x40207000)

The code for UpperCamel.hx has a bit of shell script which makes it easy to compile for Unix-env type folks:
% wget http://brianin3d-misc.googlecode.com/svn/trunk/UpperCamel/UpperCamel.hx
% chmod 755 UpperCamel.hx
% ./UpperCamel.hx
% file ./upperCamel
./upperCamel: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.6.8, dynamically linked (uses shared libs), stripped

Haxe to binary executable is a nice path for whipping up custom commands when you need them with a really low price of admission!

Go, Haxe!

Tuesday, February 17, 2009

ppm is a developer's best friend!

OK, that is a crazy overstatement, but it is pretty useful bit to know about.

So what is it? It's a baby-simple image format. Let's say we wanted to write out a 320x240 image. The file would look something like:

P6
320 240
255
{ONE CHARACTER PER R/G/B FOR EACH PIXEL}

So... if the first pixel was black (0x000000), we would write 0, 0, followed by zero. Whereas if it were (0xFFAADD) we'd cleverly write 0xFF, 0xAA, 0xDD.

Ya dig it? Here is a snippet from TextHash2Ppm.hx after I loaded the text file into an array of strings called (creatively enuff) "lines":

out.writeString( 'P6\n' );
out.writeString( lines[ 0 ].length + ' ' + lines.length + '\n' );
out.writeString( '255\n' );

for ( line in lines ) {
for ( i in 0 ... line.length ) {
var char = line.charAt( i ) ;
var value = if ( '#' == char ) 255; else 0;
out.writeByte( value );
out.writeByte( value );
out.writeByte( value );
}
}

Here is a bit I wrote recently to show files like sample_dungeon.txt to
sample_dungeon.ppm which I then converted to

Which I can then use as input to this heightmap viewer even though it looks wonky as heck.

PPM is a handy format for when you need to create images and you don't have or don't want to use an image library to create jpgs, pngs, etc...

Monday, February 9, 2009

bitmap'n it!

So... Like a lot of folks, I've always been really fascinated with bitmap type effects. They're a lot of fun to watch and pretty easy to write.

I collected together a set of small demos of some classic bitmap effects.

Franticly clicking on the demo will reset the current effect and eventually enable you to press the keys to access the different effects:
  1. pixel average: this kooky bit manipulation creates bizarre plasma effects (be patient!)
  2. clouds: different clouds and cloud like effects
  3. hough: use a hough transfer to create trippy sine waves from partial lines
  4. bump: ye olde bumpmap effect using displacement maps from the other demos

See it in action!

Wednesday, January 21, 2009

refactoring safety net

I recently started porting and collecting some code for doing various sorts of intersection, or collision, tests in haxe.

At the moment, it is pretty limited with ray/triangle and ray/sphere tests.

The first test I ported was based on based on "Fast, Minimum Storage Ray / Triangle Intersection" by Tomas Möller and Ben Trumbore and ported directly from the copy of the code on here.

The results documented in the paper are pretty impressive and having source code certainly made it an easy win, but some aspects of the code concern me:
  • points are represented as arrays, perhaps not very efficient in haxe
  • the code has multiple returns points, can't be inlined in haxe

I want to refactor the code to be as efficient as possible because this is likely to be the innermost loop of particle simulation routines, etc, but I don't want to break the implementation.

Enter the test case.

My initial testcase generated 1000 random triangles and rays and tested the culling and non-culling version of the algorithm.

All well and good, but not good enuff for refactoring since I need to make sure the same inputs produce the same outputs before and after my changes.

So... I put in some trace commands to produce xml like so:
<hit non_hit="1" cul_hit="1" t="0.5373583852">
<v0 x="0.6581358404" y="0.1374191698" z="0.9648343668" />
<v1 x="0.308879062" y="0.6053369969" z="0.3154988046" />
<v2 x="0.8667143827" y="0.1228679823" z="0.3068826511" />
<src x="0.1215154344" y="0.2182366329" z="0.4350455069" />
<dir x="0.7023522276" y="0.3298090568" z="0.1063413928" />
</hit>

Now I can verify that the same input produces the same output.

My test looks like this now:
public function testCanned() {  
var count = 0;
var tests =
loadTriangles();

for ( i in 0 ... 50 ) {
for ( test in tests ) {
verifyTriangle( test );
count++;
}
}
var stopTime = Date.now();
var diff = ( stopTime.getTime() - startTime.getTime() ) / 1000.0;

trace( count + ' tests / ' + diff + 's = ' + ( count / diff ) + ' tests/s' );
}


After a few test runs, the initial numbers look like:
AppTest.hx:99: 459600 tests / 32s = 14362.5 tests/s
AppTest.hx:99: 459600 tests / 36s = 12766.66667 tests/s
AppTest.hx:99: 459600 tests / 35s = 13131.42857 tests/s
AppTest.hx:99: 459600 tests / 35s = 13131.42857 tests/s
AppTest.hx:99: 459600 tests / 36s = 12766.66667 tests/s

So... it averages out to around 13231.738096 tests/s

My first refactoring was to use a "result" variable and some branching to only have a single return point so I can use the inline function modified:
AppTest.hx:99: 459600 tests / 31s = 14825.80645 tests/s
AppTest.hx:99: 459600 tests / 31s = 14825.80645 tests/s
AppTest.hx:99: 459600 tests / 31s = 14825.80645 tests/s
AppTest.hx:99: 459600 tests / 32s = 14362.5 tests/s
AppTest.hx:99: 459600 tests / 31s = 14825.80645 tests/s

For an average of around: 14733.145160 tests/s

This comes to 14733.145160/13231.738096 = 1.11347013167180814489 , for an 11% speedup just from this trivial change.

From some earlier work, I saw that an optimized point class could be significantly faster than a typedef, some additional tests (unpublished) show that using arrays to represent points was about 4x slower than typedefs!

The next refactoring will be to use this "InlinePoint" class

AppTest.hx:101: 459600 tests / 18s = 25533.33333 tests/s
AppTest.hx:101: 459600 tests / 17s = 27035.29412 tests/s
AppTest.hx:101: 459600 tests / 17s = 27035.29412 tests/s
AppTest.hx:101: 459600 tests / 17s = 27035.29412 tests/s
AppTest.hx:101: 459600 tests / 18s = 25533.33333 tests/s

Average is 26434.509804. 26434.509804/13231.738096 = 1.99781084028493908605.

Damn! Of course it comes at the cost of a new type, but still.

So pretty, happy, but still a little concerned about this:
var edge1 = threePt();
var edge2 = threePt();
var tvec = threePt();
var pvec = threePt();
var qvec = threePt();

That's a lot of memory allocation madness... One optimization I tried was to move the declarations to where they are actually used... not much difference...

What about passing in a workspace? This bumped up to 28725 for an improvement of 8%, but doesn't really seem worth the bother.

So that's the good news... now the bad news...
ERR: AppTest.hx:48(tests.AppTest.randomTriangle) - expected '-0.206685315' but was '0.4077964499'

Happily, it turned out to be a red herring from the refactoring of the test itself:
assertEquals( cul.x, non.y );

should have been (and now is)
assertEquals( cul.x, non.x );

Nutty!

Tuesday, January 6, 2009

stickman physaxe

So I was reading about physaxe 1.2 and thought it would be fun to have some more stickman action leveraging it.

The demo I throw together is mostly from code ripped off from the original post and little bit of stuff to make the "springs":

Move the mouse around to move gravity and click anywere to add some junk:



Usage is something like this:

var a = body( 50, 40 );
var b = body( 50, 140 );
var j = new DistanceJoint( a, b );

world.addBody( a );
world.addBody( b );
world.addJoint( j );


It is not integrated into the physaxe code right, cuz I had to loop over my joints when I stepped the world.

The interesting piece of the "DistanceJoint" look like this:

public override function preStep( invDt : Float ) {
var currentDistance = dist( b1, b2 );
if ( 0 != currentDistance ) {

var diff = ( currentDistance - this.distance ) / currentDistance;
var xdiff = ( b2.x - b1.x ) * diff;
var ydiff = ( b2.y - b1.y ) * diff;

b1.v.x += xdiff * 0.5;
b2.v.x -= xdiff * 0.5;

b1.v.y += ydiff * 0.5;
b2.v.y -= ydiff * 0.5;
}
}


It doesn't take into account the relative mass of the bodies but that should be pretty straight forward.

It should be enough for stickmen, cloth, strings, etc.

If you are interested, you can find the code here.

Friday, January 2, 2009

segmented flowers

So... let me start off a little differently by saying: I'm not really all that thrilled with how this came out.

The basic idea was to model plants, flowers, as vertlet-based segments using distances constraints for each segment. In order to keep the plants upright, I added a new a "height constraint" to keep each vertlet a certain amount above the ground.

Additionally I rooted each plant's base point so it wouldn't wander off.

Next, I added rain by modeling each drop as a vertlet and testing it's previous and current coordinates again each segment (see below)

Here are the results:


You can click to toggle the rain. I think it might be improved using a better design for the plants (eg: that branching tree algorithm).

This partially scratched the itch I had to model dynamic plants, but not quite... Hopefully I'll turn up some more information on how to do properly at some point.

I think angular constraints might work...

Anyway, if you are interested, the code is available for whatever you like.

2d line intersection test

Once upon a time, long, long ago... I wanted to find out where 2 line segments intersected in 2d.

I played with rise over run and all that dumb crap till I finally found somebuddy who had the math-magic I was looking for.

Here it is translated to haxe:

public static function intersectionTime(
line_0_x0:Float, line_0_y0:Float, line_0_x1:Float, line_0_y1:Float
, line_1_x0:Float, line_1_y0:Float, line_1_x1:Float, line_1_y1:Float
) {
var line_0_xdiff = line_0_x1 - line_0_x0;
var line_0_ydiff = line_0_y1 - line_0_y0;

var line_1_xdiff = line_1_x1 - line_1_x0;
var line_1_ydiff = line_1_y1 - line_1_y0;

var line_1_normal_x = line_1_ydiff;
var line_1_normal_y = -line_1_xdiff;
var l2 = (
line_1_normal_x * line_1_normal_x
+
line_1_normal_y * line_1_normal_y
);
if ( 0 != l2 ) {
l2 = Math.sqrt( l2 );
line_1_normal_x /= l2;
line_1_normal_y /= l2;
}

var denominator = (
-line_1_normal_x * line_0_xdiff
-line_1_normal_y * line_0_ydiff
);

var t = -1.0;
if ( 0 != denominator ) {
var numerator = ( 0
+ line_1_normal_x * ( line_0_x0 - line_1_x0 )
+ line_1_normal_y * ( line_0_y0 - line_1_y0 )
);
t = numerator / denominator;
}
return t;
}


I'm sure you can find some explanation of what it does and why it works, but sometimes... don't you just wanna rip off code?

"So what's the deal?" you ask? Fair enuff. You pass it the end points for two line segments and it returns where along the first segment the intersection would occur (-1 means never, sorry).

If it is between 0 and 1, that means it occurred some where along the first segment.

If you want to see if the intersection (or collision) occurred on both segments, you can then call with the segment orders reversed to see where on the other segment it hit ala:

var t_0 = App.intersectionTime(
line_0_x0, line_0_y0, line_0_x1, line_0_y1
,
line_1_x0, line_1_y0, line_1_x1, line_1_y1
);
var t_1 = App.intersectionTime(
line_1_x0, line_1_y0, line_1_x1, line_1_y1
,
line_0_x0, line_0_y0, line_0_x1, line_0_y1
);

var hit_on_0 = ( t_0 >= 0 && t_0 <= 1 );
var hit_on_1 = ( t_1 >= 0 && t_1 <= 1 );
var real_hit = hit_on_0 && hit_on_1;

var x = line_0_x0 + ( line_0_x1 - line_0_x0 ) * t_0;
var y = line_0_y0 + ( line_0_y1 - line_0_y0 ) * t_0;


Note if "real_hit" is true then x,y will be the coordinates for the actual intersection, otherwise it is where it would have hit on the first line (line_0).

Here you can see it in action.

Grab the code here and look at

./us/versus/them/weeds/App.hx
./us/versus/them/weeds/LineTest.hx


It's not the most optimized way to do things since there is some duplicated computation, but I know you don't wan me to have all the fun!

BTW.... does anyone know when/why these google turkeys stopped allowing the embed tag? Sheesh... Numbskulls! Yes... I am looking it in the mouth...

Monday, December 15, 2008

a point in haxe: inline ftw!

A while back, I talked about how delineating between structures and objects could have some performance implications.

Since then I have periodically doubted the conclusions I drew from my observations. My results still indicate that for Java with the JVM I used, structuring the code into a point structure and implementing the operations as a collection of static operators does make for a significant performance increase.

What I came to doubt was the universality of this observation.

Specifically, I wanted to see if this design methodology also payed off with haxe or if it was more of a JVM implementation artifact.

To test it, I wrote 3 different implementation of a "point" class:


typedef TypedPoint = {
public var x : Float;
public var y : Float;
public var z : Float;
}
class TypedPointOps {
public inline static function add( dest:TypedPoint, a:TypedPoint, b:TypedPoint ) : TypedPoint {
dest.x = a.x + b.x;
dest.y = a.y + b.y;
dest.z = a.z + b.z;
return dest;
}
}



class Point {
public var x : Float;
public var y : Float;
public var z : Float;

public function new( ?x:Float, ?y:Float, ?z:Float ) {
this.assign( x, y, z );
}

public function assign( ?x:Float, ?y:Float, ?z:Float ) : Point {
this.x = x;
this.y = y;
this.z = z;
return this;
}

public function add( a:Point, b:Point ) : Point {
this.x = a.x + b.x;
this.y = a.y + b.y;
this.z = a.z + b.z;
return this;
}
}



I wrote another version called "InlinePoint" which is just like "Point", but used the "inline" keyword.

Here is the result:




It basicly "adds" two points together 1 million times.

Here is the breakdown:

point : 0.019s
inline : 0.010s
typed : 1.355s


As you can see, the object version using the "inline" keyword is extremely fast compared to the alternatives.

In testing, I used the neato flashplayer command line tool that came as part of the Adobe Flex Builder Linux Public Alpha


% flashplayer pointsDemo.swf


For some reason it shows the "point" time as "0.149s"... weird... The "typed" time was also pretty different... eh...

So... why did I bother? Now I know I can port my JS 3D library straight to haxe without any major refactoring! :-D

Monday, November 17, 2008

haxe: bresenham's line drawing algorithm

Here is quick port I did of Bresenham's famous line drawing algorigthm I did in haxe

public function bresenhamInt(
bitmapData : BitmapData
, x0 : Int
, y0 : Int
, x1 : Int
, y1 : Int
, c : UInt
) {
var steep : Bool = Math.abs( y1 - y0 ) > Math.abs( x1 - x0 );
var tmp : Int;
if ( steep ) {
// swap x and y
tmp = x0; x0 = y0; y0 = tmp; // swap x0 and y0
tmp = x1; x1 = y1; y1 = tmp; // swap x1 and y1
}
if ( x0 > x1 ) {
// make sure x0 < x1
tmp = x0; x0 = x1; x1 = tmp; // swap x0 and x1
tmp = y0; y0 = y1; y1 = tmp; // swap y0 and y1
}
var deltax : Int = x1 - x0;
var deltay : Int = Math.floor( Math.abs( y1 - y0 ) );
var error : Int = Math.floor( deltax / 2 ); // this is a little hairy
var y : Int = y0;
var ystep : Int = if ( y0 < y1 ) 1 else -1;
for ( x in x0 ... x1 ) {
if ( steep ) {
bitmapData.setPixel( y, x, c ) ;
} else {
bitmapData.setPixel( x, y, c );
}
error -= deltay;
if ( error < 0 ) {
y = y + ystep;
error = error + deltax;
}
}
}

The pseudo code on wiki pedia made it pretty painless.

Here is a little demo comparing a really crappy floating point version I did, the above and a version like the one show, but using floating point.



It draws 20k lines, so it takes it a few seconds depending on yer rig.

You can find the source code here.