HomeJournalThis post

Thin-Film Interference Shaders in WebGPU

Turn thickness and view angle into bounded spectral interference color, expose assumptions, compare sample counts, and archive art-directed WebGPU presets.

JP
JP Casabianca
AI Engineer and Product Designer · full-stack delivery · Bogotá

A thin-film interference shader answers how thickness and view angle can drive iridescent color without disguising an RGB shortcut as full physics. This tutorial builds a bounded spectral sampler, WGSL-ready constants, an angle-thickness atlas, and reproducible art presets.

Thin-film interference shader starts with two paths

When light reaches a thin layer, part can reflect at the first boundary while another part travels through the film, reflects below, and emerges. Their phase relationship depends on wavelength, optical thickness, incident angle inside the film, refractive indices, and phase changes at reflection. Constructive and destructive interference therefore vary across the spectrum.

The Belcour and Barla research page provides a rigorous rendering reference. This thin-film interference shader adopts a deliberately smaller teaching model: one homogeneous, non-absorbing layer over a substrate, bounded indices, a compact wavelength set, and an art-directed thickness field. Those assumptions are visible rather than hidden.

The committed Node fixture calculates named spectral samples and maps them into bounded display RGB through fixed approximate response curves. Its values are mathematical outputs of local constants, not measurements of soap, oil, coatings, a display, or a production WebGPU renderer.

Draw the normal and angle convention in every thin-film interference shader debug mode. Many plausible-looking shaders are mirrored or use the wrong cosine because coordinate spaces changed between pipeline stages.

Compute optical path difference

For a simple layer, optical path difference grows with refractive index, film thickness, and the cosine of the refracted angle. Convert the external view or light angle using the chosen refraction relationship, clamp domains before square roots, and track units. Thickness in nanometers and wavelength in nanometers keep the phase ratio understandable.

Reflection phase changes matter when light crosses boundaries with different indices. A compact shader may encode the relevant phase offset for its chosen case, but should not pretend one constant covers arbitrary material stacks. A thin-film interference shader needs a named preset that includes film index, substrate index, thickness range, sample wavelengths, and illumination assumption.

Visualize both reflected paths and the added distance. That diagram catches sign and angle mistakes more effectively than tuning color until it looks iridescent. Keep an option to display raw phase or cosine response before spectral-to-color mapping.

Separate light direction from view direction even when the first study keeps them aligned. The receipt should reveal that simplifying choice instead of hard-coding it invisibly.

Thin-film phase pathIncident light splits into reflected ray ribbons at the top and bottom film boundaries, accumulating angle-dependent path difference.incident spectrumsurface reflectioninternal path + reflectionthickness
  1. One amplitude reflects at the first boundary.
  2. Another travels through the film and reflects below.
  3. Wavelength, angle, refractive index, and phase changes determine interference.
Thin-film phase path reading key
SignalInterpretation
Thin-film phase pathIncident light splits into reflected ray ribbons at the top and bottom film boundaries, accumulating angle-dependent path difference.
Figure 1: The shader color begins with a path difference, not a rainbow lookup texture.

Sample wavelengths before converting to RGB

Evaluate interference at several wavelengths across the visible range, weight by an illuminant and approximate observer response, accumulate tristimulus-like channels, then map into the display space. More samples reduce spectral aliasing but cost shader work. Fewer samples can be an intentional stylization if the limitation is named and tested.

Spectral interference color is not equivalent to cycling hue by thickness. The phase is wavelength-dependent, so color bands emerge from the different constructive conditions. The spectral color mixing article covers another spectrum-to-display workflow, while this piece focuses on reflective interference.

Compare a compact sample set against a denser CPU reference on a bounded thickness-angle grid. The artifact uses named wavelengths and only asserts finite values inside its declared RGB bounds. A production renderer should commit its own error measure and performance evidence before reducing sample count.

A denser CPU oracle can remain slow because it runs on a bounded grid during qualification. Its role is comparison evidence, not real-time rendering.

Thickness-by-angle spectral quiltA quilt grid maps increasing film thickness across columns and view angle down rows with bounded spectral colors.thin → thickview angle changes downward
AxisMeaning
Columnsbounded film thickness
Rowscosine of view angle
Cellsampled spectral-to-display result
Thickness-by-angle spectral quilt reading key
SignalInterpretation
Thickness-by-angle spectral quiltA quilt grid maps increasing film thickness across columns and view angle down rows with bounded spectral colors.
Figure 2: The atlas makes art-direction regions visible before they wrap a surface.

Build a thickness-by-angle atlas

Before wrapping the model around geometry, render a two-dimensional atlas. Put film thickness on one axis and the cosine of the relevant angle on the other. Show spectral response, mapped display color, gamut clipping, and luminance. The atlas makes discontinuities, repetition rate, and bland parameter regions easy to find.

Film thickness color repeats as phase cycles, so a very wide range can create noisy bands. Choose a bounded interval whose rhythm supports the composition. Expose thickness offset and scale as art controls, but keep them in physical units inside the receipt. A thin-film interference shader becomes easier to direct when the artist sees the whole parameter field rather than one moving highlight.

The quilt in the article is an illustrative topology. The live visual should consume the same constants as the local fixture and include a fixed fallback. It cannot establish monitor gamut or perceptual accuracy without separate calibrated evidence.

Annotate recurring color bands with their thickness interval in the atlas. That helps art direction distinguish genuine phase repetition from gamut-map flattening.

The bounded spectral sampler reports finite display channels for archived thickness and angle presets without claiming calibrated optics.

