Search code examples
c++macosopenglglutopengl-compat

OpenGL doesn't paint, but the algorithm is correct


Hello I am implementing bresenham algorithm with openGl. The calculation formula is correct, It does not draw properly on the screen. What is the problem? It is not drawn even if the value is put in hard coding. And it compiles fine.

#include <iostream>
#include <GLUT/glut.h>

void sp(int x, int y){
    glBegin(GL_POINTS);
    glVertex2i(x,y);
    glEnd();
}

void bsh_al(int xs,int ys,int xe,int ye){
    int x,y=ys,W=xe-xs,H=ye-ys;
    int F=2*H-W,dF1=2*H, dF2=2*(H-W);

    for(x=xs;x<=xe;x++){
        sp(x,y);
        std::cout << "x : "<< x << " | y : "<< y << std::endl;
        if(F<0)
            F+=dF1;
        else{
            y++;
            F+=dF2;
        }
    }  
}

void Draw() {
    bsh_al(1,1,6,4);
    glFinish();
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutCreateWindow("OpenGL");
    glutDisplayFunc(Draw);
    glutMainLoop();

    return 0;
}

coding with Xcode


Solution

  • The vertex coordinates have to be in range [-1.0, 1.0]. The bottom left coordinate is (-1, -1) and the to right is (1, 1).

    If you want to specify the vertex coordinates in pixel unit, then you have to set an orthographic projection by glOrtho. For instance:

    int main(int argc, char** argv)
    {
        glutInit(&argc, argv);
        glutCreateWindow("OpenGL");
        glutDisplayFunc(Draw);
    
        int width = glutGet(GLUT_WINDOW_WIDTH);
        int height = glutGet(GLUT_WINDOW_HEIGHT);
    
        glMatrixMode(GL_PROJECTION);
        glOrtho(0, width, height, 0, -1, 1);
    
        glMatrixMode(GL_MODELVIEW);
    
        glutMainLoop();
    
        return 0;
    }