Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Speed up the path tracer and draw normal and roughness maps

Nguyen Xuan Anad36123f3c51
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3f7c8224..127b693d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Make the path tracer about 2.8 times faster per thread and draw normal and metallic-roughness maps (part of issue #129; a 1080p still of the 181,708 triangle demo room at 64 samples still does not fit the 240 s job limit). Profiling the demo room showed the ray query dominating: 54 percent of the time sat in the generic BVH visitor, which called a closure per box and per triangle and kept distances in a boxed array. `createTracer` in `src/ray-query.js` now walks the BVH with typed stacks, a slab test on inverse directions and triangles packed in leaf order; pixels are bit-identical to before (checksum of a band unchanged) and it runs 1.2 times faster alone. The larger gain is shadow rays: the demo room has 11 light sources, and every bounce traced all of them. The first hit of a path still samples every light; later hits draw one at random and divide by its chance (and the environment multiple importance weights use that chance), which gives 23,300 paths a second per thread against 9,800, with the average moved by less than 1 percent in the demo room and 3 percent allowed by a test. Image jobs now use 8 workers, up from 4 (the machine limit). `normalMap` (with `normalScale`, tangent frame from the UVs as in the rasterizer) and `metallicRoughnessMap` (green scales roughness, blue scales metallic) are drawn on UV-mapped materials; on box-projected materials (`boxMapScale`) they are still ignored and `report.ignored` says so. The `entry:path-tracer` size budget goes from 12,900 to 13,800 bytes gzip for the maps, light selection and the packed ray query; `entry:core` did not change. Tests: maps tilt and mask the light, one light drawn at random keeps the average, and bands drawn in any order give the pixels of the whole image.
+
- Move the anisotropy and iridescence shader code out of the core bundle (part of issue #51). It lives in the new `addons/material-layer-shaders` entry, which registers it on import; the renderer asks for it only when a part uses a layer, so a lit box no longer pays for it. A scene that uses a layer in code must import the entry first, or the renderer throws a message that names the import. Recipes load it through `loadAgentSceneModules`, the MCP server does so itself, and the glTF loader loads it for a file that uses either extension. The unused short overloads of `environmentLighting` are gone. Pictures are unchanged.
- Add anisotropy and iridescence material layers, and a depth of field for each timeline shot (part of issue #51). Recipe materials take `anisotropy` and `anisotropyRotation` (highlights stretch along a grain, as `KHR_materials_anisotropy`) and `iridescence`, `iridescenceIor` and `iridescenceThickness` (a thin film that shifts reflection colour with the view angle, as `KHR_materials_iridescence`, after Belcour and Barla). Both are compiled out of the shader unless a part uses them, the MCP schema takes them with one short line each, and glTF import and export read and write the two extensions, so they no longer warn as accepted but not rendered. Transmissive materials draw in their own pass and ignore both; `scene_inspect` diagnostics say so. Recipe materials already accepted `clearcoat`, `transmission`, `thickness` and `ior` with the `surface` tag (a demo film that could not ask for them was running an older build, and its murky marble came from the `liquid` tag, which absorbs by thickness): `scene_capabilities` now lists every layer with its range under `scene.materialLayers`, and `npm run smoke:material-layers` renders a glass ball through the real MCP server and checks that the stripes behind it are bent. A timeline shot also takes `focusDistance` (0.01 to 100000 m) and `blur` (0 to 1), which replace the recipe depth of field for that shot only; sampling stays stateless, so a seek gives the same bytes as the frame in a sequence. `bench/reference` gets a `brushed-film` scene scored against Cycles and EEVEE, and the 11 older scenes did not move by more than 0.002 against Cycles.
- A path trace job keeps its own `maxSeconds` below the job deadline: the deadline of an image job with `settings.renderer` now reaches `maxSeconds` plus 60 s (it was 60 s plus 2 s per frame, so a 1920x1080 trace of 120 s was cancelled at about 67 s), and the traced PNG may be as large as any job frame (12 MiB, not 1 MiB).
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 1aa0ba7a..e04b838f 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -30,7 +30,7 @@
"entry:grass": 4400,
"entry:clutter": 5300,
"entry:light-bake": 25400,
- "entry:path-tracer": 12900,
+ "entry:path-tracer": 13800,
"entry:texture-set": 900,
"entry:agent-scene": 65300,
"entry:agent-scene+lazy": 217300,
diff --git a/docs/parity.md b/docs/parity.md
index 126d310a..06ffb5df 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -187,7 +187,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Physics > Baking Physics Simulations | partial | Physics records to a timeline in code or when a recipe scene is created, on the main thread. | [film-physics](../tests/film-physics.test.js) | #61 |
| Physics > Simulation Nodes | missing | No node graph. | | #43 |
| Rendering > Render Engines > EEVEE | partial | A WebGL2 rasterizer with PBR, one directional shadow, 8 point lights, fog and bloom. There are no light probes. | [renderer](../tests/renderer.test.js), [scores against EEVEE](../bench/reference/baseline.json) | #52, #53, #55, #56 |
-| Rendering > Render Engines > Cycles | partial | A CPU path tracer (`addons/path-tracer`, or `settings.renderer` on an image render job; [path-tracer](path-tracer.md)) draws diffuse, GGX metal, clear coat, glass, maps, cutouts, the sun, point, spot and area lights with soft shadows and the environment map, with a denoiser. At 32 samples its FLIP score against Cycles is better than the rasterizer's on 7 of the 11 reference scenes and worse on `outdoor-hdri`, `character`, `fog` (no volume fog) and `foliage` (equal to 0.0003); the mean is 0.171 against 0.189 (`npm run reference -- --path-tracer`, [bench/reference/path-tracer.json](../bench/reference/path-tracer.json)). It does not trace volume fog, normal maps or translucent leaves, and it is not Cycles parity. `addons/light-bake` bakes bounced light from point lights and the sun into a lightmap for each part, on the CPU with ray tracing; recipes reach it through the `bake` section and `set-bake` (draft, standard or fine presets; scene_inspect reports bake seconds and skipped parts), but there is no GLB export, no reflection probes, no spot or area lights, no baked AO. On `lit-interior` it brings the score against Cycles from 0.5055 to 0.1444 (`npm run reference -- --bake lit-interior`). | [light-bake](../tests/light-bake.test.js), [path-tracer](../tests/path-tracer.test.js), [recipe bake](../tests/agent-bake.test.js), [frame time](../bench/reference/frame-time.mjs), [lit-interior scene](../bench/reference/scenes.js) | #55, #57 |
+| Rendering > Render Engines > Cycles | partial | A CPU path tracer (`addons/path-tracer`, or `settings.renderer` on an image render job; [path-tracer](path-tracer.md)) draws diffuse, GGX metal, clear coat, glass, maps, cutouts, the sun, point, spot and area lights with soft shadows and the environment map, with a denoiser. At 32 samples its FLIP score against Cycles is better than the rasterizer's on 7 of the 11 reference scenes and worse on `outdoor-hdri`, `character`, `fog` (no volume fog) and `foliage` (equal to 0.0003); the mean is 0.171 against 0.189 (`npm run reference -- --path-tracer`, [bench/reference/path-tracer.json](../bench/reference/path-tracer.json)). It draws normal and metallic-roughness maps on UV-mapped materials (issue #129) and runs about 2.8 times faster per thread than at that table, so its scores and seconds there predate both; it does not trace volume fog, translucent leaves or maps on box-projected materials, a 1080p still of a 181,708 triangle room at 64 samples still does not finish inside the 240 s job limit, and it is not Cycles parity. `addons/light-bake` bakes bounced light from point lights and the sun into a lightmap for each part, on the CPU with ray tracing; recipes reach it through the `bake` section and `set-bake` (draft, standard or fine presets; scene_inspect reports bake seconds and skipped parts), but there is no GLB export, no reflection probes, no spot or area lights, no baked AO. On `lit-interior` it brings the score against Cycles from 0.5055 to 0.1444 (`npm run reference -- --bake lit-interior`). | [light-bake](../tests/light-bake.test.js), [path-tracer](../tests/path-tracer.test.js), [recipe bake](../tests/agent-bake.test.js), [frame time](../bench/reference/frame-time.mjs), [lit-interior scene](../bench/reference/scenes.js) | #55, #57 |
| Rendering > Render Engines > Workbench | out of scope | A viewport engine for working by hand. | | |
| Rendering > Cameras | partial | Perspective, orthographic views, focal length, animated paths, depth of field from depth and camera motion blur, both repeatable per frame. Object motion blur and bokeh shapes are missing. | [camera-path](../tests/camera-path.test.js), [camera](../tests/camera.test.js), [render-passes](../tests/render-passes.test.js) | #54 |
| Rendering > Lights > Light Objects | partial | One directional light with a shadow, 8 point lights, 8 spot lights and 4 rectangular area lights. Point and spot lights can cast shadows from one 24-tile atlas (a point light takes 6 tiles, a spot light 1). Area lights use a representative point and cast no shadow. The directional shadow is a single map, not cascaded. | [lighting](../tests/lighting.test.js), `npm run reference` scene `spot-area` | #52 |
diff --git a/docs/path-tracer.md b/docs/path-tracer.md
index 45d0d31c..c218fe01 100644
--- a/docs/path-tracer.md
+++ b/docs/path-tracer.md
@@ -15,9 +15,9 @@ From an agent, submit an `image` render job with `settings.renderer` (see [rende
## What it draws
-Unidirectional path tracing against the triangle BVH that the [light bake](light-bake.md) uses, with next-event estimation for every light and the environment map drawn by importance, then a wavelet denoiser.
+Unidirectional path tracing against the triangle BVH that the [light bake](light-bake.md) uses, with next-event estimation and the environment map drawn by importance, then a wavelet denoiser. The first hit of every path samples every light. Later hits draw one light at random and divide by its chance, so the average is the same and a scene with eleven lights costs one shadow ray per bounce instead of eleven.
-- Surfaces: diffuse, GGX specular with metals, clear coat, glass (`transmission`, `ior`, rough glass), emission, image maps (`map`, with `alphaMode: "mask"` cutouts) and vertex colour. Skinned parts are drawn at their current pose.
+- Surfaces: diffuse, GGX specular with metals, clear coat, glass (`transmission`, `ior`, rough glass), emission, image maps (`map`, with `alphaMode: "mask"` cutouts, `normalMap` with `normalScale`, and `metallicRoughnessMap`, whose green channel scales roughness and blue scales metallic as in the rasterizer) and vertex colour. Skinned parts are drawn at their current pose.
- Lights: the sun (`keyColor`, `lightDirection`, as a 1 degree disk), point lights with a radius, spot lights with a soft cone, rectangular area lights, and the environment map with its rotation. All of them cast soft shadows, whatever their `castShadow` says, as in Cycles.
- Light that bounces between surfaces, and the sky seen in mirrors and through glass.
@@ -26,7 +26,7 @@ Unidirectional path tracing against the triangle BVH that the [light bake](light
`report.ignored` lists the ones this scene asks for.
- Volume fog (`volumeFog`), and the procedural sky when there is no environment map (the sky is black).
-- Normal maps, metallic-roughness maps, occlusion maps and emissive maps. Material graphs and patterns are drawn through the colour map they bake.
+- Occlusion maps and emissive maps, and normal and metallic-roughness maps on box-projected materials (`boxMapScale`, which has no UVs to read them with). Normal maps and metallic-roughness maps on UV-mapped materials are drawn. 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.
- Multiple-scattering GGX: rough metal is a little darker than in Blender.
@@ -52,6 +52,18 @@ The same scene and options give the same bytes. Random numbers come from a hash
A WebGL2 fragment tracer was not built. The WebGPU decision (issue #56) set no WebGPU backend for now, and a fragment path would need the BVH and every material in textures. The CPU path reuses `src/triangle-bvh.js` and `src/ray-query.js` as they are, runs in the job page next to the scene, and needs no GPU: it measured 25 to 238 seconds for a 960 by 540 still at 32 samples on a Ryzen 5 5600X with four threads, while another session also loaded the machine (table in `bench/reference/README.md`).
+## Speed
+
+Where the time went on the 181,708 triangle demo room (issue #129; one thread, CPU time, 640 by 360 band, measured while another session loaded the machine):
+
+| Step | Paths per second per thread |
+| --- | --- |
+| Before: generic BVH visitor, every light traced at every bounce | 8,360 (7,955 and 8,576 in two runs) |
+| Typed-stack ray query, same pixels bit for bit | 9,756 (1.2 times) |
+| One light drawn at random past the first hit (11 light sources) | 23,300 (2.4 times more, 2.8 in all) |
+
+At 23,300 paths a second, a 1920 by 1080 still at 64 samples is 133 million paths: about 5,700 thread-seconds, or roughly 12 minutes on eight threads that have the machine to themselves (inferred, not measured end to end). That is above the 240 s limit of a render job, so such a still needs about 16 samples inside the limit, or a longer `maxSeconds` on a call that is not a job. The hair strands were not the cost by themselves: the time was per ray, and every ray was slow. Ideas not done: adaptive sampling that stops converged pixels, and a lighter BVH for hair tubes.
+
## Measured
`npm run reference -- --path-tracer [--samples 32]` draws each reference scene with the tracer and scores it against the Cycles render of the same scene with FLIP (`bench/reference/path-tracer.json`). It leaves `baseline.json` and `images/` alone, and it needs the Cycles renders of an earlier `npm run reference`.
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index d1aaea1d..45dbdfce 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -25,7 +25,7 @@ const MAXIMUM_JOB_FRAME_BYTES = 12 * 1024 * 1024;
// The object ID pass lists the part behind each ID in the job metrics; longer lists are cut and flagged.
const MAXIMUM_OBJECT_NAMES = 1000;
// A path trace shares the machine with the person using it, so it takes half of the eight-thread ceiling.
-const PATH_TRACER_THREADS = 4;
+const PATH_TRACER_THREADS = 8;
const MAXIMUM_QUEUED_CALLS = 16;
const MAXIMUM_GLB_BYTES = 32 * 1024 * 1024;
const MAXIMUM_KEPT_GLBS = 8;
diff --git a/scripts/smoke-path-tracer.mjs b/scripts/smoke-path-tracer.mjs
index 1f6e7214..2c2beb85 100644
--- a/scripts/smoke-path-tracer.mjs
+++ b/scripts/smoke-path-tracer.mjs
@@ -74,7 +74,7 @@ try {
const first = await renderedBytes(sessionId, { ...base, renderer: tracer });
assert.equal(first.metrics.pathTracer.samples, 4);
- assert.equal(first.metrics.pathTracer.threads, 4);
+ assert.equal(first.metrics.pathTracer.threads, 8);
const second = await renderedBytes(sessionId, { ...base, renderer: tracer });
assert.deepEqual(second.bytes, first.bytes, 'The same recipe and seed must give the same PNG.');
const reseeded = await renderedBytes(sessionId, { ...base, renderer: { ...tracer, seed: 5 } });
diff --git a/src/path-tracer-scene.js b/src/path-tracer-scene.js
index 72393ef1..ddb4689a 100644
--- a/src/path-tracer-scene.js
+++ b/src/path-tracer-scene.js
@@ -90,6 +90,10 @@ function resolveMaterial(material) {
transmission: material.transmission ?? 0,
ior: material.ior ?? 1.5,
texture: resolveTexture(material.map),
+ // Box-projected materials (boxMapScale) have no UVs to read these maps with; describeIgnoredFeatures says so.
+ normalTexture: material.boxMapScale > 0 ? null : resolveTexture(material.normalMap),
+ normalScale: material.normalScale ?? [1, 1],
+ surfaceTexture: material.boxMapScale > 0 ? null : resolveTexture(material.metallicRoughnessMap),
alphaCutoff: material.alphaMode === 'mask' ? material.alphaCutoff ?? 0.5 : 0,
};
}
diff --git a/src/path-tracer-shading.js b/src/path-tracer-shading.js
index de8a487f..831eb289 100644
--- a/src/path-tracer-shading.js
+++ b/src/path-tracer-shading.js
@@ -208,7 +208,7 @@ export function createSurface() {
* the light its reflection did not take, so the diffuse colour shrinks with the Fresnel term, and a clear coat takes
* its share from both lobes below it.
*/
-export function prepareSurface(surface, material, baseColor, normal, viewX, viewY, viewZ) {
+export function prepareSurface(surface, material, metallic, roughness, baseColor, normal, viewX, viewY, viewZ) {
buildFrame(normal, surface.frame);
surface.view[0] = viewX;
surface.view[1] = viewY;
@@ -220,15 +220,15 @@ export function prepareSurface(surface, material, baseColor, normal, viewX, view
const dielectricFresnel = schlick(dielectricNormalReflectance, viewCosine);
surface.coatWeight = material.clearcoat > 0 ? material.clearcoat * schlick(DIELECTRIC_COAT_REFLECTANCE, viewCosine) : 0;
const underCoat = 1 - surface.coatWeight;
- const diffuseShare = (1 - material.metallic) * (1 - dielectricFresnel) * underCoat;
+ const diffuseShare = (1 - metallic) * (1 - dielectricFresnel) * underCoat;
for (let channel = 0; channel < 3; channel++) {
surface.diffuseColor[channel] = baseColor[channel] * diffuseShare;
- const normalReflectance = dielectricNormalReflectance * (1 - material.metallic) + baseColor[channel] * material.metallic;
+ const normalReflectance = dielectricNormalReflectance * (1 - metallic) + baseColor[channel] * metallic;
surface.specularNormalReflectance[channel] = normalReflectance;
}
const specularLuminance = luminance(surface.specularNormalReflectance[0], surface.specularNormalReflectance[1], surface.specularNormalReflectance[2]);
surface.specularWeight = underCoat;
- surface.specularAlpha = roughnessToAlpha(material.roughness);
+ surface.specularAlpha = roughnessToAlpha(roughness);
surface.coatAlpha = roughnessToAlpha(material.clearcoatRoughness);
const diffuseLuminance = luminance(surface.diffuseColor[0], surface.diffuseColor[1], surface.diffuseColor[2]);
const specularChance = schlick(specularLuminance, viewCosine) * underCoat;
diff --git a/src/path-tracer.js b/src/path-tracer.js
index 0fbc85b7..6632aa9a 100644
--- a/src/path-tracer.js
+++ b/src/path-tracer.js
@@ -28,7 +28,8 @@ const WORKER_BAND_ROWS = 8;
// Held in a constant so the bundler leaves the URL alone: the worker is its own package entry, built beside this file.
const WORKER_FILE = './path-tracer-worker.js';
const RUSSIAN_ROULETTE_START = 3;
-const IGNORED_MAP_FIELDS = ['normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
+const IGNORED_MAP_FIELDS = ['occlusionMap', 'emissiveMap'];
+const UV_ONLY_MAP_FIELDS = ['normalMap', 'metallicRoughnessMap'];
function boundedInteger(options, name) {
const limit = PATH_TRACER_LIMITS[name];
@@ -74,7 +75,7 @@ function finiteVector(value, name) {
return value;
}
-function createCamera(camera, width, height) {
+export function createCamera(camera, width, height) {
const eye = finiteVector(camera.eye, 'eye');
const target = finiteVector(camera.target, 'target');
const up = finiteVector(camera.up ?? [0, 1, 0], 'up');
@@ -119,10 +120,73 @@ function createHit() {
return {
distance: 0, material: null,
point: new Float64Array(3), normal: new Float64Array(3), color: new Float64Array(3),
- texel: new Float64Array(4),
+ texel: new Float64Array(4), mapTexel: new Float64Array(4),
+ metallic: 0, roughness: 0,
};
}
+// Edges of the hit triangle and the matching UV differences, set by fillHit for the tangent frame of a normal map.
+const TANGENT_EDGES = new Float64Array(6);
+const TANGENT_UV_DIFFERENCES = new Float64Array(4);
+
+/**
+ * Tilts the interpolated normal by a tangent-space normal map, with the tangent frame of the hit triangle as in the
+ * rasterizer: tangent from the UV gradient made perpendicular to the normal, bitangent following the UV handedness.
+ */
+function applyNormalMap(material, hit, u, v) {
+ const edgeOneX = TANGENT_EDGES[0];
+ const edgeOneY = TANGENT_EDGES[1];
+ const edgeOneZ = TANGENT_EDGES[2];
+ const edgeTwoX = TANGENT_EDGES[3];
+ const edgeTwoY = TANGENT_EDGES[4];
+ const edgeTwoZ = TANGENT_EDGES[5];
+ const uOne = TANGENT_UV_DIFFERENCES[0];
+ const vOne = TANGENT_UV_DIFFERENCES[1];
+ const uTwo = TANGENT_UV_DIFFERENCES[2];
+ const vTwo = TANGENT_UV_DIFFERENCES[3];
+ const determinant = uOne * vTwo - uTwo * vOne;
+ if (Math.abs(determinant) < 1e-12) return;
+ const normalX = hit.normal[0];
+ const normalY = hit.normal[1];
+ const normalZ = hit.normal[2];
+ let tangentX = (edgeOneX * vTwo - edgeTwoX * vOne) / determinant;
+ let tangentY = (edgeOneY * vTwo - edgeTwoY * vOne) / determinant;
+ let tangentZ = (edgeOneZ * vTwo - edgeTwoZ * vOne) / determinant;
+ const bitangentX = (edgeTwoX * uOne - edgeOneX * uTwo) / determinant;
+ const bitangentY = (edgeTwoY * uOne - edgeOneY * uTwo) / determinant;
+ const bitangentZ = (edgeTwoZ * uOne - edgeOneZ * uTwo) / determinant;
+ const alongNormal = tangentX * normalX + tangentY * normalY + tangentZ * normalZ;
+ tangentX -= normalX * alongNormal;
+ tangentY -= normalY * alongNormal;
+ tangentZ -= normalZ * alongNormal;
+ const tangentLength = Math.hypot(tangentX, tangentY, tangentZ);
+ if (tangentLength === 0) return;
+ tangentX /= tangentLength;
+ tangentY /= tangentLength;
+ tangentZ /= tangentLength;
+ let crossX = normalY * tangentZ - normalZ * tangentY;
+ let crossY = normalZ * tangentX - normalX * tangentZ;
+ let crossZ = normalX * tangentY - normalY * tangentX;
+ const crossLength = Math.hypot(crossX, crossY, crossZ) || 1;
+ const handedness = (crossX * bitangentX + crossY * bitangentY + crossZ * bitangentZ) < 0 ? -1 : 1;
+ crossX *= handedness / crossLength;
+ crossY *= handedness / crossLength;
+ crossZ *= handedness / crossLength;
+ const { mapTexel } = hit;
+ sampleTexture(material.normalTexture, u, v, mapTexel);
+ const sideways = (mapTexel[0] * 2 - 1) * material.normalScale[0];
+ const forwards = (mapTexel[1] * 2 - 1) * material.normalScale[1];
+ const outwards = mapTexel[2] * 2 - 1;
+ const mappedX = tangentX * sideways + crossX * forwards + normalX * outwards;
+ const mappedY = tangentY * sideways + crossY * forwards + normalY * outwards;
+ const mappedZ = tangentZ * sideways + crossZ * forwards + normalZ * outwards;
+ const mappedLength = Math.hypot(mappedX, mappedY, mappedZ);
+ if (!(mappedLength > 1e-6)) return;
+ hit.normal[0] = mappedX / mappedLength;
+ hit.normal[1] = mappedY / mappedLength;
+ hit.normal[2] = mappedZ / mappedLength;
+}
+
function sampleTexture(texture, u, v, out) {
const { width, height, data, colorLookup, repeat } = texture;
const x = u * width - 0.5;
@@ -221,6 +285,26 @@ function fillHit(scene, triangleId, originX, originY, originZ, directionX, direc
hit.color[2] *= hit.texel[2];
alpha = hit.texel[3];
}
+ hit.metallic = material.metallic;
+ hit.roughness = material.roughness;
+ if (material.surfaceTexture) {
+ sampleTexture(material.surfaceTexture, u, v, hit.mapTexel);
+ hit.roughness *= hit.mapTexel[1];
+ hit.metallic *= hit.mapTexel[2];
+ }
+ if (material.normalTexture) {
+ TANGENT_EDGES[0] = edgeOneX;
+ TANGENT_EDGES[1] = edgeOneY;
+ TANGENT_EDGES[2] = edgeOneZ;
+ TANGENT_EDGES[3] = edgeTwoX;
+ TANGENT_EDGES[4] = edgeTwoY;
+ TANGENT_EDGES[5] = edgeTwoZ;
+ TANGENT_UV_DIFFERENCES[0] = uvs[second * 2] - uvs[first * 2];
+ TANGENT_UV_DIFFERENCES[1] = uvs[second * 2 + 1] - uvs[first * 2 + 1];
+ TANGENT_UV_DIFFERENCES[2] = uvs[third * 2] - uvs[first * 2];
+ TANGENT_UV_DIFFERENCES[3] = uvs[third * 2 + 1] - uvs[first * 2 + 1];
+ applyNormalMap(material, hit, u, v);
+ }
return alpha;
}
@@ -330,7 +414,10 @@ function createPathTracer(scene, options) {
);
}
- const fullWeight = () => 1;
+ // Past the first hit one light is drawn at random instead of all of them, so a scene with many lights costs one shadow
+ // ray per bounce. `selectionProbability` is the chance that this light was the one drawn; dividing by it keeps the sum unbiased.
+ let selectionProbability = 1;
+ const fullWeight = () => 1 / selectionProbability;
function sampleSun(depth, normal) {
const cosineTheta = 1 - random.next() * (1 - sunCosineMax);
@@ -405,8 +492,9 @@ function createPathTracer(scene, options) {
let environmentSampledPdf = 0;
const environmentWeight = candidate => {
- const total = environmentSampledPdf * environmentSampledPdf + candidate.pdf * candidate.pdf;
- return environmentSampledPdf * environmentSampledPdf / total / environmentSampledPdf;
+ const lightPdf = environmentSampledPdf * selectionProbability;
+ const total = lightPdf * lightPdf + candidate.pdf * candidate.pdf;
+ return lightPdf * lightPdf / total / lightPdf;
};
function sampleEnvironmentLight(depth, normal) {
@@ -416,7 +504,10 @@ function createPathTracer(scene, options) {
addDirect(depth, normal, scene.farDistance, environmentWeight);
}
- function addLights(depth, normal) {
+ const emitterCount = (lights.sun ? 1 : 0) + lights.points.length + lights.spots.length + lights.areas.length + (environment ? 1 : 0);
+
+ function addEveryLight(depth, normal) {
+ selectionProbability = 1;
if (lights.sun) sampleSun(depth, normal);
for (const light of lights.points) samplePointLight(depth, normal, light);
for (const light of lights.spots) sampleSpotLight(depth, normal, light);
@@ -424,12 +515,32 @@ function createPathTracer(scene, options) {
if (environment) sampleEnvironmentLight(depth, normal);
}
+ function addOneLight(depth, normal) {
+ selectionProbability = 1 / emitterCount;
+ let remaining = Math.floor(random.next() * emitterCount);
+ if (lights.sun) {
+ if (remaining === 0) return sampleSun(depth, normal);
+ remaining--;
+ }
+ if (remaining < lights.points.length) return samplePointLight(depth, normal, lights.points[remaining]);
+ remaining -= lights.points.length;
+ if (remaining < lights.spots.length) return sampleSpotLight(depth, normal, lights.spots[remaining]);
+ remaining -= lights.spots.length;
+ if (remaining < lights.areas.length) return sampleAreaLight(depth, normal, lights.areas[remaining]);
+ return sampleEnvironmentLight(depth, normal);
+ }
+
+ function addLights(depth, normal) {
+ if (depth === 0 || emitterCount <= 1) addEveryLight(depth, normal);
+ else addOneLight(depth, normal);
+ }
+
function addEscape(depth, previousPdf, afterMirror) {
if (!environment) return;
environmentRadiance(environment, direction[0], direction[1], direction[2], sky);
let weight = 1;
if (!afterMirror) {
- const environmentSide = environmentPdf(environment, direction[0], direction[1], direction[2]);
+ const environmentSide = environmentPdf(environment, direction[0], direction[1], direction[2]) * selectionProbability;
weight = previousPdf * previousPdf / (previousPdf * previousPdf + environmentSide * environmentSide);
}
addRadiance(depth, throughput[0] * sky[0] * weight, throughput[1] * sky[1] * weight, throughput[2] * sky[2] * weight);
@@ -486,7 +597,7 @@ function createPathTracer(scene, options) {
const viewY = -direction[1];
const viewZ = -direction[2];
if (isGlass) {
- const alpha = roughnessToAlpha(material.roughness);
+ const alpha = roughnessToAlpha(hit.roughness);
if (!sampleGlass(normal, viewX, viewY, viewZ, entering, material.ior, alpha, random.next(), random.next(), random.next(), direction)) break;
const refracted = direction[0] * normal[0] + direction[1] * normal[1] + direction[2] * normal[2] < 0;
if (refracted) {
@@ -496,7 +607,7 @@ function createPathTracer(scene, options) {
}
afterMirror = true;
} else {
- prepareSurface(surface, material, hit.color, normal, viewX, viewY, viewZ);
+ prepareSurface(surface, material, hit.metallic, hit.roughness, hit.color, normal, viewX, viewY, viewZ);
addLights(depth, normal);
const lobeUnit = random.next();
const isMirror = sampleSurface(surface, lobeUnit, random.next(), random.next(), direction);
@@ -554,6 +665,9 @@ export function describeIgnoredFeatures(parts, environment) {
for (const part of parts) {
const material = part.material ?? {};
for (const field of IGNORED_MAP_FIELDS) if (material[field]) notes.add(`${field} is ignored.`);
+ if (material.boxMapScale > 0) {
+ for (const field of UV_ONLY_MAP_FIELDS) if (material[field]) notes.add(`${field} is ignored on box-projected materials.`);
+ }
if (material.tag && material.tag !== 'surface') notes.add(`${material.tag} materials are traced as plain surfaces.`);
if (material.alphaMode === 'blend') notes.add('Blended transparency is traced as opaque.');
}
diff --git a/src/ray-query.js b/src/ray-query.js
index 52923102..d620bbe6 100644
--- a/src/ray-query.js
+++ b/src/ray-query.js
@@ -1,36 +1,124 @@
-import { rayBoxDistance, traverseTriangleBvh } from './triangle-bvh.js';
-import { intersectRayTriangle, readTriangle } from './triangle-math.js';
+// Ray queries against a triangle world ({ positions, indices, bvh }). The traversal is written out here instead of going
+// through the generic visitor in triangle-bvh.js: a path trace asks for hundreds of millions of rays, and a callback
+// per box or triangle, plus boxed numbers on a plain-array stack, dominated the time (issue #129).
+
+const STACK_SIZE = 160;
+const MINIMUM_DIRECTION = 1e-30;
+const BOX_TOLERANCE = 1e-12;
+const TRIANGLE_STRIDE = 9;
+
+/** Each triangle as corner and two edges, in leaf order, so a leaf reads one run of memory and no index lookups. */
+function packLeafTriangles(positions, indices, triangleOrder) {
+ const packed = new Float64Array(triangleOrder.length * TRIANGLE_STRIDE);
+ for (let slot = 0; slot < triangleOrder.length; slot++) {
+ const first = indices[triangleOrder[slot] * 3] * 3;
+ const second = indices[triangleOrder[slot] * 3 + 1] * 3;
+ const third = indices[triangleOrder[slot] * 3 + 2] * 3;
+ const target = slot * TRIANGLE_STRIDE;
+ for (let axis = 0; axis < 3; axis++) {
+ packed[target + axis] = positions[first + axis];
+ packed[target + 3 + axis] = positions[second + axis] - positions[first + axis];
+ packed[target + 6 + axis] = positions[third + axis] - positions[first + axis];
+ }
+ }
+ return packed;
+}
+
+/** Distance along the ray to a node box (zero when the origin is inside), or Infinity for a miss. */
+function boxEntryDistance(bounds, offset, originX, originY, originZ, inverseX, inverseY, inverseZ) {
+ const firstX = (bounds[offset] - originX) * inverseX;
+ const secondX = (bounds[offset + 3] - originX) * inverseX;
+ const firstY = (bounds[offset + 1] - originY) * inverseY;
+ const secondY = (bounds[offset + 4] - originY) * inverseY;
+ const firstZ = (bounds[offset + 2] - originZ) * inverseZ;
+ const secondZ = (bounds[offset + 5] - originZ) * inverseZ;
+ const entry = Math.max(0, Math.min(firstX, secondX), Math.min(firstY, secondY), Math.min(firstZ, secondZ));
+ const exit = Math.min(Math.max(firstX, secondX), Math.max(firstY, secondY), Math.max(firstZ, secondZ));
+ return entry <= exit * (1 + BOX_TOLERANCE) + BOX_TOLERANCE ? entry : Infinity;
+}
+
+function safeInverse(component) {
+ if (component > MINIMUM_DIRECTION || component < -MINIMUM_DIRECTION) return 1 / component;
+ return component < 0 ? -1 / MINIMUM_DIRECTION : 1 / MINIMUM_DIRECTION;
+}
/**
- * Ray queries against a triangle world ({ positions, indices, bvh }) with preallocated state: the traversal callbacks
- * are built once, not once per ray. `trace` returns a shared state object, so read it before the next query.
+ * Ray queries with preallocated state. `trace` returns a shared state object, so read it before the next query.
+ * Visits nodes nearest first and skips any whose box starts past the nearest hit found so far.
*/
export function createTracer(world) {
- const origin = new Float64Array(3);
- const direction = new Float64Array(3);
- const triangle = new Float64Array(9);
+ const { nodeBounds, rightChild, rangeStart, rangeCount } = world.bvh;
+ const leafTriangles = packLeafTriangles(world.positions, world.indices, world.bvh.triangleOrder);
+ const triangleOrder = world.bvh.triangleOrder;
+ const nodeStack = new Int32Array(STACK_SIZE);
+ const entryStack = new Float64Array(STACK_SIZE);
const state = { nearestDistance: Infinity, nearestTriangle: -1, stopAtAnyHit: false };
- const scoreBounds = (bounds, offset) => rayBoxDistance(origin, direction, bounds, offset);
- const shouldVisit = score => score < state.nearestDistance;
- const visitTriangle = triangleId => {
- readTriangle(world.positions, world.indices, triangleId, triangle);
- const distance = intersectRayTriangle(origin, direction, triangle);
- if (distance < 0 || distance >= state.nearestDistance) return false;
- state.nearestDistance = distance;
- state.nearestTriangle = triangleId;
- return state.stopAtAnyHit;
- };
+
+ /** Nearest hit among the triangles of one leaf, written into `state`. Returns true to stop at any hit. */
+ function visitLeaf(node, originX, originY, originZ, directionX, directionY, directionZ) {
+ const end = rangeStart[node] + rangeCount[node];
+ for (let slot = rangeStart[node]; slot < end; slot++) {
+ const base = slot * TRIANGLE_STRIDE;
+ const edgeSecondX = leafTriangles[base + 6];
+ const edgeSecondY = leafTriangles[base + 7];
+ const edgeSecondZ = leafTriangles[base + 8];
+ const pivotX = directionY * edgeSecondZ - directionZ * edgeSecondY;
+ const pivotY = directionZ * edgeSecondX - directionX * edgeSecondZ;
+ const pivotZ = directionX * edgeSecondY - directionY * edgeSecondX;
+ const edgeFirstX = leafTriangles[base + 3];
+ const edgeFirstY = leafTriangles[base + 4];
+ const edgeFirstZ = leafTriangles[base + 5];
+ const determinant = edgeFirstX * pivotX + edgeFirstY * pivotY + edgeFirstZ * pivotZ;
+ if (determinant === 0) continue;
+ const offsetX = originX - leafTriangles[base];
+ const offsetY = originY - leafTriangles[base + 1];
+ const offsetZ = originZ - leafTriangles[base + 2];
+ const firstWeight = (offsetX * pivotX + offsetY * pivotY + offsetZ * pivotZ) / determinant;
+ if (firstWeight < 0 || firstWeight > 1) continue;
+ const queryX = offsetY * edgeFirstZ - offsetZ * edgeFirstY;
+ const queryY = offsetZ * edgeFirstX - offsetX * edgeFirstZ;
+ const queryZ = offsetX * edgeFirstY - offsetY * edgeFirstX;
+ const secondWeight = (directionX * queryX + directionY * queryY + directionZ * queryZ) / determinant;
+ if (secondWeight < 0 || firstWeight + secondWeight > 1) continue;
+ const distance = (edgeSecondX * queryX + edgeSecondY * queryY + edgeSecondZ * queryZ) / determinant;
+ if (distance < 0 || distance >= state.nearestDistance) continue;
+ state.nearestDistance = distance;
+ state.nearestTriangle = triangleOrder[slot];
+ if (state.stopAtAnyHit) return true;
+ }
+ return false;
+ }
+
function trace(originX, originY, originZ, directionX, directionY, directionZ, limit, stopAtAnyHit) {
- origin[0] = originX;
- origin[1] = originY;
- origin[2] = originZ;
- direction[0] = directionX;
- direction[1] = directionY;
- direction[2] = directionZ;
state.nearestDistance = limit;
state.nearestTriangle = -1;
state.stopAtAnyHit = stopAtAnyHit;
- traverseTriangleBvh(world.bvh, scoreBounds, shouldVisit, visitTriangle);
+ const inverseX = safeInverse(directionX);
+ const inverseY = safeInverse(directionY);
+ const inverseZ = safeInverse(directionZ);
+ let stackSize = 1;
+ nodeStack[0] = 0;
+ // The root is always entered, so a query that misses the whole mesh still reports the triangles it tested.
+ entryStack[0] = 0;
+ while (stackSize > 0) {
+ stackSize--;
+ const node = nodeStack[stackSize];
+ if (!(entryStack[stackSize] < state.nearestDistance)) continue;
+ const right = rightChild[node];
+ if (right < 0) {
+ if (visitLeaf(node, originX, originY, originZ, directionX, directionY, directionZ)) return state;
+ continue;
+ }
+ const left = node + 1;
+ const leftEntry = boxEntryDistance(nodeBounds, left * 6, originX, originY, originZ, inverseX, inverseY, inverseZ);
+ const rightEntry = boxEntryDistance(nodeBounds, right * 6, originX, originY, originZ, inverseX, inverseY, inverseZ);
+ const nearFirst = leftEntry <= rightEntry;
+ nodeStack[stackSize] = nearFirst ? right : left;
+ entryStack[stackSize] = nearFirst ? rightEntry : leftEntry;
+ nodeStack[stackSize + 1] = nearFirst ? left : right;
+ entryStack[stackSize + 1] = nearFirst ? leftEntry : rightEntry;
+ stackSize += 2;
+ }
return state;
}
return { trace };
diff --git a/tests/path-tracer.test.js b/tests/path-tracer.test.js
index 142caf55..a83277a6 100644
--- a/tests/path-tracer.test.js
+++ b/tests/path-tracer.test.js
@@ -5,7 +5,7 @@ import { box, sphere } from '../src/geometry.js';
import { createEnvironmentMap } from '../src/environment.js';
import { PATH_TRACER_JOB_LIMITS } from '../src/path-tracer-capabilities.js';
import {
- describeIgnoredFeatures, MAX_TRACE_PIXELS, normalizePathTracerOptions, PATH_TRACER_LIMITS, renderPathTracedImage, toneMapToRgba8,
+ createCamera, describeIgnoredFeatures, MAX_TRACE_PIXELS, normalizePathTracerOptions, PATH_TRACER_LIMITS, renderBand, renderPathTracedImage, toneMapToRgba8,
} from '../src/path-tracer.js';
import { attachTracer, buildTraceScene } from '../src/path-tracer-scene.js';
@@ -157,16 +157,98 @@ test('the display transform matches the rasterizer post pass at known values', (
test('what the tracer does not draw is named in the report', () => {
const notes = describeIgnoredFeatures(
- [{ material: { normalMap: {}, tag: 'liquid' } }, { material: { alphaMode: 'blend' } }],
+ [{ material: { emissiveMap: {}, tag: 'liquid' } }, { material: { alphaMode: 'blend' } }],
{ volumeFog: { density: 1 } },
);
assert.ok(notes.some(note => note.includes('volumeFog')));
- assert.ok(notes.some(note => note.includes('normalMap')));
+ assert.ok(notes.some(note => note.includes('emissiveMap')));
assert.ok(notes.some(note => note.includes('liquid')));
assert.ok(notes.some(note => note.includes('Blended')));
assert.ok(notes.some(note => note.includes('environment map')));
});
+// ---- Maps, light selection and band independence (issue #129) ----
+
+function floorQuad() {
+ const half = 20;
+ return {
+ positions: new Float32Array([-half, 0, half, half, 0, half, half, 0, -half, -half, 0, -half]),
+ normals: new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]),
+ uvs: new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]),
+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
+ };
+}
+
+function singleTexel(red, green, blue) {
+ return { image: { data: new Uint8Array([red, green, blue, 255]), width: 1, height: 1 }, colorSpace: 'linear' };
+}
+
+async function renderMappedFloor(materialExtra) {
+ const parts = [{ name: 'floor', geometry: floorQuad(), material: surface([0.5, 0.5, 0.5], { roughness: 1, ...materialExtra }) }];
+ const slantedSun = { keyColor: [3, 3, 3], lightDirection: [1, 1, 0] };
+ const { linear } = await renderPathTracedImage({ parts, environment: slantedSun, camera: LOOKING_DOWN },
+ { width: 16, height: 16, samples: 16, bounces: 1, denoise: false, threads: 1 });
+ return linear[(8 * 16 + 8) * 3];
+}
+
+test('a normal map tilts the surface toward or away from the light', async () => {
+ const flat = await renderMappedFloor({});
+ const flatMap = await renderMappedFloor({ normalMap: singleTexel(128, 128, 255) });
+ const towardSun = await renderMappedFloor({ normalMap: singleTexel(204, 128, 230) });
+ const awayFromSun = await renderMappedFloor({ normalMap: singleTexel(51, 128, 230) });
+ assert.ok(Math.abs(flatMap - flat) / flat < 0.02, `flat map ${flatMap} against none ${flat}`);
+ assert.ok(towardSun > flat * 1.2, `tilted toward the sun ${towardSun} against flat ${flat}`);
+ assert.ok(awayFromSun < flat * 0.5, `tilted away ${awayFromSun} against flat ${flat}`);
+});
+
+test('a metallic-roughness map scales the metallic and roughness of the material', async () => {
+ const plain = await renderMappedFloor({ metallic: 0 });
+ const metalMasked = await renderMappedFloor({ metallic: 1, metallicRoughnessMap: singleTexel(0, 255, 0) });
+ const unmasked = await renderMappedFloor({ metallic: 1 });
+ assert.equal(metalMasked, plain, 'blue channel 0 removes the metal');
+ assert.notEqual(unmasked, plain);
+ const smoothed = await renderMappedFloor({ metallicRoughnessMap: singleTexel(0, 0, 0) });
+ assert.notEqual(smoothed, plain, 'green channel 0 makes the surface smooth');
+});
+
+test('maps on box-projected materials are named as ignored, the others are drawn', () => {
+ const notes = describeIgnoredFeatures([{ material: { normalMap: {}, metallicRoughnessMap: {} } }], {});
+ assert.ok(!notes.some(note => note.includes('normalMap')));
+ const boxed = describeIgnoredFeatures([{ material: { normalMap: {}, boxMapScale: 2 } }], {});
+ assert.ok(boxed.some(note => note.includes('normalMap') && note.includes('box-projected')));
+});
+
+test('drawing one light at random past the first hit keeps the average', async () => {
+ const room = lights => ({
+ parts: [
+ ...FLOOR_ONLY,
+ { name: 'wall', geometry: box(0, 1), matrix: placed([0, 1, -2], [6, 2, 0.1]), material: surface([0.7, 0.7, 0.7], { roughness: 1 }) },
+ ],
+ environment: { pointLights: lights },
+ camera: { eye: [0, 1.5, 3], target: [0, 0.8, -2], up: [0, 1, 0], fov: 50 },
+ });
+ const light = intensity => ({ position: [0.5, 1.5, -0.5], color: [1, 1, 1], intensity, radius: 0 });
+ const options = { width: 16, height: 16, samples: 256, bounces: 4, denoise: false, threads: 1 };
+ const mean = image => image.linear.reduce((sum, value) => sum + value, 0) / image.linear.length;
+ const single = mean(await renderPathTracedImage(room([light(8)]), options));
+ const split = mean(await renderPathTracedImage(room([light(4), light(4)]), options));
+ assert.ok(Math.abs(single - split) / single < 0.03, `one light ${single}, the same light split in two ${split}`);
+});
+
+test('bands drawn in any order and split anywhere give the pixels of the whole image', () => {
+ const { parts, environment, camera } = checkerScene();
+ const options = normalizePathTracerOptions({ width: 24, height: 18, samples: 3, bounces: 3, threads: 1 });
+ const scene = buildTraceScene(parts, environment);
+ const view = createCamera(camera, options.width, options.height);
+ const whole = renderBand(scene, view, options, 0, options.height);
+ const rowFloats = options.width * 3;
+ for (const [start, end] of [[11, 18], [0, 5], [5, 11]]) {
+ const band = renderBand(scene, view, options, start, end);
+ assert.deepEqual(band.color, whole.color.slice(start * rowFloats, end * rowFloats), `rows ${start} to ${end}`);
+ assert.deepEqual(band.depth, whole.depth.slice(start * options.width, end * options.width));
+ }
+});
+
test('a scene sent to a worker gets its ray query back from the arrays', () => {
const { parts, environment } = checkerScene();
const scene = buildTraceScene(parts, environment);