Skip to content

Instantly share code, notes, and snippets.

@blewert
Created October 28, 2014 14:38
Show Gist options
  • Save blewert/b475734bd467a955c756 to your computer and use it in GitHub Desktop.
Save blewert/b475734bd467a955c756 to your computer and use it in GitHub Desktop.
naive liune drawing algorithm at all possible angles
public void drawLine(GL gl, int x1, int y1, int x2, int y2)
{
//y = mx + c
//m = (change in y)/(change in x)
double dy = (y2 - y1);
double dx = (x2 - x1);
//Stop divide by zero
if(dx == 0)
dx = 1;
double m = dy / dx;
//solve(y == m*x + c, c) gives (y - m*x)
double c = (y2 - m * x2);
if(Math.abs(m) < 1.0)
{
//Swap start and end points, because they might be negative
int start = (dx < 0) ? (x2) : (x1);
int end = (dx < 0) ? (x1) : (x2);
for(int x = start; x < end; x++)
{
double y = m * x + c;
gl.glBegin(GL.GL_POLYGON);
this.plotPixel(gl, x, (int)y);
gl.glEnd();
}
}
else
{
//Gradient is too high: calculate x instead
//Swap start and endpoints, because they might be negative
int start = (dy < 0) ? (y2) : (y1);
int end = (dy < 0) ? (y1) : (y2);
System.out.printf("x: %d, y: %d, %f \r\n", start, end, dy);
for(int y = start; y < end; y++)
{
//solve(y == m*x + c, x) gives -(c - y)/m
double x = -(c - y)/m;
System.out.println(x);
gl.glBegin(GL.GL_POLYGON);
this.plotPixel(gl, (int)x, y);
gl.glEnd();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment