So I am trying to draw two triangles, but at the end I just get the white window without any triangles. I have set up the libraries correctly but I believe there could be a mistake somewhere in the code and since I am fairly new I cannot figure it out. The code complies with no errors or warnings, but the outcome is not what I have expected the window is white and there is no drawing shown in the window.
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <cstdlib>
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
int main(void)
{
GLFWwindow* window;
// initialize the library
if (!glfwInit())
{
return -1;
}
// Create a window and its context
window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "kk", NULL, NULL);
int screenWidth, screenHeight;
glfwGetFramebufferSize(window, &screenWidth, &screenHeight);
if (!window)
{
glfwTerminate();
return -1;
}
// make the window's context current
glfwMakeContextCurrent(window);
glViewport(0, 0, screenWidth, screenHeight); //specifies part of the window OpenGL can draw on
glMatrixMode(GL_PROJECTION); //controls the camera
glLoadIdentity(); //put us at (0, 0, 0)
glOrtho(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT, 0, 600); //cordinate system
glMatrixMode(GL_MODELVIEW); //defines how objects are trasformed
glLoadIdentity(); //put us at (0, 0, 0)
GLfloat first_triangle[] = {
0, 0, 0,
0,300,0,
200,300,0,
};
GLfloat second_triangle[] = {
200,300,0,
400,300,0,
400,600,0,
};
GLfloat color[] =
{
255,0,0,
0,255,0,
0,0,255
};
// Loop until the window is closed by the user
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
//OpenGL rendering
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, first_triangle); // points to the vertices to be used
glColorPointer(3, GL_FLOAT, 0, color); // color to be used
glDrawArrays(GL_TRIANGLES, 0, 3); // draw the vetices
glVertexPointer(3, GL_FLOAT, 0, second_triangle); // points to the vertices to be used
glColorPointer(3, GL_FLOAT, 0, color); // color to be used
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
};
}
You have to call glfwSwapBuffers
and glfwPollEvents
at the end of the application loop:
while (!glfwWindowShouldClose(window))
{
// [...]
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwSwapBuffers
swaps the front and back buffers and causes the window to be updated.
glfwPollEvents
process the events.