Search code examples
c++imageopengldrawopengl-compat

How to draw an image from a 2d array in modern openGL


I want to draw points with openGL, I have a 32x32 screen size and I want to fill it with the color red, however I don't understand how the parameters of glVertex2f(-1, 0.5) are working

My first instinct was to do something like this:

glutInit(&argc, argv);                 // Initialize GLUT
glutCreateWindow("OpenGL Setup Test"); // Create a window with the given title
glutInitWindowSize(32, 32);   // Set the window's initial width & height
glutDisplayFunc(displaySpectrogram); // Register display callback handler for window re-paint
glutMainLoop();           // Enter the event-processing loop

glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
glClear(GL_COLOR_BUFFER_BIT);         // Clear the color buffer (background)

glBegin(GL_POINTS);              
glColor3f(1.0f, 0.0f, 0.0f); // Red
for (int i = 0; i < 32; i++)
{
    for (int j = 0; j < 32; j++)
    {
        glVertex2f(i,j);
    }
}
glEnd();

glFlush();  // Render now

But glVertex2f() parameters range is -1 to 1 I think so I'm not sure how to achieve that.

There is another way with texture but I have no idea on how to use them and there are no tutorials for that online


Solution

  • I recommend to use an Orthographic projection. In Orthographic Projection, the view space coordinates are linearly mapped to the clip space coordinates and normalized device coordinates. The viewing volume is defined by 6 distances (left, right, bottom, top, near, far). The values for left, right, bottom, top, near and far define a cuboid (box).
    With legacy OpenGL matrices you can use glOrtho to set an orthographic projection matrix:

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, 32, 0, 32, -1, 1);