I feel like every single blog post starts with an apology for not posting. I'm going to stop that, because it's insincere.
I'm making another rhythm game!1 This time I'm using it as an adventure in C programming, since I've never actually made a computer game from scratch.

metronome, my rhythm game for the NumWorks calculator, was really fun to make. It was nice working within the contraints of the calculator's memory and clock speed, but ultimately those limitations held it back to nothing more than a toy project. I'm very proud of it as a monument to my experience with the NumWorks SDK complete with a mature software renderer (and Rust is always a joy to program in), but you can see why I felt the need for something more real. Something a little more... low-level.
the shoulders of giants (wearing spiky shoulder pads)
EVERYTHING was built on a relatively simple tech stack. I used GLFW for video and input, and miniaudio for audio.
Developer experience is not something GLFW was designed for. In fact, developer experience is not something OpenGL was designed for, and the nomenclature certainly doesn't help; but for those inexperienced with graphics programming (the innocent, pure lot of you) here's a summary of the workflow I used:
- You give OpenGL some data (coordinates, colours, normals, et cetera) which get passed into a vertex shader.
- The vertex shader calculates the positions of vertices based off of those; this can range from using a projection matrix to calculating positions from character data.
- When rasterising the vertices (you get to pick if they're triangles or lines or whatever), each pixel runs a fragment shader which interpolates values like colour, texture coordinates and normals to decide its own colour, and then it paints itself on screen.
The arrays of data are structures in VRAM (video memory) called buffers. You package your buffers into a big vertex array object (VAO), which knows what data type your buffers hold and how they're represented.
The OpenGL C bindings are designed around these concepts to faciliate as many usage cases as possible, which is why the docs are 700 entries long. Combined with function identifiers that are "impressively opaque for how verbose they are", and a horrific set up process..
// vao
glGenVertexArrays(1, &track->vao);
glBindVertexArray(track->vao);
// vbo
glGenBuffers(1, &track->vbo);
glBindBuffer(GL_ARRAY_BUFFER, track->vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), (void*)0);
...
..the shoulders of these giants sure are uncomfortable.
Usually, each vertex marches along the array and its buffers - however, when drawing lots of instances of the same object, which would usually require repeating data over and over again (say, if you had to recalculate the vertices for every instance and add them to the buffer), it's more useful to have some buffers for the vertex properties and some for the instances themselves, storing properties like rotation and position for the entire object. Then, you can use the same vertex buffer a bunch of times with different attributes.
This handy technique is called instancing, and it can make it much faster to draw thousands of simple objects without thousands of equivalent draw calls or thousands of bytes in unnecessary memory usage.
It comes in very handy when needing to draw squillions of notes on screen at the same time - in fact, with proper usage of GLSL's impressive matrix calculation support, you can do really extensive computations in the vertex shaders for much lower cost than you would have on the CPU.
As much of a horror OpenGL is to set up, she's a woman of her word. Instancing is fast as hell, especially for a game as simple as EVERYTHING. The rest of the graphics programming in this project was largely uninteresting - standard camera and projection matrix work, some wrangling of uniforms, and a disregard for texturing. In the end, I kind of grew to like it, especially once I was spending more time writing shaders than fiddling with C functions.

