./jerome{m}jack in

~/Notes/PBR in raylib.md · note · seedling · 7 min · updated

PBR in raylib

// status: seedling

raylib's default shader multiplies a texture by a tint and stops there. Physically based materials are something you bring yourself: one shader pair, and some wiring so that raylib's Material feeds it. This note is the wiring. The theory behind the shader is in Physically Based Rendering; the rest of raylib's 3D side is in Raylib 3D rendering.

Everything below was checked against raylib 6.2. The viewer is raylib itself, compiled to WebAssembly, running the shader printed on this page.

pbr · liveOne metallic-roughness shader in raylib. Pick a material, move roughness and metalness, turn on the chart to see both swept at once, or the normal map to see the tangent frame at work. Drag to look around.open ↗

What raylib sends, and what it leaves to you

DrawMesh uploads a fixed set of things from the Material you hand it. Knowing the exact list saves an afternoon, because the struct has fields that look as if they were wired and are not.

DrawMesh sendsTaken fromShader side
mvp, matModel, matNormalthe transform and the camerauniforms found by name when the shader loads
Vertex attributes, tangents includedthe meshvertexPosition, vertexTexCoord, vertexNormal, vertexTangent, found by name
maps[MATERIAL_MAP_ALBEDO].colorthe materialthe uniform at locs[SHADER_LOC_COLOR_DIFFUSE]
maps[MATERIAL_MAP_SPECULAR].colorthe materialthe uniform at locs[SHADER_LOC_COLOR_SPECULAR], if you set that slot
Every map whose texture has an idthe materialbound to the texture unit of its index; the sampler at locs[SHADER_LOC_MAP_ALBEDO + i] is set to that unit

And the list of what it does not send:

  • maps[i].value. The metalness and roughness scalars sit in the material and never reach the GPU. You send them.
  • The camera position. SHADER_LOC_VECTOR_VIEW is a slot to keep the location in, nothing more.
  • Lights. raylib has no notion of them.

The names raylib looks up on its own are the vertex attributes above, mvp, matView, matProjection, matModel, matNormal, colDiffuse, and three samplers called texture0, texture1 and texture2, which land in the albedo, metalness and normal slots. Use other names and you point the slots at them yourself, which reads better in a PBR shader anyway.

Wiring it up

Load the shader and fill in the slots:

c
shader = LoadShaderPortable("resources/shaders/pbr.vs", "resources/shaders/pbr.fs");

