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.

No comments:

Post a Comment