TExcelTAD
Home › Shaders & Graphics Programming › Debugging Shaders

Debugging Shaders

You cannot printf from a pixel shader. A single frame runs a fragment shader millions of times, and when something goes wrong the result is usually silent: a black screen, a magenta mesh, a flicker on one GPU. Shader debugging is a mix of two skills: making the shader show you its values as colors, and using a frame debugger to inspect what the GPU actually received and did.

Technique 1: output the value as a color

The fastest debugger is fragColor = vec4(value, 1.0);. Replace the final color with the intermediate value you doubt, and look.

Direction vectors are in −1..1, so remap them to 0..1 with n * 0.5 + 0.5. A sphere's normals then show the familiar pastel ball: right = pinkish red (+X), up = green (+Y), toward you = blue (+Z). Any other pattern means the normals are wrong, flipped or in the wrong space.

glsl · try it yourself
// Debug view: UVs on the left, normals of a sphere on the right.
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = fragCoord / iResolution.xy;
    if (uv.x < 0.5) {
        vec2 local = vec2(uv.x * 2.0, uv.y);           // the left half's own 0..1 UVs
        fragColor = vec4(local, 0.0, 1.0);             // red = u, green = v: check orientation at a glance
        return;
    }
    vec2 p = (uv - vec2(0.75, 0.5)) * vec2(iResolution.x / iResolution.y * 2.0, 2.0) * 1.6;
    float r2 = dot(p, p);
    if (r2 > 1.0) { fragColor = vec4(0.1, 0.1, 0.1, 1.0); return; }
    vec3 n = vec3(p, sqrt(1.0 - r2));                  // unit sphere normal, facing the viewer
    fragColor = vec4(n * 0.5 + 0.5, 1.0);
}

For UVs, the corner at the bottom-left should be black, bottom-right red, top-left green, top-right yellow. If yours is upside down, the texture's V axis is flipped (a common difference between OpenGL-style and D3D-style assets).

Out-of-range and NaN detectors

Many bugs are values outside the range you assume: a "0..1" factor that is actually 1.7, a negative light value. A false-color view makes them jump out. This shader computes a deliberately broken lighting term and paints each kind of problem in its own color:

glsl · try it yourself
// green = valid 0..1 (shown as gray level), red = above 1, blue = below 0, magenta = NaN
vec3 debugRange(float v) {
    if (isnan(v)) return vec3(1.0, 0.0, 1.0);
    if (v > 1.0) return vec3(1.0, 0.0, 0.0);
    if (v < 0.0) return vec3(0.0, 0.0, 1.0);
    return vec3(v);
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = fragCoord / iResolution.xy;
    vec2 p = uv * 2.0 - 1.0;
    // Buggy "falloff": unclamped, and sqrt of a negative number outside the circle
    float falloff = 1.3 - length(p) * 1.2;
    float bad = sqrt(1.0 - dot(p, p) * (0.8 + 0.4 * sin(iTime)));
    float v = uv.x < 0.5 ? falloff : bad;
    fragColor = vec4(debugRange(v), 1.0);
}

On the left, the red core shows where falloff exceeds 1 (it should have been clamped) and the blue rim where it goes negative. On the right, sqrt of a negative number is undefined: on most GPUs it produces NaN, shown in magenta. GLSL ES 3.00 has isnan() and isinf(); another classic NaN test is v != v, which is true only for NaN, but some compilers optimize it away, so prefer isnan.

Note: The GLSL specification says results like sqrt(-1.0) and normalize(vec3(0.0)) are undefined, not "NaN". Most desktop GPUs return NaN, but some return 0 or another value. Undefined means: guard it, do not rely on it. Field Notes has the guards.

Isolate, then bisect

  • Replace the whole output with a constant color. If even that is black, the problem is not in your math: it is the draw itself (geometry, matrices, blending, depth test). If it shows, the pipeline works and the bug is in the shader code.
  • Comment out half of the computation and output the halfway value. Repeat. Shaders are pure functions, so bisection works very well.
  • Test one input at a time: set iTime-style uniforms to a constant to rule out animation, fix the light direction to (0, 0, 1).

Technique 2: read the compiler error

Compile errors are the easy bugs, if you read them carefully. GLSL ES is stricter than many C-family languages. For example, it has no implicit conversion between int and float:

glsl · try it yourself
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    float brightness = 1;
    fragColor = vec4(vec3(brightness), 1.0);
}
Shader compile error:
ERROR: line 2: '=' : cannot convert from 'const int' to 'highp float'

Fix: 1.0. The message tells you the line, the operator, and both types; the highp comes from the playground's precision highp float; default. Other errors you will meet often: 'x' : undeclared identifier (a typo or a variable declared inside an if block), wrong operand types (vec3 * vec2, or mat4 * vec3), and 'return' : function return is not matching type (a function that returns vec3 returning vec4).

