SGL is a Object Oriented library that I made to teach myself OpenGL.
Recently I made some good progress in its development so I’d like to write up a little example program to show it off.
This example will be how to implement a FPS counter and rendering a textured cube. This is an example just to show what the code looks like, not a formal tutorial, I’ll get to that later :p
For this example I will be using Visual Studio with GLFW to create the OpenGL context.
First lets create the OpenGL context and initialize SGL:
First we create the opengl context window then initialize SGL. Initializing SGL initializes GLEW which is what SGL is built on. Also note that GLEW must be include before GLFW.
Next we need to create the a class to house the update and render logic.
Typically I make a class with 3 function:
init() setup all the required opengl objects, update(float) is where the game logic goes and render() renders everything to the screen.
Before getting to the good stuff lets add this new class to the event loop in main.cpp
Here we init the example and start the glfw window event loop. Every cycle we calculate the time since the last frame and pass it to the update function of the example. Then we render the the example and swap the front and back buffers to the context window.
Now inorder to render a cube and bind textures we will need a few objects.
A Camera to view the world.
A ShaderProgram to render meshes
Textures to bind images
Lets take a look at the initialization code:
First the ShaderProgram for rendering the cube is loaded from two files. Then it binds the mesh attributes to their locations in the order they appear in the mesh buffer, in this case (position, normal then texture coordinates). Finally the shader program is linked.
Next the crate texture is loaded from a DDS file using the Image class. SGL can load BMP, TGA, PNG and DDS texture files.
Lastly the model is loaded from a wavefront obj file.
Lets take a look at the code to render the cube.
The first thing to do in the render function is clear the screen.
The camera update function will recalculate the view and projection matrices if they were altered (i.e. if the camera has changed position or is set to look somewhere else).
Now to render the model we bind the model shader program.
Next we get the view and projection matrices from the camera and pass them to the shader along with the model transformation matrix.
The crate texture is bound and passed to the sampler in the fragment shader.
Finally the model is bound and drawn.
This is the result:
Next we want to add the FPS counter. For that we will use SGL’s BitmapFont and Text classes.
Inorder the render 2D fonts we will need a sprite batch and another shader.
In Example::init() :
And to render the text:
So that sums up this first little demo of SGL. In the future I will walk through specifics of SGL and the low level functionality.