Runnable artifact — thin-film-interference-fixture.mjs

import assert from "node:assert/strict";const wavelengths=[450,500,550,600,650],weights=[[.14,.04,.72],[.05,.32,.62],[.32,.82,.08],[.88,.42,.02],[.42,.05,.01]];const sample=(thickness,cosine,index=1.45)=>{const spectrum=wavelengths.map(w=>(1+Math.cos(4*Math.PI*index*thickness*cosine/w))/2);const rgb=[0,1,2].map(c=>spectrum.reduce((sum,value,i)=>sum+value*weights[i][c],0)/weights.reduce((sum,w)=>sum+w[c],0));return rgb.map(x=>Math.max(0,Math.min(1,x)))};for(const thickness of [180,320,560])for(const cosine of [.25,.6,1])for(const channel of sample(thickness,cosine))assert.ok(Number.isFinite(channel)&&channel>=0&&channel<=1);console.log("PASS: spectral samples remain finite and bounded");

Run node thin-film-interference-fixture.mjs. Expected receipt: PASS: spectral samples remain finite and bounded.

Translate the bounded model into WGSL

Pass refractive indices, thickness bounds, light direction, and preset parameters through a small uniform structure. Store wavelength and response weights as compile-time arrays or structured constants compatible with the target WGSL version. Use explicit f32 conversions and avoid dynamic indexing patterns that exceed the supported implementation profile.

The WGSL specification defines language behavior; the WebGPU specification defines API and pipeline rules. WGSL shader art should keep the CPU oracle close enough that representative phase and color points can be compared. A thin-film interference shader should not drift into a separate untested formula during optimization.

Clamp only at named stages. Early clamping can flatten interference, while late unchecked values can produce non-finite colors. Add debug outputs for thickness, internal cosine, phase at one wavelength, linear RGB, and mapped RGB. These views make the shader an inspectable instrument.

Test shader constants through a shared generated module or hash. Copying wavelength tables by hand invites silent divergence between the fixture and WGSL implementation.

Drive thickness with an authored field

A constant film produces angle-dependent bands; a spatial thickness field adds composition. Use a gradient, signed-distance shape, low-frequency noise, curvature, texture, or painted map. Keep the field bounded and serialize its seed, scale, transform, and source license. Do not imply the field was reconstructed from a real coating unless measurement evidence exists.

The domain-warping marble shader offers a compatible field language, but aggressive warping can overwhelm the interference logic. Start with one smooth ridge or radial field, then add restrained distortion. Preserve areas of quiet color so the effect reads as material rather than a universal rainbow overlay.

WebGPU iridescence works best when geometry, lighting, base reflectance, and thickness field have distinct roles. Save each preset as parameters, not only a screenshot. The receipt makes an art decision revisable after shader or browser changes.

Thickness textures need color-management and sampling rules of their own. Treat them as scalar data rather than letting an image loader apply an unintended display transform.

Art-directed shader surface and fallbackA curved preview surface carries contour bands beside a fixed fallback swatch and numerical transcript.fallbackpreset receiptWebGPU preview: optional enhancement
  • WebGPU consumes the same bounded spectral constants as the fixture.
  • A fixed image and parameter transcript preserve the thesis without GPU support.
  • Thickness fields are archived as art presets, not inferred material measurements.
Art-directed shader surface and fallback reading key
SignalInterpretation
Art-directed shader surface and fallbackA curved preview surface carries contour bands beside a fixed fallback swatch and numerical transcript.
Figure 3: A shader preview remains optional while its inputs and fallback stay inspectable.

Provide fallback, accessibility, and performance gates

Feature-detect WebGPU, handle adapter and device failure, and offer a fixed image generated from the same preset. A semantic transcript should name the thickness range, angle sweep, sampling count, assumptions, and visible relationship. Motion must respect reduced-motion preferences; stop continuous animation when the study is offscreen or the page is hidden.

Measure compile time, frame time, memory, and power-sensitive behavior on supported targets with a committed scene. The WebGPU generative art guide helps with renderer selection. A thin-film interference shader should degrade to a still visual rather than making the article's core explanation dependent on GPU access.

Check the figure at narrow width, zoom, forced colors for surrounding controls, and keyboard interaction. The color field itself cannot carry critical state; the atlas axes and transcript provide the readable argument.

Pause the device loop when the fallback replaces it, and release GPU resources on teardown. Graceful visual degradation should also be an honest resource lifecycle.

Archive an honest iridescent preset

Store shader version, formula variant, indices, thickness field, wavelengths, response weights, illuminant approximation, display transform, gamut map, geometry, camera, lights, seed, and fallback image digest. Label the model's simplifying assumptions beside the output. A preset is a reproducible artwork configuration, not a material certificate.

Test normal incidence, grazing limits, constant thickness, zero modulation, extreme bounds, dense CPU comparison, device loss, reduced motion, and fallback rendering. The WebGPU minimal surfaces article provides another surface context, but this preset should stand alone. A thin-film interference shader succeeds when its color logic survives inspection even after the novelty of motion fades.

Render one bounded preset and archive its thickness field before adding multiple layers or polarization. A smaller honest model gives the artist firmer control and gives reviewers a result they can actually reproduce.

Name every aesthetic deviation from the compact optical model—extra hue rotation, tone curve, bloom, or texture—so viewers can separate interference from finishing style. Compare the fixed fallback against one archived GPU frame at the same camera and preset, then record any intentional display-mapping difference instead of forcing pixel equality across renderers. Include the adapter, color target, capture method, viewport, shader revision, and fallback digest in that final complete comparison receipt.