Skip to content

Instantly share code, notes, and snippets.

@liuerfire
Created December 24, 2012 12:07
Show Gist options
  • Save liuerfire/4369039 to your computer and use it in GitHub Desktop.
Save liuerfire/4369039 to your computer and use it in GitHub Desktop.
bresenham's midpoint line algorithm
#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;
}
@New-Ash
Copy link

New-Ash commented Nov 9, 2022

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;
}

int m = 0;
int dx, dy, d, x, y;

dx = x2 - x1;
dy = y2 - y1;
d = dx - 2 * dy;
y = y1;

if (dy < 0) {
    m = -1;
    dy = -dy;
}
else if (dy >=0) {
    m = 1;
}

if(x1==x2){
    if(y1 < y2){
        int temp = y1;
        y1 = y2;
        y2 = temp;
    }
    for(y = y2;y < y1;y++){
        plot(x1,y);
        glEnd();
    }
}
else{

    for (x = x1; x < x2; x++) {

    plot(x, y);

    if (d <= 0) {
        y += m;
        d += 2*(dx -dy);
    }
    else {
        d += -2 * dy;
    }
    glEnd();
}

}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment