C++ OpenGL Introduction
In this page:
What is OpenGL?
OpenGL is a cross-platform, cross-language API for rendering 2D and 3D graphics by issuing low-level drawing commands directly to the GPU. On Ubuntu you'd install freeglut3-dev and mesa-common-dev to compile against it; on Windows, GLEW and freeGLUT provide the necessary bindings and window-management glue.
Example: What is OpenGL?
#include <GL/glut.h>
int main(int argc, char** argv) {
glutInit(&argc, argv); // low-level GPU drawing commands via OpenGL
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Creating an OpenGL Window with GLUT
GLUT (OpenGL Utility Toolkit) exists because OpenGL itself has no concept of creating a window or handling an operating system's event loop -- GLUT fills that gap, letting you open a window and register callback functions for rendering and input with just a few lines of setup code.
Example: Creating an OpenGL Window with GLUT
#include <GL/glut.h>
void display() {}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutCreateWindow("OpenGL Window");
glutDisplayFunc(display); // register a rendering callback
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Drawing Triangles
glBegin(GL_TRIANGLES) and glEnd() bracket a set of vertex calls that OpenGL groups into triangles, the fundamental building block nearly all 3D rendering breaks down into. Coordinates given between them are in normalized device space, ranging from -1.0 to 1.0 regardless of the window's actual pixel size.
Example: Drawing Triangles
#include <GL/glut.h>
void drawTriangle() {
glBegin(GL_TRIANGLES);
glVertex2f(-0.5f, -0.5f);
glVertex2f(0.5f, -0.5f);
glVertex2f(0.0f, 0.5f);
glEnd();
}
int main() {
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Viewing Volume and Projection
A projection transform maps your scene's abstract coordinate space onto the 2D viewport that actually gets displayed. Orthographic projection (used for flat 2D views and UI) preserves parallel lines and object size regardless of distance, unlike perspective projection which is used for realistic 3D depth.
Example: Viewing Volume and Projection
#include <GL/glut.h>
void setupOrtho() {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 800.0, 600.0, 0.0); // orthographic: no depth distortion
}
int main() {
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Clearing Buffers and Colors
glClearColor() sets which color the screen buffer resets to before each new frame is drawn; glClear(GL_COLOR_BUFFER_BIT) then actually applies that reset. Skipping this step leaves the previous frame's pixels behind, smearing old drawing into the new frame.
Example: Clearing Buffers and Colors
#include <GL/glut.h>
void render() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT); // reset the buffer before drawing
}
int main() {
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: