Compute shaders in raylib
// status: seedling
raylib has no LoadComputeShader. Its compute path sits one layer down, in rlgl, and it only exists in a raylib compiled for OpenGL 4.3. The default desktop build targets 3.3, where the same functions are declared, link without complaint, and do nothing.
So the first question is which build you have, not which function to call. This note answers that, then walks the calls through raylib's own example, a Game of Life on two storage buffers, and ends with what to do where compute does not exist at all: macOS and the web. It follows raylib 6.2; the two names that changed since 5.5 are in a table below. What a compute shader is, with its workgroups, shared memory and barriers, is in Compute shaders; the rest of rlgl is in Raylib 3D rendering.
Where it runs
In src/rlgl.h, the body of every compute, storage-buffer and image-binding function is wrapped in #if defined(GRAPHICS_API_OPENGL_43). That define is fixed when raylib itself is compiled, and the desktop default is GRAPHICS_API_OPENGL_33.
| Target | Compute through rlgl | Why |
|---|---|---|
| Windows, Linux | yes, in a 4.3 build | the driver has to offer an OpenGL 4.3 core context |
| macOS | no | Apple's OpenGL stops at 4.1 |
| Web | no | WebGL 2 follows OpenGL ES 3.0, which has no compute stage |
| Android, Raspberry Pi (DRM) | no | they build the ES backends, where the same bodies are compiled out |
OpenGL ES 3.1 does have compute shaders; rlgl's ES path stops at 3.0.
In a 3.3 build nothing fails loudly:
rlLoadShaderProgramComputereturns 0 and logsSHADER: Compute shaders not supported, enable GRAPHICS_API_OPENGL_43.rlLoadShaderBufferreturns 0 and logsSSBO: SSBO not enabled. Define GRAPHICS_API_OPENGL_43.rlComputeShaderDispatch,rlBindShaderBuffer,rlUpdateShaderBufferandrlReadShaderBuffercompile to empty functions and log nothing.
A program id of 0 is the thing to test for. rlGetVersion() answers the same question before anything is loaded:
bool On macOS there is no build to switch to. A 4.3 build asks GLFW for a 4.3 core context (src/platforms/rcore_desktop_glfw.c), GLFW's window guide says creation fails when the context it gets is older than the one requested, and Apple's table of Macs lists nothing above OpenGL 4.1. raylib's CMake sets GRAPHICS_API_OPENGL_33 on Apple and prints a warning when OPENGL_VERSION overrides it.
Building raylib for OpenGL 4.3
With CMake the option is OPENGL_VERSION (CMakeOptions.txt), which cmake/LibraryConfigurations.cmake turns into the define:
When raylib arrives through FetchContent, put the option in the cache before FetchContent_MakeAvailable. Raym's CMakeLists.txt does the same thing with "ES 3.0" for its web build:
set(OPENGL_VERSION "4.3" CACHE STRING "" FORCE)
FetchContent_MakeAvailable(raylib)With the Makefile in src/, it is the GRAPHICS variable, which lands on the compiler line as a -D:
Both routes default to 3.3, so treat any raylib you did not build yourself as a 3.3 build until rlGetVersion() says otherwise. A 4.3 build keeps the rest of raylib as it was: the define switches GRAPHICS_API_OPENGL_33 on as well, and raylib's default shader stays at #version 330. Your own shaders are free to say #version 430.
The calls
// Stage, program, dispatch
unsigned int ; // type: RL_COMPUTE_SHADER
unsigned int ;
void ;
// Shader storage buffers
unsigned int ;
void ;
void ;
void ;
void ;
void ;
unsigned int ;
// Image textures
void ;Each one wraps a single OpenGL call or a short run of them: glDispatchCompute, glBindBufferBase, glBufferSubData. A compute program is a bare program id, not a raylib Shader, so it is switched on with rlEnableShader(id) and off with rlDisableShader().
Two names changed between 5.5 and 6.0. The rest of the list has the same signatures in both.
| raylib | Compile the stage | Link the program | Example |
|---|---|---|---|
| 5.5 | rlCompileShader | rlLoadComputeShaderProgram | examples/others/rlgl_compute_shader.c |
| 6.0, 6.2 | rlLoadShader | rlLoadShaderProgramCompute | examples/shaders/shaders_rlgl_compute.c |
A Game of Life on two buffers
raylib's example is Conway's Game of Life, the automaton from Game of Life in Haskell with the neighbour count moved into a compute shader. Two storage buffers hold one uint per cell; each generation reads one and writes the other. This is the example's logic shader with the comments trimmed and the two upper-bound comparisons changed, for a reason given at the end of the note:
layout in;
layout readonly restrict buffer golLayout ;
layout writeonly restrict buffer golLayout2 ;
void x and y are unsigned, so x - 1 at the left edge wraps to a very large number and the upper-bound test rejects it. The < 0 tests never fire.
The C side compiles that file as one stage and links it into a program of its own:
char *golLogicCode = ;
unsigned int golLogicShader = ;
unsigned int golLogicProgram = ;
;The buffers come next. size is in bytes, a NULL data pointer makes rlgl clear the buffer to zero, and a usage hint of 0 falls back to RL_STREAM_COPY. The example fills its grid with the mouse through a second compute shader; seeding from the CPU is shorter:
unsigned int gridBytes = GOL_WIDTH*GOL_WIDTH*sizeof;
unsigned int *seed = ;
for seed = ;
unsigned int ssboA = ;
unsigned int ssboB = ;
;One generation is a bind, a dispatch and a swap. The index passed to rlBindShaderBuffer is the binding = N of the shader's layout, and the dispatch counts workgroups, not cells: 768 / 16 = 48 on each axis, which is why the width has to be a multiple of 16.
;
;
;
;
;
unsigned int temp = ssboA;
ssboA = ssboB;
ssboB = temp;Nothing is copied back to draw it. A fragment shader reads the same buffer at binding 1 and turns each cell into a pixel:
in vec2 fragTexCoord;
out vec4 finalColor;
layout readonly buffer golLayout
;
uniform vec2 resolution;
void LoadShader(NULL, path) pairs it with raylib's default vertex shader, which supplies fragTexCoord, and a blank texture the size of the window gives it a quad whose coordinates run from 0 to 1:
Shader golRenderShader = ;
const Vector2 resolution = ;
;
Image whiteImage = ;
Texture2D whiteTex = ;
;
// Each frame, after the dispatch and the swap: the render shader reads binding 1 too
;
;
;
;
;
;
;
;Moving data in and out
Both directions take the buffer id, a pointer, a size in bytes and an offset in bytes:
// CPU -> GPU: data, size in bytes, offset in bytes
;
// GPU -> CPU: destination, size in bytes, offset in bytes
;rlReadShaderBuffer is a plain glGetBufferSubData, so it waits for the GPU to finish the work the buffer depends on. It is a tool for tests and for saving state, not for every frame.
A compute program has no Shader struct, so its uniforms go through rlgl as well. rlSetUniform takes no program id; it writes to whichever program is enabled:
int widthLoc = ;
unsigned int width = GOL_WIDTH;
;
;
;Pair it with uniform uint width; in the shader and the #define repeated in every file goes away.
Writing to a texture
Storage buffers suit structured data. For an image, bind a texture to an image unit instead:
Image blank = ;
Texture2D target = ; // R8G8B8A8, which rlgl maps to GL_RGBA8 on desktop
;
;
; // image unit 0, read-write
;
;The format argument is a raylib pixel format. rlgl translates it with rlGetGlTextureFormats, so R8G8B8A8 becomes GL_RGBA8, R32 becomes GL_R32F and R32G32B32A32 becomes GL_RGBA32F. The shader has to declare the matching qualifier, layout(rgba8, binding = 0) uniform image2D target;, or it runs into the format mismatch described in Compute shaders. Access is read-only or read-write, and rlgl always binds mip level 0. None of raylib's examples uses this call.
Without compute
Where the table at the top says no, the usual substitute is a fragment-shader ping-pong: keep the state in a texture, draw a full-size quad into a second render texture through a shader that computes the next state, swap, repeat. raylib 6.0 added exactly this as shaders_game_of_life.c. Its shader ships in GLSL 330 and GLSL 100 and the example asks for nothing beyond OpenGL 3.3 or ES 2.0, which covers a default build, macOS and the web:
RenderTexture2D world1 = ;
RenderTexture2D world2 = ;
RenderTexture2D *currentWorld = &world2;
RenderTexture2D *previousWorld = &world1;
// Render textures are stored upside down: a negative source height flips them back
const Rectangle source = ;
const Rectangle dest = ;
// Each generation: draw the previous world into the current one through the shader
RenderTexture2D *tempWorld = currentWorld;
currentWorld = previousWorld;
previousWorld = tempWorld;
;
;
;
;
;The shader samples the eight neighbours with texture() and writes one colour. That is also the limit of the technique: one output per pixel, at that pixel. No scattered writes, no atomics, no variable-length output. A pipeline like Marching Cubes on the GPU - Count, Scan, Emit does not fit, and it also wants an indirect draw, which rlgl does not wrap. At that point the choices are raw OpenGL beside raylib (OpenGL - learning log) or the CPU.
The CPU version is worth keeping in any case: the same rule as a plain loop, to diff against what rlReadShaderBuffer returns.
Things that tripped me up
countis in bytes —rlReadShaderBufferandrlCopyShaderBufferhandcountstraight toglGetBufferSubDataandglCopyBufferSubData(src/rlgl.h).rlCopyShaderBufferalso takes the destination first.- The grid size is repeated in every file —
GOL_WIDTHis a#defineinshaders_rlgl_compute.cand in each shader, and the C file carries a comment saying they must match. Nothing checks it. - The example's bounds test is off by one —
gol.glslrejectsx > GOL_WIDTHandy > GOL_WIDTH, so a coordinate equal toGOL_WIDTHgets through: the right-hand neighbour of the last column is read from the first cell of the next row, and the row under the last one is read from past the end of the buffer. The listing above uses>=for both. - rlgl has no memory barrier —
glMemoryBarrierappears nowhere inrlgl.h, and the example draws from the buffer its dispatch has just written without one. The OpenGL reference only promises that shader-storage reads "will reflect data written by shaders prior to the barrier" once there is a barrier.src/external/glad.hdoes declare the function andGL_SHADER_STORAGE_BARRIER_BIT. - Draws are batched — raylib queues its 2D and immediate-mode draws until the batch is flushed, so a dispatch written between two draws does not run between them. The example dispatches before
BeginDrawing;rlDrawRenderBatchActive()forces the flush when the order matters.
References
- Compute shaders — workgroups, shared memory, barriers and atomics, independent of any library.
- Raylib 3D rendering — the rest of rlgl: shaders, render textures and the batch.
- Marching Cubes on the GPU - Count, Scan, Emit — a compute pipeline that needs more than rlgl wraps.
- raylib —
shaders_rlgl_compute.c(6.2) and its shaders — the example this note follows, by Teddy Astie. - raylib —
rlgl_compute_shader.c(5.5) — the same example under the 5.5 names. - raylib —
shaders_game_of_life.c(6.2) — the fragment-shader version, by Jordi Santonja. - raylib —
rlgl.h(6.2) — the declarations, and theGRAPHICS_API_OPENGL_43guard around each body. - Khronos OpenGL wiki — Compute Shader — the stage itself.
- OpenGL reference —
glDispatchComputeandglMemoryBarrier— version tables and the barrier bits. - WebGL 2.0 specification — built on OpenGL ES 3.0.
- Apple — Mac computers that use OpenCL and OpenGL graphics — the highest OpenGL version for each Mac model.
- GLFW — window guide — what the context version hints do when the version is unavailable.
Back to Notes · see also Compute shaders · Raylib 3D rendering · GPU Marching Cubes · OpenGL - learning log · Game of Life in Haskell