Engines add their own layer: Unity shows shader errors in the Console and in the shader asset's Inspector, Unreal in the Material Editor's Stats panel, and Godot underlines the line in its shader editor. A shader that fails to compile is drawn in a fallback: magenta in Unity, the default material's checkerboard in Unreal.

Technique 3: frame debuggers

A frame debugger captures one frame: every API call, every buffer, texture and render target, every pipeline state. You can then click a draw call and see its inputs, its outputs, and often step through its shader for a single pixel.

Tool APIs / platforms Best at
RenderDoc (free, open source) D3D11, D3D12, Vulkan, OpenGL, OpenGL ES; Windows, Linux, Android the default choice: event browser, texture viewer, pipeline state, mesh viewer, pixel history, shader debugging on D3D and Vulkan
PIX (free, Microsoft) D3D12 on Windows (and Xbox for licensed developers) GPU captures with shader debugging, plus timing captures for CPU/GPU profiling
NVIDIA Nsight Graphics D3D11, D3D12, Vulkan, OpenGL on NVIDIA GPUs frame debugging plus GPU Trace: deep hardware counters and per-draw cost
Xcode Metal debugger Metal on Apple platforms captures, shader debugging and performance counters on Apple GPUs
Spector.js (browser extension / library) WebGL 1 and 2 capturing a WebGL frame in the browser: commands, states, shaders and textures
AMD Radeon GPU Profiler D3D12, Vulkan on AMD GPUs low-level timing and occupancy

Engines integrate them: Unity's Game view and Scene view can load RenderDoc and capture with one click (and Unity has its own Frame Debugger under Window > Analysis), and Unreal ships a RenderDoc plugin. Godot can be captured by launching it from RenderDoc.

A typical RenderDoc session

  1. Launch your game from RenderDoc (Launch Application), or attach to it, and press the capture key (F12 or Print Screen by default).
  2. Open the capture. In the Event Browser, find the draw call for the broken object (name your passes with debug markers, vkCmdBeginDebugUtilsLabelEXT or the engine's profiler scopes, to make this easy).
  3. Mesh Viewer: are the vertex shader's output positions where you expect? Garbage or all-zero positions mean a wrong matrix or vertex layout.
  4. Pipeline State: which shaders, which textures and buffers are bound, the blend, depth and cull state. A forgotten depth clear or an inverted cull mode shows up here.
  5. Texture Viewer with the output target: right-click a pixel for Pixel History (every draw that touched it and whether depth or stencil rejected it), then Debug to step through the fragment shader for that pixel with real values.

The black screen checklist

When nothing appears at all, check these in order. Most "black screens" are one of the first five:

  1. Did the shader compile and link? Check the info log; in WebGL, getShaderInfoLog and getProgramInfoLog.
  2. Is the uniform actually set? A misspelled uniform name returns location -1 (WebGL: null), and setting it silently does nothing, so a matrix stays all zeros and every vertex collapses to a point. Also: uniforms are set on the currently bound program.
  3. Matrix order or layout: projection * view * model * position, not the reverse; a row-major matrix uploaded where column-major is expected is transposed. See Matrices in Shaders.
  4. The geometry is outside the clip volume: the camera is inside the object, behind it, or the near/far planes exclude it. Output a constant color and draw a single big triangle to test.
  5. Culling and winding: the triangles are back-facing (counter-clockwise vs clockwise), so all of them are culled. Disable culling as a test.
  6. Depth: the depth buffer is not cleared, the depth test compares the wrong way (common with reversed Z), or depth range differs between APIs.
  7. Alpha and blending: alpha is 0 with blending on, or the output writes to the wrong attachment.
  8. NaN or Inf: a single NaN can spread through a blur or bloom chain until the whole screen is black. Use the NaN detector above.
  9. Color space: everything very dark, not black? Linear vs sRGB mismatch, see Field Notes.

Test yourself

You replace the shader's output with vec4(1.0, 0.0, 1.0, 1.0) and the screen is still black. Where is the bug most likely?

  1. In the lighting math
  2. Outside the fragment shader: geometry, matrices, culling, depth or blending
  3. In the texture sampling
  4. In the noise function

Which RenderDoc feature lists every draw that touched one pixel, and whether it passed the depth test?

  1. Mesh Viewer
  2. Pixel History
  3. Event Browser
  4. Pipeline State

Why does float brightness = 1; fail to compile in GLSL ES 3.00?

  1. brightness is a reserved word
  2. GLSL ES has no implicit int-to-float conversion
  3. Floats must be declared as uniforms
  4. The precision qualifier is missing