Search code examples
c++openglglut

OpenGL: Bresenham's Line Drawing Algorithm Implementation


I've been trying to generate a line using Bresenham's Algorithm (Yes, I know in built functions exist, but this is something I've been asked to implement) using the following code. But for some reason, I am not being able to see the line on the window. I just get an empty window.

I initially tried drawing points with SetPixel() but I was short of 2 arguments(HDC and COLORREF) apart from just the X and Y coordinates. I don't know what the other 2 arguments do, so I had to try something else.

So I used a solution I found here on StackOverflow to generate the point. Though I do not get any compilation error or warnings, the code just doesn't seem to work. How about you try looking for the problem:

#include<iostream>
#include<GL/glut.h>
#include<stdlib.h>
#include<math.h>
using namespace std;

int x00; 
int y00;
int xEnd;
int yEnd;

void init(){
    glClearColor(1,0,0,0);
    glMatrixMode( GL_PROJECTION );
    gluOrtho2D(0,500,0,500);
}

void bres()
{     
    int dx = fabs(xEnd - x00), dy = fabs(yEnd - y00);
    int p = 2*dy-dx;
    int x, y;

    if(x00>xEnd){
        x=xEnd;
        y=yEnd;
        xEnd=x00;
    }
    else{
        x=x00;
        y=y00;
    }
    //Stack Overflow Solution to generate a point:
    glBegin(GL_POINTS);
        glColor3f(0,0,0);
        glVertex2i(x,y);
    glEnd();

    while(x<xEnd){
        x++;
        if(p<0){
            p = p + 2*dy;
        }
        else{
            y++;
            p= p + 2*dy - 2*dx;
       }
        glBegin(GL_POINTS);
            glColor3f(0,0,0);
            glVertex2i(x,y);
        glEnd();

    }

}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
    bres();
    glFlush();

}

int main(int argc, char* argv[])
{
    cout<<"Enter the co ordinates for 2 points: ";
    cin>>x00>>y00>>xEnd>>yEnd;

    glutInit(&argc, argv);
    glutInitWindowSize(600,600);
    glutInitWindowPosition(10,10);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("Bresenham's Algo");

    init();
    glutDisplayFunc(display);
    glutMainLoop();

    return 0;
}

Solution

  • Since you are using a double buffered window

    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    

    you have to call glutSwapBuffers instead of glFlush.

    If you would use a single buffered window

    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH);
    

    then glFlush would work.

    Change your code somehow like this:

    void display()
    {
        glClear(GL_COLOR_BUFFER_BIT);
        bres();
        //glFlush();
        glutSwapBuffers();
    }