Skip to content
Tech Interview Prep

Top 100 Graphics Engineer Interview Questions and Answers

The questions most likely to come up in your Graphics Engineer interview, ranked by likelihood, with senior-level answers that cover what the interviewer is listening for.

Curated: · Written: · Reviewed: —

Reviewed 0Review pending 99

99 questions · Flow follows Relevance until this set has a learning order.

Q&A-1Walk me through the vertex-to-fragment pipeline, stage by stage, and what each stage can change about a primitive?

The 90-second answer

A primitive starts as indexed vertices, becomes a clipped screen-space triangle, then becomes fragments that may write colour and depth. Programmable stages change geometry and per-vertex or per-fragment data. Fixed stages decide assembly, clipping, coverage and final blending, and you cannot reprogram those decisions from a shader.

Vertex buffers + index buffer
        |
Input Assembly: topology, stride, index format
        |
Vertex Shader: position, varyings, per-vertex attributes
        |
Tessellation: hull shader sets factors, domain shader displaces
        |
Geometry Shader: emit, delete or replace primitives
        |
Rasterizer: clip, cull, viewport, interpolate, coverage
        |
Fragment Shader: colour, depth, discard, derivatives
        |
Output Merger: depth/stencil test, blend, write to targets
StageCan modifyCannot modify
Input AssemblyWhich vertices form a triangle, strip or line, buffer bindings, vertex stride and offsetVertex values, topology after assembly
Vertex Shadergl_Position or SV_Position, every varying, per-vertex size or point size where supportedPrimitive count, other vertices, screen coverage
TessellationPatch subdivision, displaced position, new varyingsTopology outside the patch, fragment behaviour
Geometry ShaderPrimitive count and type, new vertices, per-primitive dataInput vertices already consumed, raster rules
RasterizerClipping, back-face culling, viewport mapping, interpolated varyings, which pixels are coveredShader code, vertex values, blend equation
Fragment ShaderColour for each covered sample, depth output, discard, multiple render targetsNeighbouring fragments, coverage of the triangle
Output MergerDepth and stencil tests, blending, writes to colour and depth buffersShader outputs before the test

Worked trace

Take a triangle with model positions (0,0,0), (1,0,0), (0,1,0). The vertex shader computes clipPos = Proj * View * Model * vec4(pos,1). Suppose the results are (-0.5,-0.5,0.2,1), (0.5,-0.5,0.2,1), (-0.5,0.5,0.2,1). Divide by w to get NDC, then map to a 1280 by 720 viewport: x_screen = (x_ndc + 1) * 640, y_screen = (1 - y_ndc) * 360. The first vertex lands at (320,540). The rasterizer clips against the six clip planes in clip space before that division, culls if the winding is wrong and culling is enabled, then walks the triangle and interpolates varyings with perspective correction using 1/w.

A minimal vertex and fragment pair makes the split concrete:

GLSL
// Vertex shader, GLSL 450
layout(location = 0) in vec3 inPos;
layout(location = 1) in vec3 inNormal;
layout(location = 2) in vec2 inUV;
uniform mat4 uMVP;
out vec3 vNormal;
out vec2 vUV;
void main() {
    vNormal = mat3(uMVP) * inNormal;
    vUV = inUV;
    gl_Position = uMVP * vec4(inPos, 1.0);
}
GLSL
// Fragment shader, GLSL 450
in vec3 vNormal;
in vec2 vUV;
out vec4 fragColor;
uniform sampler2D uAlbedo;
void main() {
    vec3 n = normalize(vNormal);
    float light = max(dot(n, normalize(vec3(0.3, 0.8, 0.5))), 0.0);
    fragColor = vec4(texture(uAlbedo, vUV).rgb * light, 1.0);
}

The vertex shader can move a vertex off screen, collapse a triangle to a line by making two positions identical, or pass a different normal per vertex. It cannot add a vertex. The geometry shader can, which is how particle systems and shadow volumes emit extra triangles, at a cost in occupancy and register pressure. Tessellation sits between them and only subdivides patches the hull shader accepts.

Failure modes interviewers probe

Clipping happens in clip space, so a vertex with w near zero or negative can flip a triangle across the screen if you only check NDC. Interpolating a world position linearly in screen space without perspective correction bends textures on receding surfaces. discard in the fragment shader removes a fragment after rasterization, so it does not save vertex or raster cost and it can break early-z and MSAA depth resolve assumptions. Writing gl_FragDepth disables some early depth tests on several vendors and can cost bandwidth on tiled mobile GPUs. Flat interpolation, flat in GLSL or nointerpolation in HLSL, takes the value from one vertex instead of blending, which is what you want for per-face IDs and wrong for smooth normals.

If a candidate claims a stage can do something, ask where the data lives at that point. Before rasterization there are vertices and primitives. After it there are samples. That boundary explains almost every pipeline question.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-2Walk me through transforming a point from local space to screen pixels, and what does each matrix stage do?

The 90-second answer

A point travels through four fixed-function stages, each a 4x4 matrix multiply in homogeneous coordinates. With column vectors, as in GLSL and OpenGL, the chain is:

clip = P * V * M * vec4(localPos, 1.0)

M (model) puts the object in world space. V (view) puts the world in camera space. P (projection) puts camera space into clip space, applying perspective or orthographic distortion. The GPU then divides by w to get normalized device coordinates (NDC), discards anything outside the clip volume, and the viewport transform maps NDC to window pixels and depth range.

StageInput spaceOutput spaceWhat it changes
Model MLocal / objectWorldScale, rotate, translate the mesh instance
View VWorldCamera / eyeInverse of camera transform. Camera looks down -Z in OpenGL and Vulkan, +Z in DirectX
Projection PCameraClipPerspective divide setup, field of view, near/far planes
ViewportNDCScreen pixelsScale and translate to window size, map depth to [0,1] or [-1,1]

Worked trace

Take a hypothetical scene. Local point p = (1, 0, 0, 1). Model translates by (2, 0, 0). View translates by (0, 0, -5), so the camera sits at the origin looking at the point. Projection is perspective, 90 degree vertical FOV, aspect 1, near 0.1, far 100.

GLSL
// Vertex shader, checked against GLSL ES 3.0 semantics
uniform mat4 uModel, uView, uProjection;
void main() {
    vec4 clip = uProjection * uView * uModel * vec4(aPos, 1.0);
    gl_Position = clip;
}

Step by step:

  1. Model: (1,0,0,1) becomes (3,0,0,1) in world space.
  2. View: (3,0,0,1) becomes (3,0,-5,1) in camera space. The point is 5 units in front of the camera.
  3. Projection: for 90 degree FOV and aspect 1, f = 1 / tan(45°) = 1. The z row is (far + near) / (near - far) = 100.1 / -99.9 = -1.0020 and 2 * far * near / (near - far) = 20 / -99.9 = -0.2002, with w_clip = -z_cam. So clip = (3, 0, -1.0020 * -5 - 0.2002, 5) = (3, 0, 4.81, 5).
  4. Perspective divide: ndc = clip.xyz / clip.w = (0.6, 0, 0.962). The x value 0.6 says the point sits right of centre, at 80 percent of the way from centre to the right edge (since NDC spans -1 to 1).
  5. Viewport, window 800x600, OpenGL convention: x_screen = (0.6 * 0.5 + 0.5) * 800 = 640, y_screen = (0 * 0.5 + 0.5) * 600 = 300, z_screen = (0.962 * 0.5 + 0.5) * 1.0 = 0.981 in depth range [0,1].

Result: pixel (640, 300), depth 0.981. That depth is close to the far plane, which matches a point 5 units away with far at 100 under this projection.

Failure modes interviewers probe

Clipping happens in clip space before the divide, against -w <= x <= w, -w <= y <= w, -w <= z <= w in OpenGL. A point behind the camera has negative w and gets clipped even if the divide would produce a plausible NDC. That is why checking NDC alone misleads.

Y orientation differs by API at the viewport stage, not in NDC. NDC y is up in both OpenGL and DirectX. OpenGL's viewport origin is bottom-left, so y=1 maps to the top of the window. DirectX's viewport origin is top-left, so the same NDC y=1 still maps to the top, but the mapping formula flips sign because screen y grows downward. Vulkan is the outlier: its NDC y is down, so you flip y in the projection matrix itself. Forgetting which stage flips is the classic upside-down image bug when porting between APIs.

Depth precision is non-linear under perspective. Most of the [0,1] depth range is consumed near the near plane, so pushing near from 0.1 to 1.0 in the example above buys far more usable precision than moving far from 100 to 1000 costs. That trade-off is why logarithmic depth or a reversed depth buffer shows up in large open-world renderers.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-3Derive the perspective projection matrix for a camera with given fov, aspect, near and far, and explain what the perspective divide by w does and where it breaks?

The 90-second answer

Put the camera at the origin looking down negative z in eye space, right handed. A point in front has z_eye < 0. I want a homogeneous clip position (x_clip, y_clip, z_clip, w_clip) such that after the divide, x_ndc = x_clip / w_clip, y_ndc = y_clip / w_clip, z_ndc = z_clip / w_clip, the visible volume is the cube [-1, 1]^3 in OpenGL convention.

Set w_clip = -z_eye. That single choice makes the divide a perspective divide: points farther away get a larger w, so their x_ndc and y_ndc shrink toward the centre. It also puts the eye plane at w = 0, which is where the divide is undefined.

For x and y, require the edge of the frustum at the near plane to land at x_ndc = 1. At z_eye = -n, the half width is tan(fov_y / 2) * aspect * n. So:

x_clip = (cot(fov_y / 2) / aspect) * x_eye

Let f = cot(fov_y / 2). Then x_ndc = f * x_eye / (aspect * -z_eye). At the near edge this is exactly 1. Same for y with f and no aspect term.

For z, write z_clip = A * z_eye + B and solve for the two constraints z_eye = -n maps to z_ndc = -1 and z_eye = -f maps to z_ndc = +1:

z_ndc = (A * z_eye + B) / (-z_eye) = -A - B / z_eye
-A + B / n = -1
-A + B / f = +1

Subtracting gives B * (1/n - 1/f) = -2, so B = 2fn / (n - f) and A = (f + n) / (n - f). The full matrix, column major as in GLSL, is:

GLSL
// OpenGL, right handed, f = 1.0 / tan(radians(fovY) * 0.5)
mat4 P = mat4(
  f / aspect, 0.0, 0.0, 0.0,
  0.0,        f,   0.0, 0.0,
  0.0,        0.0, (far + near) / (near - far), -1.0,
  0.0,        0.0, (2.0 * far * near) / (near - far), 0.0);

Worked trace

Take fov_y = 90 degrees, so f = 1, aspect = 1, near = 0.1, far = 100. Then A = 100.1 / -99.9 = -1.002, B = 20 / -99.9 = -0.2002.

Point P = (1, 0, -2): w = 2, x_clip = 1, z_clip = -1.002 * -2 - 0.2002 = 1.804. After divide: x_ndc = 0.5, z_ndc = 0.902. The point is 2 units away, half way to the right edge of the screen, which matches the 90 degree frustum. Point (0, 0, -0.1) gives z_ndc = -1 and (0, 0, -100) gives z_ndc = +1, as constructed. Note how much of the depth range is consumed near the camera: z = -1 already gives z_ndc = 0.80. That nonlinearity is why depth precision is dominated by the near plane.

Why the divide matters beyond projection

Clipping happens in clip space, before the divide, against the six planes x = +/- w, y = +/- w, z = +/- w. That is the whole point of keeping w around. A triangle that straddles the near plane has vertices with w of opposite signs. Clipping in homogeneous space handles that correctly. If you divided first and clipped in NDC, a vertex behind the eye would wrap to a huge positive x_ndc and the triangle would smear across the screen.

Interpolation is the other place it bites. Attributes such as texture coordinates vary linearly in world space, not in screen space. Interpolating them directly across clip space produces the classic perspective swimming on a receding floor. The fix is to interpolate attr / w and 1 / w across the triangle and divide per fragment. Modern GPUs do this for texture coordinates automatically, which is why a custom varying needs the manual form.

Where it breaks, and the vendor differences

APINDC z rangeMatrix change from the OpenGL version above
OpenGL[-1, 1]As derived, right handed, w = -z_eye
Direct3D 11[0, 1]Keep right handed and w = -z_eye: A = -f / (f - n), B = -fn / (f - n). The common D3D form uses left handed eye space instead, camera looking down +z with w = +z_eye, and then A = f / (f - n), B = -fn / (f - n). Same mapping, opposite handedness
Vulkan[0, 1] by defaultSame z mapping as Direct3D. Vulkan also flips Y relative to OpenGL because its framebuffer origin is top left, usually handled with a negative viewport height or a projection correction

Three failure modes I check for in review. First, w = 0: a vertex exactly on the eye plane divides by zero. In practice this shows up as a triangle edge crossing the camera, producing NaNs or a full screen quad. The fix is near plane clipping in clip space, not clamping after the divide. Second, a very small near relative to far, such as near = 0.01 and far = 10000, compresses depth precision so badly that distant surfaces z-fight. The projection is correct and still unusable, so I push near out or use a logarithmic depth prepass. Third, forgetting that the divide is per vertex in the vertex shader. Doing gl_Position.xyz /= gl_Position.w in the vertex shader and then interpolating the result breaks both clipping and perspective correct interpolation, because the rasterizer no longer sees the homogeneous coordinates it needs.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-4Why do we keep vertices in homogeneous coordinates through clipping and interpolation instead of dividing by w as soon as possible?

The 90-second answer

A homogeneous vertex is (x, y, z, w) and the point you draw is (x/w, y/w, z/w). Keeping w until after clipping and interpolation lets the hardware handle perspective correctly and clip primitives that cross the camera plane. Divide early and you lose the information that tells you how much a receding edge is foreshortened, and a vertex behind the eye gets mirrored to the wrong side of the screen.

Why interpolation needs w

Perspective projection is nonlinear in screen space. A value that varies linearly in world space does not vary linearly in pixels, because distant fragments are compressed. The rasterizer therefore interpolates attr/w and 1/w across the triangle and divides in the fragment shader. In GLSL that correction is on by default, which surprises people coming from software renderers:

GLSL
// GLSL ES 3.00, checked against the spec: interpolation is
// perspective-correct by default
in float attr;              // interpolated as attr/w and 1/w
noperspective in float screenAttr; // opt out, interpolated in screen space

Worked trace for a hypothetical edge, attr 0 to 1 while w goes 1 to 3. At the screen midpoint the rasterizer has interpolated 1/w = 0.667 and attr/w = 0.167, so the fragment receives 0.167 / 0.667 = 0.25. A naive screen-space lerp would give 0.5. The midpoint of the edge on screen really is a quarter of the way along the attribute, because the far end is foreshortened. Get this wrong and textures swim on floors viewed at a grazing angle, and world positions reconstructed for lighting drift exactly where the surface is most slanted.

Clipping in clip space

The view volume is six linear inequalities, no division needed: -w <= x <= w, and the same for y and z (OpenGL convention; Direct3D uses 0 <= z <= w). Each plane such as x = w passes through the origin in 4D, so Sutherland-Hodgman clipping just interpolates x, y, z, w and finds where the inequality crosses zero.

Take a segment from P1 (0.5, 0, 0, 1), inside, to P2 (2, 0, 0, 1), outside the right plane. The signed distance x - w is -0.5 at P1 and 1.0 at P2, so the crossing is at t = 0.5 / 1.5 = 1/3. The clipped point is (1, 0, 0, 1), which divides to NDC x = 1. Correct, and no divide was needed to find it.

The case that really needs w is a vertex behind the eye, where w < 0. Its NDC position is mirrored through the origin, so dividing first puts it on the wrong side of the screen and NDC clipping would keep a phantom triangle. In clip space the test x <= w simply fails, the edge is cut where it crosses the near plane, and only the in-front portion is rasterized. A point with w = 0 has no NDC position at all, yet as a direction it still clips and interpolates sensibly in homogeneous form.

The cost, and when early division is fine

Keeping w is not free. Clip space carries four components per vertex instead of three, and perspective-correct interpolation costs extra varyings and a divide per fragment. On tile-based mobile GPUs, varying bandwidth is often the binding constraint, so shipping 1/w alongside every attribute is a real budget item. Doing the divide and interpolation yourself in a compute pass buys control, for example for custom geometry processing, but you give up the hardware rasterizer's interpolation, clipping and multisampling and have to reimplement them.

Early division is acceptable when w is constant or known positive and you are interpolating screen-space quantities. Orthographic rendering, UI, 2D sprites and fullscreen post-process quads all qualify, as does anything you mark noperspective, such as a skybox gradient. The rule I use: if w varies across the primitive or can go negative, keep it homogeneous until clipping is done and let the rasterizer do the correction.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-5What does the dot product of a surface normal and the direction to a light tell you about diffuse lighting?

The 90-second answer

For diffuse lighting, dot(N, L) tells you how directly the light hits the surface. N is the unit surface normal and L is the unit direction from the surface toward the light. The dot product is cos(theta) between them, so the result is 1 when the light is straight on, 0 when it grazes the surface, and negative when the light is behind the surface.

The shader term is max(0.0, dot(N, L)). The clamp discards back-facing light instead of letting it subtract brightness.

Worked trace

Flat ground with N = (0, 1, 0). Light direction L = normalize(1, 1, 0) = (0.707, 0.707, 0).

dot(N, L) = 0 * 0.707 + 1 * 0.707 + 0 * 0 = 0.707

Diffuse strength is 0.707, so the surface gets about 71 percent of full light. Move the light to L = (1, 0, 0), level with the ground. Dot becomes 0 and the ground goes dark. Move it below the horizon to L = (0, -1, 0). Dot becomes -1, clamped to 0. Same dark result, which is correct because the ground plane blocks that light.

In a shader

GLSL
// GLSL, checked against OpenGL ES 3.0
vec3 N = normalize(normal);
vec3 L = normalize(lightPos - worldPos);
float diffuse = max(dot(N, L), 0.0);
vec3 color = albedo * lightColor * diffuse;

Both vectors must be unit length before the dot product. If L has length 2, dot doubles and the surface looks overlit. If N comes from interpolation in the vertex shader, its length shrinks across the triangle, so normalize it in the fragment shader.

dot(N, L)AngleDiffuse result
1.00 degrees, light straight onFull brightness
0.70745 degrees0.707 of full brightness
0.090 degrees, grazingNo diffuse light
NegativeLight behind surfaceClamped to 0

That single rule is also why a sphere looks round under one light. Normals on the side facing the light return positive values, normals on the far side return negative values and clamp to zero, and the transition follows the cosine falloff across the surface.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-6Why do normals need the inverse-transpose of the model matrix when an object is scaled non-uniformly, and what breaks if you use the model matrix directly?

The 90-second answer

Positions are points, so they transform with the model matrix M. Normals are directions tied to a surface, and the property that matters is perpendicularity to the tangent plane. Under non-uniform scale, M does not preserve perpendicularity, so applying M to a normal tilts it away from the surface. The inverse-transpose, (M^-1)^T, is the transform that preserves perpendicularity, which is why it is used for normals.

Worked trace

Take a 2D slice for clarity. Let M = diag(2, 1), a non-uniform scale that stretches x by 2. Take a surface with normal n = (1, 1) / sqrt(2) and tangent t = (1, -1) / sqrt(2). They are perpendicular: n . t = 0.

Transform the tangent as a direction: t' = M * t = (2, -1) / sqrt(2).

Transform the normal with M as well: n_wrong = M * n = (2, 1) / sqrt(2). Now n_wrong . t' = (4 - 1) / 2 = 1.5, not zero. The normal no longer points out of the surface. Lighting computed from it will be wrong, with diffuse terms and specular highlights shifted toward the stretched axis.

Now use the inverse-transpose. M^-1 = diag(0.5, 1), so (M^-1)^T = diag(0.5, 1). Then n_correct = (0.5, 1) / sqrt(2). Dot with t': (1 - 1) / 2 = 0. Perpendicularity is restored. Normalizing n_correct gives the direction to pass to the shader.

The reason is general. For any tangent t with n . t = 0, the transformed tangent is M * t. We need a transformed normal n' with n' . (M * t) = 0 for every such t. That condition is n'^T * M * t = 0, which holds when n' = (M^-1)^T * n, because then n'^T * M = n^T * (M^-1) * M = n^T. Only the inverse-transpose guarantees this for arbitrary M, including shear.

TransformEffect on (M^-1)^T vs MBug visible?
Uniform scale + rotation(M^-1)^T equals rotation times a scalar, same direction as MNo, which is why this bug survives early testing
Non-uniform scaleDirections change differently per axisYes, normals lean toward the stretched axis
ShearSame failure as non-uniform scaleYes, normals skew off the surface

In the shader

Precompute the normal matrix on the CPU, or compute it once per draw in the vertex shader:

GLSL
// vertex shader, GLSL ES 3.0
uniform mat4 uModel;
attribute vec3 aNormal;
varying vec3 vNormal;
void main() {
    mat3 normalMatrix = transpose(inverse(mat3(uModel)));
    vNormal = normalMatrix * aNormal;
    gl_Position = uModel * vec4(aPosition, 1.0);
}

In production I pass a precomputed mat3 uNormalMatrix uniform. Computing inverse per vertex is wasteful, and on some mobile GPUs it is slow or unavailable in older GLSL ES profiles. Normalize vNormal again in the fragment shader, because interpolation does not preserve length.

Two edge cases worth naming in an interview. First, a negative determinant, such as a mirrored model with scale (-1, 1, 1), flips winding order. The inverse-transpose handles the normal direction, but you also need to flip front-face winding or the mesh will be culled inside out. Second, normal mapping: the tangent-space normal is perturbed in tangent space, then transformed to world space with the same normal matrix applied to the TBN frame. If the TBN frame is built from the model matrix instead, the perturbation lands in the wrong place even when the base normal looks close.

The practical test I use: scale a sphere by (3, 1, 1) and check the lighting at the equator. With the model matrix the bright spot sits visibly off the silhouette. With the inverse-transpose it stays centered. That single scene catches the bug that uniform-scale test assets never will.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-7When would you choose quaternions over Euler angles for object rotation, and how does slerp avoid the problems Euler interpolation hits?

The 90-second answer

Use quaternions for runtime orientation of objects and cameras, and Euler angles only at the authoring boundary where a human thinks in yaw, pitch and roll. A unit quaternion q = (w, x, y, z) encodes a rotation as an axis and an angle in four numbers with no singular orientation. Euler angles encode three sequential rotations about local axes, and at pitch of plus or minus 90 degrees two of those axes line up. That alignment is gimbal lock: one degree of freedom disappears, and small changes in the remaining angles can swing the object wildly.

For interpolation, slerp between quaternions follows the shortest arc on the unit sphere at constant angular velocity. Interpolating Euler angles component by component does not. It can take a long, curved path, speed up and slow down mid rotation, and pass straight through the singular pitch.

PropertyEuler angles (yaw, pitch, roll)Unit quaternion
Storage3 floats, human readable4 floats, unit length required
CompositionOrder dependent, matrix conversion neededMultiply quaternions directly
SingularityYes, at pitch = ±90°None
InterpolationComponent lerp, non constant speed, can hit lockSlerp, shortest arc, constant angular velocity
DebuggingEasy to log and clamp per axisHard to read, must convert to Euler for UI

Why gimbal lock happens

Take the common ZYX order: yaw about Z, then pitch about the new Y, then roll about the new X. At pitch = 90°, the yaw axis (world Z) and the roll axis (body X after pitching) point the same way. The combined matrix depends only on yaw + roll, not on either separately.

Trace it. Start at yaw 0°, pitch 90°, roll 0°. Change yaw to 30° and the object rotates one way. Reset, then change roll to 30° instead and the object rotates the same way. Change yaw to 30° and roll to -30° and nothing moves at all. The representation has lost a degree of freedom, so an animation that increments yaw through that pose will appear to stall, then snap when pitch leaves 90°.

A quaternion has no equivalent pose. Every orientation maps to a unit 4-vector, and nearby orientations map to nearby vectors, so there is no configuration where a small input produces a discontinuous output.

Slerp, with the failure modes that matter

Slerp between q0 and q1 with parameter t in [0, 1]:

C++
// C++-style, checked against glm::slerp behaviour
Quat slerp(Quat q0, Quat q1, float t) {
    float dot = clamp(dot(q0, q1), -1.0f, 1.0f);
    if (dot < 0.0f) { q1 = -q1; dot = -dot; }  // take the short way round
    if (dot > 0.9995f) return normalize(lerp(q0, q1, t)); // nlerp, angles are tiny
    float theta = acos(dot);
    float s = sin(theta);
    return (sin((1 - t) * theta) / s) * q0 + (sin(t * theta) / s) * q1;
}

Three details decide whether this works in a shipped game or engine.

First, the double cover. q and -q describe the same rotation. If dot(q0, q1) is negative, the stored quaternions are more than 90° apart in 4D even though the rotations may be close. Without negating q1, slerp travels the long way round and the object spins 350° instead of 10°. The dot < 0 branch above fixes that.

Second, the near parallel case. When dot is close to 1, sin(theta) approaches 0 and the division blows up. Normalized lerp is indistinguishable from slerp there because the angle between the quaternions is under about 1.8°, so the fallback is both faster and stable.

Third, drift. Repeated multiplication and interpolation slowly break the unit length constraint. A quaternion of length 1.02 scales the rotated vectors by about 4% per application, which shows up as objects growing or shearing over a long animation. Normalize after composing rotations in a hierarchy, or at least before using the result to rotate a direction you then feed into lighting or physics.

Where Euler angles still win

Keep them for input and limits. A flight model, a turret, or a camera rig has real per axis limits: yaw free, pitch clamped to -80° to 80°, roll limited by the airframe. Those clamps are trivial in Euler space and awkward in quaternion space. The usual pattern is to store orientation as a quaternion internally, convert to Euler only to apply clamps or show values in an editor, and convert back. Converting near pitch 90° is exactly where that conversion is ill conditioned, so clamp before you get there, not after.

One more trap: extracting a quaternion from a matrix that includes non uniform scale gives a wrong rotation. If a parent node scales X by 2 and Y by 1, the matrix is not a pure rotation, and the extracted quaternion bakes part of that scale into the orientation. Decompose scale out first, or keep rotation and scale in separate nodes, which is what most scene graphs do for this reason.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-8How do you build a rotation matrix from an axis and angle, and in what order do you compose translation, rotation and scale so a model scales in its own space before it rotates?

The 90-second answer

State the convention before any matrix. I use column vectors, right-handed coordinates, angles in radians, and v' = M * v. Under that convention the rightmost matrix acts first, so a model that should scale in local space, rotate about its own origin, then move in the world is M = T * R * S. Reversing that order does not give a slightly different result. It gives a different object, often one that orbits the origin or shears when it rotates.

For a unit axis a = (ax, ay, az) and angle theta, Rodrigues' formula builds the rotation directly:

R = I*cos(theta) + (1 - cos(theta)) * a*a^T + sin(theta) * [a]_x

where [a]_x is the cross-product matrix [[0,-az,ay],[az,0,-ax],[-ay,ax,0]]. Expanded, the 3x3 entries are:

c + ax*ax*(1-c)ax*ay*(1-c) - az*sax*az*(1-c) + ay*s
ay*ax*(1-c) + az*sc + ay*ay*(1-c)ay*az*(1-c) - ax*s
az*ax*(1-c) - ay*saz*ay*(1-c) + ax*sc + az*az*(1-c)

with c = cos(theta) and s = sin(theta). For a homogeneous transform, embed R in a 4x4 with the last row 0 0 0 1.

Worked trace

Rotate 90 degrees about Z. Axis (0,0,1), c = 0, s = 1:

R = [[0,-1,0],[1,0,0],[0,0,1]]

Take point (1,0,0), scale by 2, rotate, then translate by (10,0,0):

S * (1,0,0) = (2,0,0)
R * (2,0,0) = (0,2,0)
T * (0,2,0) = (10,2,0)

With M = T * R * S the point lands at (10,2,0). If you compose as R * T * S instead, translation happens first: (1,0,0) scales to (2,0,0), translates to (12,0,0), then rotates to (0,12,0). The model has orbited the origin by 90 degrees. That is the classic bug when a character turns in place and swings around the world origin.

Order also decides what non-uniform scale means. R * S with S = diag(2,1,1) stretches along the object's local X axis, then rotates that stretched shape. S * R stretches along world X after rotation, so the shape changes proportions as it turns. For a turret that should stay elongated along its barrel, T * R * S is the one that holds.

Code, checked in C++17

C++
Mat4 rotationFromAxisAngle(Vec3 axis, float radians) {
    Vec3 a = normalize(axis); // caller must reject near-zero axis
    float c = cosf(radians), s = sinf(radians), t = 1.0f - c;
    Mat4 m = identity();
    m[0][0] = t*a.x*a.x + c;     m[0][1] = t*a.x*a.y - s*a.z; m[0][2] = t*a.x*a.z + s*a.y;
    m[1][0] = t*a.x*a.y + s*a.z; m[1][1] = t*a.y*a.y + c;     m[1][2] = t*a.y*a.z - s*a.x;
    m[2][0] = t*a.x*a.z - s*a.y; m[2][1] = t*a.y*a.z + s*a.x; m[2][2] = t*a.z*a.z + c;
    return m;
}
Mat4 model = translation(pos) * rotationFromAxisAngle(axis, angle) * scaling(scale);

Failure modes I check for

An axis that is not unit length scales the rotation. Rodrigues' formula assumes |a| = 1; with |a| = 2 the (1-c) terms quadruple and the result is no longer orthonormal, so normals and subsequent rotations drift. Normalize once, and reject an axis shorter than about 1e-6 instead of normalizing noise.

Degrees passed where radians are expected is the other frequent one. 90 radians is not 90 degrees, and the matrix still looks plausible because every entry stays in [-1,1]. I keep radians at API boundaries and convert only at input parsing.

Handedness and storage order bite when the matrix leaves your code. The matrix above is right-handed and column-major in memory as written. OpenGL expects column-major, DirectX and row-major engines expect the transpose, and a left-handed system flips the sign of the s terms. The symptom is a rotation that goes the wrong way around the axis while translation still works, which points straight at a transpose or handedness mismatch rather than at the angle.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-9If I apply scale, then rotation, then translation to a point, why does the order of the matrices matter, and what does it cost to multiply them in a different order?

The 90-second answer

Matrix multiplication does not commute, so T * R * S and S * R * T are different transforms. With column vectors, the rightmost matrix acts on the point first. M = T * R * S therefore means scale the point, then rotate the scaled point, then translate it. That ordering is the whole convention, and getting it backwards is the most common bug in hand-written transform code.

Assume column vectors, as in GLSL and glm, and a right-handed system. A point is p' = M * p. If your engine uses row vectors, as in some DirectX code, the written order reverses: p' = p * M and you write S * R * T. The maths is identical, the notation flips.

Worked trace

Take p = (1, 0, 0), scale by 2 on x and y, rotate 90 degrees about z, translate by (10, 0, 0).

GLSL
mat4 S = scale(vec3(2.0, 2.0, 1.0));
mat4 R = rotate(radians(90.0), vec3(0.0, 0.0, 1.0));
mat4 T = translate(vec3(10.0, 0.0, 0.0));

mat4 M = T * R * S;   // scale first, then rotate, then translate
vec3 p2 = (M * vec4(1.0, 0.0, 0.0, 1.0)).xyz;  // (10, 2, 0)

Step by step: S * p = (2, 0, 0). R * (2, 0, 0) = (0, 2, 0). T * (0, 2, 0) = (10, 2, 0).

Reverse the order and the same three matrices give a different result:

CompositionResult for p = (1, 0, 0)Steps, rightmost first
T * R * S(10, 2, 0)S: (2,0,0), R: (0,2,0), T: (10,2,0)
S * R * T(0, 22, 0)T: (11,0,0), R: (0,11,0), S: (0,22,0)
R * T * S(0, 12, 0)S: (2,0,0), T: (12,0,0), R: (0,12,0)

The second row is the practical trap. If you want an object to orbit a pivot, you translate to the pivot, rotate, then translate back. Writing the matrices in the order you describe them in English usually puts the translation first, which moves the pivot itself.

Non-uniform scale makes the order visible even without translation. Scale x by 2, then rotate 45 degrees, and the x axis stretches along the rotated direction. Rotate first, then scale in world x, and you get a different, sheared result. Neither is wrong in isolation. They describe different objects, and a model authored for one will look wrong under the other. With the uniform xy scale above, R and S happen to commute, which is why the trace needs the translation to show the difference.

Cost of the order

Multiplication is associative, so (T * R) * S and T * (R * S) give the same matrix up to floating point rounding. For three 4x4 matrices the operation count is the same either way: two matrix-matrix products, each 64 multiplications and 48 additions, 128 multiplications total.

Where order and grouping do cost you is how often you multiply. A 4x4 matrix times a vec4 costs 16 multiplications. For 100,000 vertices that is 1.6 million multiplications per frame if you apply T, R and S separately, three passes over the data. Compose M = T * R * S once on the CPU, 128 multiplications, upload one matrix, and each vertex costs 16. The saving is roughly 3x on the vertex work and one pass over memory, which is why engines precompose model matrices and only rebuild them when a transform changes.

The same logic applies to a chain of parents in a scene graph. Compose the chain once per node per frame, then reuse the result for every vertex in that subtree. Recomputing the full chain per vertex multiplies the cost by the vertex count for no benefit.

Two checks catch order bugs early. Transform the origin: under T * R * S the origin is unaffected by scale and rotation and lands exactly on the translation, which is easy to verify in a debugger. Transform a unit axis and confirm it points where the rotation says it should after scaling. If the axis length is wrong, scale was applied in the wrong space.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-10How do forward, deferred, clustered and hybrid rendering trade off when a scene has hundreds of lights and varied materials, and how would you choose between them?

The 90-second answer

I would start from the cost that dominates in the scene: light evaluation per pixel, per object, or per tile. Forward evaluates lights for every fragment of every object that registers it, so cost scales with lights times covered fragments and with shader permutations for material combinations. Deferred evaluates lights once per screen pixel, so cost scales with lights times pixels, but pays for a G-buffer and constrains materials to what fits in that buffer. Clustered forward keeps forward's material flexibility and moves light culling to screen tiles and depth slices, so cost scales with lights per cluster times fragments in that cluster. Hybrid uses clustered or deferred for opaque geometry and forward for transparent, emissive, or material-heavy objects that do not fit the main path.

For a scene with hundreds of dynamic lights and a handful of opaque materials, clustered is usually the default. For a scene with few lights and dozens of material combinations, forward is simpler and faster. Deferred wins when light count is high, materials are uniform, and bandwidth is plentiful. Hybrid is what I ship when both conditions appear in one frame, which in practice they do.

PathLight cost scales withMaterial flexibilityMain tax
ForwardLights x fragments per objectHigh, arbitrary shader per objectRedundant lighting, uniform and permutation pressure
DeferredLights x screen pixelsLow, packed into G-bufferG-buffer bandwidth, MSAA and transparency workarounds
Clustered forwardLights per cluster x fragments in clusterHigh, same as forwardTile assignment, light list overflow, cluster debug cost
HybridMix of the aboveHigh for the forward subsetTwo lighting paths to keep consistent

Worked numbers, labelled as an example

Take 1080p, about 2.07 million pixels, 200 dynamic point lights, 60 fps.

Deferred with a 128-bit G-buffer (albedo, normal plus roughness, emissive plus AO, depth or velocity packed elsewhere) writes 16 bytes per pixel: 33 MB per frame, roughly 2.0 GB/s of writes at 60 fps, then reads it again for lighting. That is before MSAA resolve, which on tile-based GPUs can be the real cost because resolve traffic stays on chip or spills to memory depending on the vendor.

Forward with the same lights: if the average light affects 5% of the screen, each light touches about 100k pixels, so 200 lights imply 20 million light-fragment evaluations per frame, about ten per pixel on average. That sounds worse than deferred, and it is, unless objects are small or lights are culled per object. The point is that forward cost is driven by overlap, not by screen size alone.

Clustered with 16x16 pixel tiles gives 120 by 68 tiles, 8,160 tiles, times say 12 depth slices, about 98k clusters. If the 200 lights distribute so the average cluster holds 8 lights, a fragment evaluates 8 lights instead of 200 or an average of 10. The saving depends entirely on distribution. A cluster covering a dense explosion can hold 60 lights and overflow a fixed list of 64, which is a visible failure, not a theoretical one.

Cluster assignment, in brief

HLSL
// Per tile and depth slice, built on the GPU from light bounds.
// Each light is tested against the cluster frustum, not the whole screen.
bool InCluster(float3 lightPos, float lightRadius, Cluster c)
{
    float d = distance(lightPos, c.center);
    return d < lightRadius + c.radius;
}
// Result: a compact list of light indices per cluster, consumed by
// the forward shading pass. Overflow is counted, not silently dropped.

Counting overflow matters. I expose a counter per frame and a debug view that tints clusters over budget. Without that, the bug report is "lights pop in the city scene" and nobody can reproduce it on a different GPU.

Where each path breaks

Forward breaks on uniform limits and shader permutations. On older hardware the per-object light array caps at a fixed count, and adding a material variant multiplies permutation count across the program cache. The symptom is hitches on first encounter with a new material and light combination, not low average frame rate.

Deferred breaks on materials. A clearcoat, a subsurface skin shader, and a refractive surface cannot all be packed into a standard G-buffer without extra buffers or a second pass. It also breaks on transparency, because transparent objects are not in the G-buffer and need a forward pass anyway, which is why pure deferred rarely survives contact with a real game.

Clustered breaks on light distribution and on small lights. A tiny light still occupies a cluster slot, and a large light spanning many clusters is written into all of them. Depth slicing helps with large lights but adds assignment cost. On tile-based mobile GPUs, the cluster grid also has to fit the tile memory budget, so tile size is a hardware constraint, not a free parameter.

Hybrid breaks on consistency. Two lighting paths means two implementations of shadows, fog, and tone mapping inputs, and they drift. I keep the lighting model shared in a common include and only split the data path, so a shadow bug fixed in one path is fixed in both.

How I would choose in an interview follow-up

Ask three questions. How many lights are dynamic per frame, and how clustered are they spatially? How many distinct material models need per-pixel effects that cannot be packed? What is the target GPU, desktop discrete or tile-based mobile? Hundreds of dynamic lights plus few materials points to deferred or clustered. Few lights plus many materials points to forward. Both, on a modern desktop GPU, points to clustered forward for opaque objects with a forward pass for transparents, which is the hybrid most engines now ship under names like forward plus.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-11How does forward-plus build per-tile light lists from a depth prepass, and how does clustered shading change the culling test?

The 90-second answer

Forward-plus keeps the forward renderer, but it stops testing every light at every fragment. A depth prepass writes linear depth for opaque geometry. A compute pass then divides the screen into tiles, usually 16x16 pixels, reconstructs the frustum for each tile from its screen rectangle and its depth range, and tests each light's bounding sphere against that frustum. Lights that pass are appended to that tile's list. The fragment shader reads only its own tile's list.

Clustered shading uses the same idea in 3D. Instead of a 2D tile with one depth range, it splits the tile further into depth slices, often with logarithmic spacing. The culling test becomes a sphere against a box in view space: x and y from the tile, z from the slice. That is the main difference. Forward-plus can keep a distant light in a tile because the tile also contains a near wall. Clustered shading puts the wall and the distant light in different clusters, so the light is culled for the near pixels.

Worked trace

Hypothetical scene: 1920x1080, 400 point lights, 16x16 tiles.

Tiles: 120 x 68 = 8,160. Naive forward rendering evaluates 400 lights per fragment, about 829 million light tests. Forward-plus evaluates 400 lights per tile in compute, about 3.3 million tests, then each fragment loops over its tile list. If the average list is 10 lights, fragment work is about 21 million evaluations. The win depends on the list staying short.

Trace for one tile: the depth prepass finds min depth 2 m and max depth 18 m in that tile. The compute pass builds the 8 frustum corners from those values. A light at position 30 m away with radius 5 m fails the depth test and is rejected for the whole tile. A light at 10 m with radius 4 m passes and is appended at slot 3 of the tile list. In clustered shading, that same tile is split into, say, 8 slices. The 30 m light now only enters slices near 30 m, and the 10 m light only enters slices near 10 m, so each cluster list is shorter.

The build

GLSL
// One workgroup per tile, one thread per light (HLSL style)
[numthreads(64, 1, 1)]
void CullLights(uint3 id : SV_DispatchThreadID) {
    uint tileId = ...; // derived from group id
    Light L = lights[id.x];
    float4 corners[8] = TileFrustum(tileId); // from screen rect + depth range
    if (SphereIntersectsFrustum(L.position, L.radius, corners)) {
        uint slot = InterlockedAdd(tileLightCount[tileId], 1);
        if (slot < MAX_LIGHTS_PER_TILE)
            tileLightList[tileId * MAX_LIGHTS_PER_TILE + slot] = id.x;
        else
            tileOverflow[tileId] = 1;
    }
}

For clustered shading, TileFrustum returns a box instead: the same x and y bounds, but z limited to the slice range. The sphere test is then against that box. Everything downstream, the list layout and the fragment loop, stays the same.

Forward-plusClustered
Region2D tile, one depth range2D tile x depth slice
Culling volumeTile frustumView-space box
List count at 1920x10808,160 tiles8,160 x slices, e.g. 65,280 at 8 slices
StrengthSimpler build, less list memoryCulls lights that share a tile but not a depth range
CostConservative when a tile spans near and far geometryMore clusters to build and store

Overflow and the depth prepass

Overflow is the failure mode to design for. If MAX_LIGHTS_PER_TILE is 64 and a tile needs 90 lights, slots 64 to 89 are dropped unless you handle them. Those pixels lose lighting or shadows, and the bug looks like missing lights in dense areas. I would set the overflow flag, count it per frame, and treat a sustained non-zero count as a content budget problem. A fallback to a global list for overflow tiles is correct but slow, so the counter still needs to be visible in profiling.

The depth prepass is the other cost. It renders opaque geometry twice, once for depth and once for colour. On a vertex-bound scene that extra pass can erase the fragment saving. I would time the two passes separately with GPU timer queries and only keep forward-plus if the fragment saving exceeds the prepass cost. Clustered shading pays the same prepass cost, plus a larger list build, so it earns its place when the depth range inside a tile is large, such as an outdoor scene where one tile contains a nearby wall and sky at 500 m.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-12Walk me through how a GPU rasterizes a triangle using edge functions and barycentric coordinates, and how helper lanes make derivatives work at quad edges?

The 90-second answer

Rasterization turns a screen-space triangle into covered pixel centers, then interpolates per-vertex attributes to those centers. The GPU does both with edge functions. For each edge, say from vertex A to B, the edge function is the signed area of the parallelogram formed by the edge and the pixel position P:

E_AB(P) = (B.x - A.x) * (P.y - A.y) - (B.y - A.y) * (P.x - A.x)

A pixel is inside when all three edge functions have the same sign as the triangle winding, with a tie-break for pixels exactly on an edge. The same three values, normalized by the triangle area, are the barycentric coordinates. They give the interpolation weights for color, UVs, normals and any other varying.

Helper lanes are the inactive lanes in a 2x2 quad that the hardware still executes so derivatives can be computed. Screen-space derivatives such as dFdx and dFdy are not per-pixel values. The hardware computes them from the four lanes in a quad, for example dFdx = F(top right) - F(top left). If a triangle covers only one pixel of a quad, the other three lanes run as helpers with extrapolated positions. Their fragments are discarded, but their interpolated values let the quad produce a derivative for the real pixel.

Worked trace

Take a triangle in pixel coordinates, A(0,0), B(10,0), C(0,10), wound counter-clockwise in a y-down screen space. Its signed area is 50. For pixel center P(2.5, 2.5):

EdgeEdge function at PBarycentric weight
BC250.50 for A
CA12.50.25 for B
AB12.50.25 for C

All three are positive, so P is inside. An attribute with values 0 at A, 100 at B and 200 at C interpolates to 0.50*0 + 0.25*100 + 0.25*200 = 75 at P. Hardware evaluates this incrementally: moving one pixel right adds a constant step to each edge function, so the inner loop is a few adds and compares per pixel, not a fresh cross product.

Perspective correction changes what gets interpolated. Screen-space barycentrics are linear in screen space, but attributes are linear in view space. So the vertex shader passes attr / w and 1 / w, the fragment shader interpolates those, then divides:

GLSL
// vertex: pass vUvW = uv / w, vInvW = 1.0 / w
// fragment:
vec2 uv = vUvW / vInvW;

Skipping this makes textures swim and compress toward the far edge of a receding quad. The error is worst when w varies a lot across the triangle, for example a ground plane viewed at a grazing angle.

Top-left rule and cracks

Two triangles sharing an edge must agree on which one owns pixels on that edge, or you get cracks or double draws. The standard fix is the top-left rule: an edge is top if it is horizontal and the triangle lies below it, left if the triangle lies to its right. Pixels on a top or left edge are included, pixels on other edges are excluded. In edge-function terms, the test becomes E > 0 for normal edges and E >= 0 for top-left edges, with the exact form depending on winding and y direction. This is why winding consistency matters. A flipped winding in one mesh makes its edge tests invert and the shared edge leaks.

Helper lanes in practice

Quad coverageReal lanesHelper lanesDerivative source
4 pixels40Differences across the quad
2 pixels22Helper values extrapolated from the edge
1 pixel13Helper values extrapolated from the edge

That extrapolation is the failure mode to know. Helper lanes compute a plausible value so dFdx does not return zero or garbage, but it is not a real sample. Code that uses derivatives for normal mapping, procedural patterns or fwidth-based anti-aliasing inherits that approximation at triangle edges. It usually looks fine because the error is confined to a one-pixel band, but a pattern that amplifies derivatives, such as a high-frequency checker, can show a visible seam along the edge.

A second failure mode is assuming helper lanes are free. They still run the fragment shader, including texture fetches in some implementations, so a shader heavy on texture work pays for discarded lanes at every triangle edge. On tile-based mobile GPUs this can be measurable in dense geometry scenes. The mitigation is keeping fragment cost low near edges, which in practice means avoiding expensive work that only feeds a derivative.

A third case is derivatives inside a discard or a divergent branch. If lanes in a quad take different paths, the derivative is computed from values that may come from different branches. Modern APIs define this as undefined or based on the quad, so robust code computes derivatives before branching, or uses explicit derivatives from a value computed uniformly across the quad. In Vulkan and D3D12 this is also why dFdx in a non-uniform control flow needs care, and why helper lane behavior is exposed through quad intrinsics in some shading languages.

So the mental model is: edge functions decide coverage and supply barycentrics, barycentrics drive interpolation with a perspective divide, and helper lanes exist to make quad-based derivatives well defined when coverage is partial. Get the tie-break and the divide right and the rest of the fragment shader can trust the values it receives.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-13What does discard or a gl_FragDepth write in a fragment shader do to early-z?

The 90-second answer

Early-z means the GPU tests depth before running the fragment shader. If a fragment fails the depth test, the shader is skipped. A shader that calls discard or writes gl_FragDepth breaks that. The hardware cannot know the final depth, or whether the fragment exists at all, until the shader has run, so it moves the depth test to after the shader. That is late-z.

GLSL
// Early-z: depth is known before this shader runs
void main() {
    outColor = texture(albedo, uv);
}

// Late-z: discard and the depth write are only known inside the shader
void main() {
    vec4 c = texture(albedo, uv);
    if (c.a < 0.5) discard;
    gl_FragDepth = c.z;
    outColor = c;
}
Shader behaviourDepth testCost
No discard, no depth writeEarly-z, before shaderOccluded fragments skip the shader
discard presentLate-z, after shaderShader runs for every covered fragment
gl_FragDepth write presentLate-z, after shaderShader runs for every covered fragment

Why it costs overdraw

Overdraw is the same pixel being shaded more than once because several primitives cover it. With early-z, only the nearest primitive pays for the shader. With late-z, every covering primitive pays, even the ones the depth test would have rejected.

Worked example with hypothetical figures: a 1920 by 1080 frame has about 2.07 million pixels. At 4 times average overdraw, late-z shades about 8.3 million fragments. Early-z would shade close to 2.07 million, once per pixel, and reject the rest before the shader. The difference is about 6.2 million extra shader executions per frame.

Depth prepass

A depth prepass renders depth only, with a cheap shader, before the main pass. The main pass then has depth already in the buffer, so early-z can reject occluded fragments before the expensive lighting shader runs. It helps when overdraw is high and the main shader is expensive. It adds a full extra pass, so it is a poor trade when overdraw is low or the shader is cheap.

The practical check is simple. If a frame is fragment bound, search the shader for discard and gl_FragDepth. Removing either one, or moving cutout geometry into the prepass with the same discard, restores early-z for the main pass.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-14How do you choose near and far planes to avoid z-fighting, and when would you switch to reversed-Z instead of just tightening the frustum?

The 90-second answer

Depth precision in perspective projection is concentrated near the near plane. With a 24-bit buffer, resolvable separation grows roughly as z^2 / (near * 2^24), where z is distance from the camera. That quadratic growth is why distant coplanar surfaces flicker. I tighten near and far to the scene first. If the scene still needs centimetres near and kilometres far, I use reversed-Z with 32-bit float depth. Logarithmic depth is last, because it needs gl_FragDepth, disables early-Z, and costs ALU per fragment.

The numbers

For near 0.1, far 1000, 24-bit depth, using dz ≈ z^2 / (near * 2^24):

DistanceResolvable separation
1 m0.6 micrometres
10 m60 micrometres
100 m6 mm
500 m15 cm

Raising near to 1.0 improves every distance by 10x: 6 micrometres at 10 m, 0.6 mm at 100 m, 1.5 cm at 500 m. Near is the lever. Far matters mainly through the ratio, and through the (far - near) / far factor, which is near 1 when far is much larger than the geometry of interest.

In practice I measure the closest visible point, often a viewmodel at 0.05 to 0.3 m, and the furthest, often sky or sightline at 500 to 2000 m. If the ratio after tightening exceeds about 10^4, I expect visible fighting at distance and plan for reversed-Z. Polygon offset still helps for decals almost coplanar with a wall, but it does not fix two separate objects at 100 m, because the offset is quantised by the same coarse steps.

Reversed-Z

Standard Vulkan mapping, NDC z in [0,1], sends near to 0 and far to 1, with depth test LESS and clear 1.0. Reversed-Z sends near to 1 and far to 0, with test GREATER and clear 0.0. For eye distance d = -z_eye, the reversed mapping is:

z_ndc = near / (far - near) * (far / d - 1)

Check the endpoints: d = near gives 1, d = far gives 0. A 32-bit float buffer stores small values with finer absolute spacing, so putting far geometry at small values spends precision where the standard layout wastes it. Near precision, already abundant, gives some back.

Before committing I check that every shader writing depth writes reversed values, shadow maps use a compatible format or a separate path, and middleware does not assume LESS. On tile-based mobile GPUs, 32-bit float depth can miss the fast path, so I profile on the lowest target device.

Failure modes

Fighting that worsens with distance and grazing angle points to frustum ratio. Flicker uniform across the screen points to exact coplanarity. Shadow acne is separate, it lives in light space and needs bias and normal offset, not a camera frustum change. Tighten first, measure again, then reversed-Z if the ratio remains extreme.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-15How would you choose between MSAA, SSAA, TAA and FXAA for a 1080p game that needs stable edges in motion without blowing the frame budget?

The 90-second answer

Assume a forward renderer at 1920x1080, a 16.6 ms frame budget, and a scene where geometry edges and thin geometry matter more than text legibility. I would default to TAA if the game has motion vectors and a stable camera, MSAA 4x if it does not, and FXAA only as a fallback for hardware that cannot do either. SSAA 4x is the quality reference I test against, not the shipping default, because its cost scales with every fragment.

The four methods attack aliasing at different points. MSAA samples geometry coverage at subpixel positions inside the pixel, typically 4 samples, and resolves them to one colour. Shading still runs once per pixel in most implementations, so shader aliasing and alpha-tested edges survive. SSAA renders the whole frame at, say, 3840x2160 and downsamples, so it fixes geometry, shader and alpha aliasing together. TAA reprojects the previous frame using per-pixel velocity, blends it with the current frame, and uses jittered sampling over time to accumulate subpixel detail. FXAA runs after rendering, finds luminance edges, and blends along them. It never sees geometry or motion.

MethodWhere it runsWhat it fixesMain cost at 1080pTemporal behaviour
MSAA 4xRasterisation, per pixelGeometric edges4x colour and depth samples, resolve passStable, no history
SSAA 4xWhole frame, 4x pixelsGeometry, shader, alpha4x shading, bandwidth and memoryStable, no history
TAAPost, with velocity bufferGeometry, shader, alpha over timeHistory buffer, resolve, ~1 to 2 ms in a typical 1080p implementationCan ghost and shimmer
FXAAPost, luminance onlyHigh contrast edgesUnder 1 ms, one extra passShimmers on subpixel motion

Cost in concrete terms. At 1080p there are 2.07 million pixels. SSAA 4x renders 8.29 million fragments. If a fragment costs 20 operations in a forward shader, that is roughly 166 million operations instead of 41 million, before bandwidth. The framebuffer also grows: MSAA 4x needs 8.29 million colour samples plus depth, about 66 MB for colour and depth at 4 bytes each, plus resolve traffic. TAA keeps one extra history buffer at display resolution, about 8 MB for RGBA8, and pays for reprojection and neighbourhood clipping every frame. FXAA pays for a few texture reads per pixel and no extra geometry storage.

TAA is where the subtle bugs live. A minimal resolve looks like this:

GLSL
vec2 uv = fragCoord / resolution;
vec2 velocity = texture(velocityTex, uv).rg; // pixels per frame
vec2 historyUV = uv - velocity / resolution;
vec3 history = texture(historyTex, historyUV).rgb;
vec3 current = texture(currentTex, uv).rgb;
vec3 clipped = clipToNeighbourhood(history, current, uv); // AABB clip
float blend = 0.9; // 0.9 history, 0.1 current, tuned per material
vec3 result = mix(current, clipped, blend);

The clip matters. Without it, a bright texel from last frame bleeds into a dark area after disocclusion and you get a ghost trail that lasts many frames at a 0.9 blend. With too aggressive a clip, TAA softens and loses the detail it was meant to accumulate. Other failure modes I check in a test scene: thin wires at distance flicker because the velocity is wrong for particles, UI rendered into the same buffer smears because it has no motion, and camera cuts need the history reset or the first frame after the cut shows the old scene. Detection is visual but systematic: a rotating test pattern, a high contrast edge moving at constant velocity, and a teleport cut, all captured as a video loop.

Choosing in practice. If the renderer is deferred or clustered and MSAA is awkward, TAA is usually the only temporal option that also covers shader aliasing. If the game is a fixed camera puzzle title with alpha-tested foliage, MSAA will leave the foliage edges jagged and SSAA or TAA will look better. If the target is a low end GPU with no velocity buffer, FXAA at 1080p is cheap and predictable, but I would warn the team that text and thin lines will blur and that shimmering will remain on diagonal motion. I would benchmark all four on the same scene at the same resolution, measure p95 frame time, and keep SSAA 2x as the offline reference for what clean edges should look like.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-16Walk me through alpha blending for transparent objects: how do the blend equations and premultiplication change the result, and why does draw order still cause artifacts?

The 90-second answer

Transparent objects are blended after opaque objects, with depth writes off and depth tests on. The blend equation decides how a fragment's colour combines with what is already in the framebuffer, and draw order decides whether that combination is even correct, because the standard over operator is not commutative.

For straight (non-premultiplied) alpha, the usual equation is:

GLSL
// src = fragment output, dst = framebuffer contents
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// result = src.rgb * src.a + dst.rgb * (1 - src.a)

For premultiplied alpha, the shader stores rgb * a already, so the factors change:

GLSL
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
// result = src.rgb + dst.rgb * (1 - src.a)   // src.rgb is already premultiplied

Worked example. A red fragment with src.rgb = (1, 0, 0), src.a = 0.5 over a blue background dst.rgb = (0, 0, 1):

PathCalculationResult
Straight(1,0,0)*0.5 + (0,0,1)*0.5(0.5, 0, 0.5) purple
Premultiplied, shader outputs (0.5, 0, 0) with a = 0.5(0.5,0,0)*1 + (0,0,1)*0.5(0.5, 0, 0.5) same

Same result when the shader does the multiplication. The difference appears when the texture is filtered or resampled. A straight-alpha texture filtered with bilinear interpolation averages the RGB of fully transparent texels, which often contain junk colours, into edge texels. That produces a dark or coloured halo around a sprite. A premultiplied texture has RGB scaled toward zero where alpha is zero, so filtering averages premultiplied values and the halo disappears. That is why premultiplied formats are preferred for sprites, particles and UI, and why engines that use them must set the blend factors above. Mixing the two conventions, for example premultiplied texture with SRC_ALPHA factors, double-multiplies the colour and makes edges too dark.

Why sorting still breaks

Back-to-front sorting by object centroid, with depth writes disabled, handles most cases. It fails when geometry intersects, when one object is large and surrounds others, or when a single mesh contains both near and far transparent parts. Centroid distance then gives the wrong order for part of the screen.

Trace with two overlapping quads, A in front of B over part of their area and behind it over the rest (an X shape in depth). Sorting by centroid draws A first, then B. Where B is actually in front, B is blended over A as if it were behind, so the crossing region shows the wrong colour and the error flips as the camera moves. No per-object order can fix intersecting transparent geometry.

Practical mitigations, in increasing cost:

  1. Split transparent meshes into smaller chunks or convex pieces and sort per chunk. Cheap, helps particles and foliage, does not fix true intersections.
  2. Depth peeling. Render the scene repeatedly, each pass extracting the next depth layer. Correct for intersections, costs one full scene render per layer and needs extra depth buffers.
  3. Order-independent transparency. Weighted blended OIT accumulates colour and weight in two render targets and resolves in a final pass. It handles intersections without sorting, at the cost of extra bandwidth and a resolve pass, and it can still show artefacts with very deep stacks.

Two rules that prevent the common bugs: keep depth test on so transparent fragments behind opaque geometry are culled, and turn depth writes off for transparent passes so a front particle does not hide a back one. Leaving depth writes on is the usual cause of disappearing smoke and glass. Sorting must also be redone when the camera moves, and for objects that move, every frame. A static sort that was correct at load time will pop visibly once the camera orbits.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-17Should lighting and shading be calculated in linear space or sRGB space, and where is the sRGB conversion done?

The 90-second answer

Lighting and shading are calculated in linear space. The sRGB conversion happens once, at the end, when the finished image is written to the display. The one exception is at the input side: a texture stored as sRGB is decoded to linear when it is sampled, then everything stays linear until that final encode.

That is the rule to state first in an interview. Linear values are proportional to light energy, so adding, multiplying and blending them gives physically consistent results. sRGB values are a display encoding of linear values, so arithmetic on them does not correspond to arithmetic on light.

What sRGB is

sRGB, defined in IEC 61966-2-1, encodes linear light for a display with a nonlinear curve. The encode used for output is:

linear <= 0.0031308 : 12.92 * linear
linear >  0.0031308 : 1.055 * linear^(1/2.4) - 0.055

People often call this gamma correction and approximate it with a 2.2 power curve. The approximation is close, but sRGB is not a pure power curve. It has a linear segment near black. For a production pipeline, use the exact piecewise curve or let the hardware sRGB framebuffer apply it.

Where each step belongs

StageSpaceAction
Albedo and emissive textures stored in sRGBsRGB on diskDecode to linear on sample
Roughness, metalness and mask texturesLinear on diskSample as linear, no conversion
Lighting, shadows and blendingLinearNo conversion
Final write to an LDR displaysRGBEncode once

A minimal shader shows the placement:

GLSL
// Lighting pass, render target is linear
vec3 linearColor = albedo * diffuseLight + specular;
// Final output pass only
vec3 srgbColor = LinearToSRGB(linearColor);
fragColor = vec4(srgbColor, 1.0);

In OpenGL, Vulkan and DirectX you can instead render to an sRGB framebuffer and let the hardware encode after blending. Pick one method. Encoding manually and also writing to an sRGB framebuffer applies the curve twice and produces a washed out image.

Why the order matters, in one trace

Average black and white in linear space: (0 + 1) / 2 = 0.5. Encoding 0.5 gives about 0.735 on screen. Average the sRGB values instead: (0 + 1) / 2 = 0.5 on screen, which corresponds to only 0.214 in linear light. The second result is much darker than intended. The same error appears in diffuse lighting, gradients and transparent blending when they are done in sRGB space.

Common mistakes to name

Sampling an sRGB albedo texture as linear leaves it too dark, because display encoded values are treated as light energy. Sampling a linear roughness texture as sRGB brightens it on decode and changes the material response. Doing the encode before tonemapping in an HDR pipeline feeds display encoded values to a tonemapper that expects scene referred linear light. Each mistake is fixed by labelling every texture and render target with its colour space and keeping a single encode at the output.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-18How would you test HDR rendering, tone mapping and exposure so highlights keep hue and detail instead of clipping to white?

The 90-second answer

I test in linear HDR before any tone mapping, because once you clip to 1.0 in an 8-bit LDR buffer you cannot tell whether the operator, the exposure, or the display transform destroyed the highlight. I render the scene to a 16-bit float target, sweep exposure in stops, and check three things at each stop: does luminance roll off smoothly, does hue survive the shoulder, and does detail survive without banding.

Exposure is a multiplier in linear space. If EV = -1, the multiplier is 2^-1 = 0.5. A pixel at 16.0 in HDR becomes 8.0 before tone mapping. Tone mapping then maps [0, inf) to [0, 1). The operator decides the shape of that shoulder, and that is where highlight preservation is won or lost.

Operators, worked trace

Take three linear values after exposure: diffuse 0.18, bright window 4.0, sun disc 16.0. Reinhard is c / (1 + c). ACES filmic here is the Narkowicz fit, clamp((c * (2.51c + 0.03)) / (c * (2.43c + 0.59) + 0.14)), which is what the shader below implements.

Linear inputReinhardACES filmic (Narkowicz)What you see
0.180.150.27ACES lifts midtones, Reinhard darkens them
4.00.800.97Both bright, ACES already near white
16.00.941.00 (clamped)Reinhard still separates, ACES fit has saturated

That last row is the point of the test. Reinhard compresses early and washes out midtone contrast, but it never reaches 1.0, so 4.0 and 16.0 stay 0.14 apart, about 36 code values in 8-bit. The Narkowicz ACES fit keeps more midtone contrast, 0.27 versus 0.15 at 0.18, but its shoulder saturates by 16.0, leaving only 0.03, about 8 code values, between 4.0 and 16.0. A production ACES implementation (Stephen Hill's fit with the RRT and output transform, or AgX) is tuned to avoid that early clamp. If a custom operator behaves like the Narkowicz fit at 16.0, I flag it, because a sun and a window will merge.

Neither operator preserves hue by itself. Both operate per channel, so a saturated red at (16.0, 0.4, 0.2) gets its channels compressed by different amounts and shifts toward orange or white depending on the curve. That is the failure I look for first.

AgX and Unreal's filmic variants fix part of this by rotating colour space before the curve and desaturating toward white in the shoulder, so highlights lose saturation deliberately instead of shifting hue. If I am testing a custom operator, I check whether it does that rotation or whether it just clamps per channel.

Shader I test against

GLSL
// GLSL, checked against a float render target
uniform float exposure; // 2^EV
uniform int operator;   // 0 Reinhard, 1 ACES, 2 AgX approximation

vec3 toneMap(vec3 c) {
    c *= exposure;
    if (operator == 0) return c / (1.0 + c);
    // ACES filmic fit (Narkowicz)
    return clamp((c * (2.51 * c + 0.03)) / (c * (2.43 * c + 0.59) + 0.14), 0.0, 1.0);
}

void main() {
    vec3 hdr = texture(hdrBuffer, uv).rgb; // linear, FP16
    vec3 ldr = toneMap(hdr);
    // sRGB encode only after tone mapping
    gl_FragColor = vec4(pow(ldr, vec3(1.0 / 2.2)), 1.0);
}

Two bugs this catches immediately. Encoding to sRGB before tone mapping compresses the wrong domain and crushes the shoulder. Applying exposure after tone mapping, as toneMap(c) * exposure, scales the display value instead of the light. With Reinhard and exposure = 2.0, that gives 0.80 * 2 = 1.6 and 0.94 * 2 = 1.88, both clamped to 1.0, so 4.0 and 16.0 become identical white. Applying exposure first gives Reinhard(8.0) = 0.89 and Reinhard(32.0) = 0.97, which preserves the separation.

Test scene and pass criteria

I build one scene, not separate demos: a grey ramp from 0.01 to 32.0 in doubling steps, a Macbeth-style patch set lit at 0.18, 1.0, 4.0 and 16.0, a saturated red and blue emitter, and a fine gradient for banding. I render it at EV = -2, -1, 0, +1 to FP16, then read back the LDR values.

Pass criteria I can defend in a review:

  • Monotonicity: no step in the ramp decreases in output as input increases. A dip means the curve or the gamut clamp is folding back.
  • Hue drift: for the red patch at 16.0, hue angle in HSV moves less than about 10 degrees from its value at 1.0. Per-channel Reinhard on saturated red typically fails this, shifting 30 degrees or more toward yellow.
  • Separation: the 4.0 and 16.0 patches differ by at least 8 code values in 8-bit output after the operator. The Narkowicz fit above sits exactly on that boundary, which is why I test the production operator, not the fit, for sign-off.
  • Banding: the fine gradient shows no step larger than 1 code value in 8-bit, or I flag that the pipeline needs dithering or a 10-bit output path.

I also test the failure mode people miss: a highlight that is white in HDR but coloured in LDR because one channel clipped in the source texture. If the albedo texture is stored as 8-bit sRGB, its maximum is 1.0, so no exposure setting can recover a highlight that was never HDR. The test scene catches that because the emitter patches are written as float values, not textures.

On a real title I would then check the same scene on the target display path. A 10-bit HDR10 output with a 1000-nit peak uses a different transfer function (PQ) and a higher ceiling than an SDR sRGB output capped at 100 nits, so an operator that preserves highlights at 100 nits can still clip them at 1000 nits if the exposure is tuned only for SDR. That is why the sweep is in stops and the operator is tested separately from the output encoding.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-19Walk me through Lambert's cosine law for diffuse lighting, and what breaks down at grazing angles?

The 90-second answer

Lambert models an ideal diffuse surface as a perfect scatterer. Outgoing radiance is proportional to how directly the light hits the surface, and it does not depend on view direction. For a normalized normal N and normalized direction to the light L, the diffuse term is max(dot(N, L), 0). That dot is cos(theta), where theta is the angle between the normal and the light. At normal incidence it is 1. At 60 degrees it is 0.5. At 90 degrees, grazing incidence, it is 0, so the surface receives no diffuse light.

In a shader that is usually written as:

GLSL
// GLSL, checked against OpenGL ES 3.0 conventions
vec3 N = normalize(normal);
vec3 L = normalize(lightPos - worldPos);
float diff = max(dot(N, L), 0.0);
vec3 diffuse = albedo * lightColor * diff * intensity;

The BRDF behind it is albedo / pi, so if you want physical units you divide by pi and fold light intensity into the light color. Many games skip the pi and tune intensity by eye. The shape of the falloff is the same either way.

Worked trace

Take a flat ground plane, N = (0, 1, 0), albedo = 0.8, lightColor = 1, intensity = 3, and ignore the pi factor for the trace. Move the light from overhead to the horizon:

Light elevationthetacos(theta)diffuse output
90 deg, overhead0 deg1.0002.400
45 deg45 deg0.7071.697
10 deg80 deg0.1740.417
1 deg89 deg0.0170.042

The surface goes dark smoothly and reaches black at the horizon. That is the intended Lambert behavior, and it is also where the model stops matching real materials.

Where it breaks at grazing

First, real diffuse does not fall to zero as cleanly. Microfacets on a rough surface shadow and mask each other, and light can bounce between facets before exiting. The result is a broader, softer terminator. Oren-Nayar and the Burley diffuse from Disney capture part of this by adding a view-dependent term that keeps some energy at grazing angles. Pure Lambert gives a hard terminator line, which is why low sun in a game can look like a cliff edge between lit and unlit ground.

Second, Lambert has no Fresnel term. For dielectrics, reflectance rises sharply at grazing angles, so a rough surface at 85 degrees incidence should show a noticeable specular sheen and less diffuse. Lambert alone predicts only darkening. In practice you pair it with a specular model such as Schlick Fresnel, F0 = 0.04 for dielectrics, so grazing pixels pick up that sheen instead of going black.

Third, the model assumes the surface is opaque, matte, and non-metallic. Metals have almost no diffuse term at all, and subsurface materials such as skin or wax scatter light past the terminator. A common cheap fix is wrap diffuse, diff = clamp((dot(N, L) + wrap) / (1 + wrap), 0, 1) with wrap around 0.3 to 0.5. It fakes subsurface bleed and softens the terminator, but it also leaks light onto back faces and causes light bleeding in corners, so it is a stylistic choice, not a correction.

Choosing an alternative

ModelGrazing behaviorCostUse it when
LambertFalls to 0, view independent1 dot productCheap matte surfaces, prototyping
Wrap / half-LambertSoft terminator, leaks light1 dot product plus remapStylized games, skin and foliage approximations
Oren-Nayar / BurleyRetains energy, view dependentSeveral dots and pow termsRough terrain and cloth where low sun matters
Lambert plus Schlick Fresnel specularDiffuse darkens, specular sheen risesExtra Fresnel mathDefault PBR pairing for dielectrics

For a medium scene I would ship Lambert plus a Fresnel specular term, keep wrap at zero, and only move to Burley if the art team complains about the terminator at low sun angles. That keeps the shader cheap and makes the grazing failure visible in a controlled way, through the specular lobe, rather than hiding it with wrap.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-20A Blinn-Phong highlight at shininess 32 looks like a broad smear on a curved panel and vanishes at grazing angles. What causes each symptom, and how would you fix it in the shader?

The 90-second answer

Two separate faults are likely, and they need different fixes. The broad smear is a shininess and interpolation problem. The disappearance at grazing angles is usually a gating or normalization problem in the shader, not a property of the half-vector itself.

Blinn-Phong computes:

GLSL
vec3 N = normalize(normal);              // interpolated, renormalized per fragment
vec3 L = normalize(lightPos - fragPos);
vec3 V = normalize(cameraPos - fragPos);
vec3 H = normalize(L + V);
float ndh = max(dot(N, H), 0.0);
float spec = pow(ndh, shininess);
vec3 color = diffuse * max(dot(N, L), 0.0)
           + specularColor * spec;

H bisects L and V. The highlight peaks where N aligns with H, which is the halfway orientation between light and camera. shininess only controls falloff around that peak. It does not move it.

Why the smear looks broad at shininess 32

Shininess is an exponent on a cosine, so the falloff is steep near the peak and flat far from it. Work it out for a fragment 20 degrees away from the peak, where N·H = cos(20°) = 0.94:

shininess0.94^n at 20° off peak0.94^n at 40° off peak (cos = 0.766)
80.610.12
320.140.0002
1280.0004about 0
256about 0about 0

At 32 the highlight still carries 14 percent of its peak value 20 degrees off centre. On a curved panel that reads as a wide sheen, especially if the panel spans a large triangle. Car paint needs something closer to 128 to 256 for a tight clearcoat glint, and the peak stays at ks regardless of exponent, so total reflected energy falls as you tighten it. Scale ks up with the exponent, a common approximation is ks * (shininess + 1) / 33 when moving from a baseline of 32, or the tighter highlight looks dimmer than the smear it replaced.

Interpolation makes this worse. If you interpolate H across the triangle instead of interpolating the normal and rebuilding H per fragment, the highlight stretches because linear interpolation does not preserve the direction of a normalized vector. The same happens if you forget to renormalize the interpolated normal. N·H then shrinks in the triangle interior, which broadens and dims the lobe in a way that varies with tessellation. Fix that first, because no exponent tuning survives a wrong N.

Why it vanishes at grazing angles

The half-vector formulation was adopted partly because it holds up at grazing incidence better than Phong. In Phong, spec = pow(max(dot(reflect(-L, N), V), 0.0), n), and the reflected vector swings rapidly with small normal changes near grazing, so the highlight smears or drops out. With N·H, the bisector changes more smoothly, so the highlight should persist as the camera moves low across the panel.

If yours disappears, look for the usual shader bug: multiplying specular by the diffuse term.

GLSL
// common mistake
float spec = pow(max(dot(N, H), 0.0), shininess) * max(dot(N, L), 0.0);

At grazing view, N·L is often small even when N·H is near 1, because the light can still be well placed while the surface turns away from it. The product then kills a highlight that should be visible. Remove the N·L gate from the specular term. Specular reflection does not require the surface to face the light in the same way diffuse does, and gating it that way is a legacy habit from fixed-function pipelines.

The other grazing failure is numerical. When L and V point in nearly opposite directions, L + V has a small magnitude and its normalized direction becomes unstable. That happens for backlit fragments, not for a front-facing panel viewed at grazing angle, so it is worth checking only if the light sits behind the panel. Clamping ndh before pow also matters. Without max(..., 0.0), a negative dot gives undefined results on some drivers and the highlight flickers out entirely.

How I would retune it

First, confirm per-fragment normalization of N and per-fragment construction of H, and remove any N·L factor from specular. Then raise shininess from 32 toward 128 and rescale ks so peak brightness is preserved. Finally, clamp the exponent or fade it with distance. A highlight narrower than a pixel aliases and shimmers as the camera moves, so for distant panels I bias shininess down by mip level or clamp it to a maximum the surface tessellation can support. If the material needs a realistic grazing response beyond that, Blinn-Phong has no Fresnel term to give you. That is the point where I would move the clearcoat layer to a microfacet model such as GGX, which keeps the half-vector idea but replaces the plain power with a proper distribution function.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-21What does the Fresnel term in a microfacet BRDF describe, and what happens to reflectance as the view angle becomes grazing?

The 90-second answer

The Fresnel term gives the fraction of light reflected at the surface instead of entering it. In the microfacet BRDF it is F(v, h), where v is the view direction and h is the half vector between view and light. The key rule is that reflectance rises as the angle becomes grazing. At normal incidence a dielectric reflects very little. At grazing incidence it reflects almost everything.

That is why water, glass and polished plastic look dark when you look straight down at them and bright when you look across them. The geometry has not changed. The view angle has.

Schlick approximation

Most real time shaders use Schlick's approximation because it needs only F0 and v·h:

GLSL
vec3 F_Schlick(vec3 F0, float VoH) {
    return F0 + (1.0 - F0) * pow(1.0 - VoH, 5.0);
}

F0 is reflectance at normal incidence. For common dielectrics such as plastic, wood and glass, F0 is about 0.04. For metals, F0 is close to 1.0 and also carries the metal colour, which is why metals have no diffuse term in the same model.

The exponent 5.0 is part of the approximation. It keeps reflectance near F0 for a wide range of angles, then bends it sharply toward 1.0 near grazing. You do not need to derive it in an interview. You need to know the shape it produces.

Worked numbers

Take a dielectric with F0 = 0.04:

v·hAngle from normalF
1.000 degrees0.040
0.85about 32 degrees0.040
0.5060 degrees0.070
0.20about 78 degrees0.357
0.0090 degrees1.000

At v·h = 0.85, F = 0.04 + 0.96 * 0.15^5 = 0.0401. Almost nothing has changed. At v·h = 0.20, F = 0.04 + 0.96 * 0.8^5 = 0.355. More than a third of the light now reflects. At grazing, F = 1.0 for the dielectric and for the metal alike.

That last row is the fact to state plainly. Fresnel reflectance tends to 1 at grazing angles regardless of material. F0 sets the starting point. The angle sets the rise.

Where it sits in the BRDF

The full specular term is D(h) * G(l, v) * F(v, h) / (4 * (n·l) * (n·v)). D from GGX spreads the highlight, G from Smith shadowing removes occluded facets, and F scales the result by angle. If F is wrong, the highlight may have the right size but the wrong brightness at glancing views. A common bug is using F0 = 0.04 for a metal and leaving a diffuse term in place. The metal then looks dark head on and grey at the rim, because its reflectance should start high and stay high.

For image based lighting the same F is used with a prefiltered environment map. The grazing brightening still appears, which is why a rough floor can pick up a strong sky reflection at the horizon line even when its direct light highlight is broad and dim.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-22Walk me through Schlick's Fresnel approximation, how F0 differs for metals and dielectrics, and how you keep a BRDF energy conserving?

The 90-second answer

Schlick approximates the Fresnel reflectance, the fraction of light reflected at a surface instead of transmitted, as a function of the angle between the view direction and the half vector:

GLSL
float F0 = 0.04; // dielectric, see below
float fresnelSchlick(float cosTheta, float F0) {
    float m = clamp(1.0 - cosTheta, 0.0, 1.0);
    return F0 + (1.0 - F0) * pow(m, 5.0);
}
// cosTheta = dot(N, H), H = normalize(V + L)

At normal incidence cosTheta = 1 and F = F0. At grazing incidence cosTheta = 0 and F = 1 for every material. That grazing rise is the physical behaviour Schlick is fitted to, and the exponent 5 comes from fitting the exact Fresnel equations for dielectrics. It is an approximation, not the exact solution, and it ignores polarization, but it is cheap and close enough for a microfacet BRDF.

F0 is where the material lives. For a dielectric, F0 = ((n1 - n2) / (n1 + n2))^2. Air to glass with n = 1.5 gives ((1 - 1.5) / (1 + 1.5))^2 = 0.04. That is why most engines default F0 = 0.04 and let the diffuse albedo carry the colour.

Metals have a complex refractive index, so F0 is a colour, not a scalar, and it is high. The same value doubles as the specular tint and, in a metalness workflow, the diffuse albedo is forced to zero because metals absorb transmitted light within a few nanometres. Typical linear-space F0 values:

MetalF0 (linear)Appearance
---------
---------
---------
---------
---------
Gold(1.00, 0.71, 0.29)yellow reflection, blue absorbed
Copper(0.95, 0.64, 0.54)orange-pink
Aluminium(0.91, 0.92, 0.92)near white, high reflectance
Iron(0.56, 0.57, 0.58)grey, lower reflectance

Worked trace, dielectric

With F0 = 0.04:

Angle to HcosTheta(1-cosTheta)^5F
------------
0 deg1.0000.0000.040
45 deg0.7070.0020.042
80 deg0.1740.3850.410
89 deg0.0170.9100.914

Two consequences follow. A dielectric looks almost non-reflective head on, which is correct, and it becomes a mirror at grazing angles, which is why water, wax and clearcoat read as glossy even with a low F0. If you clamp or ignore the grazing term, silhouettes go flat.

Energy conservation

The BRDF must not return more light than it receives. In a simple Cook-Torrance split:

GLSL
vec3 F = fresnelSchlick(dot(N, H), F0);
vec3 specular = D * G * F / (4.0 * dot(N, V) * dot(N, L));
vec3 diffuse = (1.0 - F) * albedo / PI; // scaled, not raw albedo
vec3 Lo = (diffuse + specular) * radiance * dot(N, L);

The (1.0 - F) term is the point. Light reflected specularly cannot also be scattered diffusely. Trace it with numbers: take a dielectric with diffuse albedo 0.8 and a grazing view where F = 0.4. Unscaled, outgoing is 0.8 + 0.4 = 1.2 times the incoming light in that channel, which shows up as surfaces that brighten past white under strong lights and blow out image-based lighting. Scaled, diffuse becomes 0.6 * 0.8 = 0.48, total 0.88, and the surface darkens in diffuse exactly as the specular grows. That darkening at grazing angles is physically right and is a good visual check.

For metals the same rule is stricter: set diffuse albedo to zero, or to F0 in some formulations where the tint is carried only in F. If you leave a dielectric-style diffuse term on a metal, you get a coloured plastic. Gold with F0 = 0.04 and a yellow diffuse albedo looks like painted wood under a direct light, because the reflection stays white and weak while the diffuse does all the work.

Failure modes I check for

Using dot(N, V) instead of dot(N, H) in Schlick. The approximation is defined on the half vector for a microfacet. Using the view angle shifts the curve and makes the specular lobe behave oddly when the light moves.

Treating F0 as a scalar for metals. You lose the tint and the high reflectance at once. The fix is a vec3 F0, with the dielectric case as the special case where all three components are 0.04.

Forgetting that F approaches 1 at grazing for metals too. Metals are already near 1 at normal incidence, so the curve is flatter, but the same formula handles it. A separate metal Fresnel curve is unnecessary unless you are matching measured data closely.

Double counting in clearcoat or layered materials. Each layer that reflects must reduce the energy available to the layers below it, the same (1 - F) logic applied per layer, or stacked coats will exceed unit albedo in aggregate.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-23Why can't a rough metal reuse the diffuse irradiance map for its reflections, and how does a PMREM mip chain give it the right blur for its roughness?

The 90-second answer

Diffuse and specular integrate the same environment map, but with very different kernels. Diffuse assumes a Lambertian surface, so every incoming direction contributes with a cosine weight. That kernel is so wide that the result barely changes from one normal to the next. A 32x32 irradiance cubemap captures it.

Specular reflection from GGX does not behave that way. At roughness 0 the lobe is narrow and the reflection is sharp. At roughness 1 the lobe spreads over most of the hemisphere and the reflection is a broad blur. One fixed blur cannot serve both cases, so PMREM precomputes a family of blurs and stores them as mips.

Assume a static HDR environment in linear space, a GGX PBR material, and direct lights handled separately. IBL here covers ambient diffuse and environment reflections.

How the mip chain is built

For each roughness value, PMREM importance samples the environment using the GGX distribution around the reflection direction. Smooth surfaces sample tightly around that direction. Rough surfaces sample widely. The averaged radiance for that roughness is written to one mip level. A typical bake starts at 256x256 for roughness 0 and halves down to 4x4 for roughness 1, giving 7 levels.

GLSL
// Runtime sampling
vec3 R = reflect(-V, N);
float maxMip = textureQueryLevels(prefilteredEnv); // 7 for 256 to 4
vec3 env = textureLod(prefilteredEnv, R, roughness * (maxMip - 1.0));
vec3 F = fresnelSchlick(max(dot(N, V), 0.0), F0);
vec3 specular = env * F;

Roughness therefore selects blur directly. No per pixel loop over the environment is needed.

RoughnessMip sampledWhat the surface sees
0.00Sharp mirror image
0.5About 3Softened reflection, highlights widen
1.06Broad average, close to diffuse in smoothness

Diffuse still uses its own map:

GLSL
vec3 irradiance = texture(irradianceMap, N);
vec3 diffuse = albedo * irradiance * (1.0 / PI);

Keep the PI convention consistent. If the bake already divided by PI, dividing again in the shader makes every diffuse surface too dark by a factor of PI.

How I check the bake

A constant environment of 1.0 should produce 1.0 in every prefiltered mip and PI in the irradiance map before any PI division. That catches missing normalization and black seams between cubemap faces.

A single bright texel at value 20.0 should stay sharp at mip 0 and spread at the last mip, with total energy roughly preserved. If the rough mip goes black, the GGX sampling is dropping energy. If the smooth mip is already blurred, the bake is sampling the wrong mip or the source was loaded as LDR and clipped.

A final check is a roughness sweep on a sphere under a known environment. As roughness increases, the reflected window should widen and dim in peak brightness but not vanish. A surface that turns black at mid roughness usually has its roughness remapped twice, for example glTF style squaring applied in both the material and the sampler, so the shader asks for a much rougher mip than intended.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-24How do you build a TBN frame for tangent-space normal mapping, and what breaks when UVs are mirrored?

The 90-second answer

Tangent-space normal mapping stores a perturbed normal in a frame that travels with the surface. At each fragment I build that frame from the interpolated normal N, the tangent T (direction of increasing U in world space) and the bitangent B (direction of increasing V). The texel is read as a normal in tangent space, n_ts, and transformed as n_world = T * n_ts.x + B * n_ts.y + N * n_ts.z. Lighting then uses n_world like a geometric normal.

The catch is handedness. A normal map baked for a right-handed UV layout has its green channel pointing along +B. If the UV island is mirrored, the UV-derived B points opposite to cross(N, T), the green channel ends up inverted, and bumps light as dents. I compute a handedness sign per fragment and flip the green channel when the frame is left-handed, or I bake a separate mirrored map. Picking one and being consistent across the asset matters more than which one you pick.

Building the frame in the shader

Assume the vertex shader passes world position, world normal, and UV. In the fragment shader I use derivatives of position and UV to get T and B without a tangent attribute, which avoids seams where tangent attributes disagree between adjacent triangles:

GLSL
// GLSL, fragment shader. Assumes linear-space lighting.
vec3 q0 = dFdx(vWorldPos);
vec3 q1 = dFdy(vWorldPos);
vec2 st0 = dFdx(vUV);
vec2 st1 = dFdy(vUV);

vec3 N = normalize(vNormal);
vec3 Tuv = q0 * st1.t - q1 * st0.t;
vec3 Buv = q1 * st0.s - q0 * st1.s;

// +1 for a right-handed UV frame, -1 for a mirrored one.
float handedness = dot(cross(N, Tuv), Buv) >= 0.0 ? 1.0 : -1.0;

// Orthonormalise: interpolated N is not perpendicular to Tuv.
vec3 T = normalize(Tuv - N * dot(N, Tuv));
vec3 B = normalize(cross(N, T));

vec3 nTS = texture(normalMap, vUV).rgb * 2.0 - 1.0;
nTS.y *= handedness;
vec3 nWorld = normalize(T * nTS.x + B * nTS.y + N * nTS.z);

The derivative form, often called the cotangent frame, handles arbitrary triangulation and needs no tangent attribute, at the cost of derivative instructions and a frame that can rotate within a large triangle. A per-vertex tangent attribute interpolated across the triangle is cheaper and stable on dense meshes, but it smears across UV seams and needs MikkTSpace or equivalent to bake and render with the same frame, otherwise the seam lights differently from the interior.

Worked trace

Take a flat quad facing +Z, so N = (0, 0, 1). Unmirrored, T = (1, 0, 0) and B = (0, 1, 0). A texel decoded as n_ts = (0.3, 0.4, 0.866) gives:

n_world = 0.3*(1,0,0) + 0.4*(0,1,0) + 0.866*(0,0,1) = (0.3, 0.4, 0.866)

With a light from +Z, diffuse is dot(n_world, L) = 0.866, so the surface reads as tilted toward +X and +Y in UV space.

Now mirror U, so U increases toward -X in world space. Then Tuv = (-1, 0, 0) and Buv = (0, 1, 0). cross(N, Tuv) is (0, -1, 0), its dot with Buv is -1, so handedness is -1. After orthonormalisation T = (-1, 0, 0) and B = cross(N, T) = (0, -1, 0). Flipping n_ts.y gives (0.3, -0.4, 0.866), and:

n_world = 0.3*(-1,0,0) + (-0.4)*(0,-1,0) + 0.866*(0,0,1) = (-0.3, 0.4, 0.866)

The X component follows the mirrored U, as it should, and the Y component stays +0.4 because the green flip cancels the B flip. Without the flip the result would be (-0.3, -0.4, 0.866): the bump would tilt toward -Y in world space while the texture appears to tilt toward +Y, which is the inverted lighting artists report on mirrored shells and character faces.

Failure modes I check for

SymptomCauseFix
Bumps light as dents on one island onlyMirrored UV, green channel not flippedPer-fragment handedness, or bake a mirrored variant
Visible seam line along UV bordersVertex tangents disagree across the seamDerivative frame, or MikkTSpace tangents matched at bake time
Normal darkens at grazing anglesT not orthonormalised against interpolated NGram-Schmidt step above, then renormalise
Whole mesh looks inside-out after a negative-scale transformModel matrix flips winding and frame handednessFlip handedness for negative determinant, or fix the scale in the asset

One more trap: OpenGL-style normal maps store +Y up in green, DirectX-style store -Y. That is a bake-time convention, separate from mirroring. If a mesh looks correct in the DCC and inverted in engine, check the convention before touching the shader. And never skip the final normalize on n_world. Interpolated N, Tuv and Buv are not unit length and not mutually perpendicular, so the sum drifts off the unit sphere and diffuse plus specular both shift. That drift is small on flat areas and obvious on curved ones, which is why it survives a quick test on a plane and fails on the model.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-25What does shadow bias do in shadow mapping, and what happens when it is too small or too large?

The 90-second answer

Shadow bias is a small offset added to the depth you compare against the shadow map, so a surface does not compare against its own depth and reject itself. In the light pass you reconstruct the fragment position in light space, look up the nearest occluder depth mapDepth, and test fragmentDepth - bias > mapDepth. If the test passes, the fragment is in shadow.

Too little bias gives shadow acne: striped, moire-like bands on surfaces that face the light, worst at grazing angles where a tiny depth error flips the test. Too much bias gives peter-panning and light leaks: thin occluders stop casting, contact shadows detach, and light slips around edges. Bias is therefore not a magic constant. It scales with depth precision, texel size, and the angle between the surface normal and the light direction.

GLSL
// Fragment shader, checked against GLSL 4.60 / OpenGL 4.6 conventions
vec3 lightPos = (uShadowMatrix * worldPos).xyz / (uShadowMatrix * worldPos).w;
float mapDepth = texture(uShadowMap, lightPos.xy).r;
float ndotl = max(dot(normal, uLightDir), 0.0);
// Depth bias grows at grazing angles; normal bias moves the sample along the normal
float bias = max(0.0015 * (1.0 - ndotl), 0.0005);
float inShadow = (lightPos.z - bias > mapDepth) ? 1.0 : 0.0;

In practice I use two biases together. Depth bias shifts the comparison value. Normal bias offsets the sampling position along the surface normal before the lookup, which helps acne on curved or sloped geometry without pushing thin geometry as far. Slope-scaled bias, the 1.0 - ndotl term above, is the standard compromise: almost no offset when the surface faces the light, more when it is nearly edge-on and depth changes fastest across texels.

SettingVisible resultTypical cause
Bias too smallShadow acne, flickering stripes on lit surfacesSelf-shadowing from depth quantisation and texel footprint
Bias about rightClean contact, stable edgesOffset covers quantisation error only
Bias too largePeter-panning, detached shadows, light leaks at thin edgesOccluder depth pushed behind the receiver
Normal bias too largeShadows detach from bases of objectsSample point lifted off the surface it should test

What an interviewer follows up on

PCF, percentage-closer filtering, does not fix bias. It softens the binary test by sampling a small kernel, often 3x3 or 5x5 taps, and averaging the results. That hides texel aliasing and jagged edges, at the cost of wider, softer penumbrae and more texture fetches. A 5x5 PCF kernel costs 25 fetches per fragment unless you use hardware PCF or a Poisson disc distribution, which spreads the same taps more evenly.

VSM, variance shadow mapping, stores the mean and variance of depth in the map instead of a single depth. You can then blur it and compute a shadow probability from the variance, which gives soft shadows cheaply. The failure mode is light bleeding: a bright occluder behind a thin one raises the variance and the test passes light through. VSM also needs the occluder pass to write moments correctly and clamp the variance, or distant geometry leaks.

For large scenes a single shadow map wastes resolution. Cascading shadow maps split the camera frustum into, usually, four overlapping slices with logarithmic spacing. Near cascades get high texel density for detail, far cascades cover the horizon at lower density. The trade-off is seams between cascades and extra memory: four 2048x2048 maps cost four times the memory of one, and blending between cascades needs a fade or a cross-fade in the shader or you see a hard line where one cascade ends.

Camera frustum (top view)
[ near cascade: 2048 map, high density ]
[ mid cascade:   2048 map, medium density ]
[ far cascade:   2048 map, low density ]

So the tuning order I use is: set the shadow camera frustum tightly first, add slope-scaled depth bias plus a small normal bias, then add PCF for edge quality, and only reach for VSM or cascades when resolution or scene size forces it.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-26How do you test SSAO hemisphere sampling, radius and bias, and why does it fail on thin geometry like leaves and railings?

The 90-second answer

SSAO estimates how much of the hemisphere above a surface point is blocked by nearby geometry. For each sample direction I compare the sample's scene depth with the depth reconstructed along that ray. If the scene is closer than the sample point, that direction is occluded. Averaging 16 to 32 cosine-weighted hemisphere samples gives the occlusion factor, which I multiply into diffuse lighting.

Radius sets the world-space distance over which occlusion is searched. Bias offsets the comparison depth to hide self-occlusion from depth precision and normal error. Both are testable in isolation, and thin geometry breaks the core assumption that the depth buffer describes one opaque surface per pixel.

GLSL
// View space, depth texture stores linear view depth in .r
vec3 n = normalize(normal);
vec3 t = normalize(cross(abs(n.y) < 0.99 ? vec3(0,1,0) : vec3(1,0,0), n));
vec3 b = cross(n, t);
float occ = 0.0;
for (int i = 0; i < 16; i++) {
  vec3 dir = normalize(t * rnd.x + b * rnd.y + n * rnd.z); // cosine weighted
  vec3 sp = pos + dir * radius * (0.25 + 0.75 * float(i) / 15.0);
  vec2 uv = project(sp);
  float sceneDepth = texture(depthTex, uv).r;
  float sampleDepth = -sp.z;
  float range = clamp(radius / max(sampleDepth - sceneDepth, 1e-4), 0.0, 1.0);
  occ += (sceneDepth < sampleDepth - bias) ? range : 0.0;
}
float ao = clamp(1.0 - occ / 16.0 * strength, 0.0, 1.0);

The range falloff matters. Without it a distant occluder counts as much as a contact occluder, and AO looks like a uniform darkening instead of contact darkening.

How I test it

I build a fixed test scene and check numeric AO at probe points, not screenshots by eye. Probes: a sphere resting on a plane, a box in a corner, two parallel planes 0.1 m apart, a step edge, and a thin plane 0.01 m thick with open space behind it. Camera and lighting are locked, samples use a fixed random seed per frame index, and I render the AO buffer alone.

ProbeExpected AOWhat it catches
Sphere on plane, contact point0.2 to 0.4Radius too small, bias too large
Sphere on plane, 0.5 m above0.85 to 1.0Radius too large, missing falloff
Box corner interior0.3 to 0.5Hemisphere basis or normal transform error
Flat plane, no occluders0.98 to 1.0Self-occlusion, bias too small
Thin plane, front face0.9 to 1.0Backface and depth discontinuity leaks

I sweep radius at 0.25 m, 0.5 m and 1.0 m for a scene scaled in metres, and bias at 0.01, 0.03 and 0.08 in view-depth units. A correct setting keeps the flat plane near 1.0 while the contact probe stays dark. If the flat plane drops below 0.95, bias is too small or the depth reconstruction is wrong. If contact stays above 0.6, radius is too small or the falloff is too aggressive.

Why thin geometry fails

A leaf, railing or cloth sheet has almost no thickness in the depth buffer. A sample ray from the front face can pass the edge or the surface itself and hit geometry behind it. The depth test then reports occlusion from objects that are on the other side of the sheet, so the front face darkens as if it sat in a crevice. The reverse also happens: a sample that should hit the sheet misses it, and a surface behind the sheet receives too little occlusion, which reads as a light leak or halo around the edge.

Trace for a 0.01 m leaf with radius 0.5 m: the centre pixel samples 16 directions. Eight directions cross the leaf plane within 0.05 m and hit a wall 0.4 m behind it. The depth difference is large, the range term is near 1.0, and those eight samples contribute almost full occlusion. Measured AO lands near 0.55 where the probe expects 0.95. The error is not noise. It is systematic, because every ray that crosses the plane sees the same wall.

Three fixes, in order of preference. First, reject samples whose depth discontinuity is too large relative to radius, or whose hit normal faces away from the sample direction. That stops most cross-surface samples at modest cost. Second, store a thickness or backface depth and treat a hit as occluding only if the sample point lies inside the occluder's volume. This is the approach used in thickness-aware SSAO and it handles leaves and railings correctly, at the cost of an extra render target. Third, shrink radius for thin materials or disable SSAO for them and use a baked or screen-space contact shadow instead. That is a pragmatic fallback for foliage, where per-leaf AO is rarely visible.

I also check the normal. Thin double-sided geometry often flips normals for backfaces. If the hemisphere is built from a flipped normal, samples go into the surface and the whole calculation inverts. Testing with gl_FrontFacing forced on and off separates that bug from a radius problem in one run.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-27How does HDR bloom thresholding work, and what artifacts do downsampling and upsampling introduce that you would check for in a test scene?

The 90-second answer

Bloom has to run on linear HDR values before tone mapping. After tone mapping, a pixel at 4.0 and a pixel at 40.0 both clamp near 1.0, so a small emissive light and a bright sky become indistinguishable. The chain is: render to an HDR target, extract pixels above a threshold with a soft knee, downsample that extract through a mip chain, upsample and blur back up, then add the result to the HDR frame before tone mapping.

Most visible artifacts come from the resampling steps. Downsampling a sparse bright pixel concentrates its energy into one texel at the next level, and that texel then spreads on upsample. Upsampling with plain bilinear filtering gives diamond shaped iso contours around point lights. Thresholding in sRGB space instead of linear space shifts hue, because the same linear colour is encoded unevenly across channels.

Bright pass with a soft knee

A hard step pops as a light crosses the threshold and gives the halo a hard edge. A soft knee spreads the transition over a luminance range. This form is used in the Filmic Tonemapping notes by John Hable, adapted for a linear HDR input:

HLSL
// color: linear HDR, values can exceed 1.0
float3 BrightPass(float3 color, float threshold, float knee)
{
    float luma = dot(color, float3(0.2126, 0.7152, 0.0722));
    float t = clamp((luma - threshold + knee) / (2.0 * knee), 0.0, 1.0);
    float soft = t * t * (3.0 - 2.0 * t);
    return color * soft;
}

With threshold = 1.0 and knee = 0.5, the weight is 0 at luma 0.5 and below, about 0.03 at luma 0.6, 0.5 at luma 1.0, and 1.0 at luma 1.5 and above. A pixel at luma 2.0 therefore passes through at full weight, not half weight. That knee is the first thing to tune when highlights switch on abruptly.

Downsample and upsample chain

For a 1920x1080 frame, a typical chain halves each level. The cost is dominated by the first level, which is why the chain exists.

LevelSizeTexelsRole
0960x540518,400bright pass plus first downsample
1480x270129,600wide halo
2240x13532,400widest halo
3120x688,160very wide glow

Downsampling usually uses a tent filter, where the centre texel gets more weight than its neighbours, rather than a box filter, where all taps weigh equally. Upsampling runs the chain in reverse with bilinear filtering and adds each level into the one below. Two failure modes show up in testing:

  1. Firefly flicker. Take a 1 pixel source at luma 16 on a black background. A 2x2 box average produces a single texel at luma 4 at the next level, because (16 + 0 + 0 + 0) / 4 = 4. That texel is then upsampled into a 2x2 block. If the source moves by half a pixel, its energy splits across two or four downsampled texels instead of one, so the peak halo brightness changes frame to frame even though the source is constant. A tent filter reduces this because the weight falls off with distance, so a source near a texel boundary contributes more evenly to its neighbours.
  2. Hue shift. If the bright pass runs after an sRGB conversion, a saturated red at linear (4.0, 0.2, 0.1) is encoded unevenly and the extracted halo leans orange or pink. Running the pass in linear space keeps the halo colour matching the source.

Box versus tent: when the cheaper filter is acceptable

Box (4 taps, equal weight)Tent (weighted taps)
CostCheapest, one gather with equal weightsSlightly more ALU for weights, same texture fetches with a gather
Halo shapeSquare footprint around isolated texelsRounder falloff, less visible squareness
Flicker on subpixel motionHigher, energy jumps between texelsLower, energy distributes to neighbours

The box filter is acceptable when the halo is intentionally wide and low intensity, when sources are large rather than point lights, and when the frame budget is tight, for example on a mobile GPU where the first downsample at 960x540 dominates the bloom cost. The square footprint is then hidden because later blur levels spread it further. The tent filter is worth it when HDR values are high (above about 8), when the scene has small emissive sources such as muzzle flashes or neon signs, and when the camera moves, because those are the cases where box filtering produces visible flicker and blocky halos. The deciding test is a capture of the smallest source in the scene at two subpixel positions: if peak halo brightness changes by more than about 20 percent between the two positions, the filter is too cheap for that content.

How I would test it

I build one scene with a luminance ramp rather than a few lights. A row of emissive spheres with known linear values from 0.5 to 16.0 in steps, a thin emissive line, a checkerboard of bright and dark tiles, and a large bright sky region just below threshold. Then I vary one parameter at a time.

With threshold at 1.0, spheres below 1.0 should produce no halo at all. If the sky at 0.9 produces a halo, the threshold is being applied in the wrong colour space or the HDR buffer is being clamped. With the ramp in place, I check that halo brightness grows monotonically with source luminance and that no sphere clips to white before tone mapping. I also capture the downsampled levels directly. Level 0 should show the ramp as discrete steps. If level 0 already looks blurred, the first downsample filter is too wide. If the upsampled composite shows a diamond around the smallest sphere, the upsample filter is plain bilinear without the tent weighting the downsample used, so energy is not conserved between the two directions.

A final check is motion. A static bloom that looks clean often ghosts when the camera pans, because the mip chain has no temporal history. Panning across the thin line should keep its halo centred on the line. A trailing halo means the upsample is reading stale texels or the chain is being reused across frames without being cleared.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-28How do mip level selection, texture derivatives and anisotropic filtering interact, and how would you tune them for a grazing-angle ground texture that shimmers at distance?

The 90-second answer

The GPU picks a mip level per fragment from screen-space derivatives of the texture coordinate. For uv, hardware computes dFdx(uv) and dFdy(uv) across a 2x2 quad of fragments, forms the footprint in texels, and sets lambda = log2(max(rho_x, rho_y)), where rho_x = length(dFdx(uv) * textureSize) and rho_y = length(dFdy(uv) * textureSize). That lambda selects between two mip levels for trilinear filtering. Isotropic filtering samples one texel at that level. Anisotropic filtering stretches the footprint into an ellipse, samples several texels along its major axis at a lower mip, and blends them.

For a ground plane seen at grazing angle, the footprint is long in one direction and thin in the other. Isotropic selection uses the long axis, so it picks a very coarse mip and the texture turns to mush up close to the horizon. Anisotropy fixes that by keeping the thin axis sharp while averaging along the long axis. The trade is bandwidth and cache pressure: 8x anisotropy can read several times the texels of isotropic on a full-screen ground quad.

Worked trace

Take a 2048x2048 texture on a ground quad. At a distant fragment, suppose:

uv = (0.500, 0.250)
dFdx(uv) = (0.0040, 0.0002)   // per pixel, moving right on screen
dFdy(uv) = (0.0001, 0.0004)   // per pixel, moving down on screen

Multiply by texture size:

rho_x = 2048 * length(0.0040, 0.0002) = 2048 * 0.004005 = 8.20 texels/pixel
rho_y = 2048 * length(0.0001, 0.0004) = 2048 * 0.000412 = 0.84 texels/pixel
lambda = log2(max(8.20, 0.84)) = log2(8.20) = 3.04

Trilinear filtering blends mip 3 and mip 4, weighted 0.96 and 0.04. The footprint aspect ratio is 8.20 / 0.84 = 9.8, so the ellipse is about 10:1. With 8x anisotropy, the sampler takes up to 8 taps along the major axis at roughly mip 3, instead of one tap at mip 3. That preserves detail across the thin axis, which is why distant ground stops shimmering and blurring at the same time.

Closer to the camera the same quad might give rho_x = 1.2, rho_y = 0.9, lambda = 0.26, aspect ratio 1.3. Anisotropy buys almost nothing there, but the hardware still pays for extra taps if the sampler is set to 16x globally. That is why anisotropy is a per-material or per-sampler choice, not a global max.

Choosing anisotropy and mip bias

SetupGrazing ground at distanceClose-up detailCost on ground-heavy scene
Isotropic, bias 0Blurry, stableSharpLowest
Aniso 4x, bias 0Much sharper, occasional shimmerSharpModerate
Aniso 8x, bias 0Sharp, stable if mip chain is completeSharpHigh, watch bandwidth
Aniso 16x, bias 0Marginal gain over 8x on most GPUsSharpOften wasted, cache thrash
Aniso 8x, bias -0.5Sharper still, aliasing returnsSharperSame taps, more shimmer
Aniso 8x, bias +0.5Softer, shimmer goneSlightly softSame taps, safer

I start ground, roads and walls at 8x on desktop and 4x on a bandwidth constrained target, then check a frame capture for texel reads per pixel. If the ground covers half the screen, 16x rarely survives that check. Negative bias is a last resort for shimmer. It forces a finer mip than the derivative asks for, which looks crisp in a still frame and crawls in motion.

Where derivatives break

Derivatives are computed per 2x2 quad, so they are constant across the quad and undefined at its edges. Helper lanes supply values for fragments that are discarded or outside the triangle. Two failure modes follow from that.

First, non-uniform control flow. If uv is computed inside a branch that only some lanes in the quad take, the derivative is garbage or undefined in the other lanes. The fix is to compute uv and call textureGrad with explicit derivatives from a uniform path, or hoist the computation out of the branch:

GLSL
// GLSL, checked against OpenGL ES 3.1 / Vulkan GLSL
vec2 uv = vUv;
vec2 dx = dFdx(uv);
vec2 dy = dFdy(uv);
// branch that changes shading, not uv
vec4 tex = textureGrad(albedo, uv, dx, dy);

Second, an incomplete mip chain. In OpenGL and WebGL2, a texture is incomplete if the sampler is set to a mipmap filter and the image data does not contain the full chain down to 1x1. Sampling an incomplete texture returns (0,0,0,1), black with alpha 1, not the last available level. That shows up as a black surface at distance, or black in a capture where the sampler state expects mipmaps the upload never supplied. I generate the full chain at load, check the level count in a capture, and treat a black distant surface as a completeness bug before touching anisotropy. Non-power-of-two sizes are not the cause on current targets: OpenGL ES 3.0 and Vulkan both support mipmapping for NPOT textures.

A third failure is derivative discontinuity at triangle edges. Two adjacent triangles with slightly different uv gradients produce a visible seam in mip selection, worst on tessellated terrain. Keeping the texture mapping continuous across the shared edge, usually by deriving uv from a world-space triplanar or object-space position instead of per-triangle attributes, removes it.

How I test it

I render a test scene with a checkerboard ground at known texel density, a camera that dollies from 2 m to 200 m at a fixed grazing angle, and capture three frames per stop. I check that lambda increases by roughly 1 per doubling of distance, that the horizon line does not crawl, and that a frame capture shows the expected mip level and anisotropy taps. Then I repeat with the camera pitched down to 45 degrees. If anisotropy is set correctly, the close-up frames should show identical texel reads, because the footprint is nearly square there.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-29Which BC format would you pick for an opaque albedo, a cutout leaf with alpha, and a normal map, and why?

The 90-second answer

Pick by channel count first, then by whether you need alpha or HDR. That gives you a default for almost every asset.

AssetDefaultWhy
Opaque albedo, sRGBBC14 bits per texel, no alpha channel to waste bits on
Albedo with smooth alpha, sRGBBC3Separate interpolated alpha block, 8 bits per texel
Normal map, linearBC5Two BC4 blocks, one per channel, stores XY with 4-bit indices
Single channel mask, linearBC4One BC4 block, 4 bits per texel
HDR colour, linearBC6HHalf-float endpoints, 8 bits per texel
High-quality colour, sRGBBC7Multiple partitions and modes, 8 bits per texel

All BC formats compress independent 4x4 blocks, so width and height should be multiples of 4 or the compressor pads the edge. BC1 stores 8 bytes per block. BC2, BC3, BC5, BC6H and BC7 store 16 bytes per block. Against uncompressed RGBA8 at 32 bits per texel, that is an 8x saving for BC1 and a 4x saving for the 8-bit formats, with no decompression step on the GPU. The hardware reads the block and interpolates the texel in the texture unit.

How the blocks differ

BC1 picks two RGB565 endpoints and a 2-bit index per texel. The four colours are endpoint A, endpoint B, and two blends between them. In its 3-colour mode the fourth index is transparent black, which is why BC1 works for cutout but gives you only one alpha value. BC3 keeps a BC1-style colour block and adds a separate alpha block with two 8-bit endpoints and 3-bit indices, so alpha is interpolated across 8 values. BC2 also adds a separate alpha block, but stores 4 bits per texel explicitly. That preserves hard alpha edges better and smooth alpha worse, so I use BC3 for foliage alpha and BC2 only when the alpha is mostly binary.

BC4 is one channel: two 8-bit endpoints and 4-bit indices, 16 values per block. BC5 is two BC4 blocks side by side, so a normal map gets X in the first block and Y in the second. Z is rebuilt in the shader as sqrt(1 - x*x - y*y), which is why BC5 normals look clean. Packing a normal into BC1 throws away precision because the colour endpoints and 2-bit indices quantise the XY plane coarsely, and you see faceting on curved surfaces under a moving light.

BC7 encodes RGBA in a single 16-byte block. It partitions the 4x4 block into one to three subsets depending on the mode, gives each subset its own endpoints, and chooses among 8 modes with different index bit depths. Alpha is encoded inside those endpoints rather than in a dedicated alpha block, so BC7 can carry alpha but its alpha precision is lower than BC3 for smooth alpha gradients. That extra search is why BC7 holds colour gradients and skin tones with far less banding than BC1, and why compression takes seconds per texture instead of milliseconds. BC6H is the HDR counterpart. It uses partitions and half-float endpoints, so values above 1.0 survive compression for emissive and light probe data.

Testing a choice

I compress a test sheet at 100% zoom and at mip 3, because block artefacts hide at mip 0 and explode when the texture is minified. A minimal DirectXTex call looks like this:

C++
// Checked against DirectXTex, current release
Compress(image, DXGI_FORMAT_BC5_UNORM, TEXCOMPRESS_DEFAULT, 0.5f, &out);
Compress(image, DXGI_FORMAT_BC3_UNORM, TEXCOMPRESS_DEFAULT, 0.5f, &out);

UNORM here is deliberate for the normal map. Marking it sRGB would apply the sRGB transfer function on sample and corrupt the vector. For albedo I use the sRGB variant of the same format, for example BC3_SRGB, so the endpoints are decoded correctly.

Three checks catch most mistakes. First, flip between the source and compressed texture under a rotating light. BC1 normals and BC1 gradients show stepping that BC5 and BC7 remove. Second, inspect alpha at a leaf edge. BC3 bleeds colour into semi-transparent texels because colour and alpha blocks are chosen independently, so premultiplied alpha or a colour dilation pass on the source fixes the fringe. Third, check memory on a 1024x1024 texture. BC1 is 512 KiB, BC3 and BC7 are 1 MiB, and RGBA8 is 4 MiB. If a texture is sampled once per frame, BC7 often wins on bandwidth despite the slower offline compress. If it is sampled rarely and the asset count is huge, BC1 wins on disk and load time.

The failure mode to watch is format mismatch in the import pipeline. A normal map imported as BC1 sRGB, or an HDR emissive imported as BC7, will load without an error and look wrong in a way that is hard to trace back to compression. Naming the format in the asset metadata and asserting it at load time prevents that class of bug.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-30Walk me through how you would lay out interleaved versus separate vertex buffers for a mesh with position, normal, UV and tangent, and how stride and alignment affect cache and fetch performance?

The 90-second answer

I start from which attributes each pass actually consumes. If every pass reads position, normal and UV together, one interleaved buffer wins: one binding, one sequential stream, and the vertex fetch unit can stream consecutive vertices without jumping between allocations. If a depth prepass, shadow pass or skinning pass reads position only, separate buffers win because those passes never pay for the other bytes per vertex. Layout is a bandwidth decision per pass, not a purity decision about AoS versus SoA.

Take a concrete vertex: position 12 bytes, normal 12, UV 8, total 32. That is the layout I would test first.

C++
// Checked against Vulkan 1.3 vertex input rules
struct Vertex {
    float pos[3];    // offset 0,  12 bytes
    float normal[3]; // offset 12, 12 bytes
    float uv[2];     // offset 24, 8 bytes
};
static_assert(sizeof(Vertex) == 32);

VkVertexInputBindingDescription binding{0, 32, VK_VERTEX_INPUT_RATE_VERTEX};
VkVertexInputAttributeDescription attrs[3] = {
    {0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0},
    {1, 0, VK_FORMAT_R32G32B32_SFLOAT, 12},
    {2, 0, VK_FORMAT_R32G32B32_SFLOAT, 24},
};

Stride is 32, offsets are 0, 12 and 24. Each offset is a multiple of the size of its format, which Vulkan requires for vertex attributes, and the stride equals the size of the struct that fills the buffer. If I add a vec4 tangent, the struct grows to 48 bytes and the stride becomes 48. That is real data, not padding, and the cost has to be justified by the passes that read it.

What the arithmetic says

These figures are hypothetical and assume no index reuse benefit, so they compare layouts rather than predict a frame time. A 2 million vertex mesh at 32 bytes per vertex is 64 MB of vertex data per frame, or 3.84 GB/s at 60 fps. At 48 bytes per vertex the same mesh is 96 MB per frame, 5.76 GB/s. A position-only pass over a split layout reads 12 bytes per vertex, 24 MB per frame, while the same pass over the interleaved layout still streams the full 64 MB because the fetch unit walks the whole stride. Split buffers cost three bindings and three base offsets to update, and they can lose sequential prefetch efficiency when all attributes are needed, because three streams have to stay in step.

LayoutFull pass, 2M verticesPosition-only passBinding costMain risk
Interleaved, 32 B stride64 MB64 MB, wastes 62 percent1 bindingOverfetch in depth and shadow passes
Separate, 12 + 12 + 8 B64 MB, three streams24 MB3 bindingsMore state, streams can drift
Interleaved with tangent, 48 B stride96 MB96 MB, wastes 75 percent1 bindingTangent bandwidth paid by passes that ignore it

How I test it, and where it breaks

I build the same mesh in all three layouts, keep index order identical so post-transform cache reuse is comparable, and capture with RenderDoc or Nsight Graphics. I look at vertex fetch throughput, L2 hit rate on the vertex buffer, and frame time in the full pass and in a forced position-only pass. Validation layers catch the classic failures first: an attribute offset that is not aligned to its format size, and a binding stride that disagrees with the CPU struct after a field was added. Those layouts can appear to work on one desktop driver and fail validation or run slowly on a tile-based mobile GPU, which is why I test on the lowest target, not only on my workstation.

Two subtler failures show up only in profiling. First, dynamic buffers updated per frame: interleaving a frequently rewritten attribute, such as a morph target weight, with static position data forces the whole vertex to be rewritten and re-uploaded. I move the dynamic attribute to its own buffer with a separate binding. Second, index order: a layout that measures well with a cache-friendly triangle order can look worse once the order changes, because vertex reuse hides overfetch. I re-run the comparison after any mesh optimisation pass changes the ordering, and I keep the layout decision in the asset pipeline, where stride, offsets and padding are generated from the same struct definition that fills the buffer, so the shader input layout and the CPU writer cannot drift apart.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-31How do indexed triangle lists, triangle strips and the post-transform vertex cache interact, and when would you pick one over the others for a static mesh?

The 90-second answer

An indexed triangle list stores each vertex once and references it by index. A triangle strip stores a sequence of vertices where each new vertex completes one more triangle with the previous two. The post-transform vertex cache sits between vertex fetch and the vertex shader and remembers recently transformed vertices, so a repeated index can skip the shader entirely. Its size and replacement policy are not part of the Vulkan, OpenGL or Direct3D specification and vary by vendor and generation, so I treat it as a small, unspecified cache and measure hit rates rather than tuning to a claimed entry count.

For a static mesh I ship an indexed list reordered for cache locality, usually with a Forsyth or Tipsify style scorer. A strip saves index bandwidth, about one index per triangle instead of three, but it forces restarts at every disjoint patch, it can create degenerate triangles to jump between patches, and a long strip that jumps across the mesh thrashes the cache anyway. On current GPUs index fetch is cheap, so the cache win usually dominates the index saving.

Worked trace

Take a quad split into two triangles, vertices A, B, C, D in order.

Indexed list, order A B C, A C D:

indices: 0 1 2  0 2 3
cache after tri 1: [A B C]  (3 misses, 3 shader runs)
cache after tri 2: A hit, C hit, D miss  (1 miss, 1 shader run)
total: 4 shader runs for 6 index references

Strip A B C D:

indices: 0 1 2 3
tri 1: A B C  (3 misses)
tri 2: B C D  (B hit, C hit, D miss)
total: 4 shader runs for 4 index references

Same shader cost here. The strip saved two indices. Now add a second, disconnected quad E F G H. The list just appends E F G, E G H and the cache behaviour is unchanged. The strip needs a restart, 0xFFFF for 16-bit indices or 0xFFFFFFFF for 32-bit, or a degenerate triangle such as C C D to close the first strip. The restart itself is cheap, but each restart flushes the strip state and the first triangle after it has no reuse beyond the cache, and degenerate triangles still go through setup and rasterisation as zero-area primitives.

Arithmetic, hypothetical mesh

Assume 50,000 triangles and 25,000 unique vertices, 32-byte vertex stride.

FormatIndices storedVertex shader runs, cold cacheVertex shader runs, cache hit rate 90% on repeats
Non-indexed soup150,000 vertices, no indices150,000150,000
Indexed list150,000 indices150,000 worst caseabout 37,500
Strip, one long strip50,002 indices50,002 worst caseabout 37,500 if locality holds

The 90% figure is illustrative. A well ordered list on a typical game mesh can reach a high hit rate because most triangles share edges with a recently drawn neighbour. A strip with poor locality, for example a strip that snakes across a whole level, can drop well below it. Index memory also matters: 150,000 32-bit indices is 600 KB, the strip is 200 KB. On a bandwidth bound mobile tile renderer that difference can show up, on a desktop discrete GPU it usually does not.

Reordering for the cache

The scoring idea is simple. Prefer the next triangle whose vertices are already in the cache, penalise evicting a vertex that many future triangles still need.

C++
// Pseudocode, checked against the Forsyth approach
// score = sum over vertices of (cache_hit ? 1 : 0) - eviction_penalty
while (triangles remain) {
    pick triangle with highest score;
    emit its 3 indices;
    update cache: push its vertices, evict oldest;
}

Forsyth adds a last-use distance term so a vertex used again soon is kept. Tipsify uses a FIFO approximation and is faster to run at import time. Either beats naive order, which often follows authoring order and can halve the hit rate.

When a strip still wins, and failure modes

Strips still make sense for regular grids, heightfields and ribbon geometry where one strip covers the whole surface with no restarts. They are also used historically for strip adjacency in tessellation and geometry shaders, though indexed lists with adjacency indices now cover that on Vulkan, Metal and Direct3D 11 and later.

Failure modes I check in tests:

  1. Restart handling. Forgetting the primitive restart index, or using the wrong width for the index type, produces a long thin triangle across the mesh. I render a wireframe overlay and look for spikes.
  2. Degenerate jumps. A strip that uses repeated vertices to jump patches wastes rasteriser work and can break early-z assumptions in profiling.
  3. Cache size mismatch. Tuning for one vendor's cache and shipping to another GPU, or to a software renderer with no post-transform cache, changes the hit rate. I measure vertex shader invocations with a pipeline statistics query, VK_QUERY_TYPE_PIPELINE_STATISTICS in Vulkan, rather than trusting the reorder score.
  4. Index width. Meshes under 65,536 vertices fit in 16-bit indices and halve index bandwidth. Crossing that boundary mid mesh without splitting the draw breaks indexing silently.

So the decision is: indexed list plus cache aware reordering as the default, strip only when the topology is a natural single strip and index bandwidth is the measured bottleneck.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-32How do you test a bounding sphere and an AABB against a frustum, and when does per-object culling cost more CPU than it saves?

The 90-second answer

Extract the six frustum planes in world space, normalized so the plane normal has unit length. Then test each object's bound against every plane. If the bound is completely outside any one plane, the object cannot be visible and is skipped. A sphere is tested by signed distance from its centre to the plane. An AABB is tested by its most positive corner for that plane. Per-object culling stops paying when most objects pass anyway, when the scene is small enough that the test and the branching cost more than the draw calls saved, or when the objects are already batched, instanced, or culled hierarchically.

Assume a right-handed view, planes stored as dot(n, p) + d >= 0 for inside, with n normalized. That normalization is not optional for the sphere test. Without it the distance comparison is wrong.

Sphere test

For plane (n, d) and sphere centre c, radius r:

C++
// returns false if sphere is outside this plane
bool SphereInsidePlane(const Vec3& n, float d, const Vec3& c, float r) {
    return Dot(n, c) + d >= -r;
}

The object is culled if this fails for any of the six planes. Early out on the first failure. That is the whole test. It is cheap because it is one dot product per plane, and it is conservative: a sphere that passes may still be off screen, but a sphere that fails is definitely off screen.

AABB test

An axis-aligned box has no single centre and radius that is tight in all directions, so use the corner furthest along the plane normal, the p-vertex:

C++
bool AabbInsidePlane(const Vec3& n, float d, const Aabb& b) {
    Vec3 p = { n.x >= 0 ? b.max.x : b.min.x,
               n.y >= 0 ? b.max.y : b.min.y,
               n.z >= 0 ? b.max.z : b.min.z };
    return Dot(n, p) + d >= 0;
}

If even the closest corner is outside, the whole box is outside. If that corner is inside, the box may still be outside on another plane, so test all six. The slab method in camera space is equivalent, but the plane form above works directly with the extracted frustum and with a world-space AABB.

BoundTest costTightnessWeakness
Sphere1 dot per planeGood for roughly round objects, particles, charactersVery loose for long thin objects. A sword 2 m long gets a 1 m radius sphere, so it survives culling long after it leaves the screen.
AABB3 selects plus 1 dot per planeTight for axis-aligned geometry, terrain chunks, buildingsLoose when the object rotates. A rotated plank's world AABB grows toward the diagonal of its local box, up to about 41 percent wider in 2D.
OBBMore per plane, needs axesTight for rotated rigid bodiesCost and code complexity rise, and the test is no longer a simple plane dot.

That trade-off decides the choice in practice. Spheres suit dynamic objects whose orientation changes every frame, because the bound does not need recomputing when the object rotates. AABBs suit static level geometry, where the bound is computed once and the tighter fit removes more false positives. Many engines store both and test the sphere first as a cheap reject, then the AABB for the survivors.

When per-object culling wastes CPU

Worked example, figures hypothetical but typical of a mid range CPU: 20,000 objects, 6 planes, about 8 flops per plane test. That is roughly 1 million flops plus 20,000 branches and the cache traffic to fetch each bound. At 3 GHz that is well under 0.5 ms if the bounds are contiguous, and several milliseconds if they are scattered through a scene graph with pointer chasing. The saving is the vertex processing and draw submission for culled objects. If only 5 percent are culled, you paid the full traversal to save 1,000 draws, many of which the GPU would have clipped in under a microsecond each. You lose.

Concrete cases where it loses:

  • Small scenes, under a few thousand objects, where everything is on screen most of the time. The test is pure overhead.
  • Instanced or merged geometry. Culling one instance of a 10,000 instance mesh saves almost nothing, and the mesh is drawn once anyway. Cull at the chunk or cluster level instead.
  • Static scenes with a fixed camera path. Precompute visibility per cell or per portal, or bake a hierarchical cull, rather than retesting every object every frame.
  • CPU bound frames where the render thread is already the bottleneck. Moving the test to a job system helps only if the bounds are packed in a flat array. Traversing a deep node hierarchy to find the bounds often costs more than the test itself.
  • Scenes where the real cost is overdraw or fragment work, not vertex work. Frustum culling does nothing for a full screen transparent quad that passes every plane.

The fix is usually hierarchy. Test a parent node's bound once. If it fails, skip the whole subtree without touching the children. If it passes, descend. That turns the cost from per object to per node that is near the frustum boundary, which is a small fraction in a large level. The same logic applies on the GPU with indirect draws and compute based culling, where the test runs in parallel and the CPU only uploads the surviving count.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-33What does a Hi-Z pyramid test check during occlusion culling, and when would you use a hardware occlusion query instead of a software Hi-Z test?

The 90-second answer

A Hi-Z pyramid is a downsampled copy of last frame's depth buffer, stored as a mip chain where each texel holds the farthest depth in its tile. To test an object, project its bounding box to screen space, pick the mip whose texels roughly match the box size, and compare the box's nearest depth against that stored farthest depth. If the nearest depth is greater than the stored value, every pixel of the box sits behind depth already written, so the object is fully occluded and can be skipped.

A hardware occlusion query does the same test on the GPU by drawing only the bounding box with depth test on and counting fragments that pass. It is accurate for that frame's depth, but reading the result back stalls the CPU if you need it immediately. Software Hi-Z lets you test hundreds of objects on the CPU or in a compute pass before drawing, with no stall, at the cost of building and uploading the pyramid and using last frame's depth.

Worked trace

Assume standard depth, not reversed-Z, so depth 0 is near and depth 1 is far, and a 1920 x 1080 depth buffer. Hi-Z is built with max pooling. Level 0 is 1920 x 1080, level 1 is 960 x 540, level 2 is 480 x 270, and so on. Each level halves both dimensions.

A crate projects to a 96 x 64 pixel rectangle. Its nearest corner has depth 0.62 in window space. Choose level 2, where one texel covers 4 x 4 pixels, so the rectangle covers about 24 x 16 texels. Sample the maximum depth over that texel range. If that maximum is 0.55, the crate's closest point at 0.62 is behind everything already drawn in that region. The crate is culled. If the maximum is 0.70, some depth in the tile is farther than the crate, so part of the crate could be visible and it stays in the draw list.

That one comparison is the whole test. No triangle is rasterized for a culled object, and the test itself is a few texture fetches per object.

GLSL
// CPU or compute side, pseudo-code for standard depth (0 near, 1 far)
bool IsOccluded(vec4 boxMin, vec4 boxMax, sampler2D hiZ, vec2 resolution) {
    vec2 screenMin = ProjectToScreen(boxMin);
    vec2 screenMax = ProjectToScreen(boxMax);
    vec2 size = abs(screenMax - screenMin);
    float mip = max(0.0, floor(log2(max(size.x, size.y))) - 1.0);
    float storedMax = TextureGatherMax(hiZ, (screenMin + screenMax) * 0.5 / resolution, mip);
    float nearest = ProjectToWindowDepth(boxMin); // closest point of the box
    return nearest > storedMax;
}

In practice you gather the texels overlapped by the rectangle rather than sampling only the centre, otherwise a small occluder at the edge of a large tile gives a false visible result. That is conservative and safe: false visible costs a draw, false occluded loses pixels.

With reversed-Z the convention flips. Depth 1 is near and depth 0 is far, so the pyramid must store the minimum depth in each tile and the test becomes nearest < storedMin. Using max pooling under reversed-Z would keep the nearest depth in the tile, which is the wrong end of the range and would cull incorrectly.

Software Hi-Z versus hardware queries

Software Hi-ZHardware occlusion query
Depth sourcePrevious frame, copied and downsampledCurrent frame, rendered bounding box
Where it runsCPU or compute shader, before the draw list is builtGPU, as a query object around a depth-only draw
CPU stallNone, result is in CPU or GPU memory you already ownStalls if you read the result in the same frame; typical fix is a 2 to 3 frame delay
Cost per objectA few fetches, cheap enough for thousands of objectsOne extra draw call per query, plus query slot limits
AccuracyOne frame stale, so fast moving occluders lagExact for the frame it runs in
Best useStatic and slow moving scene geometry, large object countsA small number of large, expensive objects where a stale test would waste a full draw

The stale depth point matters. If a door closes this frame, last frame's Hi-Z still shows the room behind it as visible, so objects inside are drawn once unnecessarily. That is a performance miss, not a visual error. The reverse case is the dangerous one: if you build Hi-Z from a frame where a wall was present and then remove the wall, you must rebuild or invalidate the pyramid, or you will cull objects that should now be visible.

Hardware queries avoid staleness but introduce latency in the decision. With a 3 frame delay, the culling decision for frame N is based on a query issued at frame N-3, so you are back to stale data plus pipeline complexity. That is why most engines use Hi-Z for the bulk test and reserve hardware queries for cases like a huge hero mesh or a portal volume where one draw is costly enough to justify the query slot.

A common failure mode with Hi-Z is using average depth instead of maximum depth in the downsample. Averaging pulls the stored value toward the camera compared with the true farthest depth in the tile. The stored value is then too low, so the test nearest > storedMax passes for objects that are actually in front of the farthest surface in that tile. Those visible objects get culled and disappear for a frame. Max pooling avoids that by keeping the farthest depth, which makes the test conservative in the safe direction.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-34Walk me through building a BVH with SAH, traversing it with an explicit stack, and where that design breaks down on a GPU?

The 90-second answer

Build a binary BVH top down. Each node stores an AABB and either a child range or a triangle range. To build, pick the split that minimises the Surface Area Heuristic (SAH) cost, recurse until a leaf holds few triangles, then traverse iteratively with an explicit stack so a ray can backtrack without recursion.

SAH estimates the cost of a split as the probability a ray hits the child times the cost of traversing it. For a split of parent bounds into left and right children:

C_split = C_trav + (A_L / A_P) * N_L * C_intersect + (A_R / A_P) * N_R * C_intersect

A is surface area, N is triangle count, C_trav is the cost of testing the node (often set to 1) and C_intersect is the cost of a triangle test (often set to 1 as well, so the formula reduces to area weighted triangle counts). You compare C_split against C_leaf = N * C_intersect. If the leaf is cheaper, you stop. That comparison is the whole heuristic. It trades build time for traversal time, and it only works because surface area approximates hit probability for uniformly distributed rays. For a scene lit by a few bright area lights, or rays that cluster along one axis, the approximation degrades and a split that looks cheap on paper can be traversed constantly.

Binned SAH in practice

Testing every triangle on every axis is O(N^2) per node. The standard fix is binned SAH. On each axis, sort the centroids into, say, 16 bins, accumulate count and bounds per bin, then evaluate the 15 split positions between bins. That is O(N) per node after the sort, and in practice it finds splits within a few percent of the exact SAH optimum. You also need a fallback. If all centroids coincide, as with a cluster of identical or degenerate triangles, no axis split separates them. Median split on the longest axis, or a spatial split that cuts a large triangle, keeps the tree from degenerating into a chain. Without that fallback, stack depth grows linearly and traversal becomes a linked list walk.

A worked example, with hypothetical figures. Parent area A_P = 100, left child A_L = 30, N_L = 40, right child A_R = 50, N_R = 60, C_trav = 1, C_intersect = 1:

OptionCost
Split1 + 0.30*40 + 0.50*60 = 43
Leaf (100 triangles)100

The split wins. Now move the same 100 triangles so the left child holds 95 of them in a tiny box (A_L = 5) and the right holds 5 spread over a large box (A_R = 90):

OptionCost
Split1 + 0.05*95 + 0.90*5 = 10.25
Leaf100

SAH still splits, and correctly, because most rays that enter the parent will only test the dense cluster. The failure mode is the opposite case: a large triangle spanning the whole parent forces both children to inherit its bounds, so A_L and A_R both approach A_P and the split cost approaches N_L + N_R, worse than the leaf. That is when spatial splits earn their keep. They clip the large triangle against the split plane and duplicate it into both children, which bounds the child areas at the cost of extra triangle tests.

Traversal and the stack

Recursive traversal is the clearest version and the one that breaks first. Depth is O(log N) for a balanced tree, but an unbalanced tree from a bad split can reach O(N), and on a GPU a recursive call per node is not available in the form you want. The iterative version keeps a fixed size stack of node indices:

C++
// Node: AABB bounds; childOrFirst; count (0 = internal)
uint32_t stack[64];
int sp = 0;
stack[sp++] = 0; // root
float tClosest = tMax;
while (sp > 0) {
    const Node& n = nodes[stack[--sp]];
    if (!intersectAABB(ray, n.bounds, tClosest)) continue;
    if (n.count > 0) {
        for (uint32_t i = 0; i < n.count; ++i)
            tClosest = min(tClosest, intersectTri(ray, tris[n.childOrFirst + i]));
    } else {
        // Push the farther child first so the nearer one pops first.
        uint32_t l = n.childOrFirst, r = l + 1;
        float tL = entryT(ray, nodes[l].bounds);
        float tR = entryT(ray, nodes[r].bounds);
        if (tL < tR) { stack[sp++] = r; stack[sp++] = l; }
        else         { stack[sp++] = l; stack[sp++] = r; }
    }
}

Two details matter. First, the slab test for the AABB must handle rays parallel to an axis without dividing by zero, and it must reject hits behind the ray origin. Second, pushing the nearer child last means it is popped first, so tClosest shrinks early and prunes more of the tree. The stack size is a real constraint. A balanced tree over a million triangles has depth around 20, so 64 entries is comfortable. An unbalanced tree can overflow it, and the fix is not a bigger stack but a build that guarantees balance, or a traversal that restarts from the root when the stack empties, which costs you the pruning you already did.

Where this design breaks down

On a GPU, the problem shifts from stack depth to divergence. A warp of 32 threads tracing different rays takes different branches at every node, so the warp executes the union of all paths. Wide BVHs (4 or 8 children per node) reduce depth and node visits at the cost of wider node records and more wasted AABB tests per node. That trade is usually worth it on GPUs and usually not on CPUs, where a binary tree fits cache better. Refit is the other pressure point. If vertices move every frame, rebuilding the whole tree is O(N log N) and too slow, so you refit bounds bottom up in O(N), which keeps the topology but lets quality decay as objects drift from their original bounds. After enough motion the tree is correct but slow, and you detect that by tracking the SAH cost of the root or the average number of node visits per ray, not by watching frame time alone. A rising node visit count with a flat triangle count is the signature of a tree that needs a rebuild.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-35You have 2 million static triangles for ray tracing and 50,000 dynamic particles queried every frame. How would you choose between a uniform grid, octree, kd-tree and BVH for each, and why?

The 90-second answer

I would not pick one structure for both jobs. For the 2 million static triangles I would build a BVH. For the 50,000 particles queried every frame I would use a hashed uniform grid rebuilt each frame, unless the particle distribution is strongly clustered, in which case an octree or a hashed grid with adaptive cell size wins.

The deciding factors are what you query, how objects are distributed, and how often the structure changes. A BVH stores bounds around objects, so a large triangle lives in one leaf and is tested once. A grid stores objects in every cell they overlap, so that same large triangle can be inserted into hundreds of cells and tested repeatedly. A kd-tree and an octree split space rather than objects, which suits points and rays well but can duplicate geometry at split planes.

Static triangles: BVH

Build top down. Each node holds an AABB around its triangles. Split by the surface area heuristic (SAH): for each candidate axis and position, estimate cost as traversal cost plus intersection cost weighted by the probability a ray hits each child, approximated by child surface area divided by parent surface area. Pick the split with the lowest cost, stop when a leaf holds 4 to 8 triangles or no split lowers cost.

With 2 million triangles at 4 triangles per leaf, that gives roughly 500,000 leaves and about 1 million nodes in a binary BVH. A wide BVH with 4 or 8 children per node reduces tree depth from about 19 levels to roughly 10 or 6, which matters on a GPU because a traversal step then loads one node and tests several boxes with SIMD.

Traversal is a slab test per node. For a ray origin o and direction d, compute tmin and tmax against the box on each axis. The ray hits the box when tmax >= max(tmin, 0) and tmin <= tmax on all axes. Visit the nearer child first so the closest hit tightens tmax early and prunes the rest. That ordering is where most of the speed comes from in practice.

C++
// Binary BVH traversal, iterative, nearest child first
bool IntersectBVH(const BVHNode* root, Ray ray, Hit& hit) {
    // stack of nodes to visit, push far child before near child
    // for each node: slab test, skip if tmin > hit.t
    // at a leaf: test each triangle, update hit.t on closer hit
}

Failure mode to watch: a scene with many long thin triangles, such as foliage cards or wires, produces overlapping AABBs. SAH still helps because it penalises overlap through surface area, but traversal can visit many leaves. I would check node visit counts per ray in a profiler, not just frame time. If visits per ray climb above roughly 30 for primary rays, the split quality or triangle preprocessing needs work.

Dynamic particles: uniform grid

Particles are points, so there is no large object problem. Hash each particle to a cell of size near the query radius, for example a neighbour search radius of 0.5 m gives a cell size of 0.5 m. Insertion is one hash and one append per particle, so rebuilding 50,000 particles per frame is cheap and avoids incremental update bugs.

Arithmetic for the choice: at 50,000 particles in a 100 m by 20 m by 100 m play area, a 0.5 m cell gives 200 by 40 by 200 cells, which is 1.6 million cells in a dense grid. Mean occupancy is 50,000 divided by 1.6 million, about 0.03 particles per cell. A hashed grid stores only occupied cells, roughly 49,000 of them for a uniform distribution, so memory stays near the particle count rather than 1.6 million entries and clearing cost stays near the particle count rather than a 6.4 MB memset of a dense int array every frame. If particles cluster into a few dense groups, a fixed cell size forces either tiny cells with many empty entries or large cells with hundreds of particles per cell. That is the point where I switch to an octree, which subdivides only where particles actually are.

Where kd-trees and octrees fit

StructureSplit ruleBest queryUpdate costMain failure mode
Uniform gridFixed cellsNeighbour search, point locationRebuild is cheap, incremental edit is messyClustered or multi-scale distribution
OctreeSpace, by octants, recursiveNeighbour search in clustered data, point locationInsert is local, rebalance can cascadeDeep tree in one dense cluster, pointer chasing
Kd-treeSpace, median or SAH plane, one axis at a timeRay casting, nearest neighbour on pointsRebuild is expensive, edits are hardDuplicated geometry at planes, unbalanced if built by median on skewed data
BVHObjects, by SAH on object boundsRay casting and collision on trianglesRefit is cheap, rebuild is expensiveOverlapping bounds from long thin geometry

A kd-tree is a credible alternative for the static scene if the query is rays against points or small primitives, and a SAH kd-tree can match a BVH. For triangles I prefer the BVH because each triangle is stored once, which keeps memory predictable and avoids testing the same triangle from several cells. For particles, a kd-tree rebuilt every frame costs more than a grid rebuild and gives little back, since neighbour search in a grid touches only adjacent cells.

How I would validate the pick

I would instrument three counters per query type: nodes or cells visited, primitive tests performed, and hits found. Then I would run the worst case scene, not the average one: the particle burst that spawns 10,000 particles in one corner, and the camera looking along the foliage wall. If the grid degrades under the burst, I move particles to an octree or a two-level grid. If BVH visits spike on the foliage, I split long triangles during preprocessing or switch those to a separate structure. The structure follows the measured distribution, and I remeasure when the content changes.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-36Walk me through how you would test a ray tracer's primary rays, secondary rays, reflection, refraction and termination?

The 90-second answer

Build a scene where every ray type has an analytic answer, then compare the tracer's hit point, normal, direction and final colour against that answer. One scene can cover all five if you lay it out deliberately: a camera looking at a mirror sphere, a glass sphere behind it, and a checker floor. Primary rays are the camera rays. Secondary rays are the ones spawned at a hit: reflection off the mirror, refraction through the glass, and shadow rays toward lights. Termination is what stops the recursion, by depth, by throughput, or by a miss.

I would not start with a pretty render. I would start with a debug mode that dumps, per pixel, the ray origin, direction, hit distance, object id, and the spawned child rays. Without that trace you are guessing from pixels.

A minimal test scene

Camera at (0, 0, 5) looking down -Z, fov 40 degrees. A diffuse sphere at origin radius 1. A mirror sphere at (2, 0, 0) radius 1 with reflectivity 1. A glass sphere at (-2, 0, 0) radius 1 with index of refraction 1.5. A checker plane at z = -3. One point light at (0, 4, 4). This gives you, in one 640x480 frame: a primary hit on diffuse, a primary hit on mirror, a primary hit on glass, a reflected ray that should hit the checker, a refracted ray that should exit the far side of the glass and hit the checker at a displaced position, and shadow rays from every lit point.

Primary rays: check the camera model

For pixel (320, 240), the centre pixel, the ray should be origin (0,0,5), direction (0,0,-1), and it should hit the diffuse sphere at t = 4. For a corner pixel, compute the expected direction from the pinhole model and check it matches to within half a pixel of angular error. A common bug is flipping Y, or using pixel centres versus corners. That shows up as a one pixel shift on the sphere silhouette, which a visual test will miss and a numeric test will not.

C++
// Checked against Python reference, float32
Ray primaryRay(int x, int y, int W, int H, Camera cam) {
    float u = (2.0f * (x + 0.5f) / W - 1.0f) * cam.aspect * cam.tanHalfFov;
    float v = (1.0f - 2.0f * (y + 0.5f) / H) * cam.tanHalfFov;
    return {cam.pos, normalize({u, v, -1.0f})};
}

Test the +0.5. Remove it and the centre ray is still correct, but every off-centre ray is off by half a pixel. That is exactly the kind of bug this test catches.

Secondary rays: reflection and refraction

Reflection is the easy one to verify. Take a ray hitting the mirror sphere at a known point with a known normal. The reflected direction must satisfy R = D - 2(D dot N)N, and it must be unit length. Then trace it: in my scene it should hit the checker plane, and the checker colour at that hit point is predictable. If the reflected ray instead hits the diffuse sphere, the normal is probably flipped or the ray origin was not offset.

Offset matters. Spawn the child ray at hitPoint + N * 1e-4 (for reflection) or hitPoint - N * 1e-4 (for refraction, going into the surface). Without the offset, the child ray immediately re-intersects the same sphere at t approx 0. That is the classic self-intersection acne, and it looks like black speckle on the mirror. The epsilon needs to scale with scene size. For a scene spanning about 10 units, 1e-4 works. For a scene spanning 1000 units, use 1e-3 or scale epsilon by hit distance.

Refraction needs Snell. At entry, eta = 1.0 / 1.5. At exit, eta = 1.5 / 1.0, and the normal flips. The transmitted direction is:

T = eta * D + (eta * cosTheta - cosThetaT) * N

where cosTheta = -D dot N and cosThetaT = sqrt(1 - eta^2 * (1 - cosTheta^2)). If the term under the square root goes negative you have total internal reflection, and the ray must reflect instead of refract. Test that explicitly: send a ray inside the glass sphere at 60 degrees incidence. The critical angle for 1.5 to 1.0 is asin(1/1.5) = 41.8 degrees, so at 60 degrees it must reflect. A tracer that refracts anyway will produce a bright spot where there should be none.

Ray typeSpawned fromExpected behaviour in test sceneFailure signature
PrimaryCameraHits sphere at t=4 for centre pixelSilhouette shifted by 1 px, Y flipped
ReflectionMirror sphereHits checker, colour matches analytic checker valueHits own sphere again, black speckle
Refraction inGlass sphere frontBends toward normal, exits back face displacedNo bend, straight through
Refraction outGlass sphere backBends away from normalWrong eta, exit point displaced
Total internal reflectionInside glass at 60 degReflects, no transmissionLight leaks out of the sphere
ShadowAny lit surface pointBlocked by sphere between point and lightLight leak, missing shadow

Termination: depth, throughput, and misses

Three separate mechanisms, test each one. Max depth: set it to 1 and the mirror sphere should show only the first bounce, which in my scene is the checker. Set it to 0 and secondary rays should not spawn at all, so the mirror renders black or as its base colour. That isolates depth bugs from shading bugs. Throughput: multiply the ray's throughput by the surface colour or reflectivity at each bounce, and stop when throughput drops below, say, 0.001. With Russian roulette, terminate with probability 1 - throughput and scale the surviving contribution by 1 / throughput. Test it by rendering the mirror with reflectivity 0.5 at depth 5. The result should converge to the analytic geometric series, not blow up. If you forget the 1/throughput rescale, the image gets darker as depth increases, which is easy to spot.

Misses are the fourth case. A ray that hits nothing returns the background colour, usually a gradient or an environment map. Test a ray aimed at empty space and confirm it returns background without spawning children. A tracer that spawns a child on a miss will either crash or produce NaNs, and NaNs are worth checking for explicitly: assert that no output pixel is NaN or Inf after a full frame. NaNs usually come from a zero-length normal, a division by a zero determinant in the intersection test, or sqrt of a negative number in the refraction code when total internal reflection was not handled.

What I would actually run

A small suite, each test a few lines: centre pixel ray equals (0,0,-1). Mirror reflection direction matches the formula to 1e-5. Glass entry and exit points match a reference implementation in Python. Total internal reflection at 60 degrees produces a reflected ray. Depth 0 disables secondaries. Depth 1 shows exactly one bounce. No NaNs in a 640x480 frame. That suite runs in under a second and catches the bugs that a screenshot comparison will not, because a screenshot tells you something is wrong and the trace tells you which ray did it.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-37What does Russian roulette do in path tracing, and how does it keep the Monte Carlo estimate unbiased?

The 90-second answer

Russian roulette randomly ends a light path during tracing. At each bounce the path survives with probability p and is stopped with probability 1 - p. A surviving path has its throughput divided by p, so it carries 1/p times more light. That scaling keeps the average correct, which is why the estimator stays unbiased, while most paths end early and save ray traces.

The one rule to quote

A path traced image is a Monte Carlo average. Noise, measured as standard deviation, falls as 1/√N, where N is samples per pixel. Russian roulette does not change that rule. It lowers the cost of each sample, so you can afford more samples in the same time.

GLSL
// throughput holds the accumulated colour for this path
// p is the survival probability for this bounce
if (rand() > p) {
    break; // terminate with probability 1 - p
}
throughput /= p; // survivors carry 1/p more weight

The maths behind the scaling is short. A path that would have added C to the pixel now adds C/p with probability p and adds 0 with probability 1 - p. Its expected contribution is p × (C/p) = C. The mean is unchanged. Individual surviving paths are brighter, so variance per path rises, but the average cost per path falls.

What that buys in practice

In most scenes, throughput drops quickly after a few bounces. Continuing a dim path costs a full ray trace for a small contribution. Roulette ends many of those paths early and spends the saved time on new paths. A common choice sets p from the luminance of throughput, clamped so p never gets too small:

GLSL
float p = clamp(luminance(throughput), 0.05, 0.95);

Bright paths survive almost every bounce. Dim paths survive rarely, and when one does survive it is scaled up to compensate.

Noise against samples

The 1/√N rule is why brute force is slow. Take a pixel with a standard deviation of 0.20 for a single sample (a hypothetical figure for a glossy highlight):

Samples per pixelNoise = 0.20 / √NCost
160.0501x
640.0254x
2560.012516x
10240.0062564x

Four times the samples halves the noise. Roulette helps by making each of those samples cheaper on average, not by beating the square root. If p is set too low, surviving paths carry very large weights and single bright pixels, often called fireflies, appear. Raising the floor on p, for example 0.05 instead of 0.01, is the usual fix.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-38How would you test importance sampling for a GGX BRDF and a small bright area light, and prove variance actually dropped?

The 90-second answer

I would test the estimator, not the picture. For direct lighting the Monte Carlo estimator is L = f_r * L_i * cos(theta_l) / pdf_l, summed over samples and divided by N. Importance sampling only helps if the pdf I divide by is the pdf I actually sampled from, and if that pdf puts samples where f_r * L_i * cos is large. So I build two scenes where I know the answer, measure mean and variance against a high sample reference, and check the pdf math in code review before I look at any image.

Scene one is a white furnace: a closed box with unit radiance, a diffuse or GGX surface in the centre. The outgoing radiance must equal albedo times unit radiance, for any roughness. If GGX sampling is wrong, energy appears or disappears as roughness changes. Scene two is a single small bright area light, say 0.1 m by 0.1 m at 3 m, over a rough floor. That is the case where BRDF sampling alone misses the light 99 times in 100, and light sampling alone explodes on a glossy highlight. I render both with BRDF sampling only, light sampling only, and multiple importance sampling, at fixed sample counts, and compare variance per pixel.

Sampling GGX and light, and where each fails

For GGX I sample the half vector, not the outgoing direction directly. With alpha = roughness^2, Karis sampling in HLSL:

HLSL
float3 SampleGGXH(float2 u, float alpha) {
    float phi = 2.0 * PI * u.x;
    float cosTheta = sqrt((1.0 - u.y) / (1.0 + (alpha * alpha - 1.0) * u.y));
    float sinTheta = sqrt(max(0.0, 1.0 - cosTheta * cosTheta));
    return float3(sinTheta * cos(phi), cosTheta, sinTheta * sin(phi)); // in tangent space
}

Reflect v about h to get l. The pdf for h is D(h) * cos(theta_h), and the pdf for l is that divided by 4 * dot(v, h). Substituting into the estimator, the D and cos(theta_l) terms cancel, which is the point. The weight that remains is proportional to G * F * L_i * dot(v, h) / (cos(theta_v) * cos(theta_h)). If I forget the Jacobian 4 * dot(v, h), or use alpha = roughness in one place and roughness^2 in another, the furnace test fails at intermediate roughness and the highlight gets too bright or too dark. That mismatch is the most common bug I see.

For the area light I sample a point on the light uniformly by area. The solid angle pdf is distance^2 / (area * cos(light)). A sample that lands on the light therefore carries a weight inversely proportional to that pdf. For the small light above, distance^2 / area is about 9 / 0.01 = 900, so each hit is bright but rare under BRDF sampling. Light sampling hits every time, but on a low roughness surface most of those samples land where the GGX lobe is near zero, so the variance comes from the few samples near the specular peak.

Strategypdf proportional toVariance explodes when
BRDF samplingf_r * cos(theta_l)Light subtends a tiny solid angle, or is occluded most of the time
Light samplingL_i * cos(light) / distance^2BRDF lobe is narrow and misses the sampled point, or light is large and dim
MIS combinationBoth, weighted by pdfspdfs are inconsistent, for example one side uses solid angle and the other uses area

MIS with the balance heuristic weights each technique by pdf_i / (pdf_1 + pdf_2). Both pdfs must be in the same measure, solid angle for directional work. Mixing an area pdf from one side with a solid angle pdf from the other silently biases the result, and the furnace test will not catch it because there is no distinct light. The small light scene will.

Measuring variance, not eyeballing it

I run a fixed seed harness, for example 64 samples per pixel, 16 frames with different seeds, and compute per pixel mean and variance across frames. Then I compare the mean to a 4096 sample reference and report mean squared error, which splits into bias squared plus variance. A correct sampler has near zero bias and lower variance than the baseline. A sampler with a wrong pdf has bias that does not shrink as N grows, which is how I tell the two apart.

for seed in 0..15:
    image[seed] = Render(samplesPerPixel = 64, seed)
mean, variance = per pixel over seeds
mse = mean((mean - reference)^2) + mean(variance)

Worked trace for the small light, diffuse floor, albedo 0.5, light radiance 20. BRDF sampling: hit rate about 1 in 100, each hit contributes roughly 0.5 * 20 / pdf. The mean is right but the variance across seeds is huge, and individual pixels are either black or very bright. Light sampling: every sample hits, variance drops by roughly two orders of magnitude in this scene. Flip the test to a large dim light, 4 m by 4 m at 2 m, and the ranking reverses for a glossy surface. That reversal is what I want to see. If one strategy wins everywhere, I suspect the test scene is not exercising the other pdf.

Failure modes I check explicitly: sampling h below the surface and not clamping l to the hemisphere, which produces negative cosines and NaNs at grazing angles; using u.y directly as cos(theta) instead of the GGX inversion above, which samples a cosine lobe and leaves the highlight noisy; and shadow ray epsilon that self occludes the light sample at short distances. I also test at grazing view angles, because dot(v, h) approaches zero there and the Jacobian term amplifies any error.

The pass bar I use is concrete: furnace energy within 1 percent of analytic for roughness 0.1, 0.5 and 0.9; small light scene MSE at least 10 times lower with MIS than with BRDF sampling alone at 64 samples; and no bias growth between 64 and 1024 samples. If those hold, the sampler is correct. Tuning roughness or light intensity to make a noisy image look acceptable is not a test.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-39How would you test global illumination with indirect bounces, indirect irradiance caching and denoising, and decide when the cache or denoiser is hurting more than helping?

The 90-second answer

I would test it in a scene built to expose each failure separately, not in a beauty shot. One room with a bright window, a red wall opposite a white wall, a glossy floor patch, and a thin occluder. That gives me colour bleeding from the first bounce, a sharp indirect shadow, a specular indirect highlight, and a place where a cached probe should go dark. I render it at fixed exposure in linear HDR, with the denoiser off first, then turn each system on one at a time.

Global illumination in a path tracer is the indirect part of the rendering equation accumulated over bounces. Direct light is one sample toward the light. Indirect is what happens after a bounce: the ray hits the red wall, samples its outgoing radiance, and carries that colour to the white wall. With one bounce you get the main colour bleed. With three or four you get light that has bounced around the room and filled the corners. The cost is variance. Each bounce adds another sampled term, so at a fixed sample count a multi-bounce render has more variance to average out than a single-bounce render, even though its mean is closer to the correct result.

An irradiance cache, whether it is a probe grid, a voxel cone trace, or a DDGI-style probe volume, trades that per-pixel variance for spatial and temporal reuse. Instead of tracing indirect rays for every pixel every frame, you trace them at probe positions, store irradiance, and interpolate. The win is large when the camera moves slowly and the lighting is mostly static. The loss is resolution. A probe spacing of 1 metre in a room with a 20 cm gap under a door will bleed light through the wall and miss the dark strip under the door entirely. Interpolation also smooths a sharp indirect shadow into a gradient.

A comparison I would put in the test report

Settings for the test room above, 1080p, static sun through the window. The cost column is qualitative because ray cost depends on scene complexity and hardware, so I would measure it on the target GPU rather than quote a generic multiplier.

ConfigurationRelative tracing workWhat I check
Path trace, 1 bounce, 64 spp, no denoiseLowest per pixelRed bleed present, corners too dark, heavy grain
Path trace, 4 bounces, 64 spp, no denoiseHigher per pixel, more rays per sampleCorners lift, grain increases, fireflies on the glossy patch
Path trace, 4 bounces, 16 spp, denoiser onFewer traced samples, plus a denoiser passGrain mostly gone, check for smeared detail on the thin occluder
Probe cache, 1 m spacing, updated every frameProbe tracing spread over all pixelsLight leak through the wall, soft indirect shadow
Probe cache, 0.5 m spacing, updated every 4th frameMore probes, less frequent updatesLeak reduced, ghosting when the window light moves

The pattern is stable even when the exact timings are not. Bounces cost rays. Caching costs spatial resolution. Denoising costs detail and temporal stability, and adds its own pass cost.

How I would trace a failure

Take the thin occluder. With the denoiser on at 16 spp, the edge of its indirect shadow shimmers and then sticks. That is temporal accumulation in the denoiser holding onto a history buffer that no longer matches the current frame. I check it by freezing the camera. If the shimmer stops, it is temporal. If it persists, it is spatial, usually the cache probe on one side of the occluder leaking to the other.

For the cache, I would log probe updates like this:

GLSL
// Probe update, linear HDR irradiance
vec3 probeIrradiance = vec3(0.0);
for (int i = 0; i < SAMPLES; i++) {
    vec3 dir = hemisphereSample(i, probeNormal);
    probeIrradiance += traceIndirect(probePos, dir, maxBounces);
}
probeIrradiance /= float(SAMPLES);
// blend = 1.0 replaces the cached value. blend = 0.1 is an exponential
// moving average that reaches about 63 percent of a step change in
// roughly 10 updates and about 95 percent in roughly 30 updates.
cachedIrradiance = mix(cachedIrradiance, probeIrradiance, blend);

A blend of 1.0 gives a clean probe that flickers when SAMPLES is low. A blend of 0.1 gives a stable probe that lags after a light moves. The test is to move the window light by 30 degrees and count frames until the white wall reaches 90 percent of its new value. If that takes longer than the animation allows, the blend is too low or the update rate is too slow for that motion.

Denoiser trade-offs I would call out explicitly

An AI denoiser such as OptiX or OIDN learns to separate signal from noise using colour, normals, depth, and motion vectors. It is good at removing high frequency grain from diffuse indirect light. It is weaker on three things. First, fireflies from a glossy bounce, because a single bright pixel looks like detail. Second, thin geometry, because the history buffer smears it across frames. Third, specular indirect, because the highlight moves with the view and the denoiser can treat it as noise.

My rule in the test scene: compare the denoised 16 spp image against a high sample count reference without a denoiser, region by region. If the denoised image differs more than the probe cached image does in the region that matters for gameplay, I do not ship that denoiser setting. I raise spp, clamp fireflies by limiting bounce throughput, or fix the cache resolution. Denoising is the last step, not a substitute for a cache that is too coarse.

When I would not use a cache at all

In a fully dynamic scene with many small moving lights, probe updates every frame cost almost as much as tracing indirect rays per pixel, and the interpolation artifacts remain. There I would drop the cache, keep two bounces, and spend the budget on spp plus a denoiser. The cache pays off when lighting changes slowly relative to camera movement, which is the case for the static sun in my test room and the opposite of a scene with a torch in every character's hand.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-40How would you test hardware ray tracing with RTX acceleration structures in a hybrid raster plus ray tracing renderer, and decide when to use rays over rasterization?

The 90-second answer

In a hybrid renderer I rasterize the primary view into a G-buffer, then use hardware rays only where rasterization is weak: hard shadows, reflections, refraction and specular global illumination. The rays do not traverse raw triangles. They traverse a two level BVH. A BLAS holds one static mesh, a TLAS holds every instance in the scene, and the TLAS is rebuilt or refitted when instances move. If the TLAS is stale, rays hit where the object used to be. That is the first thing I test.

HLSL
// HLSL for DXR RayQuery, inline ray tracing
RaytracingAccelerationStructure scene : register(t10);

RayQuery<RAY_FLAG_TERMINATE_ON_FIRST_HIT> q;
RayDesc ray;
ray.Origin = worldPos;
ray.Direction = normalize(reflect(-viewDir, normal));
ray.TMin = 0.02;
ray.TMax = 100.0;

q.TraceRayInline(scene, RAY_FLAG_TERMINATE_ON_FIRST_HIT, 0xFF, ray);
while (q.Proceed()) {
  if (q.CommittedStatus() == COMMITTED_TRIANGLE_HIT) {
    float t = q.CommittedRayT();
    float2 bary = q.CommittedTriangleBarycentrics();
    float4x3 objToWorld = q.CommittedObjectToWorldTransform();
    // Use t, bary and objToWorld to shade the hit.
  }
}

CommittedObjectToWorldTransform returns a float4x3, not a hit record. The ray flags passed to TraceRayInline must match the template argument used to declare the RayQuery. I keep both as RAY_FLAG_TERMINATE_ON_FIRST_HIT here because I only need the first hit for a shadow or reflection ray.

Acceleration structures: what RTX actually accelerates

RT cores accelerate BVH traversal and triangle intersection for a BVH built in the layout the hardware expects. In DXR that is the BLAS and TLAS built with BuildAccelerationStructure. In Vulkan it is VkAccelerationStructureKHR with top level and bottom level types. The API differs, the split does not.

StructureContentsRebuilt when
BLASTriangles of one meshMesh changes, LOD swap, skinning bake
TLASInstance transforms referencing BLASesAny instance moves, spawns or despawns

For dynamic geometry I avoid rebuilding BLASes every frame. Options in order of preference: refit the BLAS if topology is unchanged and vertices moved a little, keep the dynamic object raster only and give it a simple proxy BLAS, or rebuild only a small BLAS for a small dynamic mesh. Rebuilding a large character BLAS per frame is how a hybrid renderer misses 16.6 ms even though the ray query itself is cheap.

Compaction matters for memory and cache. CompactAccelerationStructure shrinks the BVH after build. I test with and without it on the target GPU, because on some integrated parts the smaller structure wins, on desktop the build time cost of compaction can outweigh it.

Hybrid split: where rays earn their cost

Raster first, because it gives per pixel depth, normal, albedo and roughness in one pass and handles primary visibility at full resolution with early z. Rays then fill effects raster cannot do without extra passes.

EffectRaster approachRay approachMy default
Shadow from one sunShadow map, resolution and bias limitsOne ray per pixel toward the sun, exact occlusionRay for hero scene, shadow map for low tier
Mirror reflectionPlanar reflection render, doubles draw costOne reflected ray, hits actual geometryRay, with a probe fallback for rough surfaces
RefractionScreen space trace, breaks at screen edgesRefracted ray through the TLASRay for water and glass
Diffuse GISSAO, baked probesMulti bounce rays, noisyProbes for diffuse, rays for specular

Worked example, hypothetical figures for a 1080p frame on a mid range RTX card: raster G-buffer 3.1 ms, ray query pass for shadows and reflections 2.4 ms, TLAS refit 0.3 ms, denoise 1.1 ms. Total 6.9 ms. If I move diffuse GI into rays as well, the ray pass rises to about 9 ms and the denoise has to work harder. That trade is the decision, not a blanket claim that rays are faster.

How I test it

First, correctness against a software reference. I render a small scene with a known answer: a sphere over a plane, a box with a mirror face, a glass cube. The software tracer in the test harness computes the same rays with a brute force triangle test. Any pixel mismatch beyond a tolerance points to a wrong transform, a flipped winding, or a TLAS built before the instance transform was updated. I run this with validation layers on, because DXR and Vulkan will happily build a TLAS from an uninitialized instance buffer and return black pixels instead of an error.

Second, bias and acne. TMin and the shadow ray origin offset decide self shadowing. Too small and a surface shadows itself, visible as striped acne on curved panels. Too large and thin geometry leaks light, visible as a gap under a door. I test both extremes on a scene with a thin leaf and a curved panel, and I record the values per material instead of using one global bias.

Third, failure modes I check explicitly. Degenerate triangles with zero area can poison a BVH build on some drivers, so the test mesh includes them and the build must either reject or skip them without dropping the whole BLAS. NaN vertices from a bad skinning matrix produce a BVH that returns no hits, so I add a NaN check in the asset pipeline and a debug view that colours rays by hit distance. On hardware without RT support, or on a driver where ray queries fall back to software, the same scene must still render through the raster path. I force that path in CI with a flag and compare the image, accepting that shadows will be softer.

Fourth, performance under motion. A static scene hides TLAS cost. I animate 2,000 instances, including a skinned character, and measure TLAS refit, BLAS refit and ray query separately with Nsight Graphics or RenderDoc counters. If refit spikes when instances cross a threshold, the fix is usually to split the TLAS into a static TLAS built once and a dynamic TLAS rebuilt per frame, then trace both. That keeps the static majority out of the per frame cost.

The point to land: hardware ray tracing is not a replacement for rasterization. It is an accelerator for traversal and intersection that pays off when you keep the acceleration structures current, keep dynamic geometry out of the rebuild path, and limit rays to effects where exact visibility beats a texture lookup.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-41Which of Vulkan, DirectX 12, Metal and OpenGL uses an implicit state machine, and which three use explicit control?

The 90-second answer

OpenGL is the implicit one. Vulkan, DirectX 12 and Metal are the explicit ones.

OpenGL keeps a global, mutable state machine. You call glEnable, glBindTexture or glUseProgram, and the driver remembers that state for the current context. When you draw, the driver works out what changed since the last draw, inserts any state changes it thinks are needed, and orders the work for you. That is why a minimal OpenGL program is short: the driver does the bookkeeping.

Vulkan, DirectX 12 and Metal flip that contract. The application records command buffers, creates pipeline objects, states resource transitions and supplies the synchronisation. The driver does less guessing, so the application owns more of the work and gets more predictable CPU cost and multi queue control in return.

APIPhilosophyWho tracks state and synchronisation
OpenGL 4.6Implicit state machineDriver, from current global bindings
Vulkan 1.3ExplicitApplication, through command buffers, pipeline objects and barriers
DirectX 12ExplicitApplication, through command lists, pipeline state objects and ResourceBarrier
Metal 3ExplicitApplication, through encoders, pipeline state and encoder barriers

What the difference looks like in code

OpenGL, with the driver tracking the bound texture and blend state:

GLSL
glBindTexture(GL_TEXTURE_2D, tex);
glEnable(GL_BLEND);
glDrawArrays(GL_TRIANGLES, 0, 3);

Vulkan, where the layout transition and the barrier are recorded by the application:

C++
VkImageMemoryBarrier barrier{};
barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
barrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
                    VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, nullptr, 0, nullptr, 1, &barrier);
vkCmdDraw(cmd, 3, 1, 0, 0);

DirectX 12 writes the same idea as a ResourceBarrier with a before state and an after state. Metal writes it as an encoder barrier. The names differ, the rule is the same: if the application does not state the transition, the explicit APIs will not invent a safe one.

The practical consequence

With OpenGL, a missing synchronisation call is usually hidden by the driver, at the cost of a possible stall you cannot see. With Vulkan, DirectX 12 or Metal, a missing barrier is your bug. Pass A writes a render target and pass B samples it with no barrier between them, and you can get a stale read or a validation layer error, even if a desktop driver happened to produce the right pixels in testing. The same applies to memory: the explicit APIs make you choose the heap or buffer storage, alignment and residency, while OpenGL allocates behind a handle.

So the one line to remember is: OpenGL asks the driver to remember and order, the other three ask the application to state and order. That is the whole explicit versus implicit split.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-42Walk me through synchronizing a Vulkan frame where a compute shader writes a texture that a graphics queue samples next, covering barriers, image layouts, fences and semaphores?

The 90-second answer

I separate three jobs. A pipeline barrier orders work inside one queue submission and can change an image layout. A semaphore orders work between queue submissions, usually graphics to present or graphics to compute. A fence tells the CPU a submission finished so it can reuse a buffer or descriptor set. Mixing them up is where most Vulkan hangs come from.

Assume one frame does this: compute writes an RGBA16F texture, then the graphics queue renders a fullscreen pass sampling it, then the swapchain image is presented. I use three frames in flight, each with its own fence, command pool and descriptor set, and a timeline semaphore per queue handoff.

Barrier for the compute to graphics handoff

The barrier has to do two things at once: make the compute writes visible, and move the image from VK_IMAGE_LAYOUT_GENERAL to VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL. If either half is missing, the fragment shader can read stale data or the driver can fault on the layout.

C++
// Vulkan 1.3, synchronization2. Checked against the 1.3 core spec.
VkImageMemoryBarrier2 barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2;
barrier.srcStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT;
barrier.srcAccessMask = VK_ACCESS_2_SHADER_WRITE_BIT;
barrier.dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT;
barrier.dstAccessMask = VK_ACCESS_2_SHADER_READ_BIT;
barrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.image = computeImage;
barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};

VkDependencyInfo dep{};
dep.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO;
dep.imageMemoryBarrierCount = 1;
dep.pImageMemoryBarriers = &barrier;
vkCmdPipelineBarrier2(cmd, &dep);

srcStageMask is when the producer must finish. srcAccessMask is which writes become visible. dstStageMask and dstAccessMask are when the consumer may start and what it reads. Setting the stage to ALL_COMMANDS would work but would stall unrelated work, for example a transfer on the same queue. Setting the access mask to 0 is the classic bug: execution is ordered, memory is not, so the fragment shader reads the previous frame's texels on some drivers and the correct ones on others.

For a render pass I would prefer a subpass dependency over a manual barrier between passes, because the dependency also carries the layout transition and can keep the attachment in tile memory on mobile. Inside a single pass, or between a compute pass and a render pass, the explicit barrier above is the right tool.

Fences, semaphores and a worked trace

PrimitiveWho waitsWhat it ordersReuse rule
VkFenceCPU, via vkWaitForFencesOne submission finishingReset with vkResetFences before resubmitting, or submit unsignaled and wait on the previous frame's fence
Binary VkSemaphoreGPU, via vkQueueSubmit wait stageOne submission to the nextCannot be reused until the wait has consumed it. Reusing it early is a validation error and a hang on some drivers
Timeline VkSemaphoreGPU and CPU, via vkWaitSemaphoresNumbered values, so several frames can share one semaphoreSignal with an increasing value. The CPU waits for value <= N, never for a bare signal

Trace for frame 12, with a timeline semaphore handoff:

  1. CPU waits on fence 12 mod 3 with a timeout, say 100 ms. Timeout means device loss or a deadlock, not a slow frame, so I dump the queue and check VK_ERROR_DEVICE_LOST.
  2. CPU records compute, inserts the barrier above, records graphics, and submits compute with signalSemaphoreValues = {12} on handoff.
  3. Graphics submission waits on handoff value 12 at VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT or the fragment stage, then signals the swapchain semaphore for present.
  4. CPU moves on to record frame 13. It does not wait on fence 12 again until it needs that slot's buffers, which is what keeps the CPU ahead of the GPU without overwriting in-flight data.

The failure modes I test for are specific. A missing layout transition shows up in sync validation as a layout mismatch and in RenderDoc as a texture bound in the wrong layout. A binary semaphore submitted twice in one frame hangs the second wait because the first wait already consumed it. A fence waited on with UINT64_MAX in a debug build hides a lost device until the watchdog kills the process, so I use a finite timeout in tests and log the last submitted frame index. A barrier with oldLayout = VK_IMAGE_LAYOUT_UNDEFINED on every frame discards the image contents, which is correct for a swapchain image cleared each frame and wrong for the compute texture that must persist between passes.

I also check the queue family. If compute runs on a dedicated compute queue and graphics on a graphics queue, the handoff needs an ownership transfer: the barrier's srcQueueFamilyIndex and dstQueueFamilyIndex differ, or I use VK_SHARING_MODE_EXCLUSIVE with a release and acquire barrier. Without that, each queue sees a valid image in its own view and the data never crosses. Validation layers with VK_VALIDATION_FEATURE_SYNCHRONIZATION_VALIDATION_EXT catch most of these before a driver does, and I run the same scene under Nsight Graphics to confirm the barrier actually stalls the fragment stage rather than the whole queue.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-43Walk me through how you would use D3D12 heaps and placed resources across copy and direct queues, and where you would place barriers in a frame that uploads a texture and renders to it?

The 90-second answer

I would keep the three heap types separate, place most GPU-only resources inside one large DEFAULT heap, and use a copy queue for uploads and a direct queue for rendering. Barriers go wherever a resource changes state or changes queue, and I run the debug layer in development so a wrong state is reported at the barrier that caused it.

A heap is a contiguous block of GPU memory with a type. D3D12_HEAP_TYPE_DEFAULT is GPU read and write with no CPU access, and it holds textures and buffers the GPU samples or renders to. D3D12_HEAP_TYPE_UPLOAD is CPU-visible, write-combined memory for CPU writes and GPU reads, and it holds staging data only. D3D12_HEAP_TYPE_READBACK is CPU-visible memory for GPU writes and CPU reads. Rendering into an UPLOAD heap or uploading into a DEFAULT heap fails validation or forces a slow path, so the types stay separate.

A committed resource owns its own heap. That is simple, but it fragments memory and wastes padding between allocations. A placed resource shares a heap at a chosen offset, which lets me budget one block and pack resources tightly:

C++
// One DEFAULT heap for GPU resources in this frame
D3D12_HEAP_DESC heapDesc{};
heapDesc.Type = D3D12_HEAP_TYPE_DEFAULT;
heapDesc.SizeInBytes = 256ull << 20; // 256 MiB, sized from GetResourceAllocationInfo
heapDesc.Flags = D3D12_HEAP_FLAG_NONE;
ComPtr<ID3D12Heap> heap;
device->CreateHeap(&heapDesc, IID_PPV_ARGS(&heap));

// Render target placed at offset 0. ALLOW_RENDER_TARGET is required
// or CreatePlacedResource fails for a render target desc.
D3D12_RESOURCE_DESC rtDesc{};
rtDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
rtDesc.Width = 1920;
rtDesc.Height = 1080;
rtDesc.Depth = 1;
rtDesc.MipLevels = 1;
rtDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
rtDesc.SampleDesc.Count = 1;
rtDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
rtDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;

D3D12_CLEAR_VALUE clear{};
clear.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
clear.Color[3] = 1.0f;

ComPtr<ID3D12Resource> rt;
device->CreatePlacedResource(heap.Get(), 0, &rtDesc,
    D3D12_RESOURCE_STATE_RENDER_TARGET, &clear, IID_PPV_ARGS(&rt));

The offset must satisfy the alignment from GetResourceAllocationInfo for that desc, commonly 64 KiB for placed resources on current drivers. For an upload buffer the row pitch must be padded to D3D12_TEXTURE_DATA_PITCH_ALIGNMENT, 256 bytes. A 1920 wide RGBA8 texture has a raw row of 7680 bytes, already a multiple of 256. A 1000 wide texture would pad to 4096 bytes per row, and skipping that padding corrupts the copy.

Queues and a worked frame

Each queue type, COPY, COMPUTE and DIRECT, has its own allocator and list. Work on different queues can run in parallel, with no implicit synchronization between them. I signal a fence on the copy queue after the upload, wait on that fence value on the direct queue, and only then draw. Within one queue ordering is guaranteed, provided barriers describe the hazards.

StepQueueActionBarrier
1CopyCopyTextureRegion from UPLOAD heap to DEFAULT textureTexture starts in COPY_DEST
2CopySignal fence value 42
3DirectWait for fence 42
4DirectTransition texture COPY_DEST to PIXEL_SHADER_RESOURCETransition barrier before first sample
5DirectDraw, sampling the texture
6DirectTransition render target RENDER_TARGET to PIXEL_SHADER_RESOURCE for a post passTransition barrier after last render
7DirectTransition both back to their initial states for next frameTransition barrier

Barriers come in three kinds. A transition barrier changes the subresource state, for example RENDER_TARGET to PIXEL_SHADER_RESOURCE. A UAV barrier orders writes to an unordered access view against later reads, needed after a compute shader writes a buffer that a vertex shader reads. An aliasing barrier orders two placed resources that share the same heap offset, so the second does not overwrite the first while the GPU still reads it.

Failure modes I check for

Wrong state is the most common. Sampling a texture still in COPY_DEST, or rendering into a resource left in PIXEL_SHADER_RESOURCE, triggers a debug layer error and on a retail driver can show stale or black output with no crash. A missing UAV barrier after a compute dispatch shows as intermittent garbage in the next pass. I enable D3D12_DEBUG_LAYER and GPU based validation in development and treat any barrier warning as a bug.

The second failure is queue synchronization. If the direct queue draws before the copy queue finishes, the texture is half uploaded. The fence wait in step 3 prevents that, and the same pattern applies in reverse for readback. The third is lifetime. A placed resource cannot be reused at the same offset until the fence for the frame that used it has passed, so I keep one heap per frame in flight, typically two or three, and only reset an allocator when its fence value is complete.

I would avoid placed resources for a single large swapchain image or for resources with wildly different lifetimes. Committed resources are clearer there, and placement only pays off when many similarly sized resources fit a budget I can size up front.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-44Why would you set loadAction and storeAction to dontCare for a transient G-buffer attachment in Metal TBDR, and what happens if you set storeAction to store instead?

The 90-second answer

In Metal TBDR the GPU renders one tile at a time and keeps that tile's attachments in on-chip tile memory. A transient G-buffer attachment is written by the geometry pass and read by the lighting pass for the same tile, then thrown away. So you set loadAction = .dontCare because the tile starts empty and every pixel will be overwritten, and storeAction = .dontCare because the driver can discard the tile memory instead of writing it to main memory. Setting storeAction = .store does not change the image. It forces a writeback of data nobody reads, and that writeback is the cost you were trying to avoid.

Why the tile makes this possible

The driver bins primitives into tiles before fragment work runs. For each tile it loads only what you asked for, runs the shaders for primitives touching that tile, then stores only what you asked for and reuses the tile memory for the next tile. If the G-buffer never leaves tile memory, you get deferred shading without paying for a full-screen G-buffer in DRAM. That only holds while the data stays resident. A store breaks it by design.

SWIFT
let descriptor = MTLRenderPassDescriptor()

// Transient G-buffer: overwritten on load, discarded on store.
descriptor.colorAttachments[0].loadAction = .dontCare
descriptor.colorAttachments[0].storeAction = .dontCare
descriptor.colorAttachments[0].texture = gBuffer // RGBA16F

// Final colour: cleared on load, kept for compositing.
descriptor.colorAttachments[1].loadAction = .clear
descriptor.colorAttachments[1].clearColor = MTLClearColorMake(0, 0, 0, 1)
descriptor.colorAttachments[1].storeAction = .store
descriptor.colorAttachments[1].texture = finalColour

The contrast is the point. The final target needs .store because a later pass or the display reads it from main memory. The G-buffer does not, so .dontCare on store is a promise to the driver that the contents are dead at the end of the tile.

What .store costs, in numbers

Hypothetical worked example: a 1920 by 1080 frame has 2,073,600 pixels. One RGBA16F attachment is 8 bytes per pixel, so 16.6 MB. With .store you write 16.6 MB and, if a later pass reads it back, read 16.6 MB again. That is 33 MB per frame for one attachment, about 2 GB/s at 60 fps. Four G-buffer attachments push that toward 8 GB/s of traffic that .dontCare removes entirely. On a phone-class GPU that traffic competes with texture fetches and the final framebuffer write, so the frame time rises even though the shader work is identical. In an Xcode frame capture you see it directly as tile memory traffic versus main memory bandwidth for that attachment.

AttachmentLoadStoreEffect
Transient G-buffer.dontCare.dontCareStays in tile memory, discarded after the tile
Transient G-buffer, misconfigured.dontCare.storeSame pixels, plus a full writeback nobody reads
Final colour.clear.storeCleared, then kept for later passes
Accumulation target.load.storePrevious contents are read and added to

The failure mode to check

The common mistake is the reverse one. If a later pass actually needs the G-buffer, for example a separate lighting pass that runs after the geometry pass has ended, then .dontCare on store discards data that pass expects to find. The symptom is black or stale lighting, and the fix is to store it and accept the bandwidth, or to fold lighting into the same tile pass so the data never needs to leave tile memory. A quick test catches both directions: render a scene with a large triangle crossing many tiles, capture the frame, and flip only the store action. With .store the image is unchanged and the bandwidth counter climbs. With .dontCare on a buffer a later pass reads, the image breaks. That pair of captures tells you which setting the data flow actually requires.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-45What does a VAO store that a VBO does not, and why does core profile OpenGL require a VAO before you can draw?

The 90-second answer

A VBO is storage. A VAO is the state that describes how to read that storage. In core profile OpenGL you cannot draw from a VBO alone because the draw call reads vertex attribute state from the currently bound VAO, and core profile has no default VAO to fall back on.

That is the whole distinction. glBindBuffer(GL_ARRAY_BUFFER, vbo) uploads bytes to GPU memory. glVertexAttribPointer does not describe the VBO in isolation. It records, into the VAO bound at that moment, the attribute index, component count, type, normalized flag, stride and offset. The VAO also records which element buffer is bound when you call glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo), and which attributes are enabled. A later glDrawElements walks the VAO, not the VBO binding you happened to leave set.

C++
// OpenGL 3.3 core, checked against the 4.6 spec
GLuint vao, vbo, ebo;
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glGenBuffers(1, &ebo);

glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);

glBindBuffer(GL_ARRAY_BUFFER, 0); // safe now: VAO already captured it
glBindVertexArray(0);

// Per frame, for this mesh:
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, nullptr);

Trace what happens if you reorder it. Bind the VAO, bind the VBO, set the pointer, then bind a different VBO and set another pointer. Both pointers land in the first VAO, because glVertexAttribPointer writes to the bound VAO. Unbind the VAO, bind a second VAO, and draw. You get GL_INVALID_OPERATION in core profile, or garbage attributes if you are on a driver that tolerates it, because the second VAO has no attribute state. The VBO itself is fine. The description of it is missing.

ObjectStoresDoes not store
VBO (GL_ARRAY_BUFFER)Raw bytes on the GPUStride, offset, attribute index, enabled state
EBO (GL_ELEMENT_ARRAY_BUFFER)Index bytesAnything about vertices
VAOAttribute pointers, enables, stride, offset, bound EBOShader program, texture bindings, blend or depth state, buffer contents

Legacy versus core

Legacy OpenGL, up to 2.1 and the compatibility profile after it, had a default VAO. You could bind a VBO, set pointers on the default object, and draw without ever calling glGenVertexArrays. It also had immediate mode (glBegin/glEnd) and fixed-function pipeline state mixed into the same global state machine, which is why bugs were hard to isolate. Core profile, introduced in 3.2, removed immediate mode and the default VAO. The intent was explicit: if you want vertex fetching, you say exactly how, in a VAO you own, and the driver can validate and cache that description instead of reconstructing it from scattered global calls every draw.

Two failure modes come up in interviews and in real code. First, unbinding the element buffer while a VAO is bound. In core profile the EBO binding is part of VAO state, so glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) with that VAO bound clears the VAO's index buffer and the next draw reads no indices. Unbinding GL_ARRAY_BUFFER is safe after setup, as in the snippet, because the VAO captured the buffer name at pointer time. Second, sharing one VAO across two VBOs with different layouts. The VAO points at the first buffer by name, so swapping the GL_ARRAY_BUFFER binding at draw time does nothing. You need one VAO per layout, or you re-record the pointers.

If an interviewer pushes, the follow-up is what the VAO does not do. It does not bind the program, so the same VAO can be drawn with different shaders as long as the attribute locations match. It does not own the VBO, so deleting the VBO while the VAO still references it leaves a dangling name and undefined rendering. That separation is the point: storage, description and program stay independent, and core profile makes you state the description explicitly.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-46Walk me through porting a lighting shader from HLSL to GLSL and Metal, and where do syntax, semantics and layout differences silently change the result?

The 90-second answer

I port the math first and the syntax second, because most cross-platform shader bugs are not compile errors. They are silent changes in matrix storage, sampler state, buffer packing and precision. The three languages look close enough to invite a line-by-line translation, and that is where the trouble starts.

Three decisions decide whether the port is correct. How a matrix is stored and multiplied, how a texture is sampled, and what precision the compiler assumes. Get those three right and the rest is mostly renaming.

Matrix layout and multiplication

HLSL, GLSL and Metal all default to column-major storage in memory. HLSL only stores row-major if you declare row_major on the matrix or the cbuffer. That declaration is common in D3D code because DirectXMath is row-major on the CPU, so a lot of HLSL code you will port is not using the HLSL default at all.

The multiplication convention still differs, and that is the trap.

HLSL
// HLSL. mul(v, M) treats v as a row vector and computes v * M.
float4 p = mul(float4(pos, 1.0), world);
GLSL
// GLSL. M * v treats v as a column vector.
vec4 p = world * vec4(pos, 1.0);
METAL
// Metal. Same column-vector convention as GLSL.
float4 p = world * float4(pos, 1.0);

mul(v, M) in HLSL and M * v in GLSL compute the same mathematical result for the same logical matrix. They stop agreeing when the storage differs. If the HLSL shader declares row_major float4x4 world; and the CPU uploads a row-major buffer, then copying that declaration and that buffer into GLSL, where mat4 is column-major, transposes the matrix in memory. A worked trace shows the symptom. Take a scale of 2 on x and a translation of 10 on x. In row-major storage the translation sits in M[3][0]. In column-major storage it sits in M[0][3]. Upload the same 16 floats to both and the object scales around a different origin. It still renders and it still lights, and it is wrong by a translation that looks like a modelling error.

There are three ways to fix it, and I pick based on update frequency. Transposing on the CPU once per frame is cheapest for a matrix that changes every frame, because the cost is 16 floats and it keeps the shader clean. Declaring row_major in HLSL and transposing on the CPU to match is the same cost moved to the upload, and it is the right choice when the CPU library is already row-major and you do not want to rewrite it. Calling transpose() in the shader is the worst option for a per-vertex matrix, because you pay it for every vertex, but it is acceptable for a single matrix in a compute shader or a one-off debug view. What I never do is leave the layout implicit. I declare it in HLSL, I use layout(row_major) or an explicit transpose in GLSL, and I test with non-uniform scale plus translation, because a pure rotation or a pure translation can hide a transpose.

Sampling, buffer packing and precision

The sampling call differs in name and in where the state lives.

HLSL
Texture2D albedo; SamplerState s;
float4 c = albedo.Sample(s, uv);
GLSL
uniform sampler2D albedo;
vec4 c = texture(albedo, uv);
METAL
texture2d<float> albedo; sampler s;
float4 c = albedo.sample(s, uv);

In HLSL the SamplerState carries filter, address mode and comparison mode with it. In GLSL the filtering comes from the texture object and the sampler uniform you bind. In Metal it comes from the sampler object you pass in. A port that compiles can still change filtering if the GLSL texture was created with linear mipmapping while the HLSL sampler used point filtering. I check the sampler state on the CPU side, not in the shader.

Constant buffers are the other silent failure. HLSL cbuffer packing follows D3D rules. GLSL std140 pads a vec3 to 16 bytes and gives arrays of vec3 a 16-byte stride. Metal [[buffer]] arguments follow Metal alignment rules, which are closer to C++ struct layout. A float3 followed by a float can pack tightly in one and padded in another. During a port I use explicit float4 slots or explicit padding, and I compare the raw buffer bytes between platforms before I look at any lighting.

Precision needs the same care, and the GLSL ES rules changed between versions. In GLSL ES 1.00 fragment shaders, float defaults to mediump unless you declare a default precision statement. In GLSL ES 3.00 there is no default precision qualifier for float in a fragment shader, so you must declare one, and code that relied on the ES 1.00 default will not compile unchanged. Desktop GLSL float is 32-bit, Metal float is 32-bit, and HLSL float is 32-bit. A world-space position reconstructed in an ES 1.00 fragment shader at mediump loses precision at distances above a few hundred units, which shows up as swimming in normal maps and banding in fog. The symptom looks like a lighting problem. It is a default qualifier problem.

AreaHLSLGLSLMetal
Matrix storage by defaultcolumn-major, row_major if declaredcolumn-major, layout(row_major) if declaredcolumn-major
Vector times matrixmul(v, M)M * vM * v
Texture sampletex.Sample(s, uv)texture(tex, uv)tex.sample(s, uv)
Fragment float precision32-bitES 1.00 defaults to mediump, ES 3.00 requires a declared default, desktop is 32-bit32-bit
Integer divisiontruncates toward zerotruncates toward zerotruncates toward zero

That last row is worth stating plainly. Integer division truncates toward zero in all three languages, so it is not a porting difference. The differences that bite are implicit conversions in constructors, which stricter GLSL profiles reject, and undefined behaviour that each compiler resolves differently.

How I test the port

I render the same scene with a debug view that outputs world position, normal and albedo before lighting. If world position differs, the matrix layout or the buffer packing is wrong. Then I compare lighting with a single directional light and a known normal. If albedo and world position match but lighting does not, the difference is in the BRDF code itself. pow with a negative base is undefined in all three languages, and rsqrt on zero is undefined too. I clamp the inputs to pow and rsqrt in all three versions rather than relying on each compiler to produce the same result for an undefined input.

The port is done when the debug views match pixel for pixel on a test scene with non-uniform scale, a mirrored UV, a texture sampled at a grazing angle, and a large world-space position. Those four cases exercise layout, derivatives, filtering and precision, which is where the three languages actually diverge.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-47In a 32-lane warp, 4 lanes take a heavy texture-fetch branch and 28 take the other path. What does SIMT execution do, and how would you restructure that shader code?

The 90-second answer

A warp of 32 lanes issues one instruction at a time, with a mask saying which lanes are active. That is SIMT. When lanes in the same warp take different branches, the hardware does not run the paths in parallel. It runs the first path with its mask, then the second path with its mask. The warp pays for both paths, and lanes not on the current path sit idle.

With 28 lanes on one path and 4 on a heavy texture fetch path, the warp still issues the full fetch path. The other 28 lanes wait. The fix is to stop mixing the two cases in one warp. Either group the work so each warp is homogeneous, or, if both sides are cheap, replace the branch with a branchless select.

Trace for the stated case

HLSL
float3 Shade(Particle p) {
    if (p.type == 0) {
        return ShadeSmoke(p);  // 24 instructions, texture fetch
    }
    return ShadeSpark(p);      // 18 instructions, texture fetch
}

A mixed warp issues roughly 24 + 18 = 42 instructions. The 4 spark lanes are idle for the first 24, the 28 smoke lanes are idle for the next 18. Each texture fetch is also issued for the warp, with only the active lanes supplying addresses, so the memory system sees a full warp request for 4 useful lanes.

If the same particles are sorted or bucketed by type before dispatch, a smoke warp issues 24 and a spark warp issues 18. No lane waits for the other path. The grouping pass costs time, so this pays off when the shader is heavy or the sorted buffer is reused, not for a single cheap pass.

Two restructures, and the trade-off

ApproachWhat changesWhen it wins
Sort or split by typeSeparate buffers or dispatches, one type per warpHeavy branch, fetch or loop on one side, data can be grouped
Branchless selectmix(a, b, t) or select computes both sides, picks oneBoth sides are a few ALU ops, no fetch, no loop

Branchless code is the common mistake here. It only helps when both sides are cheap. If one side fetches a texture, computing it unconditionally fetches for all 32 lanes and can cost more than the divergent branch. I keep branches for heavy or rare cases and use selects for clamps, sign flips and small blends.

A short branch may also be predicated by the compiler, meaning it becomes a masked instruction with no control flow at all. That usually stops at a handful of instructions. A fetch, a loop or a return keeps it as real divergent control flow. Checking the generated SASS or PTX tells you which case you have.

Verification

Profile warp execution efficiency and divergent branch count in Nsight Compute or the vendor equivalent, then compare the mixed input against a pre-sorted input. A successful restructure shows most warps executing at full width and fewer issued instructions per thread. If efficiency is already high, the branch was uniform or predicated, and sorting adds a pass for no gain. I would also check that reordering does not break a later pass that expects the original particle order.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-48Your kernel is slower at 512 threads per block than at 128. How would you check occupancy, register use and shared memory to find the limit and choose a block size?

The 90-second answer

Occupancy is how many warps are resident on a streaming multiprocessor at once, divided by the maximum that SM can hold. More resident warps give the scheduler more work to run while other warps wait on memory, so it can hide latency. I would not chase occupancy first. I would find which resource runs out first, because that resource decides whether changing block size helps at all.

Three resources usually bind: registers per thread, shared memory per block, and threads per block. The compiler reports registers per thread, for example with nvcc --ptxas-options=-v, and the occupancy API reports how many blocks can fit per SM for a given block size and shared memory size:

CUDA
int blocksPerSM = 0;
cudaOccupancyMaxActiveBlocksPerMultiprocessor(
    &blocksPerSM, kernel, blockSize, sharedBytesPerBlock);

I then do the same calculation by hand once. The smallest result is the limit, and it tells me what to change.

Worked example, with hypothetical SM limits stated up front

Suppose an SM can hold 2048 threads, 65536 registers and 64 KB of shared memory. My kernel uses 256 threads per block, 64 registers per thread and 16 KB of shared memory per block.

LimitCalculationBlocks per SM
Threads2048 / 2568
Registers65536 / (256 x 64)4
Shared memory64 KB / 16 KB4

Registers and shared memory tie at 4 blocks. That gives 1024 active threads, or 50% occupancy.

Now add a second array of live variables and registers rise to 128 per thread. Registers now allow 65536 / (256 x 128) = 2 blocks, so occupancy falls to 25%. Shrinking the block to 128 threads does not fix it: registers allow 65536 / (128 x 128) = 4 blocks, which is still only 512 active threads. Block size changed, active threads did not, because registers per thread were the binding limit. The fix is to reduce live variables, split the kernel, or accept fewer registers and check for spills to local memory, which the compiler log and a profiler will show as local loads and stores.

The shared memory case is different. If I double the tile to 32 KB per block, shared memory allows 64 / 32 = 2 blocks even though registers still allow 4. Here reducing the tile, or splitting it across blocks, directly raises occupancy. That is the trade-off to compare: a bigger tile can improve data reuse and reduce global memory traffic, but it costs blocks per SM. A smaller tile raises occupancy but may fetch the same data more than once.

How I test the choice

I sweep block sizes such as 64, 128, 256 and 512 with the same input, and record registers per thread, shared memory per block, blocks per SM and elapsed time. If occupancy rises and time falls, the kernel was latency bound and short of warps. If occupancy rises and time stays flat, the kernel is probably bandwidth bound or already has enough independent instructions per thread, and I stop tuning occupancy. If a larger block is slower despite higher occupancy, I check for a partial final wave, where one block is left running on an otherwise idle SM, and for extra synchronisation cost inside the block.

I would report the final setting as measured numbers, for example 256 threads, 64 registers, 16 KB shared, 4 blocks per SM and 1.9 ms, against 128 registers and 2.6 ms for the spilling variant. That makes the reason for the block size checkable instead of a guess.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-49What kind of data should you put in GPU constant memory, and why does it work well there?

The 90-second answer

Constant memory is for data that every thread in a warp reads at the same address, and that does not change during a draw or kernel launch. A view-projection matrix, a fog colour, a light count and material parameters are typical examples. The hardware caches that one value and broadcasts it to the whole warp, so the read is fast.

If each thread reads a different address from the constant bank, that broadcast stops working. The warp is replayed one address at a time and the access becomes slow. Data like that belongs in global memory, where coalesced access is the fast path, or in a texture when it is image data sampled with spatial locality.

Code shape

In CUDA the declaration is explicit and the host updates the value between launches:

CUDA
__constant__ float4 c_FogColour;
__constant__ float  c_FogDensity;

__global__ void shade(float4* out, int n) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) out[i] = c_FogColour * c_FogDensity;
}

In HLSL the same idea is a cbuffer. In Vulkan and DirectX 12 it is a small uniform buffer or root constants. The pattern is the same in each API: small, uniform, infrequently updated data.

Worked trace

A warp of 32 threads runs the shader above. Every thread loads c_FogDensity. The constant cache sees a single address, serves it once and broadcasts it. One transaction for the warp.

Change the load to c_Table[threadIdx.x], with 32 different entries. Now the warp needs 32 different values from a cache built to broadcast one value. The hardware serialises those reads. Profiling shows the constant load replaying, which is the signal that the data is not uniform.

That replay is the practical test. Uniform read, constant memory. Divergent read, global memory or a texture. The size limit is also worth checking before you commit: NVIDIA reserves a 64 KB constant bank, so a large lookup table will not fit even if the access pattern were uniform.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-50Walk me through sizing a compute dispatch for a 1920x1080 image blur with 16x16 thread groups, and where do you need a global barrier versus a group barrier?

The 90-second answer

For a 1920 by 1080 blur I would use a 16 by 16 thread group, dispatch ceil(width/16) by ceil(height/16), and put a global barrier only between passes that read each other's output. Inside one pass, a group barrier is enough for shared-memory tiles. Confusing the two is the classic compute bug: it passes on small images and races on large ones.

Dispatch arithmetic first. ceil(1920/16) = 120, ceil(1080/16) = 68 because 67.5 rounds up. That is 8,160 groups, 2,088,960 threads for 2,073,600 pixels. The extra 15,360 threads must exit immediately, and that guard has to sit after any group barrier or the barrier becomes divergent.

HLSL
// HLSL for D3D12, compiled with DXC
[numthreads(16, 16, 1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
    // Load tile plus 1-pixel halo into shared memory.
    // All threads in the group must reach GroupMemoryBarrierWithGroupSync().
    GroupMemoryBarrierWithGroupSync();
    if (id.x >= 1920 || id.y >= 1080) return; // after the barrier, never before
    float4 c = BlurFromShared(id.xy);
    Output[id.xy] = c;
}

Host side:

C++
uint32_t gx = (1920 + 15) / 16; // 120
uint32_t gy = (1080 + 15) / 16; // 68
cmd->Dispatch(gx, gy, 1);

Why the barrier scope matters

A group barrier orders threads in one thread group and makes shared-memory writes visible to that group. It says nothing about other groups. A global barrier orders the whole dispatch and makes global memory writes visible to every thread. D3D12 and Metal provide no portable in-dispatch global barrier. You get global ordering by ending the dispatch and inserting a barrier before the next dispatch: a UAV barrier in D3D12, a pipeline barrier in Vulkan, or an encoder barrier between Metal compute passes. Vulkan GLSL memoryBarrier() orders memory accesses, but portable Vulkan code should not treat it as a substitute for a group execution barrier, and should not assume all workgroups are resident at once. Splitting into separate dispatches is the portable pattern on all three APIs.

PatternBarrier neededWhy
---------
---------
---------
Single-pass blur, each thread reads only its tile haloGroup barrierHalo comes from shared memory, written by the same group
Two-pass separable blur, pass 2 reads pass 1 outputEnd dispatch, UAV or pipeline barrier, start pass 2Pass 2 threads live in different groups from pass 1 writers
Prefix scan or iterative solverOne dispatch per iteration, or a device-supported global syncEach iteration reads the previous iteration from all groups
Atomic accumulation into a counterNo barrier for the atomic itself, barrier before reading the resultAtomics are ordered, the final read is not

A concrete failure trace: pass 1 writes tmp[y][x], pass 2 reads tmp. If you launch them as two dispatches with no UAV barrier between them, the GPU is free to start pass 2 groups before pass 1 groups finish. On a 64 by 64 test image everything lands in one wave and the bug hides. At 1920 by 1080, with 8,160 groups across several waves, pass 2 reads stale rows and you get a one-frame-old blur or torn horizontal bands. The fix is not a bigger group barrier. It is a barrier between dispatches.

Thread group size trade-offs

16 by 16 is a starting point, not a law. Larger groups amortize the halo load: a 16 by 16 tile with a 1-pixel halo loads 18 by 18 texels for 256 outputs, about 27 percent overhead. A 32 by 8 group loads 34 by 10 for the same 256 outputs, worse in one dimension. Smaller groups, 8 by 8, cut shared memory per group and raise occupancy when registers are high, but they reload the halo more often and launch more groups. The hard limits differ by vendor and by kernel. D3D allows up to 1024 threads per group. Metal reports maxTotalThreadsPerThreadgroup per kernel, commonly 256 to 1024 depending on register and threadgroup memory use. Vulkan reports maxComputeWorkGroupSize per device. I would test 16 by 16 against 32 by 8 and 8 by 8 with the real register count from the compiler, because occupancy drops in steps when shared memory per group crosses the per-SM budget.

How I would test it

Three checks catch most of this. First, a dispatch-size unit test: feed widths of 1, 15, 16, 17, 1919, 1920 and 1921 and compare against a CPU reference, which catches the off-by-one and the missing guard. Second, a barrier-removal test: run the two-pass version with the UAV barrier deleted under a stress loop of 500 frames with a checkerboard input. If the output ever differs from the reference, the barrier was load-bearing and the test proves it. Third, run the vendor tools, Nsight Compute or RenderDoc shader debug on a capture, and look for reads of tmp with no happens-before edge. A race that only appears at full resolution is still a race, and the checkerboard test at full resolution is what surfaces it.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-51How would you test tessellation, geometry and mesh shaders for adaptive LOD and amplification limits across vendors?

The 90-second answer

I test tessellation, geometry and mesh shaders as three separate amplification contracts. For each one I fix the input count, force the LOD or emission control to its minimum and maximum, and record output primitives, dropped primitives and frame time. A stage passes only if it stays inside its limits, produces no cracks or degenerate primitives, and matches a CPU reference silhouette.

The limits are the point of the test. Tessellation factors are clamped to 1 to 64. A geometry shader in Vulkan and OpenGL is limited to 256 output vertices and 256 output primitives per invocation, so I test to that portable limit even where D3D allows more. A mesh shader in D3D12 Shader Model 6 and Vulkan EXT_mesh_shader is limited to 256 output vertices and 256 output primitives per workgroup, and the counts are published with SetMeshOutputCounts in HLSL, or the equivalent SPIR-V instruction in Vulkan, not by writing fields into the payload. If I do not assert those caps, a close camera can amplify a small input until the frame collapses and all I learn is that it got slow.

How I force the extremes

For tessellation the LOD decision lives in the hull shader, so I can test it without rendering a full scene. The clamp has to run after any test scale, otherwise a scale of zero still produces a factor of one and a scale of four never reaches the cap:

HLSL
float4 ConstantHS(float d)
{
    float edge = clamp(64.0 * (1.0 - d) * uTessScale, 1.0, 64.0);
    return float4(edge, edge, edge, edge);
}

With uTessScale at 0 every edge is 1. With it at 4 the near field saturates at 64. I compare the rendered silhouette against a CPU grid built from the same distance function. The failure I am hunting is a crack: two patches sharing an edge compute different factors because one uses view distance and the other uses screen space distance, or because one driver rounds a fractional factor up and another rounds it down. A one factor tolerance in the silhouette check is acceptable for rounding. A crack is not, because it leaves a visible T-junction seam at any tolerance.

For a geometry shader I sweep an emission uniform from 0 to 300 for a single input triangle and count emitted vertices. Beyond 256 the driver must clamp or drop the excess. I also check for NaN positions and zero area triangles, since both poison interpolation in the fragment shader and show up as flickering pixels rather than a crash.

For a mesh shader I use a workgroup that culls a cluster and compacts the survivors. I read back the counts passed to SetMeshOutputCounts and the actual primitives drawn. Divergence inside the workgroup matters here: if half the threads take a cull branch, the survivors still pay for the full workgroup, so a cull rate that looks good in a counter can still be slow.

Worked trace

Take 1,000 quad patches. At factor 1 each quad is 2 triangles, so 2,000 total. At factor 64 each quad becomes 64 by 64 cells, 8,192 triangles per patch, 8.19 million total. That is a 4,096 times amplification from the same input. If the far case takes 3 ms, the near case is not a mystery regression, it is arithmetic. So the test also asserts a frame budget at forced maximum LOD on the lowest target GPU, and the shipping LOD curve has to keep the worst camera position inside it.

StageInputPortable output capFailure I test for
Tessellation1 patchfactor 64cracks from mismatched edge factors
Geometry shader1 primitive256 vertices, 256 primitivesoverrun, degenerate output
Mesh shader1 workgroup256 vertices, 256 primitivescount mismatch, divergence cost

When I would not use the stage

Tessellation pays off when displacement needs a continuous LOD and the mesh is otherwise uniform. If the detail is sparse, a mesh shader with culling and compaction usually wins, because it can skip empty clusters entirely instead of subdividing them and discarding the result. A geometry shader is the weakest of the three on tile based mobile GPUs, where it can force a pass through tile memory, so I avoid it there and use instancing or a mesh shader instead. Testing all three on the same harness makes that choice defensible: the table of input count, forced LOD, output count and worst frame time per stage is what I put in front of a reviewer when they ask why the low tier clamps tessellation at 32 instead of 64.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-52How would you use instancing to draw 5,000 identical rocks in a single draw call, and what data would you store per instance?

The 90-second answer

Store the rock geometry once and store only what changes from rock to rock in a second buffer. The GPU reads the geometry buffer once per vertex and steps through the second buffer once per instance. One draw call then produces 5,000 rocks.

GLSL
// Geometry buffer, divisor 0: read per vertex
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aNormal;

// Instance buffer, divisor 1: read per instance
layout(location = 2) in vec3 aOffset;
layout(location = 3) in float aScale;
layout(location = 4) in float aYaw;

void main() {
    float c = cos(aYaw);
    float s = sin(aYaw);
    mat3 rot = mat3(c, 0.0, -s,
                    0.0, 1.0,  0.0,
                    s, 0.0,  c);
    vec3 world = rot * (aPos * aScale) + aOffset;
    vNormal = rot * aNormal;
    gl_Position = projection * view * vec4(world, 1.0);
}

In OpenGL you set the divisor with glVertexAttribDivisor(2, 1) and call glDrawElementsInstanced(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0, 5000). In Vulkan the equivalent is a vertex input binding with inputRate = VK_VERTEX_INPUT_RATE_INSTANCE and vkCmdDrawIndexed(..., 5000, ...). The geometry binding stays at VK_VERTEX_INPUT_RATE_VERTEX.

What goes per instance

Position is the minimum. Scale and rotation let you vary size and orientation without touching the geometry. Colour tint or a random seed for variation can ride along if the shader needs it. A full 4x4 model matrix also works and is simpler to fill on the CPU, at 64 bytes per instance. The packed form above is 28 bytes per instance (three floats for offset, one for scale, one for yaw, plus padding to 32 bytes in practice). For 5,000 rocks that is about 160 KB read per frame, which the GPU handles easily.

Individual drawsInstancing
Draw calls5,0001
Geometry upload5,000 copies or one shared buffer with 5,000 state changesOne geometry buffer, one instance buffer
Per-rock variationSet a new model matrix uniform per drawRead offset, scale and yaw from the instance buffer
CPU costState setup and submission repeated 5,000 timesOne state setup, one submission

The arithmetic that motivates it

Suppose, as a worked example, each draw costs the CPU about 5 microseconds to submit. 5,000 draws cost 25 ms, which already exceeds a 16.7 ms frame budget at 60 fps before any rendering happens. One instanced draw costs roughly that same 5 microseconds plus the buffer upload. The GPU still rasterizes every visible rock, so instancing does not reduce triangle count. It removes the CPU bottleneck and the repeated state changes.

One limit to name in the interview

Culling happens for the whole batch. If the rocks are spread across a large map, the driver cannot skip the ones behind the camera because they share a single draw. For a cluster of rocks near each other that is fine. For a world-spanning set you would split the instances into chunks, for example one instanced draw per map region, so each chunk can be frustum culled as a unit.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-53What does a GPU compute shader write into an indirect draw buffer after culling and compaction, and how does the draw call consume it?

The 90-second answer

A compute shader writes draw arguments into a GPU buffer, including the number of instances that survived culling. The CPU issues one indirect draw for the batch and the GPU reads that count when the draw executes. No CPU readback happens between culling and drawing.

In Vulkan the record is VkDrawIndexedIndirectCommand. In Direct3D 12 it is D3D12_DRAW_INDEXED_ARGUMENTS. The fields are the same:

| Field | Meaning | | IndexCountPerInstance | Indices per instance. Changes with LOD. | | InstanceCount | Instances to draw. Compaction writes this. | | StartIndexLocation | Offset into the index buffer. | | BaseVertexLocation | Added to each index. | | StartInstanceLocation | First instance ID passed to the shader. |

How the pipeline runs

  1. The CPU uploads all candidates once, for example 100,000 trees with a bounding sphere and a transform each.
  2. A compute shader tests each sphere against the frustum and a Hi-Z pyramid. Survivors write their transform into a compacted array. An atomic counter gives each survivor its slot.
  3. The shader picks an LOD from distance and writes that LOD's IndexCountPerInstance and StartIndexLocation into the record for that bucket. A near tree might write 1,800 indices, a far tree 240.
  4. A second, one-thread dispatch writes the final counter value into InstanceCount after the first dispatch has finished.
  5. The CPU calls the indirect draw. The GPU fetches InstanceCount at draw time, so the draw matches the compacted list.

Worked trace, with hypothetical figures: 100,000 candidates enter the shader. Frustum culling keeps 31,000. Hi-Z keeps 12,340. The counter ends at 12,340, so InstanceCount = 12340. The compacted buffer holds exactly 12,340 transforms, with no gaps. Next frame, if 8,000 survive, the second dispatch overwrites the same field with 8,000 and the same indirect call draws 8,000.

Compacted write, HLSL for Direct3D 12, SM 6.0

HLSL
RWStructuredBuffer<float4x4> g_transforms;
RWStructuredBuffer<float4x4> g_compacted;
RWBuffer<uint> g_counter; // g_counter[0], cleared to 0 before dispatch
RWStructuredBuffer<D3D12_DRAW_INDEXED_ARGUMENTS> g_drawArgs;
uint g_count;

bool FrustumVisible(uint i) { return true; } // replace with sphere test
bool Occluded(uint i) { return false; }     // replace with Hi-Z test

[numthreads(256, 1, 1)]
void CSCompact(uint3 id : SV_DispatchThreadID)
{
    uint i = id.x;
    if (i >= g_count) return;
    if (!FrustumVisible(i) || Occluded(i)) return;

    uint slot;
    InterlockedAdd(g_counter[0], 1, slot);
    g_compacted[slot] = g_transforms[i];
}

[numthreads(1, 1, 1)]
void CSWriteCount()
{
    g_drawArgs[0].IndexCountPerInstance = 1800; // near LOD for this bucket
    g_drawArgs[0].InstanceCount = g_counter[0];
    g_drawArgs[0].StartIndexLocation = 0;
    g_drawArgs[0].BaseVertexLocation = 0;
    g_drawArgs[0].StartInstanceLocation = 0;
}

The two dispatches are separated by a UAV barrier. CSWriteCount runs only after every block in CSCompact has finished incrementing the counter, so it cannot read a partial total. In production I use one counter and one record per LOD bucket, so g_counter[bucket] and g_drawArgs[bucket] select by bucket.

Issuing the draw

In Direct3D 12, ExecuteIndirect takes the argument buffer, a root signature, maxCommands, and optionally a count buffer. If a count buffer is supplied, the GPU reads the command count from *countBuffer + countBufferOffset and clamps it to maxCommands. That is how a variable number of bucket records can be issued without a CPU readback. With a fixed bucket count, I pass a null count buffer and set maxCommands to the bucket count.

In Vulkan, vkCmdDrawIndexedIndirect reads a fixed count from the CPU call, while vkCmdDrawIndexedIndirectCount reads the count from a GPU buffer, which serves the same purpose.

Where this breaks

A missing barrier between the compute dispatches and the indirect draw is the classic failure. The draw can read a stale InstanceCount from the previous frame, so the screen shows ghost instances or cuts off the tail of the list. The fix is a UAV barrier between dispatches plus a resource state transition on the argument buffer before ExecuteIndirect.

The counter must be cleared to zero before each frame, and the compacted buffer must be sized for the worst case survivor count, not the average. If 100,000 candidates all survive and the buffer holds 50,000, atomic writes run past the end. I size for the full candidate count or clamp the slot and accept drawing the cap.

LOD buckets need separate records because IndexCountPerInstance and StartIndexLocation differ per LOD. A single record can only describe one mesh. The payoff is one indirect draw per bucket regardless of survivor count, and the CPU never waits on a readback. The cost is that the whole candidate set lives in GPU memory and the compaction pass touches it every frame, so this wins when the candidate count is large and the survivor count varies a lot frame to frame.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-54Walk me through designing a move-only RAII wrapper for a Vulkan buffer that stays zero-overhead in a vector, survives partial allocation failure and device loss, and never frees memory the GPU is still reading?

The 90-second answer

I would make the wrapper own exactly the handles, nothing else, and split lifetime into two parts. CPU ownership ends when the wrapper is destroyed or reset. GPU lifetime ends later, when the fence for the last submission using that memory has been signalled. Conflating those two is the failure I see most often: the C++ object dies promptly, vkDestroyBuffer and vkFreeMemory run immediately, and the GPU reads freed memory two frames later. So reset() does not free. It moves the handles into a retire queue tagged with a fence value, and a separate pass frees them after that fence is known complete.

C++
// C++20, GCC 13 / Clang 17, Vulkan 1.3. One buffer, one allocation.
struct Retired { VkBuffer buf; VkDeviceMemory mem; uint64_t fence; };

class GpuBuffer {
public:
    GpuBuffer() = default;
    GpuBuffer(VkDevice dev, VkBuffer b, VkDeviceMemory m) noexcept
        : dev_(dev), buf_(b), mem_(m) {}
    ~GpuBuffer() { release(); }

    GpuBuffer(const GpuBuffer&) = delete;
    GpuBuffer& operator=(const GpuBuffer&) = delete;

    GpuBuffer(GpuBuffer&& o) noexcept
        : dev_(o.dev_), buf_(o.buf_), mem_(o.mem_) {
        o.buf_ = VK_NULL_HANDLE; o.mem_ = VK_NULL_HANDLE;
    }
    GpuBuffer& operator=(GpuBuffer&& o) noexcept {
        if (this != &o) { release();
            dev_ = o.dev_; buf_ = o.buf_; mem_ = o.mem_;
            o.buf_ = VK_NULL_HANDLE; o.mem_ = VK_NULL_HANDLE; }
        return *this;
    }
    // Factory: partial failure must not leak the buffer if allocation fails.
    static GpuBuffer create(VkDevice dev, VkDeviceSize size, uint32_t queueFamily,
                            std::vector<Retired>& retire, uint64_t lastFence);
    void release() noexcept; // enqueues to retire list, never calls vkFreeMemory
    VkBuffer get() const noexcept { return buf_; }
    explicit operator bool() const noexcept { return buf_ != VK_NULL_HANDLE; }
private:
    VkDevice dev_ = VK_NULL_HANDLE;
    VkBuffer buf_ = VK_NULL_HANDLE;
    VkDeviceMemory mem_ = VK_NULL_HANDLE;
};
static_assert(sizeof(GpuBuffer) == 24);
static_assert(std::is_nothrow_move_constructible_v<GpuBuffer>);

release() needs the retire list and the fence value of the last frame that could have used the buffer. I pass those in rather than storing a pointer to a global queue in every wrapper. Storing the queue pointer would add 8 bytes per object and couple every buffer to one frame graph. Passing it at release keeps the object at 24 bytes and makes the dependency visible at the call site.

Why the constraints interact

Three requirements pull against each other. Zero overhead says no refcount, no virtual call, no heap node per buffer. Safety in a std::vector says move must be noexcept, otherwise reallocation falls back to copy to preserve the strong exception guarantee, and copy is deleted, so the vector stops compiling or, worse, someone re-enables copy to fix it. Deferred destruction says the destructor cannot be the whole story.

The resolution is to keep the destructor trivial in effect: null the source on move, check for null on release, enqueue. The expensive work, waiting and freeing, happens in one place per frame. I check the disassembly for a move: it should be three loads, three stores, two null stores, no call. If I see an atomic operation, a shared_ptr crept in.

DesignPer movePer releaseVerdict
Wrapper above24 byte copynull check plus enqueueDefault for frame scoped buffers
unique_ptr with custom deleterpointer copydeleter callFine for one handle, awkward when buffer and memory must retire together with a fence
shared_ptratomic inc/decatomic dec, free at zeroPays cache line contention in a hot loop, and still does not know about GPU fences, so it frees too early anyway

That last point matters. Shared ownership solves CPU aliasing, not GPU lifetime. A texture shared between the renderer and the physics debug view still needs its memory held until the fence for its last use. The retire queue is not optional decoration on top of RAII. It is the second half of the lifetime.

Worked trace

Assume 3 frames in flight, fence values increase by 1 per frame, and the CPU is at frame 102 while the GPU has completed up to 99.

frame 100: buffer B bound in a draw, submitted with fence 100
frame 101: B replaced by B2, B.release() enqueues {B, fence=100}
frame 102: B.release() again on the moved-from object, buf is null, no-op
cleanup after vkWaitForFences(99): retire entries with fence <= 99 freed, B stays queued
cleanup after fence 100 signals: B freed exactly once

Self move assignment is guarded by this != &o. Without it, release() destroys the buffer and the assignment then copies nulls from itself. The object looks valid and the resource is gone. Moved-from objects must remain destructible and reassignable, which the null handles guarantee.

Failure modes I test for

Partial construction: vkCreateBuffer succeeds, vkAllocateMemory returns VK_ERROR_OUT_OF_DEVICE_MEMORY. If the two calls sit in a constructor body that throws or returns an error code, the buffer leaks because the destructor never runs for a failed construction. The factory above destroys the buffer on that path before returning an empty wrapper.

Device loss: after VK_ERROR_DEVICE_LOST, handles may already be invalid and calling vkDestroyBuffer can be pointless or can fault depending on the driver. My cleanup pass checks a device-lost flag set by the error callback and drops the retire queue without freeing, then recreates the device. I verify this with validation layers and a forced device removal test, not by reading the spec and hoping.

Retire queue overflow: if the queue grows unbounded because the GPU stalls, memory grows with it. I cap it, for example at 4096 entries, and treat overflow as a frame pacing bug to surface in telemetry. Silently freeing early to make room would reintroduce use after free under exactly the stall conditions where it hurts most.

Per buffer vkAllocateMemory also fragments. At 10,000 small buffers that is 10,000 allocations and poor locality. In production I would keep this wrapper shape but back it with a suballocator such as VMA, where the wrapper owns an offset and size inside a large block and release() returns the range to the allocator instead of calling vkFreeMemory. The move semantics and the retire queue do not change. The allocation strategy does, and that is a separate decision from ownership.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-55Walk me through how C++ struct padding changes the size and offsets of a vertex struct, a uniform buffer struct, and a shared-memory struct, and how you would lay each out safely?

The 90-second answer

C++ places each member at the next offset that is a multiple of its alignment, then rounds the struct size up to the strictest alignment. That is right for CPU code. A uniform buffer, a vertex fetch, and shared memory each have their own rules, so I never upload a C++ struct blindly. I lay the CPU struct out to match the consumer and prove it with static_assert on sizeof and offsetof.

The mismatch shows up with a scalar before a vec3. In GLSL std140, a vec3 has alignment 16 and occupies a full 16-byte slot:

C++
struct Light {              // C++
    float intensity;        // offset 0
    float pos[3];           // offset 4
    float exposure;         // offset 16
};                          // sizeof == 20
MemberC++ offsetstd140 offset
intensity00
pos416
exposure1628
total2032

The GPU reads pos from byte 16, which in the C++ buffer is exposure plus the next struct's data. Nothing crashes. The light just sits in the wrong place, which is why I check offsets in a test instead of eyeballing the render.

The fix is to declare the padding the GPU needs:

C++
struct Light {
    float intensity;
    alignas(16) float pos[3];
    float exposure;
};
static_assert(offsetof(Light, pos) == 16);
static_assert(sizeof(Light) == 32);

alignas(16) forces the gap after intensity, and the size rounds to 32. HLSL packs differently again: a float3 followed by a float shares one 16-byte row. So a layout that is correct for std140 can still be wrong for a D3D12 cbuffer. I generate offsets from one source, shader reflection or a shared table, and assert both sides agree.

Vertex and shared memory

For a vertex struct the fetch unit reads at explicit offsets with a stride. All-float members need no padding, so float px, py, pz, u, v, nx, ny, nz is a clean 32-byte stride. Add a uint8_t flags after pz and the compiler inserts 3 bytes before u, making the stride 36. If the shader expects u at offset 12, it reads flags and padding as UVs. I move the byte to the end or pack the buffer at computed offsets. #pragma pack(push, 1) removes padding but gives members alignment 1, so a float* cast to a member is undefined behaviour and wide loads can fault or slow down. I keep natural alignment and order members to minimise padding.

In shared memory, padding costs occupancy. A 20-byte struct at 256 threads per block uses 5,120 bytes. Widening pos to float4 makes it 32 bytes, or 8,192 bytes per block. On a part with 48 KB per block that drops occupancy from 9 blocks to 6. I size the struct from the access pattern and check it against the occupancy calculator, using 16-byte alignment only when the code issues a 16-byte load.

How I test it

static_assert on size and on every offset that crosses the CPU/GPU boundary, so a reorder breaks the build. A CPU test that fills the struct with a known pattern and compares CPU offsets against shader reflection. And the buffer view in RenderDoc or Nsight Graphics, which shows the byte ranges the GPU actually reads.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-56Your particle update touches only position and velocity, but the struct also holds colour, life and size. How would you decide between AoS and SoA, and where does false sharing bite?

The 90-second answer

I would start from the access pattern, not the struct. If the hot loop touches every field of a particle, AoS (array of structs) wins because one cache line brings the whole record. If the hot loop touches one or two fields and skips the rest, SoA (struct of arrays) wins because it stops dragging unused bytes through L1 and L2. False sharing is the second-order effect: two threads writing different fields that happen to share a 64-byte cache line will bounce that line between cores even though they touch disjoint data.

Take a concrete particle, checked on a typical x86-64 / ARM64 desktop where the cache line is 64 bytes:

C++
// AoS: 32 bytes per particle
struct Particle {
    float px, py, pz;   // 12
    float vx, vy, vz;   // 12
    float life;         // 4
    float size;         // 4
};
std::vector<Particle> particles(N);

// SoA: same data, split by field
struct ParticleSoA {
    std::vector<float> px, py, pz;
    std::vector<float> vx, vy, vz;
    std::vector<float> life, size;
};

Worked trace: the update loop

The integrate step reads and writes only position and velocity: 24 of the 32 bytes. It never reads life or size.

In AoS, one cache line holds exactly 2 particles (64 / 32). Loading a line to update particle 0 also loads particle 1, which the same thread will update next, so that part is fine. The waste is the 8 bytes per particle (25%) that are loaded, occupy L1, and are evicted without ever being read. For 1 million particles the array is 32 MB. The SoA position and velocity arrays total 24 MB. Same loop, 8 MB less traffic per pass, and the working set is more likely to stay resident in a 32 MB L3.

The gap widens when a second pass touches a different field. A render pass that reads only life and size (8 bytes) in AoS still pulls full 64-byte lines, so it moves 32 MB to read 8 MB of useful data. In SoA it moves 8 MB. That is the arithmetic I would quote in the interview: bytes moved per pass, not "SoA is faster."

LoopAoS bytes movedSoA bytes movedWinner
Integrate (pos + vel)32 MB24 MBSoA, modest
Fade by life (life + size)32 MB8 MBSoA, 4x
Full reset (all fields)32 MB32 MBTie, AoS simpler
Spawn one particle (all fields, random index)1 line, all fields local6 lines, one per arrayAoS

That last row is the case against SoA. Spawning, serialising, or iterating a single particle touches every array, so you pay six cache misses instead of one, and the code scatters. If particles are mostly created and destroyed rather than streamed, AoS is the honest choice.

False sharing: where it actually bites

False sharing needs two threads writing to the same cache line. It does not happen in a single-threaded update, however badly laid out. It happens when I split the AoS array by index range across threads and the split point lands mid-line, or when two threads own adjacent particles in a small struct.

Trace with 32-byte particles and 4 threads, each owning a contiguous block. Thread 0 owns particles 0 to 249,999. Its last particle, 249,999, sits at byte offset 7,999,968. Thread 1 owns particle 250,000 at offset 8,000,000. Both offsets are multiples of 32, and 8,000,000 / 64 = 125,000 exactly, so in this case the boundary happens to align to a cache line and there is no sharing. Change the struct to 36 bytes (add a float drag) and the boundary at particle 250,000 lands at offset 9,000,000, which is 32 bytes into a cache line. Thread 0's last write and thread 1's first write now hit the same line. Every iteration, the line is invalidated on the other core, transferred, written, and invalidated back. The loop slows by a factor that has nothing to do with the math.

Fixes, in order of preference: align each thread's partition to a cache line boundary (pad the partition size up to a multiple of 64 / sizeof(Particle) particles), or switch the hot fields to SoA and give each thread its own contiguous slice of each array, which makes the same alignment easy to enforce. Padding a single struct field to force alignment, such as adding dummy bytes to reach 64, only helps if the struct is exactly one per line, which wastes memory for particles.

Geometry data follows the same rule, with a GPU twist

For a static mesh uploaded once and drawn many times, interleaved vertices (position, normal, UV in one buffer) are fine because the vertex fetch reads all of them. For CPU-side skinning or normal recomputation that touches only position, SoA or separate position-only buffers win for the same reason as particles. On the GPU the analogue is coalescing: a warp of 32 threads reading px from a SoA array issues one wide transaction, while reading the same field from AoS with a 32-byte stride issues up to 32 separate transactions. The mechanism is different (memory coalescer, not L1), the decision is identical.

My default for a particle system with separate integrate, fade, and render passes is SoA for the hot fields, AoS only if profiling shows spawn and single-particle access dominating. I would verify with a perf counter run (L1 misses and line transfers between cores) before and after the change, because the win depends entirely on which fields the real loop touches.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-57What compiler flag allows a compiler to reassociate floating-point operations so it can auto-vectorize a reduction loop?

The 90-second answer

-ffast-math in GCC and Clang, or /fp:fast in MSVC. That flag tells the compiler it may reassociate floating-point operations, and reassociation is what lets it turn a scalar reduction into several SIMD partial sums.

A reduction such as sum += a[i] has a fixed rounding order in the source. A vectorized version keeps one partial sum per lane and adds those partial sums at the end. That is a different order, so under the default strict floating-point rules the compiler is not allowed to do it. The fast-math flag removes that restriction for the translation unit it is applied to.

Why the order matters, in one trace

Use doubles: 1e16, 1, 1, -1e16. At 1e16 the gap between adjacent doubles is 2, so 1e16 + 1 rounds back to 1e16.

Scalar order: (((1e16 + 1) + 1) - 1e16) gives 0. Both 1 values are lost.

Four-lane order: lane totals 1e16, 1, 1, -1e16, combined as (1e16 + -1e16) + (1 + 1), gives 2.

Same inputs and same operation, different result. The vector result is more accurate in this case, but it is not the result the source specified. That is the reassociation risk in concrete form.

What changes in code

C++
// Default: compiler keeps this order, loop stays scalar.
double sum = 0.0;
for (int i = 0; i < n; ++i) sum += a[i];

// With -ffast-math: compiler may split into partial sums.
// With intrinsics, you write the split yourself:
__m256d acc = _mm256_setzero_pd();
for (int i = 0; i + 4 <= n; i += 4)
    acc = _mm256_add_pd(acc, _mm256_loadu_pd(a + i));

Elementwise loops such as out[i] = a[i] * b[i] need no flag, because each iteration is independent and no order changes. Only reductions and other order-dependent chains need permission to reassociate.

SettingEffect on a reductionSide effect to know
Default strict FPOrder preserved, no vectorized reductionSlowest for large sums and dot products
-ffast-math / /fp:fastReassociation allowed, vectorized reductionAlso enables flush-to-zero, reciprocal approximations, and assumed finite math in GCC and Clang
IntrinsicsYou choose lane order explicitlyResult still differs from scalar in low bits, and you must dispatch for the CPU features used

Apply the flag narrowly, to a file or function doing geometry or shading math where a low-bit difference is invisible. Keep strict ordering for simulation state, deterministic replay, and checksums compared bit for bit across machines.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-58Walk me through designing a job system and task graph for frame preparation and asset streaming that avoids stalls without oversubscribing the render thread?

The 90-second answer

I would keep the render thread out of the worker pool. It owns the GPU queue, the command allocator and every barrier, so if it also runs gameplay or streaming jobs a long task delays the submit and the GPU starves. Workers prepare the frame, the render thread only records and submits.

The frame is a DAG built once per frame type, not per frame. Nodes are jobs with explicit dependencies and a cost estimate. A scheduler runs ready jobs on a pool sized to physical cores minus one for the render thread, minus one if the main thread is doing simulation. IO and decompression get their own bounded queues so a burst of texture loads cannot flood the compute pool.

C++
struct Job {
    std::atomic<int> pendingDeps;
    uint32_t costUs;          // estimate, updated from last frame
    uint8_t  priority;        // 0 = frame critical, 255 = background
    void (*fn)(Job*);
    Job* nextReady = nullptr; // intrusive list, no allocation in the hot path
};

void Complete(Job* j) {
    for (Job* d : j->dependents)
        if (d->pendingDeps.fetch_sub(1, std::memory_order_acq_rel) == 1)
            PushReady(d); // only the last finisher publishes it
}

That last-finisher rule is the whole synchronization. No central lock on the ready queue beyond a lock-free stack per worker, and no job runs until every predecessor has released it. A job that needs the GPU, such as a texture upload, is not run on a worker at all. It enqueues a copy command and the render thread inserts the barrier.

A concrete frame graph

Assume a 60 Hz target, 16.6 ms total, with about 3 ms budgeted to CPU render preparation on an 8-core machine. The graph for one frame looks like this:

[Sim tick] ──> [Cull + sort] ──> [Build draw lists] ──> [Record commands] ──> [Submit]
                  │                    │
                  │                    └──> [Update instance buffers]
[Stream IO] ──> [Decompress] ──> [Upload + mip gen] ──> [Barrier] ──> [Record commands]
[LOD select] ──> [Cull + sort]
JobRuns onTypical costDependency rule
Cull and sort, 40k objectsworkers, split by spatial partition0.6 msneeds sim tick
Build draw listsworkers0.8 msneeds cull
Decompress texture, 4 MB BC7 blockIO worker1.5 msneeds IO read
Upload and generate mipsGPU copy queue0.4 ms GPUneeds decompress, barrier before use
Record commandsrender thread only1.2 msneeds draw lists and uploads

Splitting cull by partition matters more than the pool size. Forty thousand objects in one job is a 0.6 ms tail that blocks draw list building. Eight jobs of 5k each let the scheduler balance a slow core and let draw list building start on the first finished partition if the lists are built per partition.

Streaming without stalls

Asset streaming is a priority problem, not a bandwidth problem. Each request carries a deadline: the frame by which the asset is visible. The streamer sorts by deadline, then by distance, and prefetches into a ring buffer of staging memory. If the buffer is full, the lowest priority pending request is dropped, not queued. A dropped prefetch costs a later hitch. A queued low priority request that evicts a high priority one costs a hitch now.

Trace from a level transition, hypothetical but typical numbers: 120 requests arrive, 38 are frame critical. The IO queue drains at 200 MB/s from SSD. Decompression keeps two workers busy for 9 ms. The staging buffer holds 64 MB. At frame 3 the buffer fills, the streamer cancels 22 background requests, and the critical set still lands by frame 5. Without cancellation the critical textures arrive at frame 11 and the player sees untextured geometry for six frames. The fix is visible in the trace as a flat upload timeline instead of a spike at frame 11.

Failure modes I check for

False sharing on the dependency counters. If counters sit adjacent in an array, eight workers decrementing them bounce cache lines. Padding each counter to 64 bytes, or packing a whole partition's counters into one cache line owned by one worker, removes it. I measure this with a counter of cache line transfers, not with wall time alone.

Priority inversion through the GPU. A worker finishes a mesh upload and waits on a fence that the render thread will only signal after recording. If the render thread is waiting for that worker's draw list, the frame deadlocks in practice, which looks like a 30 ms hitch. The rule that prevents it: workers never block on the render thread. They enqueue and return. The render thread polls fences with a timeout and drops to a degraded path, drawing the previous frame's buffer, rather than stalling.

Granularity collapse. A job that takes 5 microseconds costs more in scheduling and atomic operations than in work. I set a floor near 20 to 50 microseconds and merge smaller jobs, such as per-object transform updates, into one job per partition. The arithmetic is simple: at 10k jobs per frame and 1 microsecond of overhead each, scheduling alone eats 10 ms.

Oversubscription on the render thread. The symptom is submit latency growing while worker utilization looks healthy. I keep a per frame budget on the render thread, record commands in chunks, and if recording exceeds budget I split the draw list build so recording can start earlier. On consoles with a dedicated GPU core this is less acute, on PC with hyperthreading it is the first thing that breaks.

I would validate with a frame capture showing worker timelines, GPU idle gaps, and staging buffer occupancy across a level load, plus a stress scene with double the object count. If GPU idle gaps appear while workers are busy, the graph is missing a dependency or the upload path is serializing. If workers idle while the GPU is busy, the graph is too deep and I need more parallelism in cull and draw list building.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-59How would you test a lock-free command queue between render and worker threads for lost commands, reordering, and data races under load?

The 90-second answer

I would test the queue as a concurrent protocol, not as a container. The contract I write down first is: which threads produce, which consume, what ordering each payload needs, and what happens on shutdown. For a render thread fed by worker threads, that is usually MPSC: many workers push commands, one render thread pops them, and a command is never visible before its payload is fully written.

Then I test three layers. Deterministic interleavings for logic errors, stress runs for lost or torn commands, and sanitizers plus model checking for races and ordering errors. A queue that passes a functional test once has proved almost nothing.

The mechanism that breaks

A typical publish writes the payload, then publishes it with a release store on a flag or index. The consumer reads that flag with an acquire load, so it cannot see the flag set and then read stale payload bytes. A release store prevents writes before it in program order from being observed after it. An acquire load prevents reads after it from being observed before it. Relaxed ordering gives neither guarantee. The compiler and the hardware are both allowed to reorder across a relaxed operation.

On x86, stores are not reordered with other stores, so a relaxed publish often appears to work. On ARM, which ships in consoles and mobile GPUs, stores can be reordered, so the consumer can observe the flag and still read old payload bytes. That is not a torn read in the hardware sense. It is a visibility failure, and it shows up as a draw command with a half written transform or a stale texture handle.

A plain data race is a separate failure. If a worker writes command->matrix while the render thread reads it with no atomic or lock involved, C++ makes that undefined behaviour. The compiler may cache the value, hoist the read out of a loop, or assume it never changes. ThreadSanitizer reports the race even when the output looks correct on a given run. It does not report a missing release or acquire, because the accesses themselves are atomic. Ordering bugs need a different tool.

C++
// C++20, checked with clang 17 -fsanitize=thread
struct Command { uint64_t id; float matrix[16]; };
std::atomic<bool> ready{false};
Command slot;

// Producer: payload first, publish second.
slot.id = nextId++;
std::memcpy(slot.matrix, m, sizeof(slot.matrix));
ready.store(true, std::memory_order_release); // payload must be visible first

// Consumer: observe the publish, then read the payload.
if (ready.load(std::memory_order_acquire)) {
    consume(slot); // safe to read matrix here
    ready.store(false, std::memory_order_relaxed);
}

In a ring, head and tail are both std::atomic<uint64_t>. The producer loads head with acquire before reusing a slot, writes the payload, then stores tail with release. The consumer loads tail with acquire, reads the payload, then stores head with release so the producer cannot overwrite the slot until the read is done. In an MPSC ring the tail reservation itself needs a compare exchange loop, because several producers can race to claim the next slot. I keep that reservation separate from the publish step in the code, so I can audit each ordering choice on its own.

How I test it

LayerWhat I runWhat it catches
Deterministic interleavingProducer and consumer stepped one atomic at a time, every pause point enumerated, queue sizes 1, 2, 3 and 64Lost wakeup, double pop, reading a slot before publish, off by one on full and empty
Stress4 to 8 producers, 1 consumer, 10 million commands per run, randomised payload checksums, consumer verifies sequence per producerReordering, slot reuse errors, torn payloads, dropped commands under contention
Sanitizers and model checkingThreadSanitizer on the CPU build, plus a litmus test or CDSChecker run on the publish pattern, plus an ARM buildData races on payload fields, and relaxed ordering that x86 hides
Soak and shutdownQueue filled to capacity, producers blocked, consumer stopped mid frame, then resumed and drainedDeadlock on full, commands lost on thread exit, use after free of a slot the consumer still holds

For the stress run I make each command self checking. The producer writes id, then writes matrix[0] = float(id) and a checksum over the rest. The consumer recomputes the checksum before acting on the command. A torn or reordered payload fails immediately instead of producing a slightly wrong frame that nobody notices. I run the same binary with capacity set to 1. Capacity 1 forces the full path on almost every push and exposes the boundary condition that a large ring buffer hides.

I also test the wakeup path separately. A queue that only signals when it transitions from empty to non-empty can lose a wakeup if the consumer checks empty, then sleeps, and the producer pushes and signals in between. The deterministic test reproduces that interleaving by pausing the consumer between the empty check and the sleep. The fix is to recheck the head after registering intent to sleep, using a sequence counter or a condition variable style protocol.

Changing release and acquire to relaxed will not reliably fail a stress test on x86. I do not claim it will. I run the litmus test under a memory model checker, and I run the stress binary on ARM hardware, where the reordering is observable. If the relaxed version passes on x86 and fails on ARM, that is the expected result and it confirms the test setup is honest.

Failure modes I name in the interview

False sharing is the quiet one. If head and tail sit on the same cache line, every push invalidates the line the consumer is reading and vice versa. I pad them apart with alignas(std::hardware_destructive_interference_size), which is the C++17 way to ask the platform for its destructive interference size instead of hardcoding a byte count, and I measure push throughput with and without padding before I claim the queue is fast enough.

Slot reuse is the second. If a consumer holds an index to a slot across a pop, a producer can refill that slot with a new command and the consumer acts on the wrong one. A monotonically increasing index that is never reused within a frame, or a per slot sequence number, removes the ambiguity. My checksum test catches the symptom, the sequence number removes the cause.

The third is shutdown. A worker that pushes after the render thread has stopped draining writes into a ring nobody reads, and if the ring is freed on exit that write is a use after free. I test shutdown by stopping the consumer first, joining producers, then draining and asserting the count matches what was accepted. Any command accepted before shutdown must be consumed or explicitly discarded, never silently dropped.

I would not use a lock-free queue for a low rate path such as asset loading callbacks. A mutex and condition variable are easier to audit and the contention cost is irrelevant at a few hundred events per second. Lock-free pays off for the per frame command stream where a lock would serialise workers against the render thread, and it costs me the testing burden above. That trade is worth it only when the queue sits on the frame critical path.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-60Walk me through how you would profile a frame that misses its 16.6 ms budget using Nsight Graphics, PIX and hardware counters to find the bottleneck?

The 90-second answer

Start with a capture, not with counters. I capture one frame in the tool that matches the API and vendor, read the timeline to find which draw or dispatch ate the budget, then pull hardware counters only for that range. Nsight Graphics is the NVIDIA path for Vulkan, OpenGL and D3D12 on NVIDIA hardware. PIX is the Microsoft path for D3D12 on Windows and Xbox. Both sit on the same idea: a GPU timeline of events, each event with a duration, and per-event counters that explain why it took that long.

Say the frame budget is 16.6 ms and the capture shows 21.4 ms. The timeline splits it as: shadow pass 3.1 ms, opaque 12.8 ms, post 2.9 ms, UI 1.2 ms, plus gaps. I would not profile the whole frame with counters. I profile the opaque pass, and inside it the two draws over 1 ms. Counters on a 0.2 ms draw are noisy and the tool overhead changes the result.

What I look at in each tool

In Nsight Graphics I use the Event Browser to sort draws by GPU duration, then Range Profiling on the top draw to get SM busy, DRAM throughput, L2 hit rate, achieved occupancy and warp stall reasons. The Source Counters view ties a stall to a line in the shader, which is where a fix starts.

In PIX I use the GPU timeline and the GPU events view, then the counters view for the same event. PIX exposes D3D12 performance markers I insert in code, so a marker around the shadow pass or a specific mesh survives the capture. On Xbox the same workflow applies, with the added constraint that I cannot ship a debug build to retail hardware to reproduce it.

The counters that separate the common cases:

Symptom in countersLikely boundFirst check
SM busy high, DRAM throughput low, occupancy lowLatency or occupancyRegisters per thread, shared memory per block, barrier waits
DRAM throughput near peak, L2 hit rate lowMemory bandwidthTexture size and format, overdraw, render target tile size on TBDR
SM busy high, DRAM high, vertex throughput highVertex boundTriangle count, vertex shader cost, index reuse
Fragment heavy, early-z kills little, quad divergence highFragment boundOverdraw, discard rate, derivative cost at edges
Warp stalls on long scoreboard or barrierDependency stallsIndependent work between dependent instructions, sync points

A worked trace

Hypothetical numbers, labelled as such. One opaque draw, a hero mesh with a 4K albedo and a normal map, takes 8.6 ms in a 21.4 ms frame. Range Profiling reports SM busy 94%, DRAM throughput 31% of peak, L2 hit rate 88%, achieved occupancy 36%, 168 registers per thread, and the top stall is long scoreboard on texture loads.

That combination rules out bandwidth. DRAM is idle, the texture mostly hits L2, and the SMs are busy but only a third occupied. At 168 registers, a block that wants 256 threads cannot reach full occupancy on many parts, so each warp waits on a texture fetch with too few other warps to hide it. The source view points at the normal map fetch in the first lighting term, before any early-out.

The fix I would try first is not a smaller texture. I would cut register pressure: move the tangent frame computation into a cheaper form, split the fetch so diffuse can be sampled before the normal decode, and check whether the normal map can drop to BC5 or BC7 without visible loss. Then I recapture the same frame. If occupancy rises to 70% and the draw falls to 4.9 ms, the diagnosis held. If occupancy rises and time does not move, the stall was elsewhere and I look at the next stall reason rather than declaring victory.

Failure modes I watch for

Counters lie when the capture is not representative. A capture taken in a menu, or with a single warm-up frame, gives cold caches and shader compilation spikes. I capture after several frames of the same scene, and I compare the capture duration to the live frame time. If the tool adds 30% overhead, relative ordering of draws is still useful, absolute milliseconds are not.

Vendor lock-in is the other trap. Nsight counters do not exist on AMD or Apple silicon, and PIX does not profile a Vulkan title on Linux. On AMD I would use Radeon GPU Profiler and its PM4 counters, on Apple silicon the Metal HUD and Xcode GPU capture. The method transfers, the counter names and the exact stall taxonomy do not, so I never quote a counter name from one vendor as if it existed on another.

Finally, a counter tells me a resource is saturated, not what to change. High DRAM throughput with low L2 hits could be overdraw, a huge render target, or a texture sampled at the wrong mip. I confirm with a deliberate experiment: halve the render target resolution for one capture, or force a lower mip, and see which counter moves. If the draw time follows the counter, I have a cause. If it does not, I have a correlation and I keep digging.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-61At 60 fps, how many milliseconds do you have per frame, and how do you compare CPU time and GPU time against that budget?

The 90-second answer

At 60 fps you have 1000 / 60 = 16.67 ms per frame. That is the whole budget. CPU time and GPU time do not add up against it, because they run in parallel. You compare the larger of the two, plus sync time, against 16.67 ms.

That one rule decides most frame budget arguments. If the CPU needs 9 ms and the GPU needs 12 ms, the frame is not 21 ms. The GPU is the critical path at 12 ms, and the CPU work is hidden underneath it, provided the CPU finishes submitting before the GPU runs out of work.

BucketExample timeHow you measure it
CPU main thread9.0 msTimers around update, culling, recording and submission
GPU12.0 msTimestamp queries at the start and end of the frame
Sync and present3.0 msWall time left after the overlapped CPU and GPU span, including the vsync wait
Budget16.67 ms1000 / 60

In that example the frame fits, with about 1.7 ms of headroom on the critical path. Cutting 2 ms from the CPU would not make the frame faster. Cutting 2 ms from the GPU would.

Attributing the three costs

CPU cost comes from timestamps on the main thread. I would time simulation, animation, culling and command buffer recording separately, because a single total tells you the CPU is slow but not which system to fix.

GPU cost comes from timestamp queries written into the command stream. One pair brackets the whole frame. Extra pairs bracket individual passes, such as shadow mapping, depth prepass and main lighting. In Vulkan this is vkCmdWriteTimestamp. In DirectX 12 it is a timestamp query heap. In Metal it is a counter sample buffer. The difference between two GPU timestamps is GPU time for that span, independent of what the CPU was doing.

Sync cost is what remains. It includes waiting for a fence or semaphore between queues, waiting for a copy to finish before a draw can start, and waiting in the present call for vsync. With vsync on, a frame whose GPU work finishes in 12 ms will still present on the next refresh boundary, so wall time can read 16.67 ms even though neither CPU nor GPU was busy for all of it.

A concrete trace shows the split:

CPU:  update 2.0 ms, cull 1.5 ms, record 4.5 ms, submit 1.0 ms = 9.0 ms
GPU:  shadow 2.5 ms, lighting 8.5 ms, post 1.0 ms              = 12.0 ms
Wall: first CPU timestamp to present complete                  = 16.5 ms

GPU is the limit at 12.0 ms. Sync and present account for roughly the remaining 4.5 ms of wall time. The fix is in lighting, not in culling.

The failure mode to avoid

Adding CPU and GPU times together is the common mistake. It makes a healthy frame look over budget and sends optimisation at the wrong processor. The other mistake is reading only wall time. A steady 16.67 ms wall time can mean GPU bound, CPU bound or vsync bound, and each needs a different change. Separate CPU timers, GPU timestamps and present timing tell you which one you have.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-62A 4K frame shows 96% GPU busy, 70% CPU and DRAM at 85% of peak, yet halving resolution saves only 12%. How do you disentangle CPU, GPU and bandwidth limits and prove which fix helps?

The 90-second answer

I would not trust any single counter here. 96% GPU busy, 70% CPU and DRAM at 85% of peak can all be true at once, and halving resolution saving only 12% does not clear the GPU. At 4K with dynamic resolution and temporal upscaling, resolution scaling is broken as a test, because the internal render size may already be moving, and because a pass can be waiting on memory while the SMs look busy. I need per-pass GPU timestamps, a locked internal resolution, and experiments that change one resource at a time while holding the others fixed.

First I freeze the variables that make the numbers lie. Vsync off, fixed camera and scene, dynamic resolution off, temporal upscaling off or locked to a fixed internal size, GPU clocks locked if the platform allows it. I record CPU time for the main thread and the render thread separately, GPU timestamps at the start and end of every pass, and the present interval. I take the median and p95 over 300 frames after warmup. If I cannot lock clocks, I log clock and temperature alongside, because a 15% clock drop during the test will look exactly like a bottleneck.

Reading the timeline, not the averages

GPU busy time summed over queues is not the same as GPU critical path. Async compute can overlap a copy or a compute pass with graphics, so the frame interval can be shorter than the sum of pass times, and a gap on the graphics queue can be filled by another queue. I build a timeline per queue and ask two questions. Is there idle time on every queue inside the frame interval, which points to the CPU starving the GPU. Or is at least one queue back to back from first timestamp to last, which points to the GPU. Then I look inside the busy passes.

C++
// One timestamp pair per pass. Resolve after the frame, convert with the
// queue timestamp period, and keep per-pass times, not just a frame total.
vkCmdWriteTimestamp(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, pool, i * 2);
// record pass i
vkCmdWriteTimestamp(cmd, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, pool, i * 2 + 1);
// gpuMs[i] = (end[i] - start[i]) * timestampPeriodNs / 1e6

A pass that is bandwidth-bound shows high DRAM throughput and low arithmetic throughput. A pass that is compute or fragment bound shows high SM throughput and DRAM well below peak. The profiler counters separate those, and the arithmetic below predicts which one you should see.

Exact working for the bandwidth claim

Take a hypothetical 4K frame, 3840 by 2160, with three RGBA16F G-buffer targets plus depth. One write of those targets moves 3840 x 2160 x 8 bytes x 3 = 199 MB, plus depth at 4 bytes per pixel, 33 MB. A lighting pass that reads all three and writes one RGBA16F output moves another 265 MB of reads and writes. At 60 fps, roughly 500 MB per frame is 30 GB/s before texture sampling, resolve and the back buffer. That alone does not saturate a 512 GB/s card. So if DRAM reads 85% of peak, about 435 GB/s, the traffic is not coming from the obvious target writes. Something else is moving bytes, usually texture fetches with poor locality, a resolve or blit chain, or a compute pass streaming through a large buffer. The calculation tells me to hunt for the hidden traffic instead of accepting the 85% number.

Arithmetic intensity makes the same point per pass. Intensity is flops divided by bytes moved. A simple lighting pass might do 20 flops per pixel while moving 32 bytes per pixel, intensity below 1. That pass will hit the bandwidth roof long before the compute roof on most discrete GPUs. A heavy BRDF pass at 200 flops per pixel over the same 32 bytes is compute bound. Same resolution, same pass, opposite limit, which is why I timestamp per pass.

Experiments that disentangle the three limits

Change, one at a timeCPU-bound resultFragment or compute boundBandwidth bound
Lock internal size, then halve itFrame time flat, GPU gaps unchangedBusy pass time falls close to pixel ratioBusy pass time falls, and DRAM GB/s falls with it
Replace fragment shader with a null output, same inputs and targetsFlatPass time collapsesPass time falls only by the compute part, traffic remains
Halve bytes per pixel, RGBA16F to RGBA8, same shader mathFlatSmall fallPass time falls close to the byte ratio
Halve triangle count, same pixels and targetsFalls only if CPU culling or submission cost dropsFalls if vertex bound, flat if fragment boundFlat unless vertex fetch was the traffic
Merge draw calls or instance, same triangles and pixelsFalls if submission was the costFlatFlat

The order matters. I run the null shader test before the resolution test, because with upscaling on, halving the output resolution may not halve the internal work at all. I run the format test before concluding bandwidth, because a pass can be DRAM heavy from reads, not writes, and changing the output format will not move it. Each run needs the same locked scene, and I compare per-pass times, not just frame time. A CPU-bound frame often shows no change in any GPU pass time and a change only in the gaps between passes.

Failure modes that produce this exact confusing picture

A present queue or swapchain limit can cap the frame interval and make a CPU-bound game look GPU-bound, with the GPU busy because it is waiting on the present, not on work. Checking the gap between the last GPU timestamp and the present call catches that. Timestamp queries themselves add overhead and can serialize a queue if placed badly, so I keep them at pass boundaries and compare a run with timestamps against one without. Driver time for state changes shows up on the CPU profile as if it were game code. If that time scales with draw calls or state changes, the fix is submission cost, not game logic. Finally, a single pass can be bandwidth-bound while the frame is compute-bound overall. Averaging over the frame hides it, which is why the per-pass table, not the frame average, decides where I spend the next week.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-63How would you test bit-packed vertex attributes using normalized and quantized formats, and what errors would you check for?

The 90-second answer

I would test the packer, the vertex format declaration, and the shader decode as three separate things, because a bug in any one of them looks like quantization error. Pack on the CPU with a reference encoder, upload a buffer containing known codes, draw one vertex per code, pass the attribute through unchanged as a varying, and compare the GPU result against the reference decoder. The tolerance is half a least significant bit of the destination format, not an arbitrary epsilon.

Assume a position or normal in [0,1] or [-1,1] stored as a normalized integer, and a packed 10-10-10-2 attribute. The reference decode for unsigned normalized is q / (2^n - 1). For signed normalized it is clamp(q / (2^(n-1) - 1), -1, 1), so the most negative code saturates to -1. Encoding is the inverse: round(clamp(v, min, max) * scale). If my CPU encoder and the GPU disagree at an endpoint, I have a scale or saturation bug, not a precision problem.

Worked trace

For R8_UNORM, scale is 255 and the step is 1/255 = 0.00392. Half a step, 0.00196, is the largest error a correct round trip may produce.

InputCodeDecodedError
0.000.00
0.25640.250980.00098
0.51280.501960.00196
1.02551.00
1.22551.0clamped

For R8_SNORM, scale is 127 and the step is 0.00787. Input -1.0 encodes to -127 and decodes to -1.0. Input 0.5 encodes to 64 and decodes to 0.50394. A test that expects 0.5 exactly will fail on a correct implementation, which is why the test compares against the decoded code, not the original float.

For a 10-10-10-2 pack, each colour or vector component gets 10 bits, which is 1024 codes with denominator 1023 and step 0.000978, and alpha gets 2 bits, which is 4 codes. That asymmetry is deliberate for a normal plus a 2-bit material id, and a poor choice for alpha gradients. The test should include the boundary codes 0, 1, 511, 512, 1022, 1023 per channel, because a shift error moves a whole channel into its neighbour.

Packing code and the test harness

C++
// Checked against Vulkan VK_FORMAT_A2B10G10R10_UNORM_PACK32.
// CPU reference only.
uint32_t pack_1010102(float x, float y, float z, uint8_t a) {
    auto q10 = [](float v) {
        float c = std::clamp(v, 0.0f, 1.0f);
        return uint32_t(std::lround(c * 1023.0f));
    };
    uint32_t q2 = uint32_t(std::clamp(a, 0, 3));
    return q10(x) | (q10(y) << 10) | (q10(z) << 20) | (q2 << 30);
}

The harness generates codes directly, not floats, for half the cases. It writes code 0x00000000, 0xFFFFFFFF, and a pattern where each channel differs (for example x=1023, y=0, z=512, a=2), uploads them as raw bytes, and checks the varying. Generating from floats alone can hide a channel swap, because symmetric inputs decode symmetrically. It also generates floats at k/1023 for every k in a coarse sweep, plus values halfway between codes, to confirm rounding goes to the nearest code.

Choosing a format, and when not to quantize

ChoiceBytes per vertex for position + normalStep at 1.0 rangePick it whenAvoid it when
float32 x624about 6e-8 relativeworld positions, HDR values, deforming meshesbandwidth bound static meshes
UNORM16 / SNORM16 x6121/65535 or 1/32767static meshes in a bounded local space, normalslarge world coordinates, where 1/32767 over 1000 m is 3 cm
10-10-10-2 for one vec3 + id41/1023normals or colours plus a small id, tight vertex fetchalpha needs more than 4 levels, or precision below 0.001 matters
R11F_G11F_B10F4float exponent, no integer stepHDR colour where range matters more than exact stepyou need a guaranteed half-LSB bound, subnormals and overflow differ by vendor

The size win is concrete: 1 million vertices with 3 position components drop from 12 MB as float32 to 6 MB as UNORM16, and a normal plus tangent pair drops from 24 MB as float32 to 12 MB as two SNORM16 vec3s. Quantizing world positions is the common mistake. A 16-bit normalized position over a 2000 m level has a step of about 3 cm, which shows as swimming on thin geometry. I keep world positions as float32 or store them relative to a chunk origin, and quantize only local positions and normals.

Where this breaks in practice

In OpenGL the normalized flag lives on the attribute pointer call, glVertexAttribPointer(..., GL_TRUE, ...). Forget it and the shader receives the raw integer as a float, so 128 arrives as 128.0 instead of 0.502. In Vulkan the format in VkVertexInputAttributeDescription carries the normalization, so the equivalent bug is picking R8_UINT instead of R8_UNORM. The test catches both because the pass-through varying will be off by the scale factor.

A second failure is double conversion. Normalized integer attributes already arrive in the shader as floats in [0,1] or [-1,1]. Dividing by 255 again in GLSL or HLSL is a common porting error from a CPU-side decode, and it compresses the range to near black. My shader test uses a pass-through vertex shader with no arithmetic, so any scaling in the result points at the declaration or the shader, not at lighting code.

A third failure is layout. A C++ struct of three uint8_t fields plus a uint8_t alpha is 4 bytes with no padding. Add a uint16_t id after them and the compiler inserts 1 byte of padding to align the uint16_t at offset 4, so sizeof is 6, not 5. If the GPU stride is set to the packed size 5 and the CPU stride is 6, every vertex after the first reads shifted bytes. The harness therefore uploads a buffer whose stride is set explicitly and checks vertex index 1 and 2, not just vertex 0. Vertex 0 passes even with a wrong stride.

Packed float formats such as R11F_G11F_B10F are not normalized integers. They have exponent bits and no fixed step, so I keep those out of the normalized-integer test and test them separately for overflow to infinity on HDR values above the maximum representable value, because clamping behaviour there differs between vendors.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-64How would you pack blend, depth and stencil state into a 32-bit word, and test the masks and stencil ops that decode it?

The 90-second answer

I would treat the packed word as a contract between the CPU that builds it and the GPU state that consumes it, and I would test the contract at the bit level before I test any pixels. Assume a 32-bit uint32_t on the CPU, little endian in memory, and a fixed layout that never changes after shipping because saved replays and networked clients may carry the word.

One layout I have used for a fixed-function style pipeline:

bit  31 30 29 28 27 26 25 24 | 23 22 21 20 19 18 17 16 | 15 14 13 12 11 10  9  8 |  7  6  5  4  3  2  1  0
     [ blend ][ depth ][stencil op][ stencil ref ][ write mask ][ flags ]
      4 bits   4 bits    4 bits       8 bits        8 bits       4 bits

Blend and depth are small enums, stencil op is the operation applied on pass, ref is the comparison value, write mask controls which stencil bits the op may change, and flags holds per-field enables such as DEPTH_TEST, STENCIL_TEST, WRITE_DEPTH and WRITE_STENCIL.

Packing and unpacking in C++17, checked against a reference implementation:

C++
#include <cstdint>
#include <cassert>

constexpr uint32_t BLEND_SHIFT   = 28;
constexpr uint32_t DEPTH_SHIFT   = 24;
constexpr uint32_t SOP_SHIFT     = 20;
constexpr uint32_t REF_SHIFT     = 12;
constexpr uint32_t WMASK_SHIFT   = 4;
constexpr uint32_t FIELD_MASK4   = 0xFu;
constexpr uint32_t FIELD_MASK8   = 0xFFu;

enum class BlendOp : uint32_t { Copy = 0, Alpha = 1, Additive = 2, Multiply = 3 };
enum class DepthFunc : uint32_t { Never = 0, Less = 1, Equal = 2, LessEqual = 3, Always = 4 };
enum class StencilOp : uint32_t { Keep = 0, Zero = 1, Replace = 2, IncrWrap = 3,
                                  IncrSat = 4, DecrWrap = 5, DecrSat = 6, Invert = 7 };

uint32_t pack(BlendOp b, DepthFunc d, StencilOp s, uint8_t ref, uint8_t wmask, uint8_t flags) {
    return (static_cast<uint32_t>(b) & FIELD_MASK4) << BLEND_SHIFT
         | (static_cast<uint32_t>(d) & FIELD_MASK4) << DEPTH_SHIFT
         | (static_cast<uint32_t>(s) & FIELD_MASK4) << SOP_SHIFT
         | (static_cast<uint32_t>(ref) & FIELD_MASK8) << REF_SHIFT
         | (static_cast<uint32_t>(wmask) & FIELD_MASK8) << WMASK_SHIFT
         | (static_cast<uint32_t>(flags) & FIELD_MASK4);
}

BlendOp blendOf(uint32_t w) { return static_cast<BlendOp>((w >> BLEND_SHIFT) & FIELD_MASK4); }
uint8_t refOf(uint32_t w)   { return static_cast<uint8_t>((w >> REF_SHIFT) & FIELD_MASK8); }

The masks do two jobs. They stop a caller passing an out of range enum from bleeding into the neighbouring field, and they make the test independent of the enum values the compiler happens to assign. I would add a static_assert that the largest enum value fits in 4 bits, so adding a ninth stencil op fails at compile time instead of silently truncating on the GPU.

Worked trace

Pack Alpha, LessEqual, IncrSat, ref = 0xA5, wmask = 0xFF, flags = 0b1011:

FieldValueBits in word
blend10001 at 28
depth30011 at 24
stencil op40100 at 20
ref0xA510100101 at 12
write mask0xFF11111111 at 4
flags0xB1011 at 0

Result: 0x134A5FFB. Decoding reverses it exactly: (0x134A5FFB >> 28) & 0xF = 1, (0x134A5FFB >> 12) & 0xFF = 0xA5. A round trip test over every enum combination, 4 x 5 x 8 = 160 cases, plus boundary refs 0x00 and 0xFF, catches a shifted field in seconds. I would also test that setting a flag bit does not change the decoded blend value, which catches overlapping masks.

Stencil ops and the two masks people confuse

Stencil has a read mask and a write mask, and they are not interchangeable. The comparison uses (ref & readMask) == (stored & readMask). The update then writes (newValue & writeMask) | (stored & ~writeMask). If I want a portal that increments only the low nibble, I set writeMask = 0x0F and leave the high nibble untouched even when the op is Replace.

OpEffect on stored valueTypical use
Keepunchangedread only test
Zero0clear region
Replacerefmark region
IncrWrap+1 mod 256counting, wraps 255 to 0
IncrSat+1 saturating at 255counting, stops at 255
DecrWrap-1 mod 256counting down
DecrSat-1 saturating at 0counting down
Invertbitwise NOTtoggle bits

The wrap versus saturate choice is a real bug source. A counter that must never exceed 3 for a 2-bit field needs saturate, because wrap would jump from 3 to 0 and reopen a door that should stay closed. I test both at the boundary: stored 255 with IncrWrap gives 0, with IncrSat gives 255. I run the same pair at 0 for the decrement ops.

Failure modes I check for

Signed shifts. Shifting a signed int that has its top bit set is undefined behaviour in C++ before C++20 and implementation defined in practice, so every shift here is on uint32_t. A test with blend value 8 or higher, which sets bit 31, exposes this immediately.

Enum order drift between CPU and GPU. If the shader or the driver side table lists IncrSat and DecrWrap in a different order, the packed word decodes to the wrong op and the picture still renders, just wrong. I keep one shared header or a generated table and a test that prints the numeric value of each enum so a reorder shows up in review.

Mask mismatch on read versus write. Setting the write mask to 0xFF when the design intended 0x0F will overwrite bits owned by another system sharing the same stencil buffer, for example a decal pass writing the high nibble while a portal pass owns the low nibble. The test writes a sentinel 0xF0 into the high nibble, runs the op, and asserts the sentinel survives.

Shift width errors. A shift of 32 or more on a 32-bit value is undefined. Packing code that computes the shift from a field index needs an assert that the shift stays below 32, and the boundary test with the top field at shift 28 covers the realistic case.

When the state grows past 32 bits, for example separate front and back stencil ops as in OpenGL and Vulkan, I would move to a 64-bit word or two 32-bit words rather than squeezing fields and losing the spare bits that make the layout readable in a debugger.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-65What goes wrong with half-float precision, denormals, and cancellation when you do math in a fragment shader, and how do you avoid it?

The 90-second answer

Half float has only 10 mantissa bits, so it keeps about three decimal digits. Denormals sit below the smallest normal and lose bits as they get smaller, and many GPUs flush them to zero. Cancellation happens when you subtract two nearly equal numbers: the leading digits cancel, the remaining digits are mostly rounding error, and relative error explodes. In a shader the practical rule is to keep positions, world offsets, and accumulation in fp32, and use fp16 only for storage or for values that are small, bounded, and do not need subtraction.

The formats, with real limits

FormatSign / exponent / mantissaEpsilon at 1.0Max finiteSmallest normal
fp161 / 5 / 100.0009765625655040.00006103515625
fp321 / 8 / 230.000000119209293.4028235e381.17549435e-38

Epsilon here means the gap between 1.0 and the next representable value. In fp16, 1.0 + 0.0004 rounds back to 1.0, because it is less than half the gap of 0.0009765625. Adding 0.0005 rounds up to 1.00097656. In fp32 you need a change near 6e-8 before that happens. That gap is why a world position of 10,000.0 stored as fp16 cannot represent a 0.01 offset. The spacing at 8192 to 16384 is 8.0, so the offset vanishes entirely.

Denormals fill the range below the smallest normal. For fp16 that range is roughly 5.96e-8 to 6.10e-5. Each step down loses one bit of precision, so a denormal near the bottom may carry only one or two useful bits. Some hardware flushes denormals to zero, which is fast but creates a hard cliff: a value of 0.00007 survives and 0.00005 becomes zero. Other hardware handles them in slow software paths. Either behaviour is a problem if a lighting term, a fade, or a normal component is expected to decay smoothly through that range.

Cancellation, worked through

Take a = 100000.0f and b = 99999.99f in fp32. The true difference is 0.01. Each input was already rounded to a multiple of about 0.0078125 at that magnitude, so the stored values can be off by several thousandths before you subtract. The subtraction itself is exact in this case, but it exposes the error that was hidden in the low bits. Relative error on the result can be tens of percent.

The same effect hits common shader code:

GLSL
// Fragile: large world position, small local offset
vec3 worldPos = modelPos + instanceOffset; // both large, difference later
vec3 delta = worldPos - cameraPos;         // cancellation if camera is nearby

// Safer: keep the small quantity small
vec3 localDelta = localPos - cameraLocalPos;
vec3 delta32 = localDelta; // fp32, computed before any large translation

A second classic case is a dot product or sum where large positive and negative terms cancel, such as accumulating signed lighting contributions or computing variance as E[x*x] - E[x]*E[x]. When the mean is large and the variance is small, the two terms are nearly equal and the result is mostly noise. Accumulate in fp32, or subtract the mean first.

What I would do in practice

Keep vertex positions, instance transforms, and any a - b where a and b are close in fp32. Use fp16 for texture storage, colour buffers, and packed attributes where the range is known and the consumer tolerates three digits. Add a small epsilon before normalising a vector that might be near zero, and clamp denormal-prone terms such as exp(-x) results or tiny specular contributions instead of letting them decay into the denormal range. If a result flickers or pops at a threshold, check whether values are crossing the fp16 smallest normal or being flushed to zero, and check whether a large translation was applied before a small difference was taken.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-66With 64 correlated samples (rho = 0.2, variance 4) reused across frames and a heavy-tailed bright light, how do you compute effective sample size and true standard error, and choose between raising spp, MIS, and clamping within a 16 ms frame budget?

The 90-second answer

Do not quote sqrt(4/64) = 0.25. That assumes independent samples with finite variance. With equicorrelated samples at rho = 0.2, the variance of the mean is sigma^2/N times (1 + (N-1)rho). For N = 64 and sigma^2 = 4, that factor is 13.6, so Var(mean) = 0.85 and the true standard error is 0.92. Effective sample size is only 4.7. Raising spp to 256 under the same correlation gives an effective sample size of 4.9, so it buys almost nothing and blows the frame budget. Fix correlation and the heavy tail first, then spend samples.

Effective sample size under correlation

For samples with common variance sigma^2 and common pairwise correlation rho, Var(Xbar) = (sigma^2/N) [1 + (N-1)rho]. Define ESS = N / [1 + (N-1)rho], so Var(Xbar) = sigma^2 / ESS. As N grows with rho fixed, ESS approaches 1/rho. That ceiling is the trap in temporal reuse: reusing random numbers across frames, or reusing one direction set across pixels in a tile, creates correlation that no amount of extra spp inside the same correlated block removes.

ConfigurationNrhosigma^2ESSSE = sqrt(sigma^2/ESS)
Nominal independent case6404640.25
Reused sequence, current640.2044.70.92
Same reuse, 4x spp2560.2044.90.90
Decorrelated, rho = 0.05640.05415.40.51
Decorrelated plus MIS, sigma^2 = 1640.05115.40.25
Python
import math

def se_corr(var, n, rho):
    ess = n / (1 + (n - 1) * rho)
    return ess, math.sqrt(var / ess)

print(se_corr(4, 64, 0.20))   # (4.71, 0.922)
print(se_corr(4, 256, 0.20))  # (4.92, 0.902)
print(se_corr(1, 64, 0.05))   # (15.42, 0.255)

Checked against Python 3.12. The middle line is the decision point. At 64 spp costing 8 ms in your hypothetical profile, 256 spp costs about 32 ms and exceeds a 16 ms frame budget, while SE moves from 0.92 to 0.90. The budget constraint and the correlation constraint interact: spp is the expensive lever and, under reuse, the weakest one.

Why the fireflies survive averaging

Correlation explains stalled temporal accumulation. A heavy tail explains fireflies. Suppose a small bright light is hit with probability 0.001 per sample and contributes weight 1000 when hit. Its contribution to the true mean is 1.0, but in 64 samples you usually miss it entirely and occasionally one pixel gets a value near 1000/64 = 15.6 above the mean. The sample variance computed from a block that missed the light is small, so a per-pixel SE estimate looks calm precisely where the estimator is most wrong. The central limit theorem still holds eventually, but at N = 64 the distribution of the mean is skewed and a mean plus or minus 1.96 SE interval undercovers badly.

Multiple importance sampling attacks the tail directly. If a second strategy, such as sampling the light itself, covers the region where the first pdf is near zero, the combined pdf p = alpha p1 + (1-alpha) p2 stays bounded away from zero where the integrand is large. Weights f/p then stop exploding. In the table above, that is modelled as sigma^2 falling from 4 to 1. MIS also tends to decorrelate strategies because different pixels pick different dominant strategies, which is why rho falls in the example. The cost is real: evaluating both pdfs and the MIS weights adds roughly 10 to 20 percent per sample in a typical direct lighting kernel, far cheaper than quadrupling spp.

Clamping trades variance for bias, and you must price both

Clamping a weight at C caps the firefly but biases every pixel whose true weight exceeds C. Mean squared error is Var(clamped estimator) + bias^2, and only that sum decides whether clamping helps. Using the numbers above, clamping at 50 instead of 1000 changes the light contribution from 1.0 to 0.05, a bias of -0.95. Even if clamped variance drops to near zero, MSE is at least 0.90, worse than the decorrelated MIS case at 0.065. Clamping at a higher threshold, or clamping only the direct light contribution while leaving indirect paths alone, can win, but a global clamp chosen to make the image look clean usually just moves error from visible noise into systematic darkening of highlights. Detect it by comparing clamped and unclamped means over a test scene with a known bright source, not by eyeballing one frame.

What I would do in order

First, break correlation: reseed per frame and per pixel from a counter-based generator, and stop sharing one direction set across a tile. Measure rho from the lag-1 autocorrelation of pixel values across frames on a static scene; if it is near 0.2, ESS is the number to report. Second, add MIS for the light that produces the tail, and verify with a variance trace: plot per-pixel sample variance before and after on a log scale, since a drop in mean variance alone can hide a few pixels whose variance exploded. Third, only then raise spp, and size it from ESS, not N. To reach SE = 0.25 with sigma^2 = 1 and rho = 0.05 you need ESS = 16, which the MIS row already gives at 64 spp. If rho were still 0.2, reaching ESS = 16 would be impossible at any N, because the ceiling is 5. That impossibility result is what separates a senior answer from plugging numbers into sqrt(sigma^2/N).

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-67For direct lighting from a small area light at 64 samples per pixel, how do stratified and low-discrepancy sampling reduce variance versus random Monte Carlo, and when would you pick one over the other?

The 90-second answer

For direct lighting at a fixed 64 samples per pixel, random Monte Carlo, stratified sampling and low-discrepancy sampling all estimate the same integral. They differ in how evenly the samples cover the domain, here the pixel and the area light. Random points clump and leave gaps. Stratified sampling forces one jittered sample into each cell of a regular grid. A low-discrepancy sequence such as Sobol or Halton fills the domain evenly by construction, without a grid. Both remove variance that random sampling wastes on clumps, and both keep the estimator unbiased as long as the jitter or scramble is random.

I would pick stratified sampling as the default for direct lighting. It is simple, it works at any sample count, and it degrades gracefully. I would pick Sobol when the integrand is smooth and the sample count is low, because it covers the domain more evenly than a coarse grid at 16 to 128 samples. I would not expect either to fix a discontinuous integrand, such as light through slats, where the variance comes from visibility rather than coverage.

Mechanism

Stratified sampling splits each dimension into $N$ strata. In 1D with $N=8$, sample $i$ is drawn uniformly from $[i/8, (i+1)/8)$. Every eighth of the domain gets exactly one sample. If the integrand is roughly constant inside a stratum, the within-stratum variance is small, so the total variance drops. The jitter matters. Without jitter, a regular grid can alias with periodic geometry, for example slats spaced the same as the strata.

A low-discrepancy sequence takes a different route. Halton uses radical inverse in different prime bases per dimension. Sobol uses binary van der Corput sequences with direction numbers. The result is that for $N=64$, any aligned block of 64 points covers the domain evenly, and projections onto any subset of dimensions also stay even. That property is called low discrepancy. It beats a grid in higher dimensions because a grid needs $N^d$ cells, while a sequence keeps filling space as $N$ grows.

Worked trace

Hypothetical figures, labelled as such, for one pixel lit by a small area light, MSE against a 16384 spp reference:

Sampler16 spp64 spp256 spp
Random Monte Carlo0.0840.0210.0053
Stratified 8x8 over pixel and light0.0310.00780.0020
Sobol, scrambled0.0190.00470.0013

Random MSE falls by about 4x when samples quadruple, which matches the $1/N$ variance law. Stratified and Sobol sit roughly 3x and 4x below random at every count. That constant factor is the signature of better coverage on a smooth integrand. If Sobol stopped improving after 64 spp, I would check for correlation between dimensions or a discontinuity the sequence cannot represent.

Python
# Python 3.11, NumPy 1.26. Coverage check in 1D at N=64.
import numpy as np

def stratified(n, rng):
    return (np.arange(n) + rng.random(n)) / n

def halton(n, base):
    out = np.zeros(n)
    for i in range(n):
        f, x, j = 1.0, i, 0.0
        while x > 0:
            f /= base
            j += f * (x % base)
            x //= base
        out[i] = j
    return out

rng = np.random.default_rng(0)
for name, s in [("random", rng.random(64)), ("stratified", stratified(64, rng)), ("halton2", halton(64, 2))]:
    hist, _ = np.histogram(s, bins=8, range=(0, 1))
    print(name, hist)

Stratified gives exactly 8 samples per bin. Halton is near even. Random shows empty and double bins. In the renderer I repeat this check on an $8 \times 8$ grid over the light at 64 spp. Empty cells become dark patches, double cells become bright patches.

Trade-offs and failure modes

Stratified sampling is limited by dimension. Stratifying pixel $x$, pixel $y$, light $u$ and light $v$ at 4 samples per dimension already needs 256 samples. Beyond that, people stratify only the dimensions that matter, usually the light, and sample the rest randomly. It also gains little when the integrand changes sharply inside one stratum. A caustic or a slat edge inside a stratum still contributes full variance.

Low-discrepancy sequences have two practical traps. Sobol balance properties hold at powers of two, so I test 63, 64 and 65 spp and look for a jump in MSE. Halton dimensions above about 8 correlate with each other because the prime bases produce similar patterns, which shows up as diagonal banding in a glossy lobe. Scrambling the sequence, for example Owen scrambling for Sobol, restores randomness between frames and keeps the estimator unbiased in a temporal accumulation.

Blue noise is a separate choice. It does not lower MSE the way stratification does. It shapes the error into high spatial frequencies so a denoiser or the eye tolerates it. At 64 spp offline I would not choose it for variance reduction. At 2 to 4 spp in a real-time renderer with temporal accumulation, I would.

So for the stated case, direct lighting at 64 spp, I would ship stratified sampling over the light and pixel, measure MSE against a high spp reference, and switch to scrambled Sobol only if the measured MSE and the convergence slope justify the extra complexity.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-68For 50,000 particles that interact within 0.5 m, how would you size a uniform grid cell, and how does a spatial hash change the memory cost?

The 90-second answer

Size the cell to the interaction radius. If two particles can only interact when they are within r of each other, a cell of size r guarantees every neighbor sits in the same cell or one of the 26 adjacent cells in 3D. You then test 27 cells per particle instead of every other particle.

That one choice sets both costs. Make the cell smaller and you must search more cells to cover distance r, or you miss pairs. Make it larger and each cell holds more candidates, so you waste time on distance tests that fail.

Worked example, with hypothetical figures: 50,000 particles in a 50 m cube, r = 0.5 m. Cell size 0.5 m gives 100 cells per axis, or 1,000,000 cells. A uniform grid stores a head index per cell, 4 bytes each, so 4 MB for the grid plus the particle list. Average occupancy is 0.05 particles per cell, so most of the 27 cells checked are empty. That is the price of a dense grid: memory follows domain volume, not particle count.

A spatial hash keeps the same cell size and 27-cell search, but stores only occupied cells in a hash table. In this example it might hold 40,000 occupied cells instead of 1,000,000, so it uses less memory here. The cost is a hash and a chain walk per cell lookup, plus collisions when two different cells land in the same bucket.

C++
// cell size = r, invCell = 1.0f / r
int cx = int(floor(p.x * invCell));
int cy = int(floor(p.y * invCell));
int cz = int(floor(p.z * invCell));
// uniform grid: index = (cz * ny + cy) * nx + cx, direct array access
// spatial hash: bucket = hash(cx, cy, cz) & mask, then walk the chain
for (int dz = -1; dz <= 1; ++dz)
  for (int dy = -1; dy <= 1; ++dy)
    for (int dx = -1; dx <= 1; ++dx) {
      for (int j : cell(cx+dx, cy+dy, cz+dz))
        if (j > i && dist2(p[i], p[j]) < r*r) addPair(i, j);
    }

Trace: a particle in cell (10, 20, 30) visits 27 cells. If each occupied cell holds about 1 particle on average, that is roughly 27 distance tests. Brute force would be 49,999 tests for the same particle.

Uniform gridSpatial hash
MemoryFixed by domain: nx * ny * nz cellsOnly occupied cells
LookupDirect index, no collisionsHash plus chain walk
Best fitBounded, fairly uniform volumeSparse or open world, particles in part of the volume

Where it breaks

Clustering. If 2,000 particles pile into one cell, that cell alone needs about 2 million pair tests, and the particles in it dominate the frame while others finish early. I check this by recording the maximum particles per cell each frame. A spike there, not average occupancy, predicts the slow frame.

I would test correctness against brute force on a small scene, 2,000 particles, and confirm the pair list matches exactly. Then I would run the full scene and track candidate tests per particle. If that number climbs while the true neighbor count stays flat, the cell is too large or particles have clustered. Shrinking the cell is not the fix, because then a neighbor at distance r can sit two cells away and the 27-cell search misses it. The fix is to handle the cluster separately, for example by capping particles per cell or splitting the effect that creates the pile.

For a bounded simulation volume with roughly even spread, I would start with the uniform grid for its simple lookup. For an open world where particles occupy a small fraction of the space, I would use the hash and accept the extra lookup cost to avoid allocating millions of empty cells.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-69What condition must two AABBs satisfy on the x, y and z axes for them to overlap?

The 90-second answer

Two AABBs overlap only when their intervals overlap on every axis. If they are separated on any one axis, they cannot be touching in 3D.

An AABB stores a minimum corner and a maximum corner. On the x axis, the intervals [a.min.x, a.max.x] and [b.min.x, b.max.x] overlap when a.min.x <= b.max.x and b.min.x <= a.max.x. Apply the same check on y and on z. All three checks must pass.

C++
struct Aabb { Vec3 min, max; };

bool overlaps(const Aabb& a, const Aabb& b) {
    return a.min.x <= b.max.x && b.min.x <= a.max.x &&
           a.min.y <= b.max.y && b.min.y <= a.max.y &&
           a.min.z <= b.max.z && b.min.z <= a.max.z;
}

That is the broadphase test used for dynamic objects. It is cheap, six comparisons, and it has no false negatives. If the boxes do not overlap, the objects cannot collide. If the boxes do overlap, the objects might collide, so the pair goes to a more precise narrowphase test.

Worked trace

Box A: min (0, 0, 0), max (2, 2, 2) Box B: min (1, 1, 1), max (3, 3, 3) Box C: min (3, 0, 0), max (4, 2, 2)

A against B: x intervals [0, 2] and [1, 3] overlap, y intervals [0, 2] and [1, 3] overlap, z intervals [0, 2] and [1, 3] overlap. All three pass, so the boxes overlap.

A against C: x intervals [0, 2] and [3, 4] do not overlap, because 3 <= 2 is false. One failed axis is enough, so the boxes do not overlap, even though y and z do overlap.

Pairx overlapy overlapz overlapResult
A, Byesyesyesoverlap
A, Cnoyesyesno overlap

Sweep-and-prune uses this same rule to cull pairs. It sorts box endpoints on one axis and only tests pairs whose intervals overlap on that axis. The full three-axis check above then confirms or rejects each candidate.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-70Walk me through when an octree is the right choice for sparse spatial data, and when a uniform grid or BVH would beat it?

The 90-second answer

An octree wins when the data is sparse, clustered, and queried hierarchically, and loses when the data is dense and uniform or when the primitives vary wildly in size. I would not pick it from the name. I would pick it from three numbers: occupancy, query type, and update pattern.

Assume a static or slowly changing set of points, particles, or small boxes in a bounded cube, with queries like "all points in this sphere" or "nearest neighbour within r". An octree subdivides only occupied cells, so memory scales with occupied nodes, roughly O(N log range) in the worst case and closer to O(N) for well spread data, and a query descends only the branches it touches. A uniform grid pays for the whole volume whether it is occupied or not. A BVH pays for grouping primitives by surface area, which is wasted work if your primitives are points and your queries are volumetric.

A worked trace

Take a unit cube, max depth 3, split at the midpoint on each axis. Insert point p = (0.73, 0.12, 0.55).

C++
int childIndex(Vec3 p, Vec3 centre) {
    return (p.x > centre.x ? 1 : 0)
         | (p.y > centre.y ? 2 : 0)
         | (p.z > centre.z ? 4 : 0);
}

Depth 1: centre (0.5, 0.5, 0.5), p is right, below, above, so child 1 | 0 | 4 = 5. Depth 2: that child's centre is (0.75, 0.25, 0.75), p is left, below, below, so child 0. Depth 3: centre (0.625, 0.125, 0.625), p is right, below, below, so child 1. Path 5, 0, 1. A sphere query centred at (0.7, 0.2, 0.6) with radius 0.2 visits the root, child 5, and only the subcells whose AABBs intersect the sphere. It never touches the other seven root children. That pruning is the whole point, and it only pays if most of those children are empty.

The arithmetic that decides it

Labelled hypothetical, but the shape is what matters. One million points in a 1024 cubed volume, queries every frame.

StructureMemory before payloadLookupFailure mode
Uniform grid, 256 cubed cells16.7M cells. At 4 bytes per head pointer, 67 MB, plus cell listsO(1) cell from a multiply and floorEmpty volume dominates. At 512 cubed it is 134M heads, 536 MB, before any point is stored
Octree, max depth 10, leaf capacity 8Nodes only where points exist. For clustered data, often 100k to 300k nodes. At 32 bytes per node, 3 to 10 MBO(depth) descent, pointer chasing per levelPathological clustering forces deep chains, see below
BVH over points or small boxes2N nodes for N leaves. For 1M leaves, about 2M nodes. At 32 bytes, 64 MBO(log N) average, but traversal visits nodes in SAH order, not spatial orderBuild cost and refit cost on updates. Overkill if queries are pure range counts

The grid number is why sparse matters. If your points fill 30% of a 256 cubed grid, the grid is fine and faster, because one multiply replaces ten pointer hops and the cell array is cache friendly. If they fill 0.1%, the grid is paying 67 MB to store mostly nothing, and the octree is paying a few MB.

When I would not use an octree

Uniform grid: dense, roughly uniform distribution, fixed world bounds, and a hard latency budget on GPU or in a hot loop. Cell lookup is branchless and vectorisable. Particle neighbour search on a regular emitter volume is the classic case. If I can afford the head array and occupancy is above roughly 10 to 20%, the grid usually beats the octree on both speed and simplicity.

BVH: primitives are triangles or large boxes of very different sizes, or the query is a ray. An octree splits space, so a long thin triangle crossing many cells gets inserted into many leaves or forces deep subdivision around its extent. A BVH splits the primitive set by surface area heuristic, so a big triangle and a small one each get a tight node. That is why BVHs dominate ray tracing and why octrees dominate point and voxel work. The same argument applies to dynamic scenes where I need to refit bounds bottom up rather than reinsert points into a hierarchy.

Failure modes I check in tests

Clustered points at one location. Ten thousand points within a 1 cm cube inside a 1 km world force subdivision to max depth along a single path, and every query in that cluster walks the full depth. I cap depth, set a leaf capacity, and store a small vector in the leaf instead of subdividing forever. I also test the degenerate case where all points share the same coordinates, which breaks naive midpoint splits if I use strict greater than on one side only.

Loose versus tight bounds. A tight octree stores the exact cell AABB, so a sphere query must test cell intersection correctly at boundaries. A loose octree inflates each cell by a factor of two so an object fits in one node regardless of where it crosses a boundary, which simplifies insertion of moving objects but makes queries visit more nodes. I pick loose only when objects move every frame and reinsertion cost dominates.

Updates. Deleting from a tight octree leaves empty internal nodes that queries still visit. I prune empty nodes on delete, or I rebuild periodically if deletions are bursty. If more than about 20% of the set moves per frame, I stop maintaining the octree incrementally and either rebuild it or switch to a grid with a swap buffer.

On the GPU I would avoid a pointer based octree entirely. Pointer chasing across 32 byte nodes kills coalescing. I would use a linear octree encoded with Morton codes, sort the codes, and binary search, or I would use a dense grid. That constraint alone flips the choice for most GPU particle systems.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-71How would you test a binary heap and priority queue for transparency sorting, BVH builds and nearest-light queries?

The 90-second answer

I test the heap against its contract, not against a few hand-picked pops. The contract is: pop returns the element with the highest priority, ties go to the earliest inserted element, and after every push or pop every parent is no greater than its children for a min-heap, or no smaller for a max-heap. I run thousands of random pushes, pops and updates against a sorted list that implements the same rule in the simplest possible way. A mismatch is a bug in one of them, and the list is small enough to read.

A binary heap keeps a complete tree in an array. With 0-based indexing the children of i are 2*i+1 and 2*i+2, and the parent is (i-1)//2. Push appends at the end and sifts up. Pop removes the root, moves the last element there, and sifts down. Each sift moves at most the height of the tree, so both operations are O(log n) and building a heap from an array is O(n) with heapify.

Python
import heapq, random

def test_against_reference(seed=42, ops=5000):
    rng = random.Random(seed)
    heap = []   # entries are (-priority, seq, payload): min-heap, highest priority first
    ref = []    # entries are (priority, seq, payload)
    seq = 0
    for _ in range(ops):
        if ref and rng.random() < 0.4:
            got = heapq.heappop(heap)
            want = min(ref, key=lambda x: (-x[0], x[1]))
            ref.remove(want)
            assert (-got[0], got[1], got[2]) == (want[0], want[1], want[2])
        else:
            p = rng.randint(0, 20)  # narrow range forces frequent ties
            heapq.heappush(heap, (-p, seq, f"obj{seq}"))
            ref.append((p, seq, f"obj{seq}"))
            seq += 1
        for i in range(1, len(heap)):
            assert heap[(i - 1) // 2] <= heap[i]  # min-heap invariant

The reference uses the same ordering key as the heap, (-priority, seq), so there is no second interpretation of the tie rule to drift apart. The narrow priority range is deliberate. If every priority were unique, the seq field would never be compared and a broken tie-break would never be exercised. With values from 0 to 20 and 5,000 operations, ties happen constantly and the assertion checks them.

How each use case stresses the heap differently

UseHeap contentsPriorityFailure the test must catch
Transparency sortOne entry per transparent objectView depth, larger firstTwo objects at equal depth swapping order between frames
BVH buildOne entry per unsplit nodeEstimated split cost, larger firstA stale entry for a node that was already split being popped again
Nearest lightsAt most k entriesSquared distance, larger on topThe wrong light evicted when the k-th and (k+1)-th distances are equal

For transparency, push (depth, seq, id) for each object and pop into draw order. Trace: insert A at depth 2.0, B at 5.0, C at 5.0, D at 1.0, with seq 0, 1, 2, 3. The heap keys are (-2.0, 0), (-5.0, 1), (-5.0, 2), (-1.0, 3). Pops give B, then C, then A, then D. B before C is not luck, it is the seq rule, and it stays the same every frame as long as insertion order is stable. I also push a NaN depth. Comparisons with NaN are always false, so a NaN entry can sit anywhere in the array and corrupt the invariant without tripping the parent check in a way that points at the cause. The test expects NaN to be rejected at push time, or mapped to a defined rank before it reaches the heap.

For BVH construction the queue holds nodes awaiting a split, ordered by the cost reduction a split would give. When a node is split, its entry is dead and two child entries replace it. A plain heap has no decrease-key and no delete, so implementations either rebuild or use lazy deletion: each entry carries a node version, and on pop the test checks that the version still matches the node. Without that check the same high-cost node can be popped twice, split twice, and the loop spends all its time refining one leaf while other leaves never split. I count splits per node in the test and fail if any node is split more than once.

For nearest lights I keep a max-heap capped at k. Squared distance preserves ordering and avoids a square root per light. If the heap is full and a new light is closer than the heap top, pop the top and push the new one, which is O(n log k) for n lights instead of O(n log n) for a full sort. With 2,000 lights and k = 8, that is about 2,000 times 3 sift steps instead of sorting 2,000 entries. The test compares the final contents with the 8 smallest distances from the reference, including a case where the 8th and 9th lights are equidistant. The tie rule, keep the lower light id, must be written identically in the heap key and the reference key, or the test fails on a case that is actually correct under one rule and wrong under the other.

Edge cases and the complexity check

Pop on an empty heap must raise or return empty, never read index 0. One element, push then pop. Growth past a power of two, which catches an off-by-one in the parent formula. A million operations against the reference, which catches corruption that small runs miss. For timing, n pushes cost O(n log n) in total, so doubling n from 100,000 to 200,000 should multiply the time by about 2 * log(200000) / log(100000), roughly 2.1, not 4. A ratio near 4 means something is sorting or rescanning on every push. The bug I see most often is a comparator built on float equality with an epsilon, which is not a strict weak ordering. Replacing it with a total order, priority first and a unique seq second, makes the invariant well defined and the tests deterministic.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-72Walk me through how dirty flags propagate world matrices through a scene graph, and how you would test that a moved parent updates only its subtree?

The 90-second answer

Each node stores a local transform, usually built from translation, rotation and scale, and a world transform. The invariant is world = parentWorld * local, with the root using identity as its parent. A dirty flag means the cached world may be stale. Changing a local transform marks that node and every descendant dirty. A single top-down traversal then recomputes only dirty nodes, parents before children, and clears each flag after use.

C++
struct Node {
    Mat4 local, world;
    bool dirty = true;
    std::vector<std::unique_ptr<Node>> children;

    void setLocal(const Mat4& m) {
        local = m;
        markDirty();
    }
    void markDirty() {
        if (dirty) return; // subtree already marked
        dirty = true;
        for (auto& c : children) c->markDirty();
    }
    void update(const Mat4& parentWorld) {
        if (dirty) {
            world = parentWorld * local;
            dirty = false;
        }
        for (auto& c : children) c->update(world);
    }
};

The early return in markDirty matters. Without it, moving a parent with 5,000 descendants after its children were already marked would walk the subtree twice. With it, repeated edits in one frame cost one walk.

Worked trace

Scene: Root -> A -> B, and Root -> C. A has local translation (10,0,0). B has local translation (0,5,0). C has local translation (0,0,7). After the first update(identity), all worlds are correct and all flags are clear.

Now call A.setLocal(translation(20,0,0)). That marks A and B dirty. C stays clean. The next update visits Root (clean, no multiply), then A (dirty, one multiply: identity * T(20,0,0)), then B (dirty, one multiply: A.world * T(0,5,0) giving world position (20,5,0)), then C (clean, skipped). Two matrix multiplies instead of four, and the result matches a full recompute.

StrategyCost when one leaf movesCost when root movesRisk
Recompute all every frameN multipliesN multipliesSimple, wastes work on static scenes
Eager dirty propagation, as aboveO(subtree) to mark, O(subtree) to updateO(N)Flag bugs leave stale worlds
Lazy pull on readO(1) to mark, O(depth) on first readO(depth) per readReaders must all go through the accessor

For N = 10,000 nodes, a full recompute is 10,000 matrix multiplies per frame, about 640,000 scalar multiplies at 64 per multiply. Moving one leaf with a subtree of 3 nodes costs 3. That gap is why large static levels keep dirty flags even though the code looks trivial.

How I test it

I build a deterministic scene in code, no assets: a chain of 100 nodes, a wide root with 1,000 leaf children, and a branching subtree. Then I run three checks.

  1. Reference comparison. After every random edit (move, reparent, scale), I recompute every world by brute force from the root with no flags and compare element by element against the flagged traversal. Any mismatch is a propagation bug. I use a fixed seed so failures reproduce.
  2. Work counting. I instrument the multiply with a counter. Moving a leaf must multiply only its subtree. Moving the root must multiply all N. If the counter says otherwise, a flag is being cleared early or set late.
  3. Order check. I assert that a child never reads a parent world computed in a previous frame. The traversal must be depth-first, parent before child. A breadth-first or parallel update that lets children run before parents breaks this, and the reference comparison catches it as a one-frame lag.

Failure modes I have seen

Clearing the flag in setLocal instead of in update leaves children stale when the parent is edited twice before a render. Forgetting to mark descendants on reparenting leaves the moved subtree with its old parent's world baked in. A cycle in the graph, A parent of B and B parent of A, makes both markDirty and update recurse forever, so the test scene includes a cycle check that expects an error rather than a hang. The subtler one is reading world for frustum culling or skinning before update has run that frame. The matrix looks plausible and is simply one edit behind, which shows up as a character's hitbox lagging its mesh by a frame. The fix is a single update pass at the top of frame preparation, before any consumer reads a world matrix, and the test asserts that no read happens with a dirty flag still set.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-73How many comparisons does binary search need in the worst case on n sorted items, and why does sorted order make that possible?

The 90-second answer

Binary search needs at most ceil(log2(n + 1)) comparisons on n sorted items. Sorted order is what makes that possible. Each comparison tells you whether the target is in the left half or the right half, so you discard half of the remaining items every step. For 1,000,000 items that is 20 comparisons in the worst case. A linear scan would need up to 1,000,000.

That is the rule to state first. Transparency lists sorted by depth, BVH leaves sorted by Morton code, and mip levels sorted by LOD threshold all satisfy the precondition, so the same search applies to each.

Worked trace

Sorted depths: [0.10, 0.30, 0.50, 0.70, 0.90]. Search for 0.55, meaning find the first depth at or after 0.55.

StepRange searchedProbeResult
10 to 40.50Too small, search right half
23 to 40.70Too large, search left half
33 to 30.70First value >= 0.55, stop

Three comparisons for five items. The count follows from halving: after k comparisons at most n / 2^k items remain. The search ends when that reaches 1, so k is about log2(n). For n = 1,000,000, 2^20 = 1,048,576, so 20 comparisons cover the whole list.

Code

C++
// C++17. Returns the first index i with a[i] >= value, or n if none exists.
int lower_bound(const float* a, int n, float value) {
    int lo = 0, hi = n;  // answer lies in [lo, hi)
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] < value) lo = mid + 1;
        else hi = mid;
    }
    return lo;
}

The loop body is the whole mechanism. Compare the middle element, move one bound past it, repeat. No other element is touched.

Where the precondition bites

If the list is not sorted, the halving decision is meaningless. A transparency list sorted last frame but not re-sorted after objects move will place a new object at the wrong depth. A BVH leaf array sorted by an old Morton code after a refit will return a leaf that does not contain the query point. Mip thresholds that stop being monotonic after a per material bias will select the wrong level. In each case the fix is to restore the sort before searching, or to test the candidate the search returns against the real value, such as an AABB test for a BVH leaf.

For very small lists, under about 16 items, a linear scan often runs faster in practice because it reads sequentially and avoids branch mispredicts. The log2(n) bound still holds, it is just not the fastest choice at that size.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-74Walk me through designing hash tables for a spatial grid, a GPU resource cache, and shader deduplication, and how you handle collisions, resizing, and hash quality under degenerate inputs?

The 90-second answer

I would not use one hash table for all three. Spatial lookup wants a flat, power-of-two open-addressing table rebuilt or incrementally updated per frame, with cell size chosen from object size distribution. A resource cache wants chaining or open addressing with explicit ownership, eviction and a key that includes every variant that changes the resource. Shader deduplication wants a hash over canonicalised input plus a full byte compare on hit, because a collision there is not a performance bug, it is the wrong program running silently.

The common decisions are load factor, probe strategy, resize policy and what the key actually covers. Get any of those wrong and the table degrades in a way that looks like a frame hitch or a rendering artefact, not a data structure bug.

Spatial hash: array first

For particles, debris or broadphase queries I use a uniform grid hashed into a flat array. Cell size is roughly the median object diameter, or the query radius if queries dominate. Too small and one object lands in many cells. Too large and each cell holds hundreds of candidates and the query becomes brute force.

C++
// C++17, checked against a simple CPU broadphase
struct Entry { uint32_t id; int32_t next; }; // next = index in cell chain, -1 = none
uint32_t hashCell(int32_t x, int32_t y, int32_t z) {
    uint32_t h = uint32_t(x) * 73856093u ^ uint32_t(y) * 19349663u ^ uint32_t(z) * 83492791u;
    return h & (tableSize - 1); // tableSize is a power of two
}

Entries live in a dense array, heads in a separate array of int32 initialised to -1. Insertion is O(1) amortised. Query walks the chain for the cell and its neighbours. That beats std::unordered_map here because there is no per-node allocation, iteration is cache friendly, and I can clear heads with a version stamp instead of touching every bucket.

Failure mode is clustering. If objects sit on a regular lattice, say instanced tiles at integer coordinates, the multiplicative hash above can still collide heavily if tableSize is small. I test with the real level, not random points, and plot probe or chain length. If the 99th percentile chain exceeds about 8, I either enlarge the table, change the hash mix, or switch that region to a dense grid. A second failure is unbounded cell occupancy when objects move slowly and accumulate. I cap inserts per cell and spill to an overflow list that the query also checks, rather than letting one cell become a linked list of ten thousand.

Resource cache: the key is the bug surface

A texture cache keyed only by path returns the wrong asset when the same file is loaded as sRGB and linear, or with different mip bias, compression or streaming priority. My key is a struct, not a string: type tag, content hash or asset id, format, colour space, and variant flags. I hash that struct, then compare the whole struct on hit.

CacheKey must includeCollision costEviction
Spatial gridcell coords onlyextra candidates checkedclear per frame or per rebuild
Resource cacheid, format, colour space, variantwrong texture or mesh boundrefcount plus LRU, never evict in use
Shader dedupcanonical source, defines, compiler version, target API, entry pointwrong shader, possibly silentkeep for session, evict only with program

For the cache I prefer open addressing with linear probing and tombstones only if deletes are rare. If deletes are frequent, chaining is simpler and avoids tombstone accumulation that slowly fills the table with dead slots. Load factor target is 0.5 to 0.7 for open addressing. At 0.9, probe lengths explode. Arithmetic I check in review: 100k entries at load 0.7 needs 262144 slots, at 0.5 it needs 262144 as well after rounding, so the memory cost of staying at 0.5 is often zero once you round to a power of two. Resize is done outside the frame, by building a new table and swapping, because growing mid-frame stalls the render thread and can spike past 16.6 ms.

Threading matters. Workers look up resources while the main thread inserts. I either shard by hash, use a read-write lock with a short critical section, or publish immutable snapshots. A lock free read path that returns a pointer to an entry being rehashed is a use after free waiting for a stress test.

Shader deduplication: never trust the hash alone

Dedup key is the canonicalised source after preprocessing, the define set sorted, the compiler version, the target (Vulkan GLSL vs DXIL vs Metal), and the entry point. Two shaders with the same name and different defines are different programs. I compute a 64-bit hash, xxHash or FNV-1a over the bytes is fine for dedup, then on a hash hit I compare the full canonical bytes before reusing the compiled program. A 32-bit hash over a large shader library is not enough. With 50k shaders, birthday collisions become plausible, and the failure is a material that suddenly uses another material's lighting model.

Trace I use in testing: shader A and shader B differ only in a #define for USE_NORMAL_MAP. If the define is missing from the key, B hits A's entry, compiles once, and every normal mapped surface renders flat. The test that catches it is a corpus of real shaders where I mutate one define at a time and assert the dedup count changes. I also test hash quality with sequential keys, because asset ids are often sequential and a weak hash turns them into a single cluster.

What I measure

Probe length histogram, chain length per cell, resize count, cache hit rate, and dedup hit rate with zero false hits on full compare. If probe length grows while entry count stays flat, the hash or the key distribution changed, usually after a content update. That is the signal to fix the hash, not to raise the load factor and hope.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-75Walk me through how two pointers merge two sorted lists in linear time, and how you would adapt that idea to find the closest pair of points sorted by x?

The 90-second answer

Two pointers work when order gives you information for free. If two lists are sorted, the smallest unseen element must be at the head of one of them, so you never search. For closest points, sorting by x lets you keep a sliding window of points that could still beat the current best distance d. Anything left of the window is too far in x to matter, and inside the window you only need to check neighbours close in y. That turns an O(n^2) scan into O(n log n), dominated by the sort.

Merging two sorted lists

Take two lists sorted by the same key, for example triangles from two sorted buckets by depth, or vertices sorted by x from two meshes. Keep i in A and j in B.

C++
// A, B sorted ascending; out has room for A.size()+B.size()
size_t i = 0, j = 0, k = 0;
while (i < A.size() && j < B.size())
    out[k++] = (A[i] <= B[j]) ? A[i++] : B[j++];
while (i < A.size()) out[k++] = A[i++];
while (j < B.size()) out[k++] = B[j++];

Trace with A = [1, 4, 9], B = [2, 3, 10]: compare 1 and 2, emit 1, i moves to 4. Compare 4 and 2, emit 2. Compare 4 and 3, emit 3. Compare 4 and 10, emit 4, then 9, then the tail loop emits 10. Result [1, 2, 3, 4, 9, 10]. Each step advances i, j or k, so the loop runs exactly n + m times: O(n + m) time, O(n + m) space for the output, O(1) extra if you merge in place with a buffer. Using <= keeps it stable, which matters if equal keys carry a secondary order you care about, such as draw order for equal depth.

The failure mode is assuming sorted input. If a producer hands you an unsorted list, the merge silently produces garbage that still looks sorted in chunks. In a renderer I would assert sortedness in debug builds on the key, not on the whole record, because a stale key after a transform is the usual bug.

Closest pair with a sweep window

Brute force checks every pair: n = 50,000 particles means about 1.25 billion pairs, far too much per frame. Sort points by x once. Sweep left to right and maintain d, the best distance found so far, initially from the first few points.

Keep an active queue of points whose x is within d of the current point. Points that fall behind, x_current - x_point > d, can never form a closer pair with anything ahead, so drop them. That is the second pointer: the left edge of the window only moves forward.

Inside the window, order by y. For the current point, check only active points with |y - y_current| < d. The packing argument bounds that check: points in the window are at least d apart, and the region d wide in x and 2d tall in y splits into 8 squares of side d/2, each holding at most one point, so at most 7 neighbours need testing. Each test is a squared distance compare, no sqrt until you update d.

C++
sort(points.begin(), points.end(), byX);
// active kept sorted by y (balanced tree or sorted vector rebuilt per window)
for (p : points) {
    while (active.front().x < p.x - d) active.pop_front();
    for (q : active where |q.y - p.y| < d)
        d = min(d, dist(p, q));
    active.insertByY(p);
}

Worked trace, points (0,0), (1,10), (2,1), (3,10), (10,0). Sorted by x already. Start d from (0,0) to (1,10): about 10.05. Point (2,1): window holds both earlier points, y check keeps (0,0), distance sqrt(5) = 2.24, so d drops to 2.24. Point (3,10): (0,0) leaves the window since 3 - 0 > 2.24, (1,10) stays and gives distance 2, d becomes 2. Point (10,0): everything leaves the window, no checks. Total checks: 1 + 2 + 1 + 0, against 10 pairs brute force.

ApproachTimeExtra memoryWhen it wins
Brute forceO(n^2)O(1)n under a few hundred, or one-off
Sort plus sweepO(n log n)O(n)Static or sorted-once sets, exact answer needed
Uniform grid hash, cell = dO(n) averageO(n)Particles rebuilt per frame, approximate d known

Two practical notes. First, duplicates give d = 0 and the window collapses, which is correct but worth handling so you do not divide by d later. Second, if points move every frame, resorting 50,000 particles costs more than the sweep. That is where a grid hash with cell size near the interaction radius, as in spatial hashing for particles, usually beats the sweep in a game loop, at the cost of worst-case behaviour when many points share one cell. The sweep is the right tool when you need the exact closest pair and the set is sorted once, for example merging sorted vertex streams or offline mesh analysis.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-76How would you test an explicit-stack iterative DFS for scene graph and BVH traversal for correctness, stack depth, and overflow?

The 90-second answer

I would test the explicit stack as a bounded, ordered replacement for recursion, not as a generic container. The contract has three parts: it visits the same nodes in the same order as recursive DFS, it never exceeds its declared capacity on legal input, and it fails loudly instead of corrupting memory when input is degenerate. I check all three separately, because a traversal can be correct on a balanced BVH and still overflow on a deep scene graph.

For a scene graph, DFS order matters for draw order and for inheriting transforms. For a BVH, order matters for near-first traversal and early exit on a hit. The stack discipline is the same, the failure modes are not.

Reference implementation under test

C++
// C++17, checked against a recursive oracle in tests
struct Node { int child[2]; int first; int count; }; // BVH node, child[0] < 0 means leaf

bool TraverseBVH(const Node* nodes, int root, Ray ray, Hit& hit) {
    constexpr int kStack = 64;
    int stack[kStack];
    int sp = 0;
    stack[sp++] = root;
    while (sp > 0) {
        int id = stack[--sp];
        const Node& n = nodes[id];
        if (n.child[0] < 0) {
            if (IntersectLeaf(n, ray, hit)) return true; // depends on policy
            continue;
        }
        float t0 = IntersectAABB(nodes[n.child[0]], ray);
        float t1 = IntersectAABB(nodes[n.child[1]], ray);
        // Push far first so near is popped first.
        if (t1 < hit.t && t1 > 0) {
            if (sp >= kStack) return false; // overflow: counted, not silent
            stack[sp++] = n.child[1];
        }
        if (t0 < hit.t && t0 > 0) {
            if (sp >= kStack) return false;
            stack[sp++] = n.child[0];
        }
    }
    return false;
}

The test harness wraps this with counters: max_sp, pushes, pops, overflows, and the visit sequence. The recursive oracle records the same sequence. Any mismatch in sequence is a failure even if the final hit distance matches, because ordering bugs hide until a scene has overlapping bounds.

Worked trace

Take a BVH root 0 with children 1 (near, t=2) and 2 (far, t=5). Node 1 has leaf children 3 (t=3) and 4 (t=4). Stack shown bottom to top.

StepPopPush (far, then near)Stack after
0-0[0]
102, then 1[2, 1]
214, then 3[2, 4, 3]
33leaf test[2, 4]
44leaf test[2]
52leaf test[]

Peak sp is 3 here. If I swapped the push order, node 2 would be tested before the nearer subtree, and with an early-exit policy the ray could return a farther hit or waste tests on a subtree that a nearer hit would have pruned. The golden trace catches that swap. A hit-distance-only test would not.

Stack depth: the arithmetic that sets the test cases

For a balanced BVH over N leaves, depth is about ceil(log2(N)) + 1. For 1 million triangles grouped into leaves of 4, that is roughly 18 levels, and the live stack stays near that depth because each level contributes at most one pending sibling. A 64-entry stack has headroom for that case.

The dangerous cases are not the balanced ones:

InputExpected peak stackTest expectation
Balanced BVH, 1M triangles~18-20No overflow, order matches oracle
Degenerate BVH from sorted triangles, SAH disabledO(N) in the worst caseOverflow counter increments, no write past stack[64]
Scene graph chain, 10,000 nested groups10,000 if pushed naivelyMust either use a heap stack or reject with a depth error before traversal
Scene graph with shared child (DAG, not tree)Depends on visited policySame node visited once or twice, per spec, never infinitely

That last row is a real scene graph trap. A tree DFS assumes each node has one parent. Instanced or shared subgraphs break that assumption. I test a DAG with a shared node reached from two parents and assert the documented policy: either a visited set prevents reprocessing, or the transform is recomputed per instance. An unbounded loop there looks like a hang, not a stack overflow, so the harness also caps total pops at, say, 4 * node_count + 16 and fails if the cap is hit.

The test set I would run

  1. Oracle comparison on random scenes. Generate random AABBs, build the BVH, run recursive and iterative versions, compare visit sequences and hit results for 100,000 random rays. Include rays that miss everything, hit the root only, and run parallel to an axis.
  2. Push-order test. The trace above, plus a mirrored variant where near and far swap. Assert near is popped first in both.
  3. Overflow test. Feed a degenerate BVH and a 10,000-deep scene graph chain. Compile with AddressSanitizer and stack guard bytes. Pass condition is a counted overflow or a clean depth error, never a sanitizer report.
  4. Empty and single-node cases. Root is a leaf, root has one child, ray origin inside the root AABB. These catch off-by-one errors in sp handling that larger scenes mask.
  5. Mutation test. Deliberately swap the two pushes in the code under test and confirm the golden trace fails. If it does not, the test is not actually checking order.

On the GPU the same tests apply with one change: a fixed per-thread stack in registers or local memory makes overflow a correctness bug rather than a crash, because local memory spills silently and performance collapses. I would add a counter for maximum sp per warp and fail the test if it approaches the limit, even when results are correct. That turns a latent performance cliff into a visible test failure.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-77How does a free-list allocator reuse freed blocks in O(1), and how does that differ from a bump-pointer frame arena reset?

The 90-second answer

A free-list allocator stores the offset of the next free block inside the freed block itself. Allocation pops the head of that list and freeing pushes the block back onto the head. Both touch one block, so both are O(1) with no search.

A frame arena is usually not a free list. It is a bump allocator: a single offset moves forward on each allocation, and resetting the offset to zero at frame end frees everything in O(1). That works because no individual block is ever freed during the frame. A free list, by contrast, has its links overwritten by user data while a block is live and by new links when it is freed, so restoring the head alone does not restore the original list. Rebuilding a free list after a frame costs O(n) in the number of blocks.

For a GPU buffer the link is an offset, not a CPU pointer. The buffer can be device mapped, resized, or read by a shader, and in each case a device relative offset stays meaningful where a host pointer does not.

C++
// Checked against C++17. Offsets are byte offsets into the buffer.
struct FreeList {
    uint32_t head;  // offset of first free block, kNil if none
    static constexpr uint32_t kNil = 0xFFFFFFFFu;

    // A free block reuses its own first 4 bytes for the link.
    // Every block must be at least 4 bytes, rounded up to the
    // buffer alignment in practice (16 bytes on most GPU buffers).
    uint32_t next(const uint8_t* base, uint32_t block) const {
        uint32_t value;
        __builtin_memcpy(&value, base + block, sizeof(value));
        return value;
    }
    void setNext(uint8_t* base, uint32_t block, uint32_t value) const {
        __builtin_memcpy(base + block, &value, sizeof(value));
    }

    uint32_t allocate(uint8_t* base) {
        uint32_t block = head;
        head = next(base, block);  // pop
        return block;
    }
    void release(uint8_t* base, uint32_t block) {
        setNext(base, block, head);  // push
        head = block;
    }
    void rebuild(uint8_t* base, uint32_t blockSize, uint32_t blockCount) {
        for (uint32_t i = blockCount; i-- > 0;) {
            uint32_t block = i * blockSize;
            setNext(base, block, (i + 1 < blockCount) ? block + blockSize : kNil);
        }
        head = 0;
    }
};

Worked trace: free list

Four 64-byte blocks at offsets 0, 64, 128 and 192, linked by rebuild at startup.

StepOperationHead afterFree list
1rebuild00 -> 64 -> 128 -> 192
2allocate() returns 06464 -> 128 -> 192
3allocate() returns 64128128 -> 192
4release(0)00 -> 128 -> 192
5allocate() returns 0128128 -> 192

Step 4 writes 128 into block 0, because 128 was the head at that moment. Block 64 still holds its old link to 128, but block 64 is live and unreachable from the head, which is correct. After step 5 the free list is 128 -> 192. Setting head = 0 at this point would give 0 -> 128 -> 192 and lose nothing, but only by accident: block 0 happens to link to 128. If block 0 had been freed when the head was 192, resetting the head to 0 would skip block 64 entirely. The safe bulk reset is rebuild, which rewrites every link and costs O(n).

Worked trace: bump frame arena

StepOperationOffset afterLive range
1frame start0empty
2allocate 64 bytes64[0, 64)
3allocate 128 bytes192[0, 192)
4allocate 64 bytes256[0, 256)
5frame end: offset = 00empty

Step 5 is one store. No links are read or written, because none exist. That is the design to use when allocations live for exactly one frame and die together.

Where each one breaks

The free list sets a minimum block size. The link needs 4 bytes, so a request smaller than the minimum still consumes a full block. Rounding every block to 16 bytes makes that waste predictable, which suits fixed size GPU slots such as descriptors or particle entries.

Variable sizes defeat a single free list. Serving a 32-byte slot and a 4 KB upload from one list either wastes most of the large block or needs splitting, and splitting needs a search for a block that fits. One list per size class, with requests rounded up to the next class, keeps allocation O(1) at the cost of internal waste. Freed blocks are also never merged with neighbours, so a long lived buffer can fragment into blocks too small for a large request. A frame arena avoids that by construction, since the rebuild or offset reset restores the original layout.

Double free corrupts a free list silently. Releasing block 0 twice makes the list read 0 -> 0, and the next two allocations both return offset 0, so two live objects share storage. A debug build can catch it with a sentinel written on release and checked on the next release, or a generation counter per GPU slot. In a bump arena there is no per block free, so that failure mode does not exist.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-78Tell me about a time on a graphics project when visual quality and performance were in direct conflict. How did you resolve it, and what did you ship?

The 90-second answer

On a cross-platform action game I owned the frame budget for the outdoor levels. Art wanted 4096 shadow maps, full-resolution volumetric fog and 8x MSAA at a locked 60 fps on the base console. I was not there to win an argument about look. I needed to show what each feature cost on the shipping hardware and get to a version that held 16.6 ms with headroom for gameplay spikes.

I captured the worst level with PIX on a dev kit, then repeated the same camera path on a retail kit after a 20 minute thermal soak, because dev kit clocks and thermals do not match retail. The figures below are from that level's captures, not a general benchmark. GPU time was 21.4 ms. Shadows were 6.2 ms, fog 4.8 ms, opaque lighting 7.1 ms and post 3.3 ms. That split gave us something to negotiate with instead of opinions.

We shipped a tiered compromise. Shadows went to 2048 with two cascades instead of four, fog rendered at half resolution with temporal accumulation, and MSAA dropped to 4x with TAA on top for edges. Distant shadow detail got softer, which art accepted once they saw it in motion at gameplay distance rather than in a still screenshot. GPU time fell to 13.8 ms, leaving about 2.8 ms for CPU variance and particle spikes. We also added dynamic resolution between 0.85 and 1.0 as a safety valve, so a bad scene degraded resolution for a few frames instead of dropping to 30 fps.

What I actually did

Situation: the level had roughly 180 dynamic lights in the forward-plus list, dense foliage casting shadows, and fog volumes tuned by eye at full resolution. On the min-spec machine we were at 38 fps in the forest clearing, and the producer was being told we needed to cut either the fog or the shadow quality entirely.

Task: keep the look the art director had signed off for the hero area, hit 60 fps on the base SKU, and not push the problem to the next level.

Action, in order:

  1. I profiled per pass, not per frame. A single "GPU busy 96%" number tells you nothing. With PIX I split shadow depth, fog injection, main opaque and post, and checked the counters for DRAM bandwidth and L2 hit rate. In that level fog at full res was bandwidth bound, writing a large float target every frame. Shadows were vertex and depth bound because, in that level's setup, foliage cards were included in all four cascades.

  2. I built a test scene with the exact camera path QA used, plus a second path through the clearing, and recorded frame time distributions, not averages. Average was 19 ms, p95 was 24 ms. That p95 is what players feel.

| Pass | Before (ms) | After (ms) | Change | | Shadow depth | 6.2 | 2.9 | 2048, 2 cascades, foliage excluded beyond 60 m | | Volumetric fog | 4.8 | 1.6 | Half res, temporal reprojection | | Opaque + lighting | 7.1 | 6.4 | 4x MSAA + TAA, tighter light tile bounds | | Post | 3.3 | 2.9 | Bloom at half res, merged tonemap pass | | Total GPU | 21.4 | 13.8 | Headroom for CPU and particles |

The totals reconcile: 6.2 + 4.8 + 7.1 + 3.3 = 21.4 before, and 2.9 + 1.6 + 6.4 + 2.9 = 13.8 after.

  1. I put the trade-off in front of art as side-by-side captures at real viewing distance, with the frame cost printed on the slide. The 4096 shadow map looked better in a 200% crop. At 1080p on a TV across a room, the difference was mostly in the far cascade, which we replaced with a baked lightmap for static geometry. That was the key insight for that level: static trees did not need dynamic shadow updates every frame.

  2. I refused to cut geometry density or texture resolution, because those were visible in every frame and cheap once shadows stopped redrawing them four times. Cutting them would have saved about 1 ms in that capture and cost us the look everywhere.

Result: we shipped at a locked 60 fps on the base console, p95 GPU 14.9 ms in that level, and dynamic resolution rarely engaged. The compromise that hurt most was fog banding at half resolution in dark scenes. We fixed that with a blue-noise dither in the accumulation pass, which cost about 0.2 ms in that capture.

If an interviewer pushes me, the failure mode I watch for now is negotiating on a dev kit or on averages. Both hide the real constraint. I also set a rule with the team: any new visual feature has to come with a measured cost in ms on the retail kit, and if it pushes us over 14 ms GPU we either remove something else or it goes behind the dynamic resolution scaler. That rule stopped the next conflict before it started.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-79Tell me about a production rendering bug you debugged across drivers or platforms: what was the symptom, how did you isolate it, and what was the fix?

The 90-second answer

We shipped a patch that added alpha-tested foliage. On NVIDIA cards it looked fine. On AMD RX 6600 and Intel Arc, about a third of the leaves rendered black or disappeared at some angles, and the pattern changed with camera position. QA could not reproduce it on our dev machines, which were all NVIDIA.

I captured the same scene on an AMD machine with RenderDoc, stripped the frame down to one leaf mesh, and found the shader computed a flat normal from screen-space derivatives after an early discard. That is undefined behaviour when control flow diverges inside a 2x2 quad. NVIDIA happened to return a usable derivative. AMD and Intel returned zero for the discarded lanes, cross(0,0) gave a zero vector, normalize gave NaN, and the lighting term went black. The fix was to compute the derivative before the branch, or pass a real normal attribute. We moved the derivative to the top of main, before any discard, and added a cross-vendor capture test to CI.

How I isolated it

First I ruled out data. The same build, same asset pack, same save file. I swapped the AMD card into my machine and the bug followed the card, not the machine. That pointed at driver or hardware, not a bad install.

Then I bisected the frame. RenderDoc on the AMD card showed the leaf mesh drawing correctly in the vertex stage. In the fragment debugger the interpolated position was correct, the albedo sample was correct, and the computed normal was (0,0,0) or NaN on roughly half the pixels. The pattern matched quad boundaries, which is the clue for derivatives. A 2x2 quad shares derivative computation. If one lane discards and the others do not, the quad is non-uniform and the spec does not define dFdx or dFdy there. GLSL ES 3.0 and Vulkan both state this explicitly. Some drivers compute it anyway from the surviving lanes. Others return zero.

PlatformResult before fixNormal in fragment debugger
RTX 4070, driver 551CorrectUnit length, varies per pixel
RX 6600, Adrenalin 24.3Black patches, flicker with cameraZero or NaN on discarded quads
Intel Arc A750, driver 101.5444Same as AMD, slightly larger patchesZero on discarded quads
Apple M2, Metal via MoltenVKCorrect in our testUnit length

The minimal repro was a single quad with a checker alpha test and the derivative normal. It reproduced on AMD in under 20 lines and failed on NVIDIA in the opposite direction, which confirmed it was not asset data.

The bug in code

Before:

GLSL
// GLSL ES 3.0 / Vulkan GLSL
void main() {
    vec4 tex = texture(albedo, vUv);
    if (tex.a < 0.5) discard;              // diverges inside the quad
    vec3 flatNormal = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));
    vec3 colour = tex.rgb * max(dot(flatNormal, sunDir), 0.0);
    outColour = vec4(colour, 1.0);
}

After:

GLSL
void main() {
    vec3 flatNormal = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));
    vec4 tex = texture(albedo, vUv);
    if (tex.a < 0.5) discard;
    vec3 colour = tex.rgb * max(dot(flatNormal, sunDir), 0.0);
    outColour = vec4(colour, 1.0);
}

Moving the derivative above the branch makes the control flow uniform for that computation. The discard still happens, but it no longer poisons the derivative. For the shipped fix we went further and used a proper vertex normal for leaves, because a derivative normal also breaks on thin geometry where the quad spans two surfaces. The derivative version stayed only as a fallback for flat-shaded props.

What I changed after the fix

I added a rule to our shader review checklist: no dFdx, dFdy, fwidth, or implicit-derivative texture() call after a branch that can diverge, including discard, return, or a non-uniform if. Where we need derivatives in a branch, we use textureLod with an explicit level or compute the derivative before the branch.

I also added a capture test that runs the foliage scene on three vendors in CI and checks the mean luminance of the leaf pixels. It would have caught this because the AMD capture dropped by about 40 percent on the affected quads. The test is cheap, one frame, no gameplay.

The lesson I took into the next project was to treat "works on NVIDIA" as no evidence at all. If a shader relies on behaviour the spec leaves undefined, one driver will fill the gap kindly and another will not, and players will find the difference after launch.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-80Tell me about a time you delivered a graphics feature on a tight deadline. What was the situation, what trade-offs did you make, and how did you prove it worked?

The 90-second answer

Six weeks before certification we had a 4K mode that missed frame budget in the worst level by 3.2 ms. I owned dynamic resolution scaling with a TAA upscaler. We shipped it in three weeks, held 60 fps in that level at a 0.75 resolution scale, and cut two planned features to protect the date. The proof was a captured frame trace and a side-by-side capture at fixed camera positions, not a claim that it looked fine.

Situation. Target was 3840x2160 output, 16.6 ms frame. On the shipping hardware, GPU time in the city level was 19.8 ms at full internal resolution. CPU was 9.1 ms, so the GPU was the limiter. The level had 340 dynamic lights in the forward-plus path and a lot of alpha-tested foliage, which made the G-buffer and lighting passes expensive. Certification lock was fixed. A full rewrite of the lighting pass was not an option.

Task. Get GPU time under 14.5 ms, leaving 2.1 ms headroom under the 16.6 ms budget for driver variance, without dropping below a resolution scale that players would notice on a 55 inch TV. I set the floor at 0.66 and the ceiling at 1.0, with a target of staying above 0.8 in typical play.

Action. I implemented a controller that adjusts internal resolution from GPU frame time, then renders at that size and upscales with TAA. The controller used an exponential moving average and a hysteresis band so it did not oscillate every frame.

C++
// Runs on CPU, reads GPU timestamps from previous frame
float scale = 0.85f;
float lastScale = scale;
float gpuMs = gpuTimer.QueryMs();
float target = 14.5f;
float error = target - gpuMs;
if (fabs(error) >= 0.4f) {          // dead band: hold scale when close
    scale += error * 0.02f;         // proportional step, clamped per frame
    scale = clamp(scale, 0.66f, 1.0f);
    scale = clamp(scale, lastScale - 0.03f, lastScale + 0.03f);
}
lastScale = scale;
internalW = uint(3840 * scale) & ~7u;  // keep 8-pixel alignment for TAA
internalH = uint(2160 * scale) & ~7u;

TAA needed velocity. We already had per-object motion vectors for characters. For static geometry I derived velocity from the camera delta and the depth buffer, which avoided storing a velocity buffer for the whole scene. That saved about 180 MB of bandwidth per frame at 4K, which mattered because DRAM was already at 78% of peak.

Trade-offs I made explicitly. I cut checkerboard rendering. It would have given another 15% but it broke alpha-tested foliage and produced sparkle on thin geometry. I cut per-object velocity for particles and kept them at the previous frame position for one frame. Particles are small on screen and the artifact was invisible in playtests, while the code path for full particle velocity would have taken a week to validate. I kept HUD and text at native resolution by rendering them after the upscaler. That cost 0.6 ms but prevented blurry UI, which testers flag faster than a soft background.

Failure modes I checked for were ghosting on disocclusion, flicker on foliage, and a feedback loop where the controller dropped resolution, frame time fell, it raised resolution, and the scene thrashed. The dead band and a maximum change of 0.03 per frame stopped the thrash. I added a test scene with a rotating camera at fixed speed past foliage, glass, and a moving train. At scale 0.66 the train showed a one-frame trail. At 0.8 it did not. That set the practical floor for that content.

Result. Measured on the target kit, same build, same camera path:

Internal scaleGPU timeFrame rateNotes
1.0019.8 ms50 fpsMissed budget
0.8515.9 ms60 fpsOccasional dip in heavy combat
0.7514.1 ms60 fpsStable, target for shipping
0.6612.4 ms60 fpsVisible softness on foliage

In the shipping level the controller settled between 0.72 and 0.84 depending on combat density. Average GPU time was 14.3 ms over a 10 minute capture. The feature passed certification first submission. The lesson I took from it was to lock the quality floor and the measurement method before writing the upscaler, because without a fixed camera path and a numeric budget the argument about quality never ends.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-81Tell me about a time you worked with artists or designers to ship a graphics feature, and how you handled a disagreement over quality versus performance?

The 90-second answer

I would tell one story with a clear disagreement, a concrete measurement, and a shipped compromise. Pick a feature where the artist's goal and the frame budget pulled in opposite directions, show the numbers you both looked at, and end with what shipped and what you changed in the process afterwards. Interviewers are listening for whether you listened first, translated between art intent and engineering cost without dismissing either side, and made the trade-off explicit.

The story I would tell

Situation: I was the graphics engineer on a third-person game shipping on console and PC. Our environment artists wanted a new hero prop, a moss-covered stone lantern, to read at a distance in a foggy night scene. Their reference had a 4K albedo set, a full normal map, and a hand-painted lightmap-style AO baked into the albedo. My first profile showed the prop alone was fine, but the full scene was not. At 1080p the frame was 19.4 ms against a 16.6 ms budget, and the lantern's textures were pushing the streaming budget over its 512 MB cap for that level.

Task: I owned getting the lantern in without breaking the frame budget or the memory cap, and without the artists feeling their work had been quietly downgraded.

Action: I did not start with a counter-proposal. I sat with the lead artist and asked what the 4K detail was actually for. The answer was silhouette and surface breakup at 3 to 5 metres, not fine grain at close range, because the camera rarely got closer. That changed the problem. We could keep the close-range detail and cut what the camera never saw.

We built a small test scene together, one lantern, the fog, the night lighting, and the camera distances they cared about. I captured three variants side by side and timed each one. That gave us a shared artefact instead of two opinions.

VariantTexture setTrisFrame time in test sceneMemory for the prop
Artist reference4K albedo, 4K normal48,00019.4 ms full scene96 MB
My first cut2K albedo, 2K normal, no baked AO48,00017.1 ms full scene24 MB
Shipped compromise2K albedo, 2K normal, baked AO in a packed channel, LOD at 8 m48,000 near, 9,000 far15.8 ms full scene26 MB

The shipped version kept the 2K maps because the test scene showed no visible loss at the distances they named, and we moved the baked AO into the alpha channel of the albedo so we did not need a separate texture. I added a screen-space LOD switch at 8 m, which the artists approved after seeing the far view in the same capture. I also fixed a real bug in my first cut: I had been filtering the normal map with sRGB decoding on, which washed out the moss detail. Once that was corrected, the 2K version matched their reference in the capture.

Result: The level shipped at 15.8 ms in that scene, inside budget with headroom for the rest of the level, and the prop stayed within the streaming cap. The artists kept the close-range look they cared about. The disagreement was resolved by the capture, not by seniority.

What I would add if they probe

Failure mode to name: the first time I presented numbers, I showed only frame time. The artists reasonably asked whether the lantern still looked right, and I had no answer. After that I always pair a timing capture with a visual capture at the same camera positions. A second failure mode is agreeing to a compromise in a meeting and then shipping something different in code. I avoided that by putting the agreed variant, LOD distance, and texture budget in the asset spec the artists signed off on, so the importer enforced it.

If the interviewer asks about a hardware partner instead, I would use the same shape: a vendor engineer and I disagreed about whether a driver regression or our barrier placement caused a 4 ms jump, we reproduced it on a minimal capture, and the fix was a barrier we had been placing after the upload instead of before the first read. The structure stays the same. Situation, your task, what you did together, a measured result, and one thing you changed about how you work.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-82Walk me through how you would choose between tile-based deferred, tile-based forward and immediate-mode rendering for a mobile game targeting Mali, Adreno and Apple GPUs, and what would make you switch?

The 90-second answer

I would default to tile-based deferred rendering on current Mali, Adreno and Apple parts, then try to prove it wrong with measurements from the actual scene. TBDR wins when the frame is fragment and bandwidth bound, which is the usual mobile case: high overdraw, a 1080p or higher target, and a shared memory bus that cannot afford to write a full-screen G-buffer to DRAM and read it back. It loses, or needs a hybrid, when the frame is vertex bound, when a pass needs fullscreen data the tile cannot hold, or when the workload is compute heavy. So the choice is not a vendor preference. It is a bet about where the bottleneck sits, and I would instrument both paths before committing.

Why TBDR helps, in numbers

In immediate mode, every fragment that passes depth writes colour to DRAM, and a deferred pass reads it again. Take a hypothetical 1920x1080 frame at 60 fps with average overdraw of 3. A 32x32 tile holds 1024 pixels. Keeping colour, depth and stencil on chip for that tile costs roughly 1024 x (8 bytes for RGBA16F + 4 for depth + 1 for stencil) = about 13 KB, well inside the few MB of tile memory on these parts. The win is that intermediate writes never leave the chip. At 3x overdraw the immediate path moves about 1920 x 1080 x 3 x 8 bytes = 50 MB per frame just for colour writes, before reads. TBDR pays that cost only for the final store, plus a spill cost when a tile overflows.

That arithmetic flips if overdraw is near 1 and the scene is vertex heavy. Then TBDR adds a binning pass over vertices and primitives, and the saving shrinks while the extra vertex processing stays.

ArchitectureWhere fragments liveStrengthWeakness on mobile
Immediate modeDRAM framebufferSimple, no binning cost, good for compute and fullscreen passesPays DRAM write and read per layer of overdraw
Tile-based forwardTile memory, per object lightingKeeps tile locality, cheaper than full deferred for few lightsStill shades per fragment per light unless clustered
Tile-based deferredTile memory G-bufferOne lighting pass per pixel, best with many lights and high overdrawTile overflow, pass breaks flush memory, awkward for some post effects
HybridTile memory plus a compute or immediate passLets each pass use the right modelExtra passes, extra load and store, more driver variance

How I would decide

First, profile the shipped scene on the lowest target device, not a flagship. I want fragment ALU, vertex processing, DRAM bandwidth and tile spill counters. On Mali that means Arm Streamline and the Mali GPU counters for tile memory spills and external memory traffic. On Adreno, Snapdragon Profiler. On Apple, Xcode GPU capture and the tile load and store events. If DRAM bandwidth is above about 70 percent of peak while the ALU units are idle, TBDR is the right default. If vertex throughput saturates first, binning will make it worse and I would look at reducing vertex cost or using an immediate path for that geometry.

Second, count render pass breaks. Every time the pipeline needs data from a previous fullscreen pass, or switches between rendering and compute in a way the driver cannot keep on chip, the tile memory is flushed and reloaded. A chain of fullscreen post effects, each as its own pass, can erase the TBDR advantage. I would merge post passes, use transient attachments with load and store set to dontCare where the data is not needed again, and keep the main scene in as few passes as the material model allows.

Third, check tile size and overflow. A 64x64 tile quadruples the per tile memory of 32x32. With a complex G-buffer that can push the driver into spilling to DRAM, which shows up as a cliff rather than a gradual slowdown. I would test the heaviest scene, the one with the most overlapping transparent objects, because transparency is where overdraw explodes and where sorting and blending inside a tile get expensive. If spills appear, options are a smaller tile where the API exposes it, splitting the G-buffer, or moving transparency to a separate forward pass after the opaque deferred pass.

Failure modes I would test for

Tile overflow on a stress scene, measured as spill bytes per frame, not just frame time. A frame that holds 16 ms on a clean scene and drops to 25 ms with one extra particle layer is a spill problem, not a shader problem.

Driver divergence. The same Vulkan or Metal code can bin differently on Mali, Adreno and Apple silicon. I would run the same capture on all three families and compare external memory traffic, because a design that is fast on one and spills on another will fail the lowest spec device.

MSAA resolve cost. TBDR handles MSAA well inside the tile, but a resolve to DRAM at the end of a pass is a full screen read and write. If the game needs MSAA plus a deferred G-buffer plus post, I would compare 4x MSAA with a cheaper resolve against no MSAA with TAA, and measure the resolve bandwidth explicitly.

Vertex binning cost with many small draw calls. Thousands of tiny meshes can make binning dominate. In that case I would batch static geometry, use instancing, and consider whether a forward tiled path with clustered lights gives the same lighting benefit without a full G-buffer.

The decision I would defend in review is TBDR for the opaque scene, a separate forward pass for transparency, merged post processing, and a fallback measurement gate: if external memory traffic does not drop by at least 30 percent against the immediate baseline on the lowest target, the architecture change is not paying for its complexity and I would revisit it.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-83A game hitches for 40 ms the first time a new material appears, but not on the second run. How would you test whether that is shader compilation or pipeline creation, and what would you change?

The 90-second answer

I would time the two operations separately and run the same scene twice, once with a cleared cache and once warm. Shader compilation turns source or HLSL into the driver intermediate form. Pipeline creation takes that compiled shader plus blend, depth, rasterizer and input layout state and builds the driver object the GPU can execute. They can both block the render thread, and a frame graph alone cannot tell them apart.

So I wrap both calls with the same pipeline key. The key is a hash of the vertex and fragment shader, input layout, blend and depth state, render target format and sample count. Logging by that key lets me see whether a hitch repeats for the same state or only happens for a new shader variant.

C++
// D3D12 style wrapper, checked as pseudocode against the API shape
void CreatePSO(const PSODesc& desc) {
    auto t0 = Clock::now();
    auto shader = CompileOrLoad(desc.shaderKey); // logs compile time alone
    auto t1 = Clock::now();
    auto pso = device->CreateGraphicsPipelineState(desc, shader);
    auto t2 = Clock::now();
    LogHitch(Hash(desc), Ms(t1 - t0), Ms(t2 - t1));
}

If compile is 28 ms and creation is 2 ms, precompiling the shader fixes it. If compile is 0 ms because the shader came from cache and creation is 34 ms, the shader is fine and the pipeline cache or creation path is the problem.

A trace that separates them

Hypothetical numbers for a 16.6 ms frame budget:

RunCompilePSO createCPU submit that frameGPU busy
Cold, new material28 ms2 ms38 ms11 ms
Warm, same material0 ms0 ms9 ms11 ms
Cold, cached shader, new state combo0 ms34 ms41 ms11 ms
Warm, same state combo0 ms0 ms10 ms11 ms

GPU busy staying near 11 ms while CPU submit jumps to about 40 ms means the GPU finished early and waited. That points at CPU work before the draw, and the split between the two columns tells me which call did it. A warm run with no spike also tells me the on disk pipeline cache is working. If the warm run still creates the same pipeline, I would check the cache key first. A pointer, a timestamp or uninitialised padding in the hashed struct makes every key unique, so the cache never hits.

What I change after the test

For compilation, I count variants before shipping. A material with defines for fog, skinning and light count can multiply into hundreds of permutations. I compile the census that gameplay can actually reach during loading, then assert in a scripted scene that the compile counter stays at zero after load. Moving compile to worker threads helps only if creation is also off the render thread, otherwise the hitch just moves.

For creation, I precreate pipelines for the same census and warm them with one off screen draw. That last step matters because some drivers still do work on first bind. I replay the scene and check the maximum frame time and the count of creates on the render thread, rather than average fps. Average fps can look fine while one 40 ms hitch per level transition remains.

The pass condition I would defend is concrete: after loading, a scripted run through every material and state combination records zero shader compiles and zero pipeline creations on the render thread, on both a cold run that populates the cache and the warm run that reuses it.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-84How does mip-based texture streaming keep an open world inside a fixed memory budget, and how would you pick which mip to load for a texture on screen?

The 90-second answer

A texture does not need its full resolution unless it covers enough screen pixels to show it. Streaming uses that fact. For each visible texture I work out the mip level that matches its on-screen size, load only the mips down to that level, and evict the rest. The memory budget then becomes a choice about which textures get to keep their fine mips.

Assume BC7 at 1 byte per texel, which is the usual case for opaque albedo. A 2048 by 2048 texture costs 4.0 MB at mip 0. Each lower mip is a quarter of the texels above it, so the whole chain costs about 5.3 MB. Most of that cost sits in the top two mips.

MipSizeBytesCumulative from mip 0
02048 x 20484.0 MB4.0 MB
11024 x 10241.0 MB5.0 MB
2512 x 5120.25 MB5.25 MB
3256 x 2560.06 MB5.31 MB

If that texture covers 512 screen pixels across, mip 2 (512 texels across) is the right level. Loading mips 0 to 2 costs 5.25 MB. Loading only mip 2 and coarser costs about 0.33 MB. That 16x difference is the whole mechanism.

Picking the mip

The hardware already does this per fragment with texture derivatives. For streaming I do a cheaper version per object, using its projected size:

C++
int RequiredMip(float screenPixelsAcross, int textureWidth) {
    // texels across at mip m = textureWidth >> m
    // Want texels across close to, but not far above, screenPixelsAcross.
    float ratio = screenPixelsAcross / textureWidth; // e.g. 512 / 2048 = 0.25
    int mip = 0;
    while (ratio < 0.5f && mip < 12) { ratio *= 2.0f; ++mip; }
    return mip; // 0.25 -> mip 2
}

I run this when an object becomes visible and again when its projected size changes by more than a factor of two, for example when the camera zooms or moves closer. That second check matters. A wall that starts at 200 pixels across and grows to 900 pixels across needs mip 1, not the mip 3 it loaded at spawn.

Applying it to a budget

Say the pool is 4 GB and the world has 2,000 unique textures averaging 2 MB for a full chain. Keeping everything resident would need 4 GB before the player moves, and the average would hide the problem because a few 2048 textures dominate. With streaming I admit requests in priority order until the pool fills. Priority is mostly screen coverage: a texture covering 1,000 pixels outranks one covering 50 pixels, because the second one loses almost nothing at a coarser mip.

A simple trace shows the trade-off. The camera looks at a building facade using twelve 2048 textures. Each covers about 600 pixels, so each needs mip 2. Resident cost is 12 x 5.25 MB, about 63 MB, and the facade looks correct. The camera turns away. Those twelve drop to the bottom of the priority list and get evicted first when new requests arrive. If the camera turns back a second later, the streamer reloads them, but it can start with mip 3 and coarser (about 0.08 MB each) and refine to mip 2 over the next few frames. The player sees a brief softness instead of a missing texture.

Where it breaks

The failure I check first is thrashing at a cell boundary. The camera sits where two streaming cells overlap, textures flip between resident and evicted every frame, and the upload queue stays full. The fix is hysteresis: do not evict a texture until its priority has stayed low for a few frames, and do not reload a texture until its required mip has been stable for a frame or two. The second failure is pop-in that lasts too long. If a texture sits at a mip coarser than required for more than about half a second while the disk is idle, the priority score is wrong, usually because distance is weighted too heavily and a close but small texture starves. I would log, per texture, the difference between required mip and resident mip over a scripted camera path. A healthy run keeps that error at zero for textures covering more than 256 pixels and lets small textures lag. That log, not the total memory number, tells me whether the budget is being spent where the player can see it.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-85What happens if you normalize a zero-length normal from a degenerate triangle, and how does that affect the lighting calculation?

The 90-second answer

Normalizing a zero vector gives NaN. A degenerate triangle, meaning two vertices coincide or all three are collinear, has zero area. Its face normal is the cross product of its two edges, and that cross product is the zero vector. Dividing zero by its length, zero, produces NaN in each component. That NaN then flows into dot(N, L), so diffuse and specular become NaN for every pixel the triangle covers. The pixel does not render black. It renders NaN, which tone mapping, blending and mip generation can spread further.

Worked trace

A = (0, 0, 0)
B = (1, 0, 0)
C = (2, 0, 0)
edge1 = B - A = (1, 0, 0)
edge2 = C - A = (2, 0, 0)
cross(edge1, edge2) = (0, 0, 0)
length = 0
normalize((0, 0, 0)) = (0, 0, 0) / 0 = (NaN, NaN, NaN)
diffuse = max(dot(N, L), 0.0) = NaN

A non-degenerate triangle with C = (0, 1, 0) gives cross = (0, 0, 1), length 1, and a finite diffuse term. The difference is only the area. Zero area means no direction to normalize.

How I catch it

I check the length before normalizing, both offline and in the shader. Offline, I reject faces whose area is below a small epsilon and log the mesh and face index, because a shader guard only hides the broken asset. In the shader, I render a debug view that writes length(N) or an isnan test, so a NaN normal shows up directly instead of as a strange lighting artefact.

GLSL
vec3 safeNormalize(vec3 n) {
    float lenSq = dot(n, n);
    return lenSq > 1e-12 ? n * inversesqrt(lenSq) : vec3(0.0, 1.0, 0.0);
}

vec3 N = safeNormalize(normalMatrix * inNormal);
vec3 L = normalize(lightPos - worldPos);
float ndotl = max(dot(N, L), 0.0);
vec3 colour = albedo * lightColour * ndotl;

The same zero normal also appears when a vertex normal attribute was never written and reads as (0, 0, 0). The debug view looks the same in both cases, so I check the exporter and vertex buffer setup before changing the lighting code. The guard keeps the frame valid while I fix the source mesh.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-86How would you design a cross-API abstraction over Vulkan, Direct3D 12 and Metal that keeps explicit control over memory, barriers and queues without paying for it per draw?

The 90-second answer

I would make the abstraction thin, explicit and mostly compile-time. It owns naming and lifetime, it does not own scheduling decisions. The engine asks for a buffer with a usage, a heap class and a queue family. The backend creates the native object in exactly that form and returns a handle that wraps it. Barriers, queue submits, fences and descriptor updates stay visible in the interface, with the same granularity as the native APIs. If a call would need a guess on Vulkan, it needs a guess on Direct3D 12 and Metal too, so the caller supplies the state transition.

That rule is what preserves performance. A hidden auto-barrier, a lazy descriptor bind or a pooled allocation inside a draw call can look convenient and then cost a stall that profiling cannot attribute to a line of engine code.

What the interface looks like

C++
// Checked against C++20. No virtual dispatch on the frame path.
template <class Backend>
struct Buffer {
    typename Backend::BufferHandle native;
};

struct Barrier {
    Resource res;
    ResourceState before, after;
    QueueFamily queue; // explicit, never inferred
};

// Backend concepts, satisfied by VulkanBackend, D3D12Backend, MetalBackend
template <class B>
concept GraphicsBackend = requires(B b, Barrier bar, Submit s) {
    { b.transition(bar) } -> std::same_as<void>;
    { b.submit(s) } -> std::same_as<void>;
    { b.createBuffer(BufferDesc{}) } -> std::same_as<typename B::BufferHandle>;
};

Dispatch happens once, when the backend is chosen at startup. After that the frame loop calls the concrete type through a template or a function pointer table filled at init. A virtual call per draw is small in isolation and measurable at scale. Hypothetical but typical figures from a 5,000 draw scene: 0.4 microseconds of extra dispatch and argument packing per draw is 2 ms per frame. That is the difference between 16.6 ms and missing budget on a console CPU.

Where the APIs genuinely differ

ConceptVulkanDirect3D 12Metal
MemoryVkBuffer plus VkDeviceMemory, or VMA suballocationHeap, placed resource, committed resourceMTLBuffer with storageMode, or MTLHeap
BindingDescriptorSet, push constantsDescriptorHeap, root signature, root constantsArgument buffers, render pipeline state
SyncPipeline barrier, queue submit, fence, semaphoreResourceBarrier, command queue, fenceResource barrier via encoder, command buffer, completion handler
ShaderSPIR-V, reflection from SPIR-VDXIL, reflection from DXILMetal Shading Language, reflection from compiled library

The abstraction maps the common subset directly and exposes the remainder as backend-specific escape hatches. A transient G-buffer attachment on Metal wants loadAction dontCare and storeAction dontCare. The equivalent on Vulkan is an attachment with loadOp dontCare. The interface should carry those fields explicitly rather than defaulting to store, because storing a transient tile buffer on a TBDR part can spill it to DRAM.

Failure modes I test for

First, barrier inference. If the abstraction inserts a barrier before every draw to be safe, a scene with a depth prepass followed by a G-buffer pass pays for a redundant layout transition and a cache flush. I log every barrier the backend emits during a captured frame and diff it against a hand written list for the same frame. Any barrier not in the list fails the test.

Second, descriptor churn. Vulkan descriptor sets, Direct3D 12 descriptor heaps and Metal argument buffers have different update costs and different limits. A design that reallocates a descriptor set per material change will fragment a Direct3D 12 heap and exhaust it after a few thousand unique materials, while looking fine on Vulkan. I run a stress scene with 10,000 material switches and check heap high water marks per backend.

Third, shader reflection mismatch. SPIR-V, DXIL and Metal reflection name constants and pack structs differently. A float3 in HLSL can arrive as a float4 in Metal if the layout annotation is dropped. I compile one source through all three paths, reflect the bindings, and compare offsets and sizes byte for byte before a frame is ever drawn.

Fourth, lifetime. A handle that outlives its fence is a use after free on the GPU. The wrapper holds a reference to the frame fence that last used the resource and refuses destruction until that fence is signalled. Partial allocation failure during device creation must unwind in reverse order, which a move-only wrapper with a custom deleter handles cleanly.

When I would not abstract

For a single platform title, or for a feature that only one API can express, such as a specific ray tracing pipeline or a mesh shader path, I would write the native code behind the same handle types and skip the common interface. The abstraction earns its keep when the same frame graph runs on at least two APIs and the team can afford the reflection and barrier tests above. Without those tests it becomes a second, slower renderer that hides the hardware from the people trying to tune it.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-87Frame time jumped 4 ms after a driver update. How do you isolate whether it is the driver, your code, or the test setup, and decide what to ship?

The 90-second answer

I freeze the comparison first. Same build, same scene, same resolution, same GPU, same capture script, old driver and new driver back to back, at least five runs each. I compare median and p95 frame time, not the best run. If the regression does not reproduce under those conditions, I treat it as test noise, thermal state, or a background process and stop there.

If it does reproduce, I split the frame with PIX on DirectX 12 and compare pass by pass: vertex, fragment, compute, copy, and present. A driver change usually moves time in one place. A shader compiler change moves fragment or compute. A power or scheduling change moves everything a little and shows up in GPU clocks. A change in barrier or heap handling shows up in CPU submit time rather than GPU execution time.

Then I bisect before touching game code. I run a minimal scene that uses only the suspect pass. If the minimal scene is also slower on the new driver, I have a driver or OS issue and I file it with a capture and exact build numbers. If the minimal scene is fine, the regression is in how my code interacts with the new driver, for example a shader pattern the new compiler handles worse.

Isolation trace

Hypothetical numbers, labelled as such, for a 1080p scene at 11.2 ms on driver 537.58 and 15.4 ms on driver 552.12:

CheckOld driverNew driverReading
Median frame, full scene11.2 ms15.4 msRegression reproduced
Median frame, minimal scene, same shaders6.1 ms6.3 msNot a global clock or present issue
Shadow pass GPU time1.8 ms4.6 msSuspect pass isolated
Shadow pass, depth prepass disabled1.7 ms1.9 msEarly depth path is the trigger
CPU submit time per frame3.1 ms3.2 msNot a CPU or barrier issue
GPU clock during capture2.41 GHz2.40 GHzNot thermal throttling

That pattern points at the depth prepass interacting with early depth testing on the new driver. In HLSL, writing SV_Depth in a fragment shader disables early depth testing for that shader, because the depth is not known until the shader runs. I vary one thing at a time: remove the SV_Depth write, change the depth function from D3D_COMPARISON_FUNC_LESS_EQUAL to D3D_COMPARISON_FUNC_LESS, and remeasure. In this example, removing the depth write brings the new driver back to 2.0 ms. The prepass no longer culls fragments on the new driver, so the main pass shades pixels it used to skip.

What I check next

I check the driver and OS release notes for the exact builds, looking for shader compilation, power management, and scheduling changes. I record the full stack in the bug report: GPU model, VRAM, driver build, OS build, and the PIX capture file. Vendors act on a capture with one pass isolated. They do not act on a full game frame time.

I also diff my own output between drivers. I compare the DXBC or DXIL for the suspect shader. If instruction count or register count changed, the compiler changed, and I need to find which source construct caused it. A driver update can also change how it executes barriers or transient resources, so I check whether CPU submit time moved even when GPU time did not.

Harness snippet

This is our internal runner, checked against Python 3.11. The flags are ours, not the engine's. The runner writes one frame time in milliseconds per line to frame_times.csv:

Python
# perf_harness.py, Python 3.11
import subprocess, statistics

def run_once(exe, scene):
    subprocess.run(
        [exe, "--scene", scene, "--frames", "300",
         "--fixed-clock", "--no-vsync", "--capture-frame", "120"],
        check=True,
    )
    with open("frame_times.csv") as f:
        return [float(line) for line in f if line.strip()]

old = [t for _ in range(5) for t in run_once("game.exe", "level1")]
new = [t for _ in range(5) for t in run_once("game.exe", "level1")]
print("old median", statistics.median(old))
print("new median", statistics.median(new))

The fixed clock flag matters. Without it, a laptop GPU boosts differently on the two drivers and I chase a power policy as if it were a shader bug. Where clock locking is not available, I record clocks from the capture and discard runs where clocks differ by more than 2%.

Decision

If the minimal repro is slower on the new driver and my code did not change, I ship a workaround only if it is cheap and safe, and I file the vendor bug the same day. Here the workaround might be to drop the depth prepass for that material, or to split the shader into two variants and select by driver build number. I gate on the exact build, not on a vague new driver check, and I add a test that fails if the workaround path is taken on an old driver.

If the regression is in my code interaction, I fix the code. In the early depth example, I restructure the shader so it does not write depth in a way that kills early testing, or I remove the prepass and accept the extra shading cost. The fix is done when the new driver is within 5% of the old driver on the full scene and the minimal scene is unchanged.

If I cannot reproduce under controlled conditions, I do not ship a workaround. I add the new driver to the CI matrix, keep the capture script in the repo, and retest on the next build. A workaround for a phantom regression usually costs more than the regression would have.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-88At 1080p, ray tracing at 2 samples per pixel takes 11 ms of a 12 ms GPU budget. How would 0.66 resolution scaling with a denoiser change cost and quality, and when would you fall back to raster instead?

The 90-second answer

Dropping to 0.66 scale cuts the ray tracing work by the pixel count, not by 34 percent. Pixel count scales with the square of the linear scale, so 0.66 squared is 0.44. An 11 ms pass becomes about 4.8 ms before the denoiser. Add roughly 1.5 ms for a temporal denoiser at 1080p and the total is about 6.3 ms, well inside a 12 ms GPU budget. The cost is softer detail and more reliance on the denoiser to hide noise at 2 samples per pixel. I would keep that tier while it holds frame rate and the image still matches a high sample reference. I would switch to raster when even the lowest scale plus denoiser misses the budget, or when the denoiser artifacts become more distracting than the simpler raster lighting.

The arithmetic

Assume a 1920 by 1080 frame, 2 spp, and a measured 11 ms for the ray tracing pass alone. These figures are a worked example, labelled as such, but the scaling math is exact.

OptionRender pixelsRay pass estimateDenoiserTotal estimate
1.0 scale, 2 spp2,073,60011.0 ms1.5 ms12.5 ms
0.66 scale, 2 spp903,0004.8 ms1.5 ms6.3 ms
1.0 scale, 1 spp2,073,6005.5 ms1.5 ms7.0 ms
0.66 scale, 1 spp903,0002.4 ms1.5 ms3.9 ms

The comparison that decides the design is row 2 against row 3. Both land near 6 to 7 ms. Row 2 keeps 2 spp and upscales a cleaner image. Row 3 keeps native resolution and halves the samples, so the denoiser receives noisier input with more fireflies from small bright lights. On a scene with emissive sources, row 2 usually looks better. On a scene dominated by fine geometry, row 3 can look sharper because the upscaler blurs thin edges. I would test both on the same scene rather than pick by theory.

Resolution scaling also changes what the denoiser sees. It needs noisy colour plus albedo, normal, roughness and motion vectors at the render resolution. Upscaling happens after denoising. If you upscale first and denoise at display resolution, you pay the denoiser cost at full pixel count and you feed it interpolated noise, which it handles worse.

How I test it

I render a reference at 64 spp with the denoiser off. Then I render each option and compare on a still frame with PSNR and SSIM, and on a 5 second camera pan with a flicker check: in a static region, consecutive frames should barely differ. A denoiser that smears moving detail passes the still test and fails the pan, so the pan is the one I trust.

The test scene needs a small bright emissive light, thin geometry such as railings, a glossy floor and a moving character. The emissive light exposes fireflies and clamping. Thin geometry exposes upscaling blur and wrong normals in the denoiser input. The moving character exposes ghosting, where temporal history from the previous frame leaks into newly revealed pixels for more than a frame or two.

When raster wins

Raster fallback means shadow maps plus screen space reflections or a probe for the floor, and no ray traced global illumination. It costs a fraction of the ray pass, often 2 to 3 ms for the same scene, and it has no denoiser artifacts. Its failures are different: reflections vanish when the reflector leaves the screen, and contact shadows detach at grazing angles.

I switch to raster when the lowest ray traced tier, 0.5 scale at 1 spp, still exceeds the budget at p95, or when PSNR against the reference drops below about 30 dB on the still frame. Below that point the ray traced image is no longer a faithful version of the scene. A clean raster image reads better than a noisy ray traced one, and the player notices the noise before they notice the missing indirect bounce.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-89How do you select a mesh LOD from screen-space error, and what stops it popping or thrashing between levels while streaming?

The 90-second answer

Pick the coarsest LOD whose projected error stays under a pixel budget, usually 1 to 2 pixels for the silhouette. For each LOD I store a geometric error bound, the maximum distance a simplified vertex can move from the original surface, measured in world units. At runtime I project that bound to screen space and compare it with the budget. Hysteresis stops thrash: I use a tighter threshold to step up to a finer LOD than I use to step down to a coarser one, and I add a short dwell time before a downgrade is allowed. Streaming is a separate priority problem. I keep the resident LOD plus the next finer one for visible objects, load by error per byte, and never evict the LOD currently drawn.

Screen-space error

For a perspective camera, a world-space error e at distance d from the camera projects to roughly:

error_px = e * screenHeight / (2 * d * tan(fovY / 2))

Equivalently, error_px = e * focalPx / d, where focalPx = screenHeight / (2 * tan(fovY / 2)). I precompute e per LOD during the offline simplification, ideally as a Hausdorff-style bound or a conservative percentile of vertex displacement, and I also store the projected bounding sphere radius so a tiny but close object is not judged by vertex error alone.

Worked example, labelled as hypothetical figures: screenHeight = 1080, fovY = 60 degrees, so focalPx = 1080 / (2 * tan(30 deg)) = 935 px. A rock at d = 20 m has LOD errors e = 0.02 m, 0.08 m, 0.30 m from fine to coarse. Projected errors are 0.94 px, 3.7 px, 14 px. With a 1.5 px budget, the coarsest (14 px) and middle (3.7 px) both exceed the budget, so the finest (0.94 px) is selected. At d = 60 m the same errors project to 0.31 px, 1.25 px, 4.7 px. Now the coarsest (4.7 px) still exceeds the budget, but the middle (1.25 px) fits, so the middle LOD is selected. That distance dependence is the whole point. A fixed distance cutoff would keep the fine rock at 60 m and drop it too early when the camera zooms.

C++
// lods[0] = coarsest (largest error), lods[count-1] = finest (smallest error)
// focalPx precomputed per frame from height and fovY
int SelectLOD(const LodSet& set, float distance, float budgetPx, float focalPx) {
    for (int i = 0; i < set.count; ++i) {          // scan coarse to fine
        float errPx = set.lods[i].error * focalPx / distance;
        if (errPx <= budgetPx) return i;           // first fit is the coarsest fit
    }
    return set.count - 1;                          // none fit: use finest
}

Hysteresis and popping

Without hysteresis an object sitting exactly on the threshold flips every frame as the camera micro-moves, and the silhouette visibly pops. I split the thresholds:

TransitionThresholdReason
---------
Coarser to finer (upgrade)error_px > 1.0 * budgetReact quickly when detail is visibly missing
Finer to coarser (downgrade)error_px < 0.5 * budget for 10 framesRequire sustained slack before dropping detail

The 2x gap means the object must move well inside the budget before I downgrade, so small camera jitter cannot cross both thresholds. The dwell counter handles the slow drift case, where the camera creeps toward the boundary over seconds. Upgrades are immediate because a missing silhouette is more noticeable than extra triangles for a few frames. I also fade or morph over 100 to 200 ms when the art team can afford a second draw, but I do not rely on fading to fix thrash. Hysteresis fixes thrash, fading only hides the pop that remains.

Streaming

LOD selection assumes the chosen mesh is resident. In an open world it often is not, so I treat residency as a budgeted cache. Each frame I score visible objects by projected error if they stayed at their current resident LOD, multiplied by screen area, and I load in that order until I hit a per-frame byte budget, for example 8 MB or 2 ms of upload time, whichever comes first. I always keep the currently drawn LOD pinned until its replacement has finished uploading, then swap atomically. Eviction goes to the lowest score, which is usually far, small, or off-screen objects. I prefetch one level finer than the selected LOD for objects the camera is approaching, using camera velocity, because the upgrade request otherwise arrives exactly when the player reaches the object.

Failure modes I check in a test scene: a long thin mesh whose vertex error is small but whose silhouette error is large, which the bounding sphere term catches; a streaming hitch when a whole district unloads at once, which the per-frame budget prevents; and a downgrade storm when the camera teleports, which I handle by allowing immediate downgrades on teleport and only applying dwell to continuous motion.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-90Walk me through designing GPU-driven frustum and occlusion culling with indirect draws for 200,000 instances, including compaction, Hi-Z, and when you would fall back to the CPU?

The 90-second answer

I would keep the CPU out of the per-instance loop. The CPU uploads one buffer of instance records, one buffer of mesh references, and the camera matrices for this frame. A compute pass tests every instance against the frustum, then against a Hi-Z pyramid built from last frame's depth, and appends survivors to a compacted list. A second, tiny pass or the same pass with a counter writes the indirect draw arguments. The renderer then issues one vkCmdDrawIndexedIndirect or DrawIndexedInstancedIndirect per mesh, with the count taken from that buffer. No readback, no per-frame CPU loop over 200,000 items.

Assumptions I would state up front: Vulkan or D3D12 with indirect draws and compute, a depth prepass or the previous frame's depth available, and instances that are mostly static so the instance buffer changes rarely. If I have no depth history on frame one, occlusion culling is disabled and only frustum culling runs.

Data layout

Per instance, 64 bytes is a comfortable budget: bounding sphere centre and radius packed with the model matrix offset, or a full matrix if the instance count is lower. For 200,000 instances at 64 bytes that is 12.8 MB, read once by the cull pass. That read is sequential, so the pass is bandwidth bound, not ALU bound. I would store instances in SoA if the cull needs only the sphere: centres in one array, radii in another, matrices in a third read only by the draw. That lets the cull pass skip the matrix data for rejected instances.

HLSL
struct Instance { float3 centre; float radius; float4x4 model; uint meshId; };
struct IndirectDraw { uint indexCount; uint instanceCount; uint firstIndex; int vertexOffset; uint firstInstance; };
// cull pass: one thread per instance, 256 threads per group
// writes survivors to compacted[] and increments counter[meshId]

The indirect buffer needs one entry per mesh, not per instance. With 40 meshes that is 40 entries, 20 bytes each in D3D12 layout, padded to 32 bytes in Vulkan. The instanceCount field is what the GPU fills in. I would zero that buffer each frame with a fill, or have the cull pass write it, and I would keep a separate copy of the counts on the CPU only for debugging, never for submission.

Frustum test and compaction

Extract six planes from the view-projection matrix on the CPU and pass them as a constant buffer, or extract them in the shader. The test is the standard sphere test: for each plane, dot(centre, normal) + distance > -radius must hold for all six. A sphere is cheap and conservative. An AABB test is tighter for elongated objects but needs the world-space box, which means reading the matrix in the cull pass and losing the SoA benefit. I would use spheres for the first pass and only add AABB refinement if profiling shows too many survivors.

Compaction is where the design usually breaks. A global atomic counter per mesh serialises appends. With 200,000 instances and 40 meshes, contention is low because threads for different meshes hit different counters. Threads for the same mesh contend, but the append is a single atomic add and a store. The failure mode is non-deterministic ordering of survivors, which matters if I later sort by depth for transparency or for overdraw. For opaque instances I accept it. For transparent instances I would not use this path, or I would do a prefix sum compaction instead, which costs an extra pass and a scan but gives stable order.

Worked trace, hypothetical but labelled as such: 200,000 instances, camera facing a city block. Frustum test keeps 61,000. Hi-Z test keeps 38,000. The cull pass reads 12.8 MB and writes 38,000 records at 64 bytes, about 2.4 MB. At 500 GB/s effective bandwidth that is roughly 30 microseconds of memory traffic, plus the atomic overhead. The alternative, CPU culling, would touch the same data over PCIe or through a readback and stall the pipeline for milliseconds.

Occlusion with Hi-Z

I build a Hi-Z pyramid from the depth buffer after the depth prepass or after the opaque pass of the previous frame. Each mip takes the maximum depth of a 2x2 block, because in reversed-Z or standard depth the farthest value is the conservative one for occlusion. To test an instance I project its bounding sphere centre to screen space, find the mip where the sphere covers roughly one texel, and compare the sphere's nearest depth against the pyramid texel. If the sphere is behind the stored depth by a margin, it is occluded.

Two details decide correctness. First, I use last frame's depth, so a fast camera cut or a teleport makes the test wrong for one frame. The symptom is a one-frame pop where occluded objects appear or visible objects vanish. I handle that by disabling occlusion culling for one frame after a cut, detected by a large change in camera position or by a frame counter reset. Second, the sphere test is conservative in the wrong direction for thin objects. A long thin wall seen edge-on projects to a small screen area, and the pyramid texel may cover it even though parts are visible. The fix is a margin on the depth comparison and, for large objects, testing the eight corners of the AABB instead of the centre. That costs more but only for objects above a screen-size threshold.

StageInputOutputCost driver
Frustum cull200,000 spheres, 6 planes61,000 survivorsSphere read, 6 dot products
Hi-Z build1920x1080 depthPyramid, about 1.33x depth sizeOne pass per mip, bandwidth
Occlusion test61,000 projected spheres38,000 survivorsPyramid fetch, divergent
Compaction38,000 survivorsIndirect args, 40 meshesAtomic counter, write bandwidth

When I would not do this

If the instance count is under about 10,000, CPU culling with a BVH or a simple loop is simpler and the GPU pass overhead dominates. If the scene is mostly dynamic and the instance buffer is rewritten every frame, the upload cost may exceed the cull saving. If the camera moves very fast, last-frame Hi-Z lags and I would fall back to frustum only, or to hardware occlusion queries for a small set of large occluders. Hardware queries avoid the pyramid build but they stall the CPU if I read the results, so I would use them only for a handful of hero objects and never in the main loop.

How I would test it

I would render a debug view with three colours: green for frustum survivors, yellow for occlusion survivors, red for culled. Then I would run a scene with known occluders, a wall that should hide a row of boxes, and check the counter values against the expected counts. I would also capture with Nsight Graphics or PIX and check that the indirect draw count matches the compacted buffer, that the draw is a single call per mesh, and that no CPU readback appears in the timeline. A regression test would fix the camera, disable occlusion, and compare the survivor count to a golden value, because a silent change in plane extraction or depth format shows up there first.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-91Walk me through how you would run a postmortem on a 45 ms frame spike you suspect was caused by a buffer upload or a GPU synchronization stall?

The 90-second answer

I would start from a captured frame, not from the spike in the FPS graph. I need CPU timestamps, GPU timestamps and markers on the same timeline, with the frame number attached to every event. Then I separate three cases that look identical in a frame-time plot: the CPU stalls while the GPU is idle, the GPU stalls while the CPU is already ahead, and the GPU is genuinely busy doing a copy.

For an upload stall, the copy queue or a memcpy shows up on the GPU timeline and the CPU is blocked in a map or a fence wait. For a synchronization stall, the GPU timeline has a bubble, the CPU timeline shows a wait, and no copy work explains the gap. If I cannot draw that timeline, I do not have a postmortem, I have a guess.

Worked trace, hypothetical capture

Frame 1842, budget 16.6 ms, measured 47.3 ms. PIX or Nsight Graphics capture, GPU timestamps in ms relative to frame start:

TimeCPUGPUReading
0.0Submit frame 1842, 212 drawsDraws 1 to 180 executeNormal
4.1MapBufferRange on dynamic vertex buffer, blocks 31 msIdle after draw 180 at 5.0CPU wait, GPU starved
5.0 to 36.0Blocked in map, driver flushing staging pagesIdle bubbleSync or upload, not shading
36.2Unmap, submit draws 181 to 212Copy of 96 MB texture, 6.1 msUpload work starts late
42.3Submit frame 1843Draws 181 to 212 execute, 4.8 msFrame ends at 47.3

That trace rules out a shader cost. The GPU was idle for 31 ms while the CPU waited. The copy itself took 6.1 ms, which is real but secondary. The primary fault was the CPU blocking on a buffer the GPU had not finished reading, then paying the upload after the block.

Arithmetic checks the copy. A 96 MB upload at an effective 16 GB/s on PCIe 4.0 x16 is 6.0 ms, matching the measured copy. If the same data went through a staging buffer that needed a CPU memcpy first, at roughly 10 GB/s that memcpy alone is 9.6 ms. Two serial copies explain why a single asset can eat a whole frame even when the GPU copy engine looks fast on paper.

How I confirm which mechanism it was

I look for four signals in the capture. First, frequency. A spike on the first frame a mesh or texture appears points to first-use upload, page-in or pipeline creation. A spike every N frames points to a ring buffer wrapping or a fence being waited on in a cycle. Second, size correlation. I log upload bytes per frame and plot them against frame time. A 40 ms spike that tracks a 120 MB texture streaming in is an upload. A spike with near zero upload bytes is synchronization or compilation. Third, queue. On D3D12 or Vulkan, a copy queue that is busy while the direct queue is idle means the work was placed on the wrong queue or the copy was submitted too late. Fourth, wait location. A CPU stack sample inside vkQueueWaitIdle, MapBufferRange with a flush, or a fence wait with a long timeout tells me the thread was parked, not computing.

I also check the driver counters for the frame. High page faults, high staging allocation count, or a large vkCmdCopyBuffer with a small transfer count all point to upload path problems. A long gap between the last draw of the previous frame and the first draw of the next, with both queues empty, points to a barrier or a render pass dependency that serialized work the engine could have overlapped.

Fix, and the failure mode of the fix

For per-frame dynamic data I use a ring staging buffer with a fence per ring slot, not one fence for the whole frame. The CPU writes into a slot only after that slot's fence signals, and the slot size is a multiple of the frame's worst case update, not the average.

C++
// One slot per frame in flight, 3 slots for 3 frames in flight.
struct RingSlot {
    uint8_t* cpuPtr;      // persistently mapped, coherent
    Fence  fence;         // signalled when GPU finished reading this slot
    uint32_t bytesUsed;
};

void UploadDynamic(RingSlot& slot, const void* src, uint32_t bytes) {
    slot.fence.Wait();    // only this slot, not the whole GPU
    memcpy(slot.cpuPtr, src, bytes);
    slot.bytesUsed = bytes;
    // Record a copy from this slot into the real buffer on the copy queue,
    // then signal the slot fence after that copy completes.
}

Persistent mapping removes the map and unmap cost per frame. The ring removes the stall where the CPU overwrites data the GPU is still reading. For large one-off uploads, such as a 96 MB texture, I chunk them across frames with a per-frame byte budget, for example 8 MB per frame, and I put them on the copy queue so the direct queue keeps drawing the old mip or a placeholder.

The ring has its own failure mode. If a frame update exceeds the slot size, the write either truncates or forces a stall on a larger allocation. I guard that with an assert in development builds and a fallback to a one-off staging allocation in shipping builds, plus a counter for how often the fallback fires. If that counter climbs, the slot size is wrong for the content, not the code.

In the postmortem I would close with the capture, the byte count, and the before and after frame times on the same scene. A fix that only moves the spike from frame 1842 to frame 1843 because the ring wrapped later is not a fix, and the timeline will show it.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-92A PR moves a lighting loop from float to half precision to save bandwidth. What would you check in review before approving it for a large open world?

The 90-second answer

I would ask where the half values come from before I look at the frame time. Half precision is fine for a normalized direction or a 0 to 1 colour. It is not fine for a world position in a large open world, because the spacing between representable values grows with the size of the number. If the PR converts vWorldPos to half before subtracting the light position, the light direction will be wrong far from the origin even if it looks correct in the test level near 0,0,0.

So my review question is simple: which values stay in float, and what is the largest coordinate the game actually uses? If the author cannot answer that, I would not approve it.

Why the position breaks

Binary16 has 10 mantissa bits. That gives about three decimal digits of precision. The spacing between consecutive values is roughly the magnitude divided by 1024.

MagnitudeSpacing in halfWhat that means
1 mabout 0.001 mFine for a direction
100 mabout 0.1 mNoticeable jitter in a subtraction
1,000 mabout 1 mLight vector quantised in metre steps
10,000 mabout 8 to 10 mTwo nearby objects map to the same half position

Worked trace, with a hypothetical but typical open world offset. Take a light at 10,004 m and a fragment at 10,000 m on the x axis. The true offset is 4 m. In half, 10,000 and 10,004 can round to the same representable value or to values 8 m apart, depending on the exact numbers. The subtraction then gives 0 or 8 instead of 4, and normalizing that gives a direction that is off by tens of degrees or a zero vector. The diffuse term max(dot(N, L), 0) jumps between frames as the camera moves, which shows up as flickering lighting on distant geometry.

Cancellation makes it worse. Subtracting two large, close values in half throws away most of the significant bits before the subtraction even happens. Doing the subtraction in float and converting the result is the safe order:

HLSL
// Risky: convert first, subtract second

half3 offset = (half3)lightPos - (half3)vWorldPos;
half3 L = normalize(offset);

// Safer: subtract in float, convert the direction
float3 offsetF = lightPos - vWorldPos;
half3 L = normalize((half3)offsetF);

The second version still gets the bandwidth saving on the varying if the author packs the normalized direction, but the precision loss happens after the large values have cancelled each other. That is the split I would ask for.

What I check in the PR

First, the diff should show the scope of the conversion. I want world position, view vector and any accumulation over many lights kept in float. Colour, albedo and the final normalized direction are reasonable candidates for half.

Second, I want a capture at the far edge of the world, not just at the origin. Same camera, same scene, before and after, with a debug view of the light vector. A mean error over the whole frame hides this bug because most pixels near the camera are fine. The maximum error and its location tell the story.

Third, I check the small end of the range as well. Half denormals lose precision below about 6e-5 and some hardware flushes them to zero. If the shader multiplies small weights or adds a tiny ambient term in half, that term can vanish. Keeping accumulation in float avoids that too.

The trade-off to state in review

Half saves bandwidth on varyings and can be faster on hardware with native fp16 arithmetic, but it does not save anything if the conversion forces extra instructions or if the target GPU runs fp16 at the same rate as fp32. I would ask for the frame time on the lowest tier device, not only on the development GPU, and I would accept a narrower change if the full conversion fails the far-offset capture: keep the subtraction and accumulation in float, convert only the packed direction and colour terms, and ship that. It keeps most of the saving without betting the lighting on a representation that cannot hold the inputs.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-93What do you gain and lose by moving lighting from per-vertex to per-fragment evaluation, and what platform support can you assume?

The 90-second answer

Per-vertex lighting evaluates the lighting equation once per vertex and interpolates the resulting colour across the triangle. Per-fragment lighting interpolates position, normal and other attributes, then evaluates the equation for every pixel the triangle covers. That move buys accuracy where the surface changes inside a triangle, and it costs fill rate, because the work scales with pixels rather than vertices.

The classic failure of per-vertex lighting is a highlight that falls between vertices. A Blinn-Phong specular peak, a normal-mapped bump, or a sharp diffuse falloff across a large triangle gets sampled only at its corners, so the interior can miss the peak entirely or smear it in straight bands. Per-fragment evaluation fixes that because each pixel sees its own normal and light direction.

Per-vertexPer-fragment
Work scales withVertices submittedPixels covered, including overdraw
Specular highlight inside a large triangleOften missed or bandedEvaluated at the pixel that needs it
Normal mappingNeeds a fragment stage anywayNatural fit
Large flat triangle, few verticesVery cheapPays per pixel for a result that barely changes
Interpolation artefactColour bands, wrong peak positionNormal must be renormalized per pixel

What it costs, in numbers

Take a hypothetical scene at 1920 x 1080. That is 2,073,600 pixels. Suppose the lit meshes cover 60 percent of the screen once, with no overdraw, so about 1.24 million fragment evaluations. If the same meshes have 200,000 vertices, per-vertex lighting does 200,000 evaluations and per-fragment does roughly six times as many, before counting extra passes, transparency or shadow map lookups. On a vertex-bound scene with small triangles the gap shrinks. On a screen-filling low-poly mesh it grows, which is why the upgrade is usually paired with a check on fill rate and overdraw.

The fragment version also needs the normal interpolated and normalized in the shader. Interpolated normals are not unit length inside the triangle, and skipping the normalize gives a diffuse term that varies with triangle size.

GLSL
// GLSL ES 3.00, fragment shader. Checked against the OpenGL ES 3.0 spec.
#version 300 es
precision mediump float;

in vec3 vNormal;    // interpolated, not unit length
in vec3 vWorldPos;
out vec4 fragColor;

uniform vec3 uLightDir;
uniform vec3 uLightColor;

void main() {
    vec3 n = normalize(vNormal);
    float diff = max(dot(n, uLightDir), 0.0);
    fragColor = vec4(uLightColor * diff, 1.0);
}

Platform support

You can assume per-fragment lighting on any current mainstream target. Vulkan, Direct3D 11 and later, Metal, OpenGL ES 3.0 and WebGL2 all require a programmable fragment shader, and fixed-function per-vertex lighting was removed from OpenGL core in 3.1. The practical limit is not support, it is budget on tile-based mobile GPUs, where a fragment-heavy pass writes tiles and can spill to memory if overdraw is high. Test on the lowest target device, not only on desktop.

When I would not upgrade

Distant, low-poly, vertex-bound content with no specular or normal detail gains little, and the extra fragment cost can push a fill-bound frame over budget. I keep per-vertex or baked lighting there, and spend the fragment budget on the close-up hero assets. The decision test is simple: render the same scene both ways, compare the highlight and normal detail on a close-up, then measure frame time at full resolution on the weakest target. If the visual difference is invisible at gameplay distance, the upgrade is not worth paying for every pixel.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-94How would you test that clip space, NDC and the viewport transform behave as expected across OpenGL, Direct3D, Vulkan and Metal?

The 90-second answer

I would test the three stages separately, because a port that looks correct in one API can be upside down, depth reversed or culled inside out in another. Clip space is the homogeneous space before the divide, where clipping happens. NDC is clip space after dividing by w. The viewport transform maps NDC to framebuffer pixels and to the depth range. The APIs agree on the pipeline order and disagree on the ranges and on which way y and winding point.

StageOpenGLDirect3D 11/12VulkanMetal
Clip test-w <= x,y,z <= w-w <= x,y <= w, 0 <= z <= w-w <= x,y <= w, 0 <= z <= w-w <= x,y <= w, 0 <= z <= w
NDC rangex,y,z in [-1,1]x,y in [-1,1], z in [0,1]x,y in [-1,1], z in [0,1]x,y in [-1,1], z in [0,1]
Viewport originbottom left, y uptop left, y downtop left, y down unless height is negativetop left, y down
Default front facecounter clockwiseclockwisedepends on frontFace, commonly clockwise in portsclockwise
Depth mappingz_ndc in [-1,1] mapped by depth rangez_ndc in [0,1]z_ndc in [0,1]z_ndc in [0,1]

That table is the whole porting risk. A projection matrix written for OpenGL, with z in [-1,1] and y up, fed unchanged to Vulkan or Metal gives z values that clip against 0 to w instead of -w to w, and an image flipped vertically. The fix is not a shader tweak. It is a different projection, typically y flipped and z remapped as z' = 0.5*z + 0.5, plus a viewport with negative height in Vulkan if you want to keep the old matrix.

Worked trace

Take a vertex in clip space: (0.5, -0.25, 0.5, 1.0). After the divide, NDC is (0.5, -0.25, 0.5) in every API. The difference is whether that vertex survives clipping and where it lands.

In OpenGL, z = 0.5 is inside [-1,1], so it passes. In Direct3D, Vulkan and Metal, z = 0.5 is inside [0,1], so it also passes. Now change the vertex to (0.5, -0.25, -0.5, 1.0). OpenGL keeps it. The other three clip it, because z is below 0. A test that only uses z = 0.5 will never catch a missing z remap. A test with z = -0.5 and z = 1.5 catches it immediately, because 1.5 is outside both ranges but for different reasons.

For the viewport, use a 1920 by 1080 framebuffer and NDC (0.5, 0.5, 0.25). OpenGL maps x to (0.5 + 1) * 1920 / 2 = 1440, and y to (0.5 + 1) * 1080 / 2 = 810 measured from the bottom. Direct3D, Vulkan with a positive height and Metal map y from the top, so y = (1 - 0.5) * 1080 / 2 = 270. Depth differs too. OpenGL writes depth = 0.25 * 0.5 + 0.5 = 0.625 into a [0,1] depth buffer. The others write 0.25. If you read back the depth buffer in a test and expect one value, you have encoded the API difference in the assertion instead of discovering it in a screenshot.

How I test it

I render a single triangle whose vertices are chosen in clip space, not in world space, so the expected result is known without trusting the projection code under test. One vertex at a time is enough. I set the viewport and scissor to a known size, clear to a known colour, draw a point or a tiny triangle at the probe position, and read back the pixel and the depth.

C++
// Expected framebuffer position for a probe NDC point.
// yUp = true for OpenGL, false for D3D/Vulkan(positive height)/Metal.
Vec2 expectedFb(Vec2 ndc, float w, float h, bool yUp) {
    float x = (ndc.x + 1.0f) * 0.5f * w;
    float y = yUp ? (ndc.y + 1.0f) * 0.5f * h
                  : (1.0f - ndc.y) * 0.5f * h;
    return {x, y};
}
// Expected depth written to a [0,1] depth buffer.
float expectedDepth(float zNdc, bool glStyle) {
    return glStyle ? zNdc * 0.5f + 0.5f : zNdc;
}

The probe set I run per API is small and deliberate. Corners of NDC at (-1,-1), (1,1) and (0,0) check the viewport scale and the y direction. A vertex with w negative checks that clipping happens before the divide, because dividing first would flip x and y and produce a point on the wrong side of the screen. Vertices with z at -0.5, 0, 0.5, 1 and 1.5 check the clip range and the depth mapping. A triangle wound clockwise in NDC checks front face handling, by writing the front facing flag to a colour channel in the fragment shader and asserting it matches the API convention.

I also run a golden image comparison across APIs, but only after normalising for the known differences. I flip the OpenGL image vertically, remap depth, and then compare with a tolerance of one pixel and a small depth epsilon. Without that normalisation, a cross API golden test fails on every frame and teaches nobody anything. With it, a failure points at a real bug, such as a projection matrix that was remapped twice, or a viewport height that was negated in Vulkan while the shader also flipped y.

The failure mode I see most often is a port that passes on a centred, symmetric test scene. A cube at the origin looks fine upside down and with reversed depth. The probe vertices above are asymmetric on purpose. They break that symmetry, so the test fails for the right reason on the first run instead of in a shipped level.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-95How would you choose depth-stencil and colour formats and attach multiple render targets for a deferred pass on desktop and tile-based mobile GPUs?

The 90-second answer

I start from what each attachment has to survive, not from a favourite format. Depth needs enough precision for the scene's depth range and for the tests I run against it. Colour needs enough precision and range for the data written in that pass, and no more bandwidth than that. Then I check the hardware limits for simultaneous attachments, because MRT is where desktop and tile-based designs diverge.

For a deferred G-buffer on desktop I would typically use D32F or D24S8 for depth, plus three or four colour targets: albedo in RGBA8 or BC7-compressed where possible, normal and roughness packed into RGBA16F or RGBA8, and emissive or velocity in RGBA16F. On a tile-based mobile GPU I would cut that list, use D24S8 or D16 if the depth range allows it, and prefer formats the tile memory can hold without spilling to DRAM.

Depth-stencil formats

Format (Vulkan / D3D12 / Metal names vary)Bytes per pixelUse it whenWatch out for
D16_UNORM2Mobile, shallow depth range, no stencilZ-fighting returns quickly past a few hundred metres, no stencil
D24_UNORM_S8_UINT4General desktop and mobile default24-bit depth is plenty for most games, stencil is only 8 bits
D32_SFLOAT4Reversed-Z, very large or very small near planeSlower depth compare on some older hardware, no stencil
D32_SFLOAT_S8_UINT8Reversed-Z plus stencil, shadow or stencil-buffer effectsDouble the depth bandwidth of D24S8, check vendor support
D24_UNORM_S8_UINT with separate stencil read4Stencil tests in a later passSome APIs need a separate stencil view or a layout transition to read it

The arithmetic decides quickly. At 1920x1080, D24S8 is 4 bytes x 2,073,600 pixels = 8.3 MB per full-screen write, before MSAA resolve. D32F_S8 is 16.6 MB. If I also write three RGBA16F targets, that is 8 bytes each, 49.7 MB combined. A pass that writes 74 MB of attachments at 60 fps is pushing 4.4 GB/s just for those writes, and reads for the lighting pass roughly double it. That is fine on a desktop card with hundreds of GB/s, and it is the whole budget on a phone.

Precision is the other axis. D24 gives about 16.7 million distinct depth values, D16 gives 65,536. With a near plane of 0.1 m and far of 1000 m, D16 will z-fight on distant overlapping geometry no matter how I bias it. D24 handles that range, and reversed-Z with D32F handles it better because the float representation spends precision near the camera where it matters. I only pick D16 when the scene is a small arena or a cockpit, where I can tighten near and far and prove it with a test scene.

Render target formats

Colour format follows the data. Albedo is LDR and sRGB, so RGBA8_SRGB is enough and halves the bandwidth of RGBA16F. Normal maps are stored as signed data in [-1, 1], so I pack them into RGBA8 with a bias, or use a dedicated format like R11G11B10F if I want HDR normals without a full 16-bit target. Roughness and metalness fit in one or two 8-bit channels. Emissive, velocity and HDR lighting accumulators need RGBA16F, because RGBA8 clips at 1.0 and banding shows up in bloom and tone mapping.

Two traps come up in interviews and in production. First, sRGB render targets: writing linear HDR data into an sRGB target applies conversion on write on most hardware, which silently changes lighting math. I keep G-buffer targets linear and do the sRGB conversion once, at the final output. Second, blending: in D3D12 and Vulkan, blend state is per attachment, so one MRT can blend while another does not. In older OpenGL and in some Metal configurations, MRT blending and write masks are more constrained. If I need different blend modes per target, I test that explicitly on each API instead of assuming it.

MRT attachment selection

The limits are similar on paper and different in cost. Vulkan guarantees at least 8 colour attachments, D3D12 allows 8 simultaneous render targets, and Metal allows up to 8 render targets per pass on modern Apple GPUs. The real limit is tile memory on TBDR hardware. A Mali or Adreno tile might hold a few megabytes. Three RGBA16F targets at 1080p will not fit in one tile, so the driver spills, reloads, or splits the pass, and the frame time jumps in a way that does not show up on desktop.

C++
// Vulkan-style attachment selection for a deferred pass
VkFormat depthFormat = useReversedZ ? VK_FORMAT_D32_SFLOAT_S8_UINT
                                      : VK_FORMAT_D24_UNORM_S8_UINT;
std::vector<VkFormat> colourFormats = {
    VK_FORMAT_R8G8B8A8_UNORM,   // albedo, sRGB handled at output
    VK_FORMAT_R16G16B16A16_SFLOAT, // normal + roughness packed
    VK_FORMAT_R16G16B16A16_SFLOAT  // emissive / velocity
};
// On TBDR: drop the third target, pack velocity into alpha of albedo
// or recompute it, and set loadOp = DONT_CARE for transient targets.

That last comment matters. On tile-based GPUs, transient attachments that are never read after the pass should use load and store actions that discard them, so they stay in tile memory. Storing them to DRAM costs a full write and a later read for no benefit. On desktop immediate-mode GPUs the same setting is mostly harmless, but the win is on mobile.

My selection process is therefore: list the data each pass actually needs, pack channels aggressively, pick the smallest format that holds the range, count the bytes at target resolution, and check the attachment count and tile budget on the weakest device I ship to. If the count or the bytes exceed that budget, I split the pass or move a target to a compute-written buffer instead of adding another MRT. I verify with a capture in RenderDoc or Xcode GPU Frame Capture, checking actual DRAM traffic and spill counters, not just the format names in the code.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-96How would you test sampler addressing, filtering and swizzling so a texture layout that looks correct on one GPU does not produce seams, shimmer or cache thrashing on another?

The 90-second answer

I would use one procedural texture whose value encodes its own coordinates, sample it through a fullscreen quad with an explicit sampler, read the framebuffer back, and compare each pixel against a CPU reference using the same addressing and filtering rules. Then I vary one thing at a time: UV range, sampler descriptor, forced mip, and upload layout. That separates a sampler bug from a shader bug, and a swizzle bug from a filtering bug.

The texture is 256 by 256 RGBA8. R holds x divided by 255, G holds y divided by 255, B is constant, A is 255. A checkerboard hides half-texel errors. A coordinate texture turns an offset, wrap or scramble into a numeric error I can assert on.

Addressing: test the edges

I sweep UV from -0.25 to 1.25 on both axes with nearest filtering and mip 0 forced. The CPU reference applies the addressing rule per axis before lookup.

Modeu = -0.25u = 1.25Check
Wrap0.750.25Seam at tile boundary, no dark line
Clamp to edge0.01.0Edge texel stretched, no border colour
Clamp to borderborderborderBorder texel only
Mirror0.250.75Fold at edge, period 2.0
Mirror once0.250.75Reflect once, then clamp outside that

I repeat the sweep with linear filtering and magenta border texels. Magenta inside the quad means the filter footprint read outside the intended range. For an atlas I add a 4 texel magenta gutter around each subrect and force mip 2. At that mip the footprint spans about 4 base texels, so magenta bleeding in means the gutter is too small or the UVs need a half-texel inset.

Filtering and mips

For filtering I use a ramp where value equals x and sample along a horizontal line. Nearest must give a staircase stepping at texel centres. Linear must give a straight ramp between centres. I check the first and last texel separately, since implementations differ on clamping before or after the footprint.

For mips I force explicit LOD so screen derivatives do not hide the result:

HLSL
// HLSL, checked against Vulkan GLSL
Texture2D<float4> tex;
SamplerState samp;
float4 v = tex.SampleLevel(samp, uv, lod);

I render at lod 0, 1, 2 and 4 and compare against a CPU box downsample. At lod 4 a 256 texture is 16 by 16, so one wrong texel in the chain shows as a block error. Then I use implicit LOD on a grazing quad and measure variance along the line for anisotropy 1 versus 4. If variance stays high at 8, I record the frame cost of that budget on the target GPU instead of guessing.

Swizzling and access pattern

Tiled layouts group texels into blocks, often 8 by 8 in Morton order, so neighbouring pixels share cache lines. I test correctness by uploading through the production path, including any tiled or compressed format, and sampling at texel centres with nearest. Every pixel must equal its coordinate. A swizzle mismatch gives blocks that are internally correct but permuted, which I print as a 32 by 32 error map.

For performance I time reads along x, along y, and strided by 32 texels. A row of RGBA8 is 1024 bytes. A warp reading 32 consecutive texels along x touches 128 bytes, one 128-byte cache line if aligned. The same warp reading down a column touches 32 different lines. That is the arithmetic behind most transpose problems.

If a pass reads transposed, I compare two fixes. Transposing on upload costs a CPU pass and extra memory, but keeps the shader simple and helps every consumer. Changing the shader to tile through shared memory, or swapping the traversal order, costs no upload time but complicates the shader and only helps that pass. I transpose on upload when several passes share the texture and the data is static. I tile in the shader when the texture streams in every frame or only one pass reads it transposed.

This exact-compare approach is the wrong tool for BC-compressed textures, where the coordinate encoding cannot survive compression, and for hardware anisotropic filtering, where vendors approximate differently and a pixel-exact match will fail on a correct implementation. There I switch to tolerance bands and variance measures. I also set every sampler field explicitly in Vulkan and D3D12 and never rely on a driver default. The suite reports max texel error, pixels outside tolerance, and time per access pattern, per API and per GPU.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-97When would you put data in a constant buffer versus a structured buffer, and how does that change for per-frame versus per-object data?

The 90-second answer

A constant buffer is for small data that is the same for every thread in a draw. A structured buffer is for larger, indexed data that threads pick from individually. Per-frame data such as view-projection, camera position and time belongs in the first. Per-object data such as a model matrix or material parameters belongs in the second, with a per-draw index selecting the element. That split is the placement decision.

HLSL
// HLSL, Direct3D 12 style bindings. Vulkan and Metal equivalents are
// uniform buffers and storage buffers / SSBOs.
cbuffer FrameCB : register(b0)
{
    float4x4 viewProj;  // 64 bytes
    float3 cameraPos;   // 12 bytes
    float time;         // 4 bytes, shares the 16-byte register with cameraPos
};                      // total 80 bytes

struct ObjectData
{
    float4x4 model;     // 64 bytes
    float4 tintRough;   // rgb tint, a roughness; 16 bytes
};                      // total 80 bytes, no padding ambiguity

StructuredBuffer<ObjectData> objects : register(t0);

ObjectData obj = objects[objectIndex];
float4 worldPos = mul(obj.model, float4(position, 1.0));

Why the two behave differently

PropertyConstant bufferStructured buffer
AccessUniform. Every thread reads the same value.Indexed. Each thread can read a different element.
SizeSmall. A few hundred bytes to a few KB is typical.Large. Thousands of elements are normal.
UpdateWrite the buffer, bind it for the draw.Upload the array once, change only the index per draw.
BindingDescriptor slot for constants, often b0.Shader resource slot, often t0.

Packing, stated exactly

HLSL packs cbuffer members sequentially into 16-byte registers. A member cannot straddle a 16-byte boundary, and array elements are padded to a 16-byte stride. A float3 therefore takes 12 bytes, and a following float can share its register, as cameraPos and time do above. A float4 always starts a new register. If the CPU side declares the same fields in a C++ struct with default alignment, the offsets will differ. I dump offsets from both sides and compare them. A mismatch here reads the next field as the current one, which looks like a shading bug and is not.

Worked placement

Take 5,000 static objects. At 80 bytes each, the object array is 400 KB. Uploading that once and binding it once costs one upload at level load. The alternative, a per-object constant buffer, means 5,000 CPU writes and binds per frame. That adds CPU work per draw and, if the writes are not kept ahead of the GPU with a ring buffer or multiple frames in flight, can leave the GPU waiting for the next bind. With a well-managed dynamic buffer and a few hundred objects it can still be fine, so the cost is a function of object count and buffering, not a guaranteed stall. At 5,000 objects the structured buffer plus index is the cheaper and simpler path.

The per-frame constant buffer stays at 80 bytes and is written once per frame. Each draw then supplies only an integer objectIndex, through a root constant, a vertex attribute or an instance ID.

Failure modes I check

Indexing is the silent one. An uninitialised or off-by-one index reads a valid but wrong element, so objects swap transforms with no error. I test with a debug view that colours each object by objectIndex % 8. If the pattern does not match, the index path is broken.

The other is layout drift between CPU and GPU structs after someone adds a field on one side only. Comparing the offset dump catches it before any rendering code is touched.

Rule I state in interviews: if every thread in the draw reads the same value, it is constant buffer data. If threads read different elements, it is structured buffer data. Per-frame goes in the first, per-object goes in the second, and the index bridges them.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-98Walk me through how you would optimize a fragment shader with a dynamic loop and divergent branches, and how you would decide whether unrolling helps or hurts instruction cache?

The 90-second answer

I would start from the compiled output, not the source. I would disassemble the shader, check register count, spill stores, loop body size and branch structure, then profile warp stall reasons and instruction cache misses. Unrolling is only a win if it removes loop overhead and enables scheduling without pushing the shader over its register budget or its instruction cache footprint. Branching is only a win if the divergent path is rare, short, or can be flattened with predication or arithmetic selection.

Take a lighting loop over 8 lights with a dynamic early-out. In HLSL it might look like this:

HLSL
float3 Accumulate(float3 n, float3 v, int count)
{
    float3 acc = 0.0;
    for (int i = 0; i < count; ++i)
    {
        Light L = lights[i];
        float d = length(L.pos - worldPos);
        if (d > L.range) continue;
        float att = saturate(1.0 - d / L.range);
        acc += att * BRDF(n, v, L);
    }
    return acc;
}

The compiler sees a loop-carried dependency on acc, a buffer load for lights[i], and a data-dependent continue. It will keep the loop, generate a branch per iteration, and inline BRDF only if the inlining budget allows it. My first move is to make the bound uniform and known at compile time where possible, for example requesting partial unroll with #pragma unroll 4 on a fixed 8-light loop, and to hoist the range test into a mask. I would then verify in the DXIL disassembly that the requested factor was actually applied, because the compiler can ignore or adjust the hint.

StrategyWhat it changesWhen it helpsWhen it hurts
No unroll, dynamic boundSmall code, loop overhead per iterationLarge or data-dependent loops, tight icacheLoop overhead dominates, compiler cannot schedule loads early
Partial unroll, factor 4Fewer branches, more independent loads in flightFixed small loops, 4 to 16 iterationsRegister pressure rises, spills appear
Full unrollNo loop branch, straight-line codeTiny loops, 2 to 4 iterations, heavy per-iteration mathCode size explodes, icache misses, long compile times
Flatten branch with selectBoth sides computed, result chosenShort branches, similar cost on both sidesExpensive side computed for every lane
Keep branchOnly taken path executes per warpRare heavy path, for example a shadow fallbackWarp divergence serializes both paths

Branching in a warp. In a 32-lane warp, if 4 lanes take the heavy path and 28 take the light path, the warp executes the light path with the 4 heavy lanes inactive, then executes the heavy path with the 28 light lanes inactive. Inactive lanes do not issue work of their own, but the warp still spends instruction slots on both sequences, so the cost is roughly the sum of both paths. Suppose the light path is 6 instructions and the heavy path is 40. Divergent execution costs about 46 instruction slots for that warp. If I rewrite the heavy path as a select after computing a cheap approximation, or move the heavy work to a separate pass for the 4 lanes, I can cut that. The decision depends on the ratio. If the heavy path is taken by 30 of 32 lanes most of the time, keeping the branch is fine. If it is taken by 1 lane in 32, I want it out of the main shader.

Unrolling and instruction cache. Unrolling trades loop overhead for code size. Say the loop body is 24 instructions and the loop overhead is 4. Four iterations without unrolling cost about 4 times 28, or 112 instructions. Unrolling by 4 gives 4 times 24 plus one loop overhead, or about 100 instructions, and it lets the compiler interleave the 4 light loads. That is a clear win if registers stay under the limit. Full unrolling of 8 iterations gives roughly 192 instructions of straight-line code before BRDF is inlined. Instruction cache size and line size are not published consistently across vendors, so I would not size this from a datasheet number. I would measure instruction cache miss stalls in Nsight Graphics or PIX and compare variants directly.

Register pressure is the usual limiter. Each extra unrolled iteration needs live values for position, attenuation and BRDF intermediates. On a hypothetical SM with 65,536 registers and a 2,048-thread limit, 40 registers per thread allows about 65,536 divided by 40, or 1,638 threads, which is about 80 percent of the thread limit. At 72 registers per thread the limit is about 65,536 divided by 72, or 910 threads, about 44 percent. That drop in resident warps can cost more latency hiding than the unroll gains. I check for local memory spills in the disassembly. A spill store and reload per iteration usually costs more than the loop branch I removed.

How I would decide in practice. I would build three variants: baseline, partial unroll with a uniform bound, and flattened branch. I would measure each on the target scene at the target resolution, with the same camera path, and record frame time, warp stall breakdown, register count and icache misses. I would also test the worst case, a scene where the early-out rarely triggers, because a shader tuned for the average case can regress badly there. The variant I ship is the one that wins on the worst case without spilling, not the one with the fewest instructions on paper.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-99How do FIFO, mailbox and immediate present modes differ on vsync, tearing, frame pacing and input latency, and how would you test which one a game should ship with?

The 90-second answer

Present mode decides when a finished frame reaches the scanout, and that timing controls tearing, pacing and latency together. FIFO waits for the next vblank and is the vsync path. Mailbox also waits for vblank but keeps only the newest frame, so a late frame replaces a queued one instead of delaying the next. Immediate presents as soon as the frame is ready, with no vblank wait, so it can tear. FIFO_RELAXED in Vulkan behaves like FIFO when the frame makes the deadline and like mailbox when it misses, which is the adaptive vsync behaviour.

Assume a 60 Hz display, 16.7 ms per refresh, and a game that renders in 10 ms. Input is sampled at the start of the frame, so the photon latency is roughly render time plus the wait until the next scanout that shows that frame.

ModeVsyncTearingPacing when render is lateAdded latency
FIFOOn, queue depth usually 2-3NoneBackpressure, frame times quantise to multiples of 16.7 msUp to 1-2 frame times plus queue
MailboxOnNoneDrops the stale queued frame, keeps 60 Hz cadenceAbout 1 frame time
ImmediateOffYes, when present lands mid-scanoutNo quantisation, frame time follows render timeLowest, render time plus scanout position
FIFO_RELAXEDOn if on time, off if latePossible on late framesKeeps cadence when possible, drops the wait when lateBetween FIFO and mailbox

Trace at 60 Hz, render takes 10 ms, present called at t=10 ms

Vblank at t=0, 16.7, 33.3 ms. Scanout takes the frame interval, so a frame shown at t=16.7 is scanned out during 16.7 to 33.3.

FIFO: frame ready at 10 ms waits, shown at 16.7 ms. Next frame ready at 26.7 ms, shown at 33.3 ms. Input sampled at 0 ms reaches the screen between 16.7 and 33.3 ms depending on scanout position, so 17 to 33 ms of latency. If render slips to 20 ms, the frame misses 16.7, shows at 33.3, and the following frame is held by the queue. The player sees a 33 ms step.

Mailbox: same wait to 16.7 ms. If render slips to 20 ms, that frame still shows at 33.3 ms, but if another frame is already queued it is discarded and the newest frame takes the 33.3 slot. Cadence stays at 60 Hz, latency stays near one frame, and the cost is a dropped simulation step rather than a hitch.

Immediate: frame ready at 10 ms is shown at once. The top of the screen may already be scanned out, so the top half shows the old frame and the bottom half shows the new one. That split line moves with render time, which is tearing. Latency is lowest because there is no wait, but the image is inconsistent from frame to frame.

Why the queue matters

FIFO with a deep queue decouples the render thread from the display. The GPU can run ahead, which hides small CPU stalls, but it also means the frame on screen is older. A queue of 3 at 60 Hz can add 50 ms before the player sees input. That is why competitive titles cap the number of frames in flight, often to 1 or 2, and why DXGI and Vulkan expose it as swapchain image count and max frames in flight rather than leaving it to the driver.

Mailbox trades that buffer for freshness. It is the right default for a 60 Hz game that cannot hold 60 fps every frame, because the display cadence stays clean and latency does not grow when the scene gets heavier. It is a poor choice if the game relies on the queue to smooth CPU spikes, since dropping a frame also drops the work in it.

Immediate is only defensible with a tear-free alternative the player can see, such as a high refresh display at 144 Hz where a 7 ms frame rarely straddles a scanout in a visible way, or with a hardware tear control feature. Even then, pacing follows render time, so a variable 8 to 14 ms render produces variable motion.

How I would test the choice

I would run the same scene in each mode and record three things: frame time distribution, present latency, and a capture of the scanout. Frame time comes from PresentMon on Windows or the Vulkan frame timing layers, plotted as a histogram rather than an average. FIFO shows spikes at 33.3 ms when the deadline is missed. Mailbox shows a flat 16.7 ms cadence with dropped frames counted separately. Immediate shows the raw render distribution.

For latency I would use a test scene with a flashing pixel driven by input, or a photodiode on the screen in the lab, and measure input to photon. The numbers should match the trace above within a few milliseconds. If FIFO latency is 50 ms with a queue of 3, reducing swapchain images to 2 and max frames in flight to 1 should bring it near 33 ms without changing render time.

For tearing I would pan a high contrast vertical edge at a fixed speed and capture with a high speed camera or by reading back the back buffer timing. Immediate shows a horizontal discontinuity whose position tracks present time. The other modes show none, and FIFO_RELAXED shows it only on frames that miss the deadline.

Ship decision: FIFO for a locked 60 fps console style target where pacing matters more than the last 16 ms of latency, mailbox for a PC title that must hold cadence on weaker hardware, and immediate only when the target refresh is high enough that tearing is rare and the player opts in. I would expose the choice in settings and default to mailbox on PC, FIFO on a fixed refresh console build.

Curated: · Written: · Reviewed: —

Difficulty: Hard