Raylib for 3D
// status: budding
Raylib is Ramon Santamaria's "videogame programming without the fuss" library — a thin C layer over OpenGL (desktop 2.1/3.3/4.3, ES 2.0/3.0, or WebGL) that gets a triangle on screen in about ten lines. I used it in Raym to focus on the algorithm rather than the boilerplate, and these are the bits of its 3D side worth writing down.
The sections on conventions, lighting, shadows, instancing, batching and skyboxes were checked against the raylib 6.x source: a master commit from 14 October 2026, the day before the 6.2 release. Where 5.x differs, they say so.
Why pick raylib for 3D
- Small C API — include
raylib.hand link the compiled static/shared library. No framework-sized build-system archaeology. - Batteries included — windowing, input, audio, file I/O, image loading, and a math library (
raymath.h). The similarly styledrayguiis a separate companion library. - Readable internals — the code is genuinely small and well-commented. When you hit a weird behaviour, reading the source is faster than searching for docs.
- Portability — same code compiles to desktop, web (emscripten), Android, and RPi.
Where it stops being the right tool: anything that needs a modern GPU pipeline (raylib's rlgl compute path targets OpenGL 4.3), large-scene culling, or a more involved lighting architecture. At that point, raw OpenGL or Vulkan gives you more control.
The hello-cube
int Everything inside BeginMode3D(camera) / EndMode3D() uses the 3D pipeline. Outside, it's 2D and UI.
Cameras
Camera3D is a plain struct. Five built-in modes via UpdateCamera(&camera, mode):
CAMERA_FREE— fly-through with mouse + WASD + E/Q.CAMERA_ORBITAL— auto-orbits the target. Great for demos.CAMERA_FIRST_PERSON— mouselook + WASD, stays on ground.CAMERA_THIRD_PERSON— follows a target with mouse orbit.CAMERA_CUSTOM— do nothing, you drive it yourself.
For anything real, bypass UpdateCamera and move position/target yourself — the built-in modes are prototype-grade. The camera exposes its matrices via GetCameraMatrix and GetCameraProjectionMatrix when you need them.
Coordinates & conventions
Raylib keeps OpenGL's defaults, and most "why is my mesh invisible" questions come down to one of these.
- Right-handed, Y up.
raylib.hdescribesMatrixas "column major, OpenGL style, right-handed", andMatrixLookAtbuilds a view in which the camera looks down −Z. Y-up is a convention rather than a rule, since the camera'supfield decides, but the library assumes it wherever it has to choose:DrawGridandDrawPlanelie in the XZ plane andGenMeshHeightmapdisplaces Y. With X to the right and Y up, +Z points at the viewer. - Counter-clockwise is front, and back faces are culled.
rlglInitsetsglFrontFace(GL_CCW)andglCullFace(GL_BACK)and enables culling, so a triangle that appears clockwise from the camera is not drawn at all.DrawTriangle3Dasks for the same order. - No frustum culling. The back-face test is the only culling raylib does for you:
DrawModelsubmits every mesh, on screen or not.GetModelBoundingBoxandGetMeshBoundingBoxgive you the boxes; the visibility test is yours to write, and Spatial acceleration structures and GPU-Driven Visibility for Large Worlds are where that goes next. Clipping does exist: the near and far planes default to 0.05 and 4000 units. - Degrees outside, radians inside.
Camera3D.fovy, the angle ofDrawModelExandrlRotateftake degrees. Everything inraymath.htakes radians:MatrixRotate,MatrixRotateXYZ,QuaternionFromAxisAngle, thefovYofMatrixPerspective. In orthographic modefovyis not an angle at all but the height of the view in world units. - Matrices. Field names are column-major:
m12,m13andm14hold the translation.MatrixMultiply(a, b)appliesafirst andbsecond, the reverse of how the maths is usually written;DrawModelExbuilds its transform as scale, then rotation, then translation that way.
Culling and the clip planes are changed through rlgl.h:
; // foliage, cloth, the inside of a box
;
;
; // cull fronts instead
; // back to the default
; // read by the next BeginMode3DWhat to draw
Two families of API sit on top of the same mesh pipeline:
- Immediate-mode primitives —
DrawCube,DrawSphere,DrawCylinder,DrawPlane,DrawLine3D,DrawRay,DrawBoundingBox,DrawGrid. Good for debug viz, placeholder geometry, and gizmos. These helpers submit geometry through rlgl's internal path; reuse aMeshorModelwhen persistent geometry is the better fit. - Meshes & models — persistent GPU buffers.
Mesh,Material, andModelstructs. This is what you want for anything drawn more than once.
DrawGrid and DrawRay are the two I keep reaching for while debugging. Any time a 3D coordinate seems off, dropping a DrawSphere at that point answers it faster than a printf.
Meshes
A Mesh is a flat struct of CPU-side geometry arrays plus GPU object IDs:
typedef struct Mesh Mesh;UploadMesh(&mesh, dynamic) copies CPU-side arrays to GPU buffers. UpdateMeshBuffer(mesh, i, data, size, offset) patches one buffer for dynamic geometry. UnloadMesh(mesh) frees both sides.
Built-in generators for the usual primitives:
Mesh sphere = ;
Mesh torus = ;
Mesh knot = ;
Mesh plane = ; // subdivided
Mesh hf = ;
Mesh cubicmap = ;GenMeshHeightmap and GenMeshCubicmap are the "terrain in one line" shortcuts — the first turns a grayscale image into a plane with displaced Y, the second turns a black-and-white image into blocky stacked cubes. For anything organic, generate your own vertex arrays and call UploadMesh.
Models & materials
A Model bundles one or more meshes with materials and an optional skeleton:
Model model = ;
model.materials.maps.texture = ;
;
;Depending on the build configuration, current raylib supports OBJ, IQM (skeletal animation), glTF/glb, VOX (MagicaVoxel), and M3D. glTF/glb is a practical interchange format for an asset pipeline.
A Material is a default-shader + up to 12 texture maps:
| Map | Slot |
|---|---|
MATERIAL_MAP_DIFFUSE / ALBEDO | base colour |
MATERIAL_MAP_METALNESS | metallic |
MATERIAL_MAP_NORMAL | normal map |
MATERIAL_MAP_ROUGHNESS | roughness |
MATERIAL_MAP_OCCLUSION | AO |
MATERIAL_MAP_EMISSION | emissive |
MATERIAL_MAP_HEIGHT | height/parallax |
MATERIAL_MAP_CUBEMAP | environment |
MATERIAL_MAP_IRRADIANCE | diffuse IBL |
MATERIAL_MAP_PREFILTER | specular IBL |
MATERIAL_MAP_BRDF | split-sum LUT |
The stock shader is unlit and primarily handles the base texture and tint. For lighting or PBR, you ship a custom shader and wire the required maps and uniforms yourself; PBR in raylib walks through the metallic-roughness case. The raylib-extras organisation collects useful community examples and helpers.
Shaders
Shader is a vertex+fragment program pair loaded from files:
Shader sh = ;
int locTime = ;
model.materials.shader = sh;
// in the draw loop
float t = ;
;
;Locations raylib discovers automatically when a custom shader uses its conventional names:
mvp— full MVP matrix.matModel,matView,matProjection— components.colDiffuse— the tint passed toDrawModel.texture0..texture2— up to three samplers.
Other application-specific uniforms still need an explicit location. Camera-dependent examples commonly assign SHADER_LOC_VECTOR_VIEW themselves with GetShaderLocation(sh, "viewPos").
Pass NULL for either stage to use the built-in one:
Shader sh = ; // default VS, custom FSCross-platform tip: the shader source still has to match the selected graphics backend. Raylib's examples usually choose separate GLSL 330 desktop and GLSL 100/300 ES files at compile time; LoadShaderFromMemory is useful when you prefer to assemble those variants in code.
Lighting — rlights.h
Raylib doesn't ship built-in lighting: the stock shader is unlit and nothing in raylib.h creates a light. What tutorials call raylib lighting is examples/shaders/rlights.h, a header from the examples folder that you copy into your project along with the lighting.vs / lighting.fs pair it was written for. It feeds up to four lights to a forward shader, and it is a single-header library, so exactly one source file defines RLIGHTS_IMPLEMENTATION before including it:
Shader sh = ;
sh.locs = ;
int ambientLoc = ;
float ambient = ;
;
Light lights = ;Each frame the shader needs the camera position, and any light you changed has to be pushed again:
float t = ;
float cam = ;
;
lights.position = ;
; // nothing reaches the GPU until this call
;
; // immediate-mode shapes: per block
;
;
; // models: model.materials[0].shader = sh
;The whole header is a struct and two functions:
Light—type,enabled,position,target,colorandattenuation, plus the uniform locations it caches.CreateLight(type, position, target, color, shader)— fills the struct, looks uplights[i].enabled,.type,.position,.targetand.colorin the shader, and uploads them once.iis a static counter inside the header, so lights take slots in creation order.UpdateLightValues(shader, light)— uploads those five values again. Call it after any change, togglingenabledincluded.- Two types —
LIGHT_DIRECTIONAL, whose rays run frompositiontowardstarget, andLIGHT_POINT. MAX_LIGHTSis 4, andlighting.fscarries its own#define MAX_LIGHTS 4. Change both or neither.
The shading in lighting.fs is plain: Lambert diffuse per light, a Phong specular term from reflect() with the exponent fixed at 16, an ambient uniform that the shader divides by ten, and a pow(1.0/2.2) gamma step at the end. Its vertex shader wants matModel and matNormal; raylib fills those, and mvp, for any shader that uses the conventional names. viewPos and ambient are yours to set.
What it does not give you:
- Attenuation. The struct has the field, but the header never uploads it and the shader has no such uniform: a point light is as bright at fifty units as at one.
- Spot lights, shadows, normal mapping, a shininess per material, or a fifth light without editing both files.
Past that point it is often simpler to drop the helper than to extend it. Raym doesn't include rlights.h at all: its terrain shader takes one lightPos / lightColor pair set with plain SetShaderValue calls and does the rest in GLSL, with Blinn-Phong from a half vector and the diffuse term quantised into four bands:
// Raym — resources/shaders/lighting_shader.fs (excerpt)
vec3 lightDir = ;
float diff = ;
// Calculate specular reflection (Blinn-Phong)
vec3 halfwayDir = ;
float spec = ;
// Apply cell shading to diffuse lighting (4 bands for better definition)
diff = ;
vec3 ambient = ambientStrength * lightColor;
vec3 diffuse = diff * lightColor;
vec3 specular = specularStrength * spec * lightColor;For many lights you graduate to your own pipeline (see Deferred vs forward rendering); raylib's shaders_deferred_rendering.c example is a G-buffer version that still creates its lights with rlights.h. The header is "demo quality" but perfect for small projects.
Shadows
rlights.h has no shadows, and neither does anything in raylib.h. The reference is examples/shaders/shaders_shadowmap_rendering.c: one directional light, a 1024×1024 depth map, and a 3×3 percentage-closer lookup with a slope-scaled bias. Three things in it are worth knowing before you start:
- It builds its own depth-only framebuffer with rlgl (
rlLoadFramebuffer,rlLoadTextureDepth(w, h, false),rlFramebufferAttach), becauseLoadRenderTextureattaches its depth as a renderbuffer, which a shader cannot sample. - The light is an ordinary orthographic
Camera3D, and its view and projection are read back withrlGetMatrixModelview()andrlGetMatrixProjection()while the scene is drawn from it. - The depth texture is bound by hand to a spare slot with
rlActiveTextureSlotandrlEnableTexturebefore the second pass.
The theory, cascades and the biasing problem are in Shadow mapping.
Textures & render targets
Texture2D tex = ;
Image img = ; // CPU-side
RenderTexture2D rt = ; // FBORender-to-texture is the gateway to post-processing:
;
;
;
;
;
;
;
;
;
;
;
;The negative height is the Y-flip for the flipped FBO coordinate system — easy to forget and produces an "everything is upside down" bug that baffles for longer than it should.
SetConfigFlags(FLAG_MSAA_4X_HINT) asks for a 4× multisampled window, but only if it runs before InitWindow, and only for the main framebuffer: a scene drawn into a RenderTexture2D gets no MSAA and needs a post-process filter instead (see real-time anti-aliasing).
Instancing
DrawMeshInstanced takes an array of transforms and a custom shader that reads them from the conventional instanceTransform mat4 attribute. Use raylib's semantic location instead of hard-coding a numeric attribute index:
Matrix *transforms = ;
for
transforms = ;
Shader instanceSh = ;
instanceSh.locs = ;
instanceSh.locs =
;
Material mat = ;
mat.shader = instanceSh;
;The instance VS multiplies by instanceTransform before MVP:
in vec3 vertexPosition;
in mat4 instanceTransform; // one per instance, not per vertex
uniform mat4 mvp;
void What DrawMeshInstanced expects, and what it does with it:
- The attribute. A
mat4attribute occupies four consecutive locations, and raylib enables all four with a divisor of 1. In 6.x,LoadShaderresolvesSHADER_LOC_VERTEX_INSTANCETRANSFORM(andmvp) by itself when the names are the conventional ones, so the two assignments above are belt and braces. In 5.x that enum did not exist and the attribute location went inshader.locs[SHADER_LOC_MATRIX_MODEL], which is the line older tutorials show. - The material. The shader comes from
material.shader, not fromBeginShaderMode. The material's diffuse colour arrives ascolDiffuseand its texture maps are bound as they are forDrawMesh. - The matrices.
mvphere is view × projection only, plus whateverrlPushMatrixtransform is active. The model matrix is identity andmatModelis not uploaded, so world-space position has to come frominstanceTransform.matNormalis uploaded as identity for the same reason, and the stocklighting_instancing.vsuses it: rotated instances are lit with unrotated normals. Build the normal from the instance matrix instead:
fragPosition = vec3;
fragNormal = ;- The cost. Every call allocates an array, converts the matrices, creates a VBO, draws, and deletes the VBO again. That is fine for a few thousand moving instances; for a large static set it is pure overhead, and the fix is your own instance buffer through rlgl (
rlLoadVertexBuffer,rlSetVertexAttributeDivisor,rlDrawVertexArrayInstanced). - The limits. The transform is the only per-instance data, nothing is culled per instance, and the function body exists only for the OpenGL 3.3 and ES backends.
Instancing is not batching, which is the other mechanism and is automatic. Everything drawn through rlBegin / rlEnd (DrawCube, DrawSphere, lines, text, 2D textures) is appended to one CPU-side vertex buffer, the render batch. A change of primitive mode or texture starts a new draw call inside it. The batch is uploaded and drawn when its buffer fills (8,192 quads by default on desktop, 2,048 on the ES backends), when its 256 draw-call slots run out, when the active shader changes, or when a function such as BeginMode3D, EndMode3D, BeginTextureMode or EndDrawing runs. Meshes never go through it: each DrawMesh, and so each mesh of each DrawModel, is its own draw call. Many small immediate shapes are already batched; many copies of one mesh want DrawMeshInstanced.
rlgl — the layer below
rlgl.h is Raylib's OpenGL abstraction layer: a thin wrapper that presents an immediate-mode interface (rlBegin, rlVertex3f, rlColor4ub, rlEnd) and batches draws internally. It is how DrawCube is implemented, and how you drop below the friendly API when you need to:
- Build custom meshes vertex-by-vertex without touching OpenGL directly.
- Push/pop matrix state (
rlPushMatrix,rlRotatef,rlTranslatef) à la old GL. - Manage your own VBOs/VAOs/SSBOs (
rlLoadVertexBuffer,rlLoadVertexArray). - Dispatch compute shaders on GL 4.3+ with
rlLoadShaderProgramCompute(namedrlLoadComputeShaderProgrambefore 6.0) andrlComputeShaderDispatch; Compute shaders in raylib has the walk-through.
When you need a modern feature Raylib doesn't expose at the top level, rlgl is almost always where it lives. If that fails, you can mix raw OpenGL into a raylib program — the GL context is just there.
Custom mesh via rlgl
The cleaner path is usually: build float arrays, call UploadMesh, done. When you need immediate-mode for viz:
;
;
;
;
;
;Raylib's internal batcher starts a new draw call when the primitive type or texture changes, and flushes when the shader changes, its buffers fill, or EndMode3D/EndDrawing runs (the details are under Instancing above). Keep all your immediate-mode calls contiguous per material to avoid unnecessary draw calls.
Skyboxes
Standard cube-map skybox — the examples/models/models_skybox_rendering.c sample is the reference:
- Load an image in a supported cubemap layout with
LoadTextureCubemap, or convert an equirectangular panorama to a cubemap with a shader pass. - Create a unit cube mesh and assign a material with a custom shader that samples the cubemap.
- Draw from inside the cube with back-face culling and depth writes temporarily disabled. The sample shader removes view translation so the skybox stays centred on the camera.
In code, following the sample:
Mesh cube = ;
Model skybox = ;
skybox.materials.shader = ;
// "environmentMap" is not one of raylib's conventional names: point it at the cubemap's unit by hand
;
Image img = ; // all six faces in one image
skybox.materials.maps.texture =
;
;
// each frame, first thing inside BeginMode3D
; // we are inside the cube
; // the sky writes no depth
;
;
;The parts that are easy to get wrong:
- The sampler value is the map index.
DrawMeshbinds each material map to the texture unit of its own index, and the cubemap, irradiance and prefilter slots as cubemaps. The uniform therefore getsMATERIAL_MAP_CUBEMAP, not 0. - One image, six faces.
LoadTextureCubemaptakes a single image and a layout: a vertical or horizontal strip, a 3×4 or 4×3 cross, orCUBEMAP_LAYOUT_AUTO_DETECT. - Translation is stripped in the vertex shader, with
mat4 rotView = mat4(mat3(matView));, so the cube turns with the camera but never moves away from it. - Draw it first. With depth writes off, the sky leaves nothing in the depth buffer and everything drawn afterwards covers it. Drawn last, the same small cube would paint over anything further away than its faces.
HDR equirectangular → cubemap conversion is also one example away, using a LoadShader pass and an FBO. The sample's useHDR switch loads the panorama as a plain texture and renders it into the six faces with GenTextureCubemap, a static helper inside the example rather than a raylib function; the skybox shader then tone-maps and gamma-encodes when its doGamma uniform is set.
Things that tripped me up
- Y axis on render textures —
DrawTextureRecwithheight = -texture.heightis the fix. The Raylib coordinate system is Y-up but FBO textures are stored Y-down. - Repeated high-detail primitives add up — for many spheres or other repeated shapes, profile the immediate helper and consider drawing a reused mesh or instanced model.
- Material slot 0 is the common case — a successfully loaded model normally has a default material there, and most tutorials assume it. Multi-material models have the per-mesh material index in
model.meshMaterial[i]. - Model-relative assets matter —
LoadModelresolves referenced textures from the model's directory. Keep the expected asset layout intact or wire textures explicitly. - Shader uniforms must be set while bound —
SetShaderValuebinds the shader implicitly, but cache the locations withGetShaderLocationonce, not per-frame. - Y-up vs Y-down in glTF — both coordinates conventions appear in the wild. A flipped normal map usually means your tangent space disagrees with the asset's.
- Render-state ownership —
BeginMode3Dswitches projection/view state and enables depth testing. If you mixrlglor raw OpenGL calls with Raylib helpers, verify the state at the point of use instead of assuming every state is reset. - Batch capacity is configurable — rlgl batches immediate-mode geometry, and compile-time settings such as
RL_DEFAULT_BATCH_BUFFER_ELEMENTScontrol its capacity. Defaults can change between Raylib versions, so check the version you build against before tuning them. - rlgl compute is backend-specific — raylib exposes it for the OpenGL 4.3 backend, not its WebGL path. Cross-platform projects need another implementation for that work.
- State changes don't wait for the batch —
rlDisableBackfaceCulling()and its neighbours change GL state at once, while immediate-mode geometry is only drawn at the next flush. AroundDrawCube-style helpers, callrlDrawRenderBatchActive()before changing state;DrawModeldraws straight away. rlights.hcounts lights globally — the slot index is one static counter, not one per shader. Lights for a second shader continue from where the first stopped, and a fifthCreateLightreturns a zeroedLightthat should not reachUpdateLightValues.
Ecosystem
- raygui — immediate-mode UI in the same spirit.
- raylib-extras — community extras: PBR, particle systems, glTF tooling, camera controllers.
- r3d — a third-party project that describes itself as a "3D Extension Library for raylib", with PBR among its listed topics.
- rres — Raylib's resource packaging format.
- raymath.h — the built-in math lib. Quaternions, matrices, SLERP, everything you'd want.
References
- raylib.com — docs and API cheatsheet.
- raylib examples — the
models/andshaders/folders are the most useful. - Raylib cheatsheet — one-page API reference on the site.
- Ramon Santamaria's talks on the philosophy and internals of Raylib.
Back to Notes · see also Ray Picking Through the Rendering Pipeline · real-time anti-aliasing · Debugging Graphics Without Guessing · Raym