With of all the above set up, we can finally put things together, and render our first triangle!
To recap, here are the steps we have to follow to put all of the above together.
When the program loads we:
- create a vertex buffer and put some vertices into it;
- load our shaders and link them into a shader program;
- create a vertex array to specify our vertices’ layout;
- create a matrix uniform for our projection matrix.
Since we abstracted a lot of functionality into the different types, we can do all of this in just a few lines of code. This is a good example of how abstraction helps think about a problem on a higher level to prevent getting caught up in the details.
With everything set up, we can now draw the vertices we created as follows:
- activate shader program and set uniforms;
- bind vertex buffer and array objects;
- upload vertices to GPU and draw them;
- reset state for potential further draw calls (optional, but good practice).
And the resulting image may look something like this:
The code for both of these parts can found in the
OnRenderFrame() of the final game window.
In fact I put together all the source code above into a neat little stand-alone project which you can find on my GitHub page.
Feel free to take a look and do with the code as you will.
In this post we went from an empty game window to creating several types to make using OpenGL in C# much easier.
That allowed us to put together a simple example renderer drawing a colourful triangle using our own shaders.
I use virtually the same code as above, though with a lot more additional features and a few more layers of abstraction in my own graphics library which is also available on GhitHub.
The library is still heavily in development, and I am currently in the middle of refactoring large parts of it. However it already has a lot of features and is working well and fast enough to power the complex rendering pipeline of Roche Fusion.
I hope this post has been useful to you. Of course feel free to ask questions or comment below.
I would love to hear what you think, especially if this post may have convinced you to look into OpenGL in C# yourself.
There will also be more posts on OpenGL and computer graphics in general coming up in the future. These may include but are not limited to keyframe animations, GPU simulated particle systems, a variety of post processing techniques, and more!
If you have any particular topic you would like me to cover, Feel free to let me know, and I will prioritize those subjects.
For the time being,
Enjoy the pixels!