Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Trace the subsurface block in the path tracer as a bounded random walk (part of #283)

Nguyen Xuan Anb62f58b28042
diff --git a/changes/283.md b/changes/283.md
index e3303e03..526ff15d 100644
--- a/changes/283.md
+++ b/changes/283.md
@@ -1,2 +1,3 @@
- Add a material `subsurface` block for skin, wax and leaves (part of #283): `weight` (0 to 1), `radius` (red, green, blue mean free path in units of `scale`, default `[1, 0.2, 0.1]`), `scale` (metres, default 0.05) and an optional `color`, named as Blender's Principled BSDF Subsurface Weight, Radius and Scale. Recipes and the MCP `scene_create` schema accept it with bounded numbers. The rasterizer widens the sun's diffuse past the shadow edge per channel and lets light through thin parts by the thickness the sun shadow map gives; the code is a lazily loaded addon (`@codepawlhq/67js/addons/subsurface-shader`, loaded by a recipe on its own) that compiles in only when a part has a weight above 0, so a scene without it draws the same picture and pays nothing. The path tracer does not read the block yet. `bench/reference/render-blender.py` exports it as Random Walk subsurface, and the reference scenes `subsurface` and `subsurface-off` score it against Cycles.
- Raise the subsurface addon back-face translucency from 0.5 to 1.0 (part of #283) so thin parts such as leaves pass more light, measured on the `subsurface` reference scene against Cycles; scenes without a subsurface weight draw the same picture.
+- The path tracer traces the `subsurface` block (part of #283): a bounded Random Walk for parts with a weight above 0 (mean free path radius times scale, colour mapped to a single scattering albedo, at most 32 scattering events, exit back to the surface) and thin translucency for a card with nothing behind it. A weight of 0 draws exactly the pictures it drew before. Against the Cycles render with subsurface on, the `subsurface` scene scores 0.0795 with weight 1 and 0.0875 with weight 0 at 64 samples; the GPU tracer still ignores the block.
diff --git a/changes/283.size.md b/changes/283.size.md
index 25f39ca1..bb698ece 100644
--- a/changes/283.size.md
+++ b/changes/283.size.md
@@ -8,3 +8,5 @@
- tool:scene_apply: the material subsurface block, twice (add-material and set-material), about 1,650 bytes.
- tool:scene_create_asset: the material subsurface block, about 825 bytes.
- result:scene_capabilities: one line naming the subsurface block, with the ranges kept in the tool schema.
+- entry:path-tracer: grows by about 1,040 bytes gzip for the subsurface random walk (path-tracer-subsurface.js) and the shading split, which the tracer carries for every scene because the walk runs inside its path loop.
+- entry:path-tracer+lazy: the same 1,040 bytes.
diff --git a/docs/path-tracer.md b/docs/path-tracer.md
index 83f2c07a..e187bf80 100644
--- a/docs/path-tracer.md
+++ b/docs/path-tracer.md
@@ -23,14 +23,18 @@ Unidirectional path tracing against the triangle BVH that the [light bake](light
- Emission: `emission` times `emissiveColor` (the base colour when none is given) times the `emissiveMap` texel at the hit, so a screen or a sign glows with its picture and lights what is near it. An emissive surface is found by the paths that hit it, not sampled as a light, so a small bright panel is noisy at low sample counts.
- Volume fog: `environment.volumeFog` is traced as a homogeneous medium inside its box, with its `density`, `color` (the scattering albedo), `anisotropy` (Henyey-Greenstein) and `maxDistance`. The distance to each scattering event is drawn from the exact free-flight distribution, so there is no step count and no banding. Every event is lit by next-event estimation (sun, point, spot, area lights and the sky, with shadow rays) and light reaching a surface through the fog is dimmed by it. Fog events count as bounces. `noiseAmount`, `noiseScale`, `drift`, `steps` and the `ambient` glow are rasterizer tricks and are not used.
+## Subsurface
+
+A part with a material `subsurface` weight above 0 sends that share of its diffuse light through a bounded random walk, after the Random Walk model of Blender's Principled BSDF (issue #283). The walk starts inward from the hit with a cosine-weighted direction, scatters isotropically with a per-channel mean free path of radius times scale in metres (one channel draws the distance and the other two are weighted by the mean density, so every channel stays unbiased), and leaves where it meets the part's own surface; there the path continues as white diffuse light with the walk's throughput, lit by every light. The colour is the block's `color`, or the base colour, mapped to a single scattering albedo with the fit Cycles uses, so a colour of 1 gives an albedo of 1 and gains no energy. A walk ends after 32 scattering events (`SUBSURFACE_WALK_STEPS`) or when it meets another part, and then its path ends. A point with no surface of its own behind it is a card: half of the colour is reflected on the near side and half is transmitted through it. The specular lobe and clear coat stay as they are, a weight of 0 takes the unchanged code path (the same samples and pixels), and the GPU tracer ignores the block until #302 packs it.
+
## What it does not draw
`report.ignored` lists the ones this scene asks for; a render job returns it as `metrics.pathTracer.ignored`. It names occlusion maps, anisotropy, iridescence, sheen, moss, splat layers, baked `lightMap`s, tagged materials (foliage, liquid, water and the like, traced as plain surfaces), blended transparency, and the fog fields above.
- The procedural sky when there is no environment map (the sky is black).
- Occlusion maps. Normal and metallic-roughness maps are drawn on UV-mapped and on box-projected materials. Material graphs and patterns are drawn through the colour map they bake.
-- Translucent leaves (foliage looks darker than in the rasterizer), liquids, foam and blended transparency (traced as plain or opaque surfaces).
-- Lights seen in mirrors (area lights and spot lights are lit but not visible), caustics, subsurface scattering, motion blur, depth of field, bloom and colour grade.
+- Translucent leaves without a `subsurface` block (foliage looks darker than in the rasterizer), liquids, foam and blended transparency (traced as plain or opaque surfaces).
+- Lights seen in mirrors (area lights and spot lights are lit but not visible), caustics, motion blur, depth of field, bloom and colour grade.
- Multiple-scattering GGX: rough metal is a little darker than in Blender.
## Limits
diff --git a/src/path-tracer-capabilities.js b/src/path-tracer-capabilities.js
index d41ca2d2..6ca6d2de 100644
--- a/src/path-tracer-capabilities.js
+++ b/src/path-tracer-capabilities.js
@@ -18,7 +18,7 @@ export const OIDN_DEFAULT_SAMPLES = 16;
export const PATH_TRACER_CAPABILITIES = Object.freeze({
setting: 'settings.renderer { type: "pathTracer", samples, bounces, denoise (true | false | "wavelet" | "oidn" | "none"), seed, maxSeconds, noiseThreshold }; image jobs only, no passes. Past maxSeconds the job fails.',
noiseThreshold: 'Default 0 draws every sample. Above 0 a pixel stops once its standard error relative to its mean is under the value, checked from 16 samples on: faster and noisier, and it cost quality on spot-area (score 0.0658 at 0, 0.0900 at 0.03). docs/path-tracer.md has the table.',
- traces: 'emissive maps and strength; volume fog as a uniform medium (density, colour, anisotropy, box; noise, drift and ambient are not used).',
- skips: 'occlusion maps, translucent leaves, liquids, anisotropy, iridescence, sheen, caustics, depth of field, bloom; metrics.pathTracer.ignored in the job result lists what the scene asked for.',
+ traces: 'emissive maps and strength; volume fog as a uniform medium (density, colour, anisotropy, box; noise, drift and ambient are not used); the material subsurface block as a bounded random walk (at most 32 scattering events, mean free path radius times scale in metres), and a card with nothing behind it as thin translucency.',
+ skips: 'occlusion maps, liquids, anisotropy, iridescence, sheen, caustics, depth of field, bloom; metrics.pathTracer.ignored in the job result lists what the scene asked for.',
limits: PATH_TRACER_JOB_LIMITS,
});
diff --git a/src/path-tracer-scene.js b/src/path-tracer-scene.js
index cae58caa..3544e5b8 100644
--- a/src/path-tracer-scene.js
+++ b/src/path-tracer-scene.js
@@ -3,6 +3,7 @@ import { createTracer } from './ray-query.js';
import { SUN_BIT, POINT_FIRST_BIT, SPOT_FIRST_BIT, AREA_FIRST_BIT } from './light-link-bits.js';
import { boxProjectedGeometry, columnLengths } from './export-box-uv.js';
import { resolveTraceVolume } from './path-tracer-volume.js';
+import { resolveTraceSubsurface } from './path-tracer-subsurface.js';
// The scene a path trace reads: every part flattened into one world-space triangle soup with per-vertex normals, UVs
// and colours, one resolved material per part, the lights in plain arrays, and the environment map as a sampling table.
@@ -95,6 +96,7 @@ function resolveMaterial(material) {
clearcoat: material.clearcoat ?? 0,
clearcoatRoughness: material.clearcoatRoughness ?? 0,
transmission: material.transmission ?? 0,
+ subsurface: resolveTraceSubsurface(material.subsurface),
ior: material.ior ?? 1.5,
texture: resolveTexture(material.map),
normalTexture: resolveTexture(material.normalMap),
diff --git a/src/path-tracer-shading.js b/src/path-tracer-shading.js
index 1ea2942b..8346fdc6 100644
--- a/src/path-tracer-shading.js
+++ b/src/path-tracer-shading.js
@@ -196,6 +196,9 @@ export function createSurface() {
sampledCoat: false,
coatAlpha: MINIMUM_ALPHA,
diffuseChance: 1,
+ // The diffuse light a part with subsurface sends through its random walk instead, and the Fresnel share it keeps.
+ subsurfaceChance: 0,
+ diffuseShare: 1,
specularChance: 0,
// Outputs of evaluate().
value: new Float64Array(3),
@@ -248,10 +251,33 @@ export function prepareSurface(surface, material, metallic, roughness, baseColor
const coatChance = surface.coatWeight;
const sum = diffuseLuminance + specularChance + coatChance;
surface.diffuseChance = sum > 0 ? diffuseLuminance / sum : 1;
+ surface.subsurfaceChance = 0;
+ surface.diffuseShare = diffuseShare;
surface.specularChance = sum > 0 ? specularChance / sum : 0;
surface.coatChance = sum > 0 ? coatChance / sum : 0;
}
+/**
+ * Moves `weight` of the diffuse lobe to the subsurface walk: the surface keeps the rest of the diffuse light, all of the
+ * specular and the coat, and `subsurfaceChance` is the chance of taking the walk, drawn before sampleSurface().
+ */
+export function splitSubsurface(surface, weight) {
+ surface.subsurfaceChance = surface.diffuseChance * weight;
+ surface.diffuseChance -= surface.subsurfaceChance;
+ for (let channel = 0; channel < 3; channel++) surface.diffuseColor[channel] *= 1 - weight;
+}
+
+/** A white Lambertian surface facing `normal`: where a subsurface walk leaves, the walk's throughput carries the colour. */
+export function setWhiteDiffuse(surface, normal) {
+ buildFrame(normal, surface.frame);
+ surface.diffuseColor.fill(1);
+ surface.diffuseChance = 1;
+ surface.subsurfaceChance = 0;
+ surface.specularChance = 0;
+ surface.coatChance = 0;
+ surface.coatWeight = 0;
+}
+
function microfacetTerm(alpha, viewCosine, lightCosine, halfCosine) {
return ggxDistribution(alpha, halfCosine) * smithMasking(alpha, viewCosine) * smithMasking(alpha, lightCosine) / (4 * viewCosine * lightCosine);
}
diff --git a/src/path-tracer-subsurface.js b/src/path-tracer-subsurface.js
new file mode 100644
index 00000000..997df63f
--- /dev/null
+++ b/src/path-tracer-subsurface.js
@@ -0,0 +1,104 @@
+import { buildFrame } from './path-tracer-shading.js';
+import { subsurfaceUniformValues } from './subsurface-limits.js';
+
+// Subsurface scattering for the path tracer, after the Random Walk model of Blender's Principled BSDF: light that enters
+// a part walks through it with an isotropic phase function and per-channel mean free path (radius times scale, in metres),
+// and leaves where the walk meets the part's own surface. A walk is capped at SUBSURFACE_WALK_STEPS scattering events, so a
+// path never runs unbounded; a walk that hits the cap ends its path, which only removes light.
+
+export const SUBSURFACE_WALK_STEPS = 32;
+const MINIMUM_FREE_PATH = 1e-6;
+const CHANNELS = 3;
+
+export const WALK_OUTCOME = Object.freeze({ exit: 0, thin: 1, lost: 2 });
+
+/** The traced form of a material's subsurface block: null when the weight is 0, so those parts take the unchanged code path. */
+export function resolveTraceSubsurface(block) {
+ if (!block || !(block.weight > 0)) return null;
+ const [weight, ...rest] = subsurfaceUniformValues(block);
+ const meanFreePath = rest.slice(0, CHANNELS).map(length => Math.max(length, MINIMUM_FREE_PATH));
+ const color = rest[CHANNELS] < 0 ? null : rest.slice(CHANNELS, CHANNELS * 2);
+ return { weight, meanFreePath, color };
+}
+
+/**
+ * Single scattering albedo whose multiple scattering result is the wanted colour (Chiang, Bitterli and others, "Practical
+ * and controllable subsurface scattering for production path tracing", the fit Cycles uses). 0 maps to 0 and 1 maps to 1.
+ */
+export function singleScatterAlbedo(multipleScatterAlbedo) {
+ const albedo = Math.min(1, Math.max(0, multipleScatterAlbedo));
+ const root = Math.sqrt(9.59217 + 41.6808 * albedo + 17.7126 * albedo * albedo);
+ const offset = 4.09712 + 4.20863 * albedo - root;
+ return Math.min(1, Math.max(0, 1 - offset * offset));
+}
+
+/**
+ * Builds the walk for one tracer. `intersect(scene, origin, direction, hit)` is the tracer's nearest-hit query and `random.next()`
+ * its random stream. The returned function starts at a surface point, walks inward from it, and reports how it ended:
+ * exit (the exit hit is in `exitHit`, and `weight` was multiplied by the walk's throughput), thin (nothing of this part lies
+ * behind the point, so the part is a card and the caller transmits through it) or lost (the walk ended inside).
+ */
+export function createRandomWalk(scene, random, intersect) {
+ const frame = new Float64Array(9);
+ const position = new Float64Array(3);
+ const direction = new Float64Array(3);
+ const extinction = new Float64Array(CHANNELS);
+ const albedo = new Float64Array(CHANNELS);
+
+ function pickInwardDirection(normal) {
+ const radius = Math.sqrt(random.next());
+ const angle = 2 * Math.PI * random.next();
+ const height = Math.sqrt(Math.max(0, 1 - radius * radius));
+ buildFrame(normal, frame);
+ const across = radius * Math.cos(angle);
+ const along = radius * Math.sin(angle);
+ for (let axis = 0; axis < 3; axis++) direction[axis] = frame[axis] * across + frame[3 + axis] * along - normal[axis] * height;
+ }
+
+ function pickScatterDirection() {
+ const height = 2 * random.next() - 1;
+ const angle = 2 * Math.PI * random.next();
+ const ring = Math.sqrt(Math.max(0, 1 - height * height));
+ direction[0] = ring * Math.cos(angle);
+ direction[1] = height;
+ direction[2] = ring * Math.sin(angle);
+ }
+
+ function walk(subsurface, color, pointX, pointY, pointZ, normal, material, exitHit, weight) {
+ for (let channel = 0; channel < CHANNELS; channel++) {
+ extinction[channel] = 1 / subsurface.meanFreePath[channel];
+ albedo[channel] = singleScatterAlbedo(color[channel]);
+ }
+ position[0] = pointX - normal[0] * scene.surfaceOffset;
+ position[1] = pointY - normal[1] * scene.surfaceOffset;
+ position[2] = pointZ - normal[2] * scene.surfaceOffset;
+ pickInwardDirection(normal);
+ for (let scatters = 0; ; scatters++) {
+ const found = intersect(scene, position[0], position[1], position[2], direction[0], direction[1], direction[2], exitHit);
+ const ownsBoundary = found && exitHit.material === material;
+ if (!ownsBoundary) return scatters === 0 ? WALK_OUTCOME.thin : WALK_OUTCOME.lost;
+ // One channel draws the distance; weighting by the mean density over the three channels keeps every channel unbiased.
+ const hero = Math.min(CHANNELS - 1, Math.floor(random.next() * CHANNELS));
+ const distance = -Math.log(1 - random.next()) / extinction[hero];
+ if (distance >= exitHit.distance) {
+ let survival = 0;
+ for (let channel = 0; channel < CHANNELS; channel++) survival += Math.exp(-extinction[channel] * exitHit.distance) / CHANNELS;
+ if (!(survival > 0)) return WALK_OUTCOME.lost;
+ for (let channel = 0; channel < CHANNELS; channel++) weight[channel] *= Math.exp(-extinction[channel] * exitHit.distance) / survival;
+ return WALK_OUTCOME.exit;
+ }
+ if (scatters === SUBSURFACE_WALK_STEPS) return WALK_OUTCOME.lost;
+ let density = 0;
+ for (let channel = 0; channel < CHANNELS; channel++) density += extinction[channel] * Math.exp(-extinction[channel] * distance) / CHANNELS;
+ if (!(density > 0)) return WALK_OUTCOME.lost;
+ for (let channel = 0; channel < CHANNELS; channel++) weight[channel] *= albedo[channel] * extinction[channel] * Math.exp(-extinction[channel] * distance) / density;
+ position[0] += direction[0] * distance;
+ position[1] += direction[1] * distance;
+ position[2] += direction[2] * distance;
+ pickScatterDirection();
+ }
+ }
+ // The last direction of the walk, which the caller reads to orient the exit normal.
+ walk.direction = direction;
+ return walk;
+}
diff --git a/src/path-tracer.js b/src/path-tracer.js
index 884e8375..92c5f441 100644
--- a/src/path-tracer.js
+++ b/src/path-tracer.js
@@ -5,8 +5,9 @@ import { acesChannel, displayColor } from './view-transform.js';
import { VIEW_TRANSFORM_NAMES } from './view-transform-names.js';
import {
buildFrame, createSurface, environmentPdf, environmentRadiance, evaluateSurface, luminance, mirrorWeight, prepareSurface,
- roughnessToAlpha, sampleEnvironment, sampleGlass, sampleSurface,
+ roughnessToAlpha, sampleEnvironment, sampleGlass, sampleSurface, setWhiteDiffuse, splitSubsurface,
} from './path-tracer-shading.js';
+import { createRandomWalk, WALK_OUTCOME } from './path-tracer-subsurface.js';
import { henyeyGreensteinPhase, sampleHenyeyGreensteinCosine, volumeInterval } from './path-tracer-volume.js';
// Offline still renderer: unidirectional path tracing on the CPU with next-event estimation for every light, the
@@ -693,6 +694,37 @@ function createPathTracer(scene, options) {
return henyeyGreensteinPhase(volume.anisotropy, cosine);
}
+ const walkSubsurface = createRandomWalk(scene, random, intersect);
+ const walkWeight = new Float64Array(3);
+
+ /**
+ * Sends the diffuse light of the hit through its subsurface random walk. On success the path stands where the walk left (or,
+ * for a card with nothing behind it, on the near or far face), `normal` faces out of that point, `surface` is a white diffuse
+ * lobe there with its lights added, and the throughput carries the walk. False when the walk ended inside the part.
+ */
+ function enterSubsurface(depth, subsurface) {
+ const color = subsurface.color ?? hit.color;
+ walkWeight.fill(1);
+ const outcome = walkSubsurface(subsurface, color, hit.point[0], hit.point[1], hit.point[2], normal, hit.material, shadowHit, walkWeight);
+ if (outcome === WALK_OUTCOME.lost) return false;
+ const entryScale = surface.diffuseShare * subsurface.weight / surface.subsurfaceChance;
+ if (outcome === WALK_OUTCOME.exit) {
+ const facing = shadowHit.normal[0] * walkSubsurface.direction[0] + shadowHit.normal[1] * walkSubsurface.direction[1] + shadowHit.normal[2] * walkSubsurface.direction[2] < 0 ? -1 : 1;
+ for (let axis = 0; axis < 3; axis++) {
+ hit.point[axis] = shadowHit.point[axis];
+ normal[axis] = shadowHit.normal[axis] * facing;
+ }
+ for (let channel = 0; channel < 3; channel++) throughput[channel] *= walkWeight[channel] * entryScale;
+ } else {
+ // A card: half of the colour is reflected on the side the ray came from and half is transmitted diffusely through it.
+ if (random.next() < 0.5) for (let axis = 0; axis < 3; axis++) normal[axis] = -normal[axis];
+ for (let channel = 0; channel < 3; channel++) throughput[channel] *= color[channel] * entryScale;
+ }
+ setWhiteDiffuse(surface, normal);
+ addLights(depth, normal);
+ return true;
+ }
+
/** Follows one camera ray. Leaves the radiance in `radiance` and the first-hit features in `features`. */
function trace(originX, originY, originZ, directionX, directionY, directionZ, pixel, sample) {
random.reset(pixel, sample, options.seed);
@@ -759,8 +791,18 @@ function createPathTracer(scene, options) {
afterMirror = true;
} else {
prepareSurface(surface, material, hit.metallic, hit.roughness, hit.color, normal, viewX, viewY, viewZ);
+ const subsurface = material.subsurface;
+ if (subsurface) splitSubsurface(surface, subsurface.weight);
addLights(depth, normal);
- const lobeUnit = random.next();
+ let lobeUnit = random.next();
+ if (subsurface) {
+ if (lobeUnit < surface.subsurfaceChance) {
+ if (!enterSubsurface(depth, subsurface)) break;
+ lobeUnit = 0;
+ } else {
+ lobeUnit -= surface.subsurfaceChance;
+ }
+ }
const isMirror = sampleSurface(surface, lobeUnit, random.next(), random.next(), direction);
const cosine = direction[0] * normal[0] + direction[1] * normal[1] + direction[2] * normal[2];
if (cosine <= 0) break;
diff --git a/tests/path-tracer-subsurface.test.js b/tests/path-tracer-subsurface.test.js
new file mode 100644
index 00000000..703f52a6
--- /dev/null
+++ b/tests/path-tracer-subsurface.test.js
@@ -0,0 +1,92 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { box, sphere } from '../src/geometry.js';
+import { createEnvironmentMap } from '../src/environment.js';
+import { renderPathTracedImage } from '../src/path-tracer.js';
+import { PATH_TRACER_CAPABILITIES } from '../src/path-tracer-capabilities.js';
+import { createRandomWalk, resolveTraceSubsurface, singleScatterAlbedo, SUBSURFACE_WALK_STEPS, WALK_OUTCOME } from '../src/path-tracer-subsurface.js';
+
+const IMAGE = { width: 24, height: 24, samples: 16, bounces: 4, denoise: false, threads: 1 };
+const CAMERA = { eye: [0, 0, 3], target: [0, 0, 0], up: [0, 1, 0], fov: 30 };
+
+function placed(scale) {
+ return new Float32Array([scale, 0, 0, 0, 0, scale, 0, 0, 0, 0, scale, 0, 0, 0, 0, 1]);
+}
+
+function ballScene(materialExtra) {
+ return {
+ parts: [{ name: 'ball', geometry: sphere(24, 16), matrix: placed(0.6), material: { tag: 'surface', metallic: 0, roughness: 1, emission: 0, color: [1, 1, 1], ...materialExtra } }],
+ environment: { map: createEnvironmentMap({ width: 8, height: 4, data: new Float32Array(8 * 4 * 3).fill(1) }) },
+ camera: CAMERA,
+ };
+}
+
+function meanRadiance(linear) {
+ let sum = 0;
+ for (const value of linear) sum += value;
+ return sum / linear.length;
+}
+
+test('a weight of 0 or no block at all draws exactly the same pixels', async () => {
+ const plain = await renderPathTracedImage(ballScene({ color: [0.7, 0.4, 0.3] }), IMAGE);
+ const off = await renderPathTracedImage(ballScene({ color: [0.7, 0.4, 0.3], subsurface: { weight: 0, radius: [1, 0.2, 0.1], scale: 0.05 } }), IMAGE);
+ assert.deepEqual(off.linear, plain.linear);
+ assert.equal(resolveTraceSubsurface({ weight: 0 }), null);
+ const on = await renderPathTracedImage(ballScene({ color: [0.7, 0.4, 0.3], subsurface: { weight: 1, radius: [1, 0.2, 0.1], scale: 0.05 } }), IMAGE);
+ assert.notDeepEqual(on.linear, plain.linear);
+});
+
+test('a walk that never reaches a surface stops after the step cap', () => {
+ let queries = 0;
+ const part = {};
+ const walk = createRandomWalk({ surfaceOffset: 1e-5 }, { next: Math.random }, (scene, x, y, z, dx, dy, dz, hit) => {
+ queries++;
+ hit.material = part;
+ hit.distance = 1e9;
+ return true;
+ });
+ const subsurface = resolveTraceSubsurface({ weight: 1, radius: [1, 1, 1], scale: 0.01 });
+ const exitHit = { material: null, distance: 0 };
+ const outcome = walk(subsurface, [1, 1, 1], 0, 0, 0, [0, 0, 1], part, exitHit, new Float64Array(3).fill(1));
+ assert.equal(outcome, WALK_OUTCOME.lost);
+ assert.equal(queries, SUBSURFACE_WALK_STEPS + 1);
+});
+
+test('a card with nothing of its own behind the point is walked as thin', () => {
+ const walk = createRandomWalk({ surfaceOffset: 1e-5 }, { next: Math.random }, () => false);
+ const subsurface = resolveTraceSubsurface({ weight: 1, radius: [1, 1, 1], scale: 0.01 });
+ const outcome = walk(subsurface, [1, 1, 1], 0, 0, 0, [0, 0, 1], {}, { material: null }, new Float64Array(3).fill(1));
+ assert.equal(outcome, WALK_OUTCOME.thin);
+});
+
+test('the single scattering albedo maps 0 to 0 and 1 to 1 and grows between', () => {
+ assert.ok(singleScatterAlbedo(0) < 1e-4);
+ assert.ok(Math.abs(singleScatterAlbedo(1) - 1) < 1e-4);
+ assert.ok(singleScatterAlbedo(0.5) > 0.5 && singleScatterAlbedo(0.5) < 1);
+});
+
+test('a white part under a uniform sky never returns more light than arrives', async () => {
+ const sky = 1;
+ const on = await renderPathTracedImage(ballScene({ subsurface: { weight: 1, radius: [1, 1, 1], scale: 0.05 } }), { ...IMAGE, samples: 32 });
+ const off = await renderPathTracedImage(ballScene({}), { ...IMAGE, samples: 32 });
+ assert.ok(on.linear.every(Number.isFinite));
+ assert.ok(meanRadiance(on.linear) <= sky * 1.02, `mean ${meanRadiance(on.linear)}`);
+ assert.ok(meanRadiance(on.linear) >= meanRadiance(off.linear) * 0.8, 'but most of the light still comes back');
+});
+
+test('a thin slab lit from behind glows with subsurface and stays dark without', async () => {
+ const slab = materialExtra => ({
+ parts: [{ name: 'slab', geometry: box(0, 1), matrix: new Float32Array([2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0.01, 0, 0, 0, 0, 1]), material: { tag: 'surface', metallic: 0, roughness: 1, emission: 0, color: [0.2, 0.6, 0.1], ...materialExtra } }],
+ environment: { keyColor: [4, 4, 4], lightDirection: [0, 0, -1] },
+ camera: CAMERA,
+ });
+ const on = await renderPathTracedImage(slab({ subsurface: { weight: 1, radius: [1, 1, 1], scale: 0.01 } }), IMAGE);
+ const off = await renderPathTracedImage(slab({}), IMAGE);
+ assert.ok(meanRadiance(on.linear) > meanRadiance(off.linear) * 5, `${meanRadiance(on.linear)} against ${meanRadiance(off.linear)}`);
+});
+
+test('the capability list names subsurface as traced', () => {
+ assert.match(PATH_TRACER_CAPABILITIES.traces, /subsurface/);
+ assert.doesNotMatch(PATH_TRACER_CAPABILITIES.skips, /translucent leaves/);
+});