// raylib finds mvp, matModel, matNormal and the vertex attributes by
// name. Everything else has to be pointed at the right slot.
shader.locs[SHADER_LOC_COLOR_DIFFUSE] = GetShaderLocation(shader, "albedoColor");
shader.locs[SHADER_LOC_MAP_ALBEDO] = GetShaderLocation(shader, "albedoMap");
shader.locs[SHADER_LOC_MAP_NORMAL] = GetShaderLocation(shader, "normalMap");
shader.locs[SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(shader, "viewPos");
metallicLoc = GetShaderLocation(shader, "metallicValue");
roughnessLoc = GetShaderLocation(shader, "roughnessValue");
useNormalMapLoc = GetShaderLocation(shader, "useNormalMap");

LoadShaderPortable is LoadShader on desktop; the web section below says what it does in a browser.

The material is the default one with the shader swapped in. The default material already carries a 1×1 white texture in the albedo slot, so the shader can sample albedoMap whether or not you load an image:

c
material = LoadMaterialDefault();
material.shader = shader;
material.maps[MATERIAL_MAP_NORMAL].texture = GenTextureDimples(256, 4, 1.1f);

Each draw then sends the two scalars, and lets DrawMesh do the rest:

c
static void DrawBall(Vector3 position, float radius, float roughness, float metallic)
{
    // DrawMesh sends the albedo colour, the matrices and the textures.
    // The two scalars are ours to send.
    SetShaderValue(shader, roughnessLoc, &roughness, SHADER_UNIFORM_FLOAT);
    SetShaderValue(shader, metallicLoc, &metallic, SHADER_UNIFORM_FLOAT);
    // GenMeshSphere puts its poles on the Z axis; stand it up first.
    Matrix transform = MatrixMultiply(MatrixScale(radius, radius, radius), MatrixRotateX(-90.0f*DEG2RAD));
    transform = MatrixMultiply(transform, MatrixTranslate(position.x, position.y, position.z));
    DrawMesh(sphere, material, transform);
}

DrawMesh draws at once, so changing a uniform between two calls gives two different materials from one shader. That is all the chart in the viewer is: twelve calls to this function.

Once a frame, the camera position and the lights go up the same way:

c
SetShaderValue(shader, shader.locs[SHADER_LOC_VECTOR_VIEW], &camera.position, SHADER_UNIFORM_VEC3);

A light here is a position and a colour already multiplied by its intensity, in a two-element uniform array. raylib's rlights.h helper is built for its own basic lighting example and does not fit; a struct of your own with two locations per light is less code than adapting it.

The fragment shader

The whole material model is the metal/dielectric split, three lines:

glsl
// The metal/dielectric split: a metal has no diffuse colour and tints
// its reflection; everything else reflects about 4%, untinted.
vec3 f0 = mix(vec3(0.04), albedo, metallic);
vec3 diffuseColor = albedo*(1.0 - metallic);

Then one loop over the lights, with the usual Cook-Torrance terms:

glsl
for (int i = 0; i < MAX_LIGHTS; i++)
{
    vec3 toLight = lights[i].position - fragPosition;
    float distance2 = dot(toLight, toLight);
    vec3 L = toLight*inversesqrt(distance2);
    vec3 H = normalize(V + L);

    float nDotL = max(dot(N, L), 0.0);
    float nDotH = max(dot(N, H), 0.0);
    float vDotH = max(dot(V, H), 0.0);

    float D = DistributionGGX(nDotH, alpha);
    float G = GeometrySmith(nDotV, nDotL, roughness);
    vec3 F = FresnelSchlick(vDotH, f0);

    vec3 specular = D*G*F/(4.0*nDotV*max(nDotL, 0.0001));
    vec3 diffuse = (1.0 - F)*diffuseColor/PI;
    vec3 radiance = lights[i].color/distance2;

    color += (diffuse + specular)*radiance*nDotL;
}

D, G and F are GGX, Smith with Schlick's approximation, and Schlick's Fresnel; the PBR note derives them. Two details are easy to get wrong:

  • alpha is roughness squared. The slider is perceptual roughness; the distribution wants its square. alpha = roughness*roughness once, at the top.
  • Roughness needs a floor. At exactly zero the GGX term is 0/0 where the normal meets the half vector. The shader clamps to 0.045.

Colour in, colour out

albedoColor arrives as an 8-bit sRGB colour, because that is what a raylib Color is. Lighting has to happen in linear space, so the shader converts on the way in and back on the way out:

glsl
// Colours arrive in sRGB; the lighting maths wants linear.
vec3 albedo = pow(albedoColor.rgb*texture(albedoMap, fragTexCoord).rgb, vec3(2.2));
glsl
// Reinhard tone mapping on brightness alone, so a strong colour keeps
// its hue instead of washing out toward white.
color /= 1.0 + dot(color, vec3(0.2126, 0.7152, 0.0722));
color = pow(color, vec3(1.0/2.2));      // back to sRGB for the screen

Skip the first conversion and every material looks chalky; skip the second and everything is too dark. A normal map is data, not colour, and must not be converted.

Something to reflect

A metal has no diffuse colour. Light it with two point lights against a black void and it is a black ball with two dots on it. Real PBR renderers solve this with image-based lighting: a prefiltered environment cubemap, an irradiance map, and a lookup table. The viewer cheats with eight lines:

glsl
// What the surface "sees" in a direction: sky above, ground below, and a
// horizon that blurs as the surface gets rougher.
vec3 Environment(vec3 dir, float roughness)
{
    float blur = mix(0.03, 1.0, roughness);
    return mix(groundColor, skyColor, smoothstep(-blur, blur, dir.y));
}
glsl
// Ambient: diffuse from the whole sky, specular from the mirror direction.
vec3 F = FresnelSchlickRoughness(nDotV, f0, roughness);
color += (1.0 - F)*diffuseColor*Environment(N, 1.0);
color += F*Environment(reflect(-V, N), roughness);

It is a stand-in, and an honest one: the horizon you see in the smooth spheres of the chart is this function. It is enough to make metals read as metals, and it has the same inputs a real environment lookup would. The real thing is in the IBL section of the PBR note; raylib's Material even has IRRADIANCE, PREFILTER and BRDF slots, and DrawMesh binds the first two as cubemaps. Generating the maps is left to you.

Normal maps need tangents

A tangent-space normal map stores directions relative to the surface, so the shader needs the surface's frame at every pixel: normal, tangent, bitangent. The normal comes with the mesh. The tangent does not, unless you ask:

c
// A normal map needs tangents, and GenMeshSphere does not make them.
sphere = GenMeshSphere(1.0f, 48, 64);
GenMeshTangents(&sphere);

GenMeshTangents needs texture coordinates and normals to work from, and stores a vec4 per vertex whose w is the handedness. For a model loaded from glTF, raylib reads tangents from the file when it has them. Once a mesh has them, DrawMesh binds them to vertexTangent without being asked.

The vertex shader builds the frame in world space:

glsl
// World-space frame for the normal map. The tangent is re-squared
// against the normal, since interpolation and scaling skew it.
vec3 n = normalize(mat3(matNormal)*vertexNormal);
vec3 t = normalize(mat3(matModel)*vertexTangent.xyz);
t = normalize(t - dot(t, n)*n);

fragNormal = n;
fragTangent = t;
fragBitangent = cross(n, t)*vertexTangent.w;

and the fragment shader uses it to turn the texel into a world-space normal:

glsl
vec3 tangentNormal = texture(normalMap, fragTexCoord*normalTiling).xyz*2.0 - 1.0;
mat3 tbn = mat3(normalize(fragTangent), normalize(fragBitangent), N);
N = normalize(tbn*tangentNormal);

The dimples in the viewer are not an image file. The program writes the texture at start-up: each cell holds one cosine-shaped bowl, whose slope is known exactly, so the normal can be written directly with no height map in between. Turn on normal map and each dimple picks up its own highlight and its own piece of horizon, which is the point of doing the lighting per pixel.

On the web

raylib's web target is WebGL 2, which speaks GLSL ES 3.00. The shaders above are GLSL 330 and need only a different first line, so the loader swaps it:

c
// WebGL 2 speaks GLSL ES 3.00. The shaders are written for GLSL 330 and
// need nothing but a different header, so swap `#version 330` at load time.
static char *ToGlslEs(const char *source)
{
    const char *header = "#version 300 es\nprecision highp float;\n";
    const char *body = strstr(source, "#version 330");
    body = body ? strchr(body, '\n') : NULL;
    body = body ? body + 1 : source;
    char *out = (char *)malloc(strlen(header) + strlen(body) + 1);
    strcpy(out, header);
    strcat(out, body);
    return out;
}

This is the same trick Raym uses. It works as long as the shader stays inside what both dialects share, which this one does: no layout qualifiers, no integer textures, constant loop bounds.

The build is CMake with Emscripten, raylib configured for PLATFORM=Web and OPENGL_VERSION "ES 3.0". The page's sliders call one exported C function. The whole viewer is about 128 KB of WebAssembly.

What this does not do

  • No image-based lighting. See above. It is the single biggest step from "looks like PBR" to "looks right".
  • No shadows. Shadow mapping covers the technique; raylib ships a shadow-map example.
  • No packed textures. raylib's own PBR example reads metalness, roughness and occlusion from one texture in the metalness slot. This shader takes scalars, to keep the viewer honest about what each one does. Adding the lookup is three lines.
  • One light model. Two point lights with inverse-square falloff. Directional and spot lights are a few more lines each.

If you would rather not write any of this, r3d is a third-party 3D extension library for raylib that lists PBR among its features.

Things that tripped me up

  • maps[].value is decorative. Setting material.maps[MATERIAL_MAP_ROUGHNESS].value changes nothing on screen by itself. DrawMesh uploads two colours and the textures, and that is the end of the list.
  • GenMeshSphere has its poles on Z. It also runs u from pole to pole and v around, the opposite of what most sphere maps assume. The first version of the viewer showed its dimples stretched into ovals around a pole that faced the camera.
  • raylib's example has an odd tone-mapping line. pbr.fs in the official example ends with pow(color, color + vec3(1.0)) under the comment "HDR tonemapping". That is not a tone curve. Copy the BRDF from that file if you like, and replace the last lines.
  • The MSAA flag goes before the window. SetConfigFlags(FLAG_MSAA_4X_HINT) after InitWindow has no effect on the window that already exists.
  • A black metal is not a bug in the BRDF. With no environment there is nothing to reflect. Check the ambient term before the maths.

References

  • raylib's own example: shaders_basic_pbr.c and its fragment shader.
  • DrawMesh in rmodels.c: everything it uploads is in the first half of the function, under the comment "Send required data to shader".
  • Karis, B. — Real Shading in Unreal Engine 4 (SIGGRAPH 2013 course notes): the source of the roughness remapping and the split-sum approximation.
  • LearnOpenGL: PBR — the most approachable derivation of the three terms.
  • r3d — "3D Extension Library for raylib".

Back to Notes · see also Raylib 3D rendering · Physically Based Rendering · Shadow mapping · Normals for Implicit Surfaces