class Demo_viewer
: public GLFW_window
{
public:
// ...
demo_viewer.h
Make your OpenGL window class derive from GLFW_window
GLFW_window
Our GLFW_window class’s constructor takes care of telling GLFW how to set up the window:
GLFW_window::GLFW_window(const char* title, int width, int height) {
glfwInit();
// Request core profile and OpenGL version 3.2
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
// Create the window and select it as the target for rendering commands
window = glfwCreateWindow(width, height, title, NULL, NULL);
glfwMakeContextCurrent(window);
// Set a few more options/keyboard callbacks.
// ...
glfw_window.cpp
Main Loop
After window is constructed, we run the window’s event loop:
Vertex shaderdemo.vert computes per-vertex quantities that are interpolated and fed into fragment shader
Positions
Colors
Fragment shaderdemo.frag outputs color of rasterized pixels
Vertex and Fragment Shaders
#version 150
#extension GL_ARB_explicit_attrib_location : enable
layout (location = 0) in vec3 v_position; // bind v_position to attribute 0
layout (location = 1) in vec4 v_color; // bind v_color to attribute 1
out vec4 v4f_color; // Interpolated output to be read by fragment shader
void main() {
// pass through color and position from the vertex attributes
v4f_color = v_color;
gl_Position = vec4(v_position, 1.0);
}
demo.vert
#version 150
in vec4 v4f_color; // Interpolated input read from vertex shader
out vec4 f_color; // Final color output produced by fragment shader.
// (Can name this anything you want...)
void main() {
// pass through interpolated fragment color
f_color = v4f_color;
}
demo.frag
Displaying the Completed Frame
int GLFW_window::run() {
// ...
// Event loop
while (!glfwWindowShouldClose(window_)) {
timer(); // fire off timer (for animations)
paint(); // draw scene
glfwSwapBuffers(window_); // swap buffers
glfwPollEvents(); // handle events
}
//...
}
glfw_window.cpp
GLFW double-buffers by default: show only fully drawn frames
Drawing happens in off-screen buffer
Entire rendered frame moved on-screen by glfwSwapBuffers
Synchronized to screen refresh to prevent tearing (see glfwSwapInterval(1) in glfw_window.cpp).
Vertex and Fragment Shaders: Result
GLSL
Fragment and vertex shaders written in GLSL
Built-in Types
Standard: float, int, bool, arrays, structs
Vectors: vec2, vec3, vec4
Matrices: mat2, mat3, mat4
Multiplication operator is overloaded!
Textures: sampler1D, sampler2D, sampler3D
Swizzle operator: flexible way to access vector components