So clearly, if embarrassing levels of parallelism have been doing us so much good on the graphics front... maybe this is an untapped market in C programming!
premature optimisation and parallelism
Now, parallelism has always been a nightmare. But I always say, as a developer, there are so many things working against you, especially when you're trying to use multiprocressing to optimise your program.
- Multithreading has too much overhead.
- Pipelining and branch prediction are a thing.
- The compiler is smarter than you.
- You're stupid. Like, seriously stupid.
In fact, I witnessed this first hand when trying to make a software renderer. Despite this, I thought it would be a good idea to separate the game into two threads:
- Input and game logic
- Graphics, rendering, rasterisation, resizing and everything in between
why?
GLFW does have asynchronous input callbacks - you can set up a specific function to be fired every single time a key stroke is detected. Except they're not really asynchronous at all. Input is only polled once you call
glfwPollInput, which unleashes a queue of input events.This means that as much as I want to check input as frequently as possible, if the game only ran in one thread, I would only be able to do it as often as I could run
glfwPollInput.Accounting for frame rate, this is pitifully low for a rhythm game like EVERYTHING; literal milliseconds actually matter. The only solution I could think of is to poll input completely separately to rendering/graphics - and that's why this. Well..
If using all your cores works so well for Nvidia, what's gonna stop me?
Thing is, OpenGL is thread-specific. This means that only one thread can hold your
GL context and own all the memory associated with it. Only that thread can actually
call OpenGL functions like draws and frame pushes. This isn't too much of a bother;
in fact, it encourages us to make our rendering/input split clearer. I initialise
OpenGL in one thread, let it do the glDraw calls, and handle input through the window
in the other:
#pragma omp section
{
while (win_continue(game->window)) {
// who needs object oriented programming???
// #justUseCStructs
win_poll(game->window);
game_handle_input(game);
game_update_ms(game);
}
}
#pragma omp section
{
win_init_gl(game->window);
r_init(&game->renderer);
while (win_continue(game->window)) {
r_update(&game->renderer, &game->track.a);
win_push(game->window); // !!!
}
r_uninit(&game->renderer);
}
You might have noticed, though, that the renderer thread also uses the window. This isn't as much of a problem as OpenGL, because GLFW doesn't need to worry about VRAM, but it still isn't thread-safe at all. What this meant is that the number of loops per second tanked both for the rendering thread and the input thread, because ownership of the GLFW window was being transferred every frame.
Now surely there had to be a way to avoid this. As ancient as C's philosophy is, C11 brought with it the beauty of atomics, and that meant that I was free to fuck around with semaphores as much as I wanted to.
Of course, I've already been using atomics - I need to pass an atomic Track pointer to
the renderer (track.a) so that it knows which notes to start drawing from
in the immutable note array. To further
separate the window as much as possible from the
rendering, I set up a semaphore system that would keep ownership of the GLFW window
almost entirely in the game logic thread.
atomic_bool ready_to_push = false;
#pragma omp parallel sections
{
#pragma omp section
{
while (win_continue(game->window)) {
win_poll(game->window);
game_parse_input(game);
if (atomic_load(&ready_to_push)) {
win_push(game->window);
atomic_store(&ready_to_push, false);
}
}
}
#pragma omp section
{
win_init_gl(game->window);
r_init(&game->renderer);
while (win_continue(game->window)) {
r_update(&game->renderer);
atomic_store(&ready_to_push, true);
while (atomic_load(&ready_to_push) && win_continue(game->window)) {}
}
}
}
For some reason, this just ... didn't work. Maybe it was optimised away (despite
my futile volatiles), but checking an atomic sephamore resulted in flickering,
and honestly not even faster speeds (even though the input thread wouldn't have to
be doing that much extra).
So in the end, I decided to tank the performance loss generated by switching ownership every frame because the game was going to run fast enough anyways - and thousands of input ticks per second was more valuable than hundreds of frames.
However, one really annoying thing is that in all my work separating rendering
from keyboard input (via the KeyCallback), there's one other input source that
I didn't account for - resizing the window, dispatched through the
FramebufferSizeCallback. Ridiculous and random, but I had to use it to resize the
window vertically to fill the space, except the window resizing method is glViewport.
It was a quick workaround with another set of frame buffer size atomics, but I had almost
entirely forgotten about how much data I had to manage between GLFW and OpenGL.
moral of the story?
In all my efforts to parallelify a rhythm game, I succeeded only in confusing myself and increasing the complexity of the program. You will pretty much never, ever outsmart a computer. This is funny because it seems like my goal in a lot of things I do, like reverse engineering and modding.
Sometimes there are happy endings though - as frustrating as the C desktop game development environment is \coughglfwcough\ - I did manage to poll for input several times a millisecond, so you can bet your right cheek there's no lag in this game.
It is heavily in need of a visual rework though. I'll probably add screenshots of EVERYTHING once it's finished, but with university starting and my tendency (common to many) to leave projects unfinished, I would not be getting too hopeful. See you next time!
-
"No, shrub, not again!" <