Created
December 24, 2012 12:07
-
-
Save liuerfire/4369039 to your computer and use it in GitHub Desktop.
bresenham's midpoint line algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <GL/glut.h> | |
void init() | |
{ | |
glClearColor(0.0, 0.0, 0.0, 0.0); | |
glMatrixMode(GL_PROJECTION); | |
glLoadIdentity(); | |
gluOrtho2D(0.0, 500.0, 0.0, 500.0); | |
} | |
void midPoint(int x1, int y1, int x2, int y2) | |
{ | |
if (x1 > x2) | |
{ | |
midPoint(x2, y2, x1, y1); | |
return; | |
} | |
int slope; | |
int dx, dy, d, x, y; | |
dx = x2 - x1; | |
dy = y2 - y1; | |
d = dx - 2 * dy; | |
y = y1; | |
if (dy < 0) { | |
slope = -1; | |
dy = -dy; | |
} | |
else { | |
slope = 1; | |
} | |
for (x = x1; x < x2; x++) { | |
glBegin(GL_POINTS); | |
glVertex2f(x, y); | |
if (d <= 0) { | |
d += 2 * dx - 2 * dy; | |
y += slope; | |
} | |
else { | |
d += -2 * dy; | |
} | |
glEnd(); | |
} | |
} | |
void display() | |
{ | |
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); | |
glColor3f(1.0, 0.0, 0.0); | |
midPoint(10, 10, 110, 210); | |
glColor3f(0.0, 1.0, 0.0); | |
midPoint(10, 10, 210, 110); | |
glColor3f(1.0, 1.0, 0.0); | |
midPoint(210, 10, 10, 110); | |
glFlush(); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
glutInit(&argc, argv); | |
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); | |
glutInitWindowPosition(50, 50); | |
glutInitWindowSize(500, 500); | |
glutCreateWindow("Bresenham\'s midpoint line algorithm"); | |
init(); | |
glutDisplayFunc(display); | |
glutMainLoop(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
midPoint(100, 200, 100, 350);
will not give any output since you are iterating only over the x coordinate so the for loop will never run.
use the modified midPoint();
void midPoint(int x1, int y1, int x2, int y2)
{
if (x2 < x1)
{
midPoint(x2, y2, x1, y1);
return;
}
}