Click to See Complete Forum and Search --> : Bresenham's Algorithm


KostyaB
September 24th, 2005, 01:59 PM
When I wrote this algorithm for a slope of 1 >= m >= -1 it worked fine, but when I added the first if else block to work with steeper slopes it doesn't work properly. I'm pretty sure its my handling of stepping over x instead y or the placement of the if else block.

Thanks for any advice.

void doBresenham( int x1, int y1, int x2, int y2 )
{
int mSlope, increaseSameY, increaseNewY, increaseSameX, increaseNewX;
int dX, dY, p, x, y;

if (x1 > x2)
{
doBresenham(x2, y2, x1, y1);
return;
}

dX = x2 - x1;
dY = y2 - y1;

if ( (dY/dX) <= 1.0 && (dY/dX) >= -1.0 ) {

if (dY < 0) {
dY = -dY;
mSlope = -1.0;
}
else {
mSlope = 1.0;
}

increaseSameY = 2 * dY;
increaseNewY = 2 * dY - 2 * dX;
p = 2 * dY - dX;
y = y1;

for (x = x1; x <= x2; x++)
{
glVertex2i( x, y );
if (p < 0)
{
p += increaseSameY;
}
else
{
p += increaseNewY;
y += mSlope;
}
}

}
else {

if (dX < 0) {
dX = -dX;
mSlope = -1.0;
}
else {
mSlope = 1.0;
}

increaseSameX = 2 * dX;
increaseNewX = 2 * dX - 2 * dY;
p = 2 * dX - dY;
x = x1;

for (y = y1; y <= y2; y++)
{
glVertex2i( x, y );
if (p < 0)
{
p += increaseSameX;
}
else
{
p += increaseNewX;
x += mSlope;
}
}
}

}

cilu
September 24th, 2005, 02:50 PM
What does it mean "it does not work properly"? Have you ran it in debugger and watch the values of the variables?

cilu
September 24th, 2005, 02:52 PM
[ moved thread ]