Skip to content

Instantly share code, notes, and snippets.

@ErisianArchitect
Created September 1, 2012 01:54
Show Gist options
  • Save ErisianArchitect/3562620 to your computer and use it in GitHub Desktop.
Save ErisianArchitect/3562620 to your computer and use it in GitHub Desktop.
Bresenham Line 2D
public static void DoLine(int startX, int startY, int endX, int endY, Action<int, int> callback)
{
int dx, dy;
int sx, sy;
int accum;//accumilator
dx = endX - startX;//Start X subtracted from End X
dy = endY - startY;
sx = ((dx) < 0 ? -1 : ((dx) > 0 ? 1 : 0));//if dx is less than 0, sx = -1; otherwise if dx is greater than 0, sx = 1; otherwise sx = 0
sy = ((dy) < 0 ? -1 : ((dy) > 0 ? 1 : 0));
//dx = (dx < 0 ? -dx : dx);//if dx is less than 0, dx = -dx (becomes positive), otherwise nothing changes
dx = Math.Abs(dx);//Absolute value
//dy = (dy < 0 ? -dy : dy);
dy = Math.Abs(dy);
endX += sx;//Add sx to End X
endY += sy;
//x = 6
//y = 5
//accum = 3
//accum - 5 = 1
//startx + 1 = 1
//accum - 5 = -4
//accum + 6 = 2
//startY + 1 = 1
if (dx > dy)//if dx is greater than dy
{
accum = dx >> 1;//Accumilator = dx / 2
do
{
//Plot point
callback(startX, startY);
//Subtract dy from accumilator
accum -= dy;
//if accumilator is less than 0
if (accum < 0)
{
//Add dx to accumilator
accum += dx;
//Add sy to Start Y
startY += sy;
}
//Add sx to Start X
startX += sx;
} while (startX != endX);
}
else
{
accum = dy >> 1;
do
{
callback(startX, startY);
accum -= dx;
if (accum < 0)
{
accum += dy;
startX += sx;
}
startY += sy;
} while (startY != endY);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment