Shader Code
Efficient GPU Mathematics
Shader Code lessons
Interpolation Playground
Every curve maps t=[0,1] to [0,1] but with different motion feel. Linear is robotic. Ease-in accelerates. Ease-out decelerates. Smoothstep and smootherstep have zero derivatives at endpoints. Watch the dots move at different speeds through the same interval:
Coordinate Space Selection
// Reconstruct world position from depth
vec2 uv = gl_FragCoord.xy / uResolution;
float depth = texture(uDepthTex, uv).r * 2.0 - 1.0;
vec4 clipPos = vec4(uv * 2.0 - 1.0, depth, 1.0);
vec4 worldPos = uInvViewProj * clipPos;
worldPos /= worldPos.w; // perspective divideFMA and Horner Method
Branch Avoidance
GPU warps execute in SIMD lockstep. Divergent branches stall idle lanes. Replace conditionals with branchless math:
// BAD: warp divergence
if (dot(n, l) > 0.0) diffuse = albedo * NdotL;
else diffuse = vec3(0.0);
// GOOD: branchless
float NdotL = max(dot(n, l), 0.0);
vec3 diffuse = albedo * NdotL;
// Patterns: step(), mix(), clamp()
float mask = step(0.0, x); // x>=0 ? 1 : 0
vec3 result = mix(a, b, mask); // selectSmoothstep vs Smootherstep
smoothstep is C1 (zero 1st derivative at endpoints). smootherstep is C2 (zero 1st AND 2nd derivatives) -- critical for seamless noise normals:
GPU Warp Divergence Simulator
32 GPU threads execute in lockstep. When a branch causes divergence, non-taken threads idle — wasting cycles. Toggle between branching and branchless to see the cost:
Texture Fetch Latency
Dependent texture reads stall the pipeline — the 2nd fetch needs the 1st result. Optimized code fires textures early, does ALU while waiting, and packs channels:
Precomputed BRDF LUTs
Precision
// inversesqrt = 1 SIMD instruction
vec3 n = v * inversesqrt(dot(v, v)); // fast normalize
// Fire texture early, ALU while waiting
vec4 albedo = texture(uAlbedo, uv); // fetch
vec3 normal = computeNormal(uv); // ALU
vec3 color = albedo.rgb * light(normal);
// Channel packing
vec4 orm = texture(uORM, uv);
float ao = orm.r;
float roughness = orm.g;
float metallic = orm.b;