Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Bake lightmaps on the GPU tracer kernel (closes #302)

Nguyen Xuan An9b3abf5ab0c9
diff --git a/bench/reference/README.md b/bench/reference/README.md
index 07f91da6..7bee7de5 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -1570,7 +1570,13 @@ FLIP mean error, lower is better (measured, one run, Blender 5.2.2, 960 by 540):
| `temple-hall-rose` | 0.5652 | 0.5727 | 0.8878 |
| `megacity-dusk-blue-hour` | 0.1128 | 0.1081 | 0.0688 |
-Known gaps shown on purpose, not hidden by a per-scene setting: the dark band of mid-distance trees in the dawn frame is a 67js defect (the lower tree levels shade near black under sky light and a low sun, issue #394); the temple hall is lit flat in 67js while Cycles leaves it dark, the closed-room-without-bake gap (an open roof is not a bake).
+Known gaps shown on purpose, not hidden by a per-scene setting: the dark band of mid-distance trees in the dawn frame is a 67js defect (the lower tree levels shade near black under sky light and a low sun, issue #394); the temple hall is lit flat in 67js while Cycles leaves it dark, the closed-room-without-bake gap (an open roof is not a bake). The hall has an opt-in for it: `--bake temple-hall-rose` bakes it on the GPU (see below), which takes `temple-hall-rose` from 0.5652 to 0.1181 against Cycles (and makes EEVEE worse, 0.5727 to 0.9019, because EEVEE has no indirect light here); the committed rows above are the plain scene.
+
+### The hall baked on the GPU (2026-11-04, issue #302)
+
+`node bench/reference/run.mjs --grand --scene temple-hall-rose --skip-cpu --skip-blender --bake temple-hall-rose` draws the hall with the light bake on the GPU tracer's kernel (``bakeLightmapsAsync` with `backend: gpu`, which takes up to 1,024 parts where the CPU bake stops at 256; the hall has more than 256). The scene's `bakeOptions` in `look-options.js` are `{ backend: 'gpu', texelsPerUnit: 2, samples: 128, maxSeconds: 300 }`: 2 texels per unit is the density the closed `temple-hall` scene already uses, and the default 6 would need 1,542,896 texels against a limit of 1,000,000. At 2 the bake has 493,632 texels, 3 bounces, and took 16.7 s and 30.1 s in two runs, each including the 7 s kernel compile (RTX 3060, headless Chrome, other sessions on the machine; the two runs gave the same score). Against the same Cycles frame: 0.5652 without the bake, 0.1181 with it (FLIP, 960 by 540, measured). The frame is `images/grand-temple-hall-rose-baked.jpg`. Leave `--skip-cpu` on: the SwiftShader page would run the GPU bake on the CPU. At 256 samples the bake is refused by the ray work limit (758 million of 400 million), so 128 is the most the limit allows at this density. The committed `grand.json` row stays the plain scene.
+
+`lit-interior` with the GPU bake (`--bake lit-interior --bake-backend gpu --bake-samples 512`, the same Cycles frame, measured 2026-11-04): 0.0914 against Cycles, where the CPU bake at its defaults (128 samples) scores 0.1129. `bake-compare.mjs` bakes one scene with named option sets on either backend and prints seconds and the gap between lightmaps; the numbers are in `docs/light-bake.md`. `--bake-density <texels per unit>` and `--bake-samples <n>` set those two bake options for a run.
## The reference harness drew `foliage` in a breeze (2026-11-03, part of issue #191)
diff --git a/bench/reference/bake-compare.mjs b/bench/reference/bake-compare.mjs
new file mode 100644
index 00000000..c147db79
--- /dev/null
+++ b/bench/reference/bake-compare.mjs
@@ -0,0 +1,31 @@
+// Bakes one reference scene on the CPU and on the GPU backend of the light bake and prints seconds and agreement.
+// node bench/reference/bake-compare.mjs <scene id> '<variants json>'
+// The variants are named bake options; the first is the reference the others are compared with, for example
+// '{"cpu":{"backend":"cpu","samples":128},"gpu":{"backend":"gpu","samples":512}}'
+// Run it through GPU_LOCK_WEIGHT=heavy bash ~/.agents/tools/gpu-lock.sh: the GPU bake takes the whole GPU for seconds.
+import { constants, setPriority } from 'node:os';
+import { chromium } from 'playwright';
+import { createServer } from 'vite';
+
+const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+const [sceneId, variantsJson] = process.argv.slice(2);
+const variants = JSON.parse(variantsJson);
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
+await server.listen();
+const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;
+const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'] });
+try {
+ const page = await browser.newPage({ viewport: { width: 960, height: 540 } });
+ page.on('pageerror', error => console.log('PAGE ERROR', error.message));
+ page.on('console', message => message.type() === 'error' && console.log('PAGE CONSOLE', message.text()));
+ page.setDefaultTimeout(0);
+ await page.goto(`${serverUrl}/bench/reference/harness.html`, { timeout: 180000 });
+ await page.waitForFunction(() => window.compareBakeBackends, null, { timeout: 180000 });
+ const results = await page.evaluate(([id, named]) => window.compareBakeBackends(id, named), [sceneId, variants]);
+ console.log(JSON.stringify(results, null, 1));
+} finally {
+ await browser.close();
+ await server.close();
+}
diff --git a/bench/reference/harness.js b/bench/reference/harness.js
index 6edad090..df4de4de 100644
--- a/bench/reference/harness.js
+++ b/bench/reference/harness.js
@@ -141,11 +141,11 @@ async function bakeScene(scene, bakeOptions) {
if (bakeOptions.preset) {
return bakeScenePreset(scene, bakeOptions.preset);
}
- const { bakeLightmaps } = await import('/src/light-bake.js');
+ const { bakeLightmapsAsync } = await import('/src/light-bake-gpu.js');
const { pointLights, keyColor, lightDirection } = scene.environment;
const started = performance.now();
// A scene as large as a hall can need its own texel density to stay under the bake's texel limit.
- const baked = bakeLightmaps(scene.parts, { pointLights, keyColor, lightDirection }, { ...scene.bakeOptions, ...bakeOptions });
+ const baked = await bakeLightmapsAsync(scene.parts, { pointLights, keyColor, lightDirection }, { ...scene.bakeOptions, ...bakeOptions });
return { parts: baked.parts, report: baked.report, seconds: (performance.now() - started) / 1000 };
}
@@ -266,7 +266,53 @@ async function measureReferenceFrameTime(id, { bake, probes = false, cascades =
medianMilliseconds: frameMilliseconds[Math.floor(measuredFrames / 2)], p95Milliseconds: frameMilliseconds[Math.floor(measuredFrames * 0.95)] };
}
+// The light each baked part holds, in linear radiance: the lightmap bytes decoded from sRGB and multiplied by the map's peak.
+function lightmapRadiance(part) {
+ const texture = part.material.lightMap ?? part.material.emissiveMap;
+ if (!texture) return null;
+ const peak = part.material.lightMap ? part.material.lightMapScale : part.material.emission;
+ const bytes = texture.image.data;
+ const radiance = new Float32Array((bytes.length / 4) * 3);
+ for (let texel = 0; texel < bytes.length / 4; texel++) {
+ for (let channel = 0; channel < 3; channel++) {
+ const encoded = bytes[texel * 4 + channel] / 255;
+ radiance[texel * 3 + channel] = (encoded <= 0.04045 ? encoded / 12.92 : ((encoded + 0.055) / 1.055) ** 2.4) * peak;
+ }
+ }
+ return radiance;
+}
+
+// Bakes a scene once per named variant of options (each may set `backend`) and compares every lightmap with the first variant's:
+// seconds, and the mean of the gaps between lightmaps as a share of the first one's light. The GPU kernel is compiled by a
+// one-sample bake before the first GPU variant, so the seconds measured are the trace.
+async function compareBakeBackends(id, variants) {
+ const scene = await SCENES[id]();
+ const results = {};
+ let reference = null;
+ for (const [name, bakeOptions] of Object.entries(variants)) {
+ if (bakeOptions.backend === 'gpu') await bakeScene(scene, { ...bakeOptions, samples: 1 });
+ const baked = await bakeScene(scene, bakeOptions);
+ const radiance = baked.parts.map(lightmapRadiance);
+ reference ??= radiance;
+ let referenceSum = 0;
+ let bakedSum = 0;
+ let differenceSum = 0;
+ radiance.forEach((partRadiance, index) => {
+ if (!partRadiance || !reference[index]) return;
+ for (let value = 0; value < partRadiance.length; value++) {
+ referenceSum += reference[index][value];
+ bakedSum += partRadiance[value];
+ differenceSum += Math.abs(partRadiance[value] - reference[index][value]);
+ }
+ });
+ const { texels, rayWork, used, gpu, gpuCompileSeconds } = baked.report;
+ results[name] = { seconds: baked.seconds, texels, rayWork, used, gpu, gpuCompileSeconds, meanRatioToFirst: bakedSum / referenceSum, meanGapShareOfFirst: differenceSum / referenceSum };
+ }
+ return results;
+}
+
window.measureReferenceFrameTime = measureReferenceFrameTime;
+window.compareBakeBackends = compareBakeBackends;
async function renderReferencePathTraced(id, options) {
const scene = await REFERENCE_SCENES[id]();
diff --git a/bench/reference/images/grand-temple-hall-rose-baked.jpg b/bench/reference/images/grand-temple-hall-rose-baked.jpg
new file mode 100644
index 00000000..1ed791ec
Binary files /dev/null and b/bench/reference/images/grand-temple-hall-rose-baked.jpg differ
diff --git a/bench/reference/look-options.js b/bench/reference/look-options.js
index 6e05ae89..31f9e003 100644
--- a/bench/reference/look-options.js
+++ b/bench/reference/look-options.js
@@ -248,6 +248,9 @@ function templeHallRose() {
environment: environment(lighting, { keyColor: [11, 9.6, 7.4], lightDirection: normalized(sunDirection), volumeFog: fogBox(0.012, [-HALL.halfWidth, 0, HALL.back], [HALL.halfWidth, HALL.roofHeight - 1, HALL.front + 2], 190, 0.55) }),
camera: { eye: [0, 1.8, HALL.front - 3], target: [0, 13, HALL.back], up: [0, 1, 0], fov: 58, near: 0.1, far: 300 },
shadow: sunShadow(sunDirection, [0, 15, NAVE_MIDDLE], 105, 200),
+ // Used by `--bake temple-hall-rose` (the hall has more parts and texels than the CPU bake takes): the GPU bake at the density the
+ // closed `temple-hall` scene uses. Without --bake the hall is drawn as before.
+ bakeOptions: { backend: 'gpu', texelsPerUnit: 2, samples: 128, maxSeconds: 300 },
};
}
diff --git a/bench/reference/run.mjs b/bench/reference/run.mjs
index be626af4..ebeef357 100644
--- a/bench/reference/run.mjs
+++ b/bench/reference/run.mjs
@@ -78,6 +78,14 @@ const skyOnlyOptions = skyOnlyFlag >= 0 ? { skyOnly: true, texelsPerUnit: skyTex
// texel density, scaled down to the preset's path work budget, and the scene's own `bakeOptions` are ignored. Needs --bake.
const bakePresetFlag = argumentsGiven.indexOf('--bake-preset');
const bakePreset = bakePresetFlag >= 0 ? argumentsGiven[bakePresetFlag + 1] : null;
+// --bake-backend <cpu|gpu> picks the tracer of the --bake rows (the GPU path tracer's kernel; the default is the CPU reference),
+// and --bake-samples <n> and --bake-density <texels per unit> set those on top of the scene's own bake options.
+const bakeBackendFlag = argumentsGiven.indexOf('--bake-backend');
+const bakeBackend = bakeBackendFlag >= 0 ? argumentsGiven[bakeBackendFlag + 1] : null;
+const bakeSamplesFlag = argumentsGiven.indexOf('--bake-samples');
+const bakeSamples = bakeSamplesFlag >= 0 ? Number(argumentsGiven[bakeSamplesFlag + 1]) : null;
+const bakeDensityFlag = argumentsGiven.indexOf('--bake-density');
+const bakeDensity = bakeDensityFlag >= 0 ? Number(argumentsGiven[bakeDensityFlag + 1]) : null;
const probesFlag =argumentsGiven.indexOf('--probes');
const probesValue = probesFlag >= 0 ? argumentsGiven[probesFlag + 1] : undefined;
const probedSceneIds = probesFlag >= 0 && probesValue && !probesValue.startsWith('--') ? probesValue.split(',') : null;
@@ -105,7 +113,7 @@ const sceneIdsGiven = lookIds ?? (sceneFlag >= 0 ? argumentsGiven[sceneFlag + 1]
// The fresh bake.json lands in the work directory and is checked against the committed one (compare-scores.mjs); --update-baseline replaces
// the committed bake.json and images/<id>-baked.jpg with it.
const bakeScoreRun = bakedSceneIds !== null && !sceneSet && !pathTracerFlag;
-const bakeVariantFlags = ['--sky-only', '--bake-preset', '--probes', '--ambient', '--ambient-occlusion', '--cascades', '--no-object-probes', '--object-probes', '--no-water', '--ssr-water', '--no-ground-bounce', '--floor-sky', '--floor-sky-rooms'];
+const bakeVariantFlags = ['--sky-only', '--bake-preset', '--bake-backend', '--bake-samples', '--bake-density', '--probes', '--ambient', '--ambient-occlusion', '--cascades', '--no-object-probes', '--object-probes', '--no-water', '--ssr-water', '--no-ground-bounce', '--floor-sky', '--floor-sky-rooms'];
const bakeScoreIsBaseline = bakeScoreRun && argumentsGiven.includes('--update-baseline') && !bakeVariantFlags.some(flag => argumentsGiven.includes(flag));
const onlyScenes = sceneIdsGiven ?? (bakeScoreRun ? bakedSceneIds : null);
const skipCpu = skipCpuFlag || bakeScoreRun || Boolean(viewTransform);
@@ -135,7 +143,7 @@ async function renderBackend(backend, serverUrl, graphics) {
// Object probes are on by default, as in a recipe, so the baseline scores what a user gets.
const objectProbesThisScene = !argumentsGiven.includes('--no-object-probes') && (objectProbeSceneIds === null || objectProbeSceneIds.includes(id));
const probes = probesThisScene || (objectProbesThisScene ? 'objects' : false);
- const bake = bakesThisScene ? { ...skyOnlyOptions, ...(bakePreset ? { preset: bakePreset } : {}) } : null;
+ const bake = bakesThisScene ? { ...skyOnlyOptions, ...(bakePreset ? { preset: bakePreset } : {}), ...(bakeBackend ? { backend: bakeBackend } : {}), ...(bakeSamples ? { samples: bakeSamples } : {}), ...(bakeDensity ? { texelsPerUnit: bakeDensity } : {}) } : null;
const result = await page.evaluate(([sceneId, shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bakeOptions, cascadeCount, withProbes, ambientScale, selectedViewTransform]) => window.renderReferenceScene(sceneId, { describe: shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bake: bakeOptions, cascades: cascadeCount, probes: withProbes, ambient: ambientScale, viewTransform: selectedViewTransform }), [id, describe, ambientOcclusion, ambientOcclusionRadius, bake, cascades, probes, ambient, viewTransform]);
if (result.glError !== 0) throw new Error(`${id} on ${backend} gave WebGL error ${result.glError}.`);
graphics[backend] = result.graphics;
diff --git a/changes/302-gpu-bake.md b/changes/302-gpu-bake.md
new file mode 100644
index 00000000..47270f56
--- /dev/null
+++ b/changes/302-gpu-bake.md
@@ -0,0 +1 @@
+- The light bake can trace on the GPU (issue #302): `bakeLightmapsAsync(parts, lighting, { backend: 'gpu' })` starts a cosine weighted path at every covered texel in the GPU path tracer's kernel (a texel mode of the same shader, so lights, materials, maps and the bounce rules are the tracer's) and resolves with the same `{ parts, report }`; `report.backend`, `report.gpu` and `report.gpuCompileSeconds` say what ran. `backend` is `cpu` (the default and the reference) or `gpu`, as for the path tracer; the synchronous `bakeLightmaps` refuses `gpu` and names the addon. It lives in its own addon, `67js/addons/light-bake-gpu`, so the CPU bake and the core bundle do not carry it. It needs WebGL2 with float targets, does not take light linking (`affects`) or a sky-only bake, and `bench/reference/bake-compare.mjs` measures it against the CPU bake.
diff --git a/changes/302.size.md b/changes/302.size.md
new file mode 100644
index 00000000..13c07077
--- /dev/null
+++ b/changes/302.size.md
@@ -0,0 +1,4 @@
+- entry:light-bake: grows by about 315 bytes gzip for the `backend` option and its validation and for the bake loop split into rasterize, gather and finish steps (exported, so the GPU bake in the new addon shares them with the CPU bake).
+- entry:light-bake+lazy: the same bytes.
+- entry:light-bake-gpu: new addon (`67js/addons/light-bake-gpu`, about 49 KB raw): `bakeLightmapsAsync`, the texel packing and the GPU path tracer kernel it loads. No core bundle imports it.
+- scene:agent-scene+lazy: the recipe bake reads the CPU bake's split loop and `backend` validation, about 283 bytes gzip counting lazy modules.
diff --git a/docs/light-bake.md b/docs/light-bake.md
index 46192f8b..003929d2 100644
--- a/docs/light-bake.md
+++ b/docs/light-bake.md
@@ -39,7 +39,16 @@ The unwrap gives the texel count before any ray is traced, so the work of a bake
A node that hosts cloth is skipped like a hair host: the cloth simulation replaces its geometry every frame, so a lightmap built on the rest geometry would not follow it (and the renderer refuses a light map on geometry without `lightUvs`, which failed every frame after t=0). Baked parts read every other material field live, so motion tracks on colour still work; the lightmap itself is fixed at the rest pose.
-## What it bakes
+## GPU backend
+
+```js
+import { bakeLightmapsAsync } from '67js/addons/light-bake-gpu';
+
+const { parts: bakedParts, report } = await bakeLightmapsAsync(parts, lighting, { backend: 'gpu', samples: 512, bounces: 2 });
+```
+
+`backend` is `cpu` (the default and the reference) or `gpu`, named as for the path tracer's `backend`. `bakeLightmapsAsync` takes the same arguments and options as `bakeLightmaps` and resolves with the same `{ parts, report }`; the synchronous `bakeLightmaps` throws a `TypeError` for `gpu` and names this addon. A GPU bake rasterizes the texels as the CPU bake does, then sends all covered texels of all parts to the path tracer's kernel in one batch (`src/light-bake-gpu.js`, `src/path-tracer-gpu.js`): the kernel starts a cosine weighted path at each texel, follows `bounces` hits with the tracer's own lights, materials and maps, and returns the light that arrives. The albedo, smoothing, dilation, sky visibility and the baked parts then come from the same code as on the CPU. It is its own addon (`67js/addons/light-bake-gpu`), so the CPU bake and the core bundle do not carry it. It needs a page with WebGL2 and float render targets (`EXT_color_buffer_float`, `EXT_float_blend`) and throws without them. It takes up to 1,024 parts where the CPU bake takes 256 (`MAX_GPU_BAKE_PARTS`; the texel and ray work limits are the same). It does not take a light with `affects` (the kernel has no light linking) or `skyOnly`, and `report` adds `gpu` and `gpuCompileSeconds` (the kernel compiles once per page). The GPU result is not byte identical to the CPU one: the CPU gatherer treats every part as a diffuse surface, while the kernel also follows specular lobes, clear coat and glass, and it draws other random numbers.
+
The bake traces cosine-weighted paths from each texel through up to `bounces` reflections. Each hit adds its own emission and the direct light it receives from the point lights and the sun, with shadow rays. A texel stores that light times its own albedo. Direct light is not baked: it stays live, so shadows and moving lights keep working. The stored light is only what has bounced at least once, so a scene needs the same lights at run time that it gave the bake.
@@ -99,3 +108,16 @@ The result is deterministic: the same parts, lights and options give the same by
## Measured
The `lit-interior` reference scene (25,648 texels at the defaults) bakes in about 6 s in the page on an RTX 3060 machine, running at below-normal priority. Its score against Cycles goes from 0.5055 to 0.1444 with the bake (`npm run reference -- --bake lit-interior`; details in `bench/reference/README.md`). Frame time on the same scene (960x540, 4 samples, RTX 3060, below-normal priority, 200 frames read back after each draw, two runs of each in alternating order): median 2.08 and 2.02 ms without the bake, 1.88 and 1.66 ms with it, so the bake costs no measurable draw time (one extra texture read per baked part; the spread between runs is load on the machine). `node bench/reference/frame-time.mjs lit-interior gpu` repeats it. The recipe path on a closed room with 8 boxes bakes 13,184 texels in 4.8 s at `standard`.
+
+### GPU against CPU (issue #302)
+
+`lit-interior` (28,784 texels at texelsPerUnit 6, 3 bounces), RTX 3060, headless Chrome, kernel already compiled, measured 2026-11-04 with `node bench/reference/bake-compare.mjs lit-interior '<variants>'`:
+
+| Bake | Samples | Path steps | Seconds | Mean light against the CPU bake at 512 samples | Mean gap, share of that light |
+| --- | --- | --- | --- | --- | --- |
+| CPU | 512 | 44.2 M | 17.8 | 1.000 | 0 |
+| CPU | 128 | 11.1 M | 6.7 | 1.002 | 0.018 |
+| GPU | 128 | 11.1 M | 0.26 | 1.049 | 0.056 |
+| GPU | 512 | 44.2 M | 0.70 | 1.054 | 0.055 |
+
+The recipe preset `standard` resolves to 81 samples, 3 bounces and 4.86 texels per unit on this scene (4.7 M path steps, 1.7 s on the CPU), so the GPU bake at 512 samples runs 9.4 times those path steps in 0.70 s. The kernel compiles once per page and that takes 7.4 s, which comes on top of the first GPU bake of a page (a cold `run.mjs` row measured 32 s for the bake with the compile, other sessions using the machine). The GPU light is about 5 percent above the CPU's and the gap does not shrink with samples (0.056 at 128, 0.055 at 512, against 0.018 for the CPU's own noise at 128), so it is a bias, not noise; the likely cause (inferred, not isolated) is that the CPU gatherer treats every part as a diffuse surface, while the kernel also traces the specular lobe of a rough dielectric. Score of the baked `lit-interior` against Cycles (FLIP, 960 by 540, same Cycles frame): CPU bake 0.1129, GPU bake at 512 samples 0.0914.
diff --git a/package.json b/package.json
index e139872a..219748a1 100644
--- a/package.json
+++ b/package.json
@@ -76,6 +76,7 @@
"./addons/grass": "./build/grass.js",
"./addons/clutter": "./build/clutter.js",
"./addons/light-bake": "./build/light-bake.js",
+ "./addons/light-bake-gpu": "./build/light-bake-gpu.js",
"./addons/ground-bounce": "./build/ground-bounce.js",
"./addons/floor-sky-visibility": "./build/floor-sky-visibility.js",
"./addons/path-tracer": "./build/path-tracer.js",
diff --git a/src/light-bake-gpu.js b/src/light-bake-gpu.js
new file mode 100644
index 00000000..31693881
--- /dev/null
+++ b/src/light-bake-gpu.js
@@ -0,0 +1,91 @@
+import { buildTraceScene } from './path-tracer-scene.js';
+import { traceTexelsOnGpu } from './path-tracer-gpu.js';
+import { checkBudget, checkedBakeSize, finishLightmaps, planLightmaps, rasterizeEntries, traceLightmaps } from './light-bake.js';
+
+// The GPU side of the light bake: the texels of every part go to the path tracer's kernel in one batch, which starts a
+// cosine weighted path at each texel and returns the light that arrives. The CPU gatherer in light-bake.js stays the
+// reference. This module holds the asynchronous bake API, so the CPU bake and every bundle that uses it carry none of this.
+
+const BAKE_SEED = 1;
+// The bake keeps every bright sample (the CPU gatherer has no clamp), so the kernel's firefly clamp is set out of reach.
+const NO_FIREFLY_CLAMP = 1e6;
+
+/** The plan's lights in the shapes the path tracer reads. A light limited by `affects` cannot be traced: the kernel has no light linking. */
+function traceEnvironment({ lights }) {
+ const linked = [...lights.pointLights, ...lights.spotLights, ...lights.areaLights, ...(lights.sun ? [lights.sun] : [])].some(light => light.affects !== null);
+ if (linked) throw new RangeError('A light bake on the GPU backend does not support light linking (`affects`). Use the CPU backend.');
+ return {
+ pointLights: lights.pointLights,
+ spotLights: lights.spotLights.map(light => ({ ...light, angle: Math.acos(light.cosineHalfAngle), penumbra: light.blend / (1 - light.cosineHalfAngle) })),
+ areaLights: lights.areaLights.map(light => ({ ...light, direction: light.normal, up: light.along })),
+ keyColor: lights.sun?.color ?? [0, 0, 0],
+ lightDirection: lights.sun?.direction ?? [0, 1, 0],
+ };
+}
+
+/** The covered texels of all parts as one list of world points and normals, and where each part's slice starts. */
+function packCoveredTexels(rasterized) {
+ let count = 0;
+ for (const { covered } of rasterized) for (const flag of covered) count += flag;
+ const points = new Float32Array(count * 3);
+ const normals = new Float32Array(count * 3);
+ const slices = [];
+ let next = 0;
+ for (const { positions, normals: texelNormals, covered } of rasterized) {
+ const texelIndices = [];
+ for (let texel = 0; texel < covered.length; texel++) {
+ if (!covered[texel]) continue;
+ points.set(positions.subarray(texel * 3, texel * 3 + 3), next * 3);
+ normals.set(texelNormals.subarray(texel * 3, texel * 3 + 3), next * 3);
+ texelIndices.push(texel);
+ next++;
+ }
+ slices.push(texelIndices);
+ }
+ return { count, points, normals, slices };
+}
+
+/**
+ * Traces every covered texel on the GPU and resolves with `entries` (per rasterized part, `light` and `escaped` in the
+ * layout the CPU gatherer returns), the `gpu` name and the kernel's `compileSeconds`.
+ */
+async function gatherOnGpu(plan, settings, rasterized, shouldStop) {
+ const environment = traceEnvironment(plan);
+ const texels = packCoveredTexels(rasterized);
+ const scene = buildTraceScene(plan.parts, environment);
+ const traced = await traceTexelsOnGpu(scene, texels, { samples: settings.samples, bounces: settings.bounces, seed: BAKE_SEED, fireflyClamp: NO_FIREFLY_CLAMP }, shouldStop);
+ let next = 0;
+ const entries = rasterized.map(({ resolution }, entryNumber) => {
+ const light = new Float32Array(resolution * resolution * 3);
+ const escaped = new Float32Array(resolution * resolution);
+ for (const texel of texels.slices[entryNumber]) {
+ light.set(traced.radiance.subarray(next * 3, next * 3 + 3), texel * 3);
+ escaped[texel] = traced.escaped[next];
+ next++;
+ }
+ return { light, escaped };
+ });
+ return { entries, gpu: traced.gpu, compileSeconds: traced.compileSeconds };
+}
+
+/** `traceLightmaps` for either backend: the CPU trace as it is, or the same steps with the texels gathered by the kernel. */
+export async function traceLightmapsAsync(plan, tracedSettings) {
+ const settings = { ...plan.settings, ...tracedSettings };
+ if (settings.backend === 'cpu') return traceLightmaps(plan, settings);
+ if (settings.skyOnly) throw new RangeError('A sky visibility bake runs on the CPU backend only.');
+ const sizes = checkedBakeSize(plan, settings);
+ const rasterized = rasterizeEntries(plan, settings);
+ const gathered = await gatherOnGpu(plan, settings, rasterized, () => checkBudget(plan, settings));
+ const result = finishLightmaps(plan, settings, rasterized, gathered.entries, sizes);
+ return { parts: result.parts, report: { ...result.report, gpu: gathered.gpu, gpuCompileSeconds: gathered.compileSeconds } };
+}
+
+/**
+ * `bakeLightmaps` with a choice of tracer: `options.backend` is "cpu" (the default, the reference) or "gpu", which traces the
+ * texels with the GPU path tracer's kernel and needs a page with WebGL2. Resolves with the same `{ parts, report }`;
+ * `report.backend` names the tracer, and a GPU bake adds `gpu` and `gpuCompileSeconds`.
+ */
+export async function bakeLightmapsAsync(parts, lighting, options = {}) {
+ const plan = planLightmaps(parts, lighting, options);
+ return traceLightmapsAsync(plan, { ...plan.settings, skyOnly: options.skyOnly === true });
+}
diff --git a/src/light-bake.js b/src/light-bake.js
index fcee471c..b8babd05 100644
--- a/src/light-bake.js
+++ b/src/light-bake.js
@@ -24,6 +24,8 @@ export const MAX_BAKE_RAY_WORK = 400_000_000;
export const MAX_BAKE_TEXELS = 1_000_000;
export const MAX_BAKE_TRIANGLES = 200_000;
export const MAX_BAKE_PARTS = 256;
+// The GPU tracer takes as many parts as the path tracer does (MAX_TRACE_PARTS); the CPU bake keeps 256.
+export const MAX_GPU_BAKE_PARTS = 1024;
export const MAX_BAKE_POINT_LIGHTS = MAX_POINT_LIGHTS;
export const MAX_BAKE_SPOT_LIGHTS = MAX_SPOT_LIGHTS;
export const MAX_BAKE_AREA_LIGHTS = MAX_AREA_LIGHTS;
@@ -62,6 +64,8 @@ export function normalizeBakeOptions(options = {}) {
if (options === null || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Light bake options must be an object.');
const normalized = {};
for (const name of Object.keys(BAKE_LIMITS)) normalized[name] = boundedNumber(options, name);
+ normalized.backend = options.backend ?? 'cpu';
+ if (normalized.backend !== 'cpu' && normalized.backend !== 'gpu') throw new TypeError('Light bake backend must be "cpu" or "gpu".');
return normalized;
}
@@ -864,7 +868,8 @@ function createSkyVisibilityGatherer({ tracer, offset, samples }) {
export function planLightmaps(parts, lighting, options = {}) {
const settings = normalizeBakeOptions(options);
const lights = normalizeLights(lighting);
- if (!Array.isArray(parts) || parts.length === 0 || parts.length > MAX_BAKE_PARTS) throw new RangeError(`Light bake takes from 1 to ${MAX_BAKE_PARTS} parts.`);
+ const maximumParts = settings.backend === 'gpu' ? MAX_GPU_BAKE_PARTS : MAX_BAKE_PARTS;
+ if (!Array.isArray(parts) || parts.length === 0 || parts.length > maximumParts) throw new RangeError(`Light bake takes from 1 to ${maximumParts} parts.`);
parts.forEach(validatePart);
const triangleTotal = parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);
if (triangleTotal > MAX_BAKE_TRIANGLES) throw new RangeError(`Light bake takes at most ${MAX_BAKE_TRIANGLES} triangles in total.`);
@@ -903,13 +908,31 @@ export function estimateBake(plan, { samples, bounces, texelsPerUnit }) {
return { texels, rayWork: texels * samples * bounces * raysPerHit };
}
-/** Traces a plan with the given settings (samples, bounces, texelsPerUnit, maxSeconds) and returns the baked parts and the report. */
-export function traceLightmaps(plan, tracedSettings) {
- const { parts, lights, started, skipped } = plan;
- const settings = { ...plan.settings, ...tracedSettings };
- const { texels: texelTotal, rayWork } = estimateBake(plan, settings);
- if (texelTotal > MAX_BAKE_TEXELS) throw new RangeError(`Light bake would use ${texelTotal} texels; the limit is ${MAX_BAKE_TEXELS}. Lower maxResolution or texelsPerUnit.`);
+export function checkedBakeSize(plan, settings) {
+ const { texels, rayWork } = estimateBake(plan, settings);
+ if (texels > MAX_BAKE_TEXELS) throw new RangeError(`Light bake would use ${texels} texels; the limit is ${MAX_BAKE_TEXELS}. Lower maxResolution or texelsPerUnit.`);
if (rayWork > MAX_BAKE_RAY_WORK) throw new RangeError(`Light bake would trace about ${rayWork} rays; the limit is ${MAX_BAKE_RAY_WORK}. Lower samples, bounces or texelsPerUnit.`);
+ return { texels, rayWork };
+}
+
+export function checkBudget(plan, settings) {
+ if (performance.now() - plan.started > settings.maxSeconds * 1000) throw new Error(`Light bake passed maxSeconds (${settings.maxSeconds}).`);
+}
+
+/** Where every texel of every bakeable part sits in the world: the same input to the CPU and the GPU tracer. */
+export function rasterizeEntries(plan, settings) {
+ return plan.entries.map((entry) => {
+ const resolution = lightmapResolution(entry.area, entry.unwrapped.utilization, settings);
+ return { entry, resolution, ...rasterizeTexels(entry.unwrapped.geometry, entry.part.matrix, resolution) };
+ });
+}
+
+/**
+ * The CPU tracer's turn: for each rasterized part, `light` (the mean radiance that arrives at each texel, three floats)
+ * and `escaped` (the share of first rays that left the scene).
+ */
+function gatherOnCpu(plan, settings, rasterized) {
+ const { parts, lights } = plan;
const world = buildWorld(parts);
const scale = sceneScale(world.positions);
const offset = scale * 1e-4;
@@ -920,44 +943,57 @@ export function traceLightmaps(plan, tracedSettings) {
const gather = settings.skyOnly
? createSkyVisibilityGatherer({ tracer, offset, samples: settings.samples })
: createGatherer({ world, tracer, albedoOfPart, emissionOfPart, directIrradiance, offset, samples: settings.samples, bounces: settings.bounces });
- const baked = parts.slice();
- const partReports = [];
const sum = [0, 0, 0];
- for (const { part, index, unwrapped, area, slot } of plan.entries) {
- const resolution = lightmapResolution(area, unwrapped.utilization, settings);
- const { positions, normals, covered, nearestDistance } = rasterizeTexels(unwrapped.geometry, part.matrix, resolution);
+ const point = [0, 0, 0];
+ const normal = [0, 0, 0];
+ return rasterized.map(({ entry, resolution, positions, normals, covered }) => {
+ const light = new Float32Array(resolution * resolution * 3);
+ const escaped = new Float32Array(resolution * resolution);
+ for (let texel = 0; texel < resolution * resolution; texel++) {
+ if (!covered[texel]) continue;
+ checkBudget(plan, settings);
+ for (let axis = 0; axis < 3; axis++) {
+ point[axis] = positions[texel * 3 + axis];
+ normal[axis] = normals[texel * 3 + axis];
+ }
+ escaped[texel] = gather(point, normal, entry.index * 1_000_003 + texel, sum);
+ light.set(sum, texel * 3);
+ }
+ return { light, escaped };
+ });
+}
+
+/** Lightmaps and parts from the gathered light: albedo, smoothing, dilation, sky visibility and the baked copies of the parts. */
+export function finishLightmaps(plan, settings, rasterized, gathered, sizes) {
+ const baked = plan.parts.slice();
+ const partReports = [];
+ rasterized.forEach(({ entry, resolution, positions, normals, covered, nearestDistance }, entryNumber) => {
+ const { part, index, unwrapped, area, slot } = entry;
+ const { light, escaped } = gathered[entryNumber];
+ const albedo = diffuseAlbedo(part.material);
const radiance = new Float32Array(resolution * resolution * 3);
const skyVisibility = new Float32Array(resolution * resolution * 3);
let skySum = 0;
let skyTexels = 0;
- const albedo = albedoOfPart[index];
- const point = [0, 0, 0];
- const normal = [0, 0, 0];
let peak = 0;
for (let texel = 0; texel < resolution * resolution; texel++) {
if (!covered[texel]) continue;
- if (performance.now() - started > settings.maxSeconds * 1000) throw new Error(`Light bake passed maxSeconds (${settings.maxSeconds}).`);
- for (let axis = 0; axis < 3; axis++) {
- point[axis] = positions[texel * 3 + axis];
- normal[axis] = normals[texel * 3 + axis];
- }
- const visible = gather(point, normal, index * 1_000_003 + texel, sum);
- skyVisibility.fill(visible, texel * 3, texel * 3 + 3);
+ skyVisibility.fill(escaped[texel], texel * 3, texel * 3 + 3);
// Only texels inside a chart count toward the mean, so the gutter around a chart does not change what the part sees on average.
if (nearestDistance[texel] === 0) {
- skySum += visible;
+ skySum += escaped[texel];
skyTexels++;
}
for (let channel = 0; channel < 3; channel++) {
// The lightMap slot stores the light that arrives; the shader multiplies it by the live surface colour.
- radiance[texel * 3 + channel] = slot ? sum[channel] : sum[channel] * albedo[channel];
+ radiance[texel * 3 + channel] = slot ? light[texel * 3 + channel] : light[texel * 3 + channel] * albedo[channel];
peak = Math.max(peak, radiance[texel * 3 + channel]);
}
}
const meanSkyVisibility = skyTexels > 0 ? skySum / skyTexels : 1;
partReports.push({ name: part.name, resolution, peak, skyVisibility: meanSkyVisibility });
const sealed = meanSkyVisibility < SKY_VISIBLE_ENOUGH && !part.material.occlusionMap;
- if (peak <= 0 && !sealed) continue;
+ if (peak <= 0 && !sealed) return;
let bakedResult = part;
const spacing = Math.sqrt(area / Math.max(skyTexels, 1));
const [smoothRadiance, smoothSkyVisibility] = smoothTexels([radiance, skyVisibility], covered, positions, normals, resolution, spacing);
@@ -967,7 +1003,16 @@ export function traceLightmaps(plan, tracedSettings) {
if (smoothPeak > 0) bakedResult = (slot ? lightMappedPart : bakedPart)(part, unwrapped.geometry, lightmapTexture(smoothRadiance, resolution, smoothPeak), smoothPeak);
if (sealed) bakedResult = skyVisibilityPart(bakedResult, unwrapped.geometry, skyVisibilityTexture(smoothSkyVisibility, resolution), slot);
baked[index] = bakedResult;
- }
- const report = { parts: partReports, skipped, texels: texelTotal, rayWork, seconds: (performance.now() - started) / 1000 };
+ });
+ const report = { parts: partReports, skipped: plan.skipped, texels: sizes.texels, rayWork: sizes.rayWork, backend: settings.backend, seconds: (performance.now() - plan.started) / 1000 };
return { parts: baked, report };
}
+
+/** Traces a plan with the given settings (samples, bounces, texelsPerUnit, maxSeconds) and returns the baked parts and the report. */
+export function traceLightmaps(plan, tracedSettings) {
+ const settings = { ...plan.settings, ...tracedSettings };
+ if (settings.backend !== 'cpu') throw new TypeError('Light bake backend "gpu" is asynchronous: use bakeLightmapsAsync from light-bake-gpu.js.');
+ const sizes = checkedBakeSize(plan, settings);
+ const rasterized = rasterizeEntries(plan, settings);
+ return finishLightmaps(plan, settings, rasterized, gatherOnCpu(plan, settings, rasterized), sizes);
+}
diff --git a/src/path-tracer-gpu-shader.js b/src/path-tracer-gpu-shader.js
index 78fb4f3d..561d721a 100644
--- a/src/path-tracer-gpu-shader.js
+++ b/src/path-tracer-gpu-shader.js
@@ -17,7 +17,45 @@ void main() {
gl_Position = vec4(corner * 2.0 - 1.0, 0.0, 1.0);
}`;
-const buildSource = hasSubsurface => `#version 300 es
+// Camera mode: one pixel is one jittered camera ray.
+const CAMERA_MAIN = `void main() {
+ ivec2 pixelCoordinate = ivec2(gl_FragCoord.xy);
+ int row = pixelCoordinate.y;
+ uint pixel = uint(row * uSize.x + pixelCoordinate.x);
+ uint sampleIndex = uint(uSample);
+ if (uHasSun) sunFrame = buildFrame(uSunDirection);
+ float jitterX = hashJitter(pixel, sampleIndex, uSeed, 1u);
+ float jitterY = hashJitter(pixel, sampleIndex, uSeed, 2u);
+ float screenX = ((float(pixelCoordinate.x) + jitterX) / float(uSize.x) * 2.0 - 1.0) * uHalfSize.x;
+ float screenY = (1.0 - (float(row) + jitterY) / float(uSize.y) * 2.0) * uHalfSize.y;
+ vec3 rayDirection = normalize(uForward + uRight * screenX + uAbove * screenY);
+ tracePath(uEye, rayDirection, pixel, sampleIndex);`;
+
+// Texel mode: one pixel is one lightmap texel. The path starts on the texel's surface with a cosine weighted direction,
+// so the radiance it returns is the light arriving at the texel (the caller multiplies by the albedo). The first
+// uBounces + 1 hits are followed, which is the bake's bounce count.
+const TEXEL_UNIFORM = `uniform sampler2D uTexelPoints;
+uniform sampler2D uTexelNormals;
+uniform int uTexelCount;
+uniform int uSampleCount;`;
+
+const TEXEL_MAIN = `void main() {
+ ivec2 pixelCoordinate = ivec2(gl_FragCoord.xy);
+ int texelIndex = pixelCoordinate.y * uSize.x + pixelCoordinate.x;
+ uint pixel = uint(texelIndex);
+ uint sampleIndex = uint(uSample);
+ if (uHasSun) sunFrame = buildFrame(uSunDirection);
+ vec3 normal = texelFetch(uTexelNormals, pixelCoordinate, 0).xyz;
+ vec3 origin = texelFetch(uTexelPoints, pixelCoordinate, 0).xyz + normal * uSurfaceOffset;
+ float firstUnit = (float(uSample) + hashJitter(pixel, sampleIndex, uSeed, 1u)) / float(uSampleCount);
+ float secondUnit = hashJitter(pixel, sampleIndex, uSeed, 2u);
+ float coneRadius = sqrt(firstUnit);
+ float angle = TWO_PI * secondUnit;
+ vec3 rayDirection = buildFrame(normal) * vec3(coneRadius * cos(angle), coneRadius * sin(angle), sqrt(max(0.0, 1.0 - firstUnit)));
+ if (texelIndex >= uTexelCount) rayDirection = normal;
+ tracePath(origin, rayDirection, pixel, sampleIndex);`;
+
+const buildSource = (hasSubsurface, texelBake) => `#version 300 es
precision highp float;
precision highp int;
precision highp sampler2D;
@@ -71,6 +109,7 @@ uniform vec3 uVolumeMinimum;
uniform vec3 uVolumeMaximum;
uniform vec3 uVolumeAlbedo;
uniform vec3 uVolumeShape;
+${texelBake ? TEXEL_UNIFORM : ''}
${hasSubsurface ? SUBSURFACE_UNIFORM : ''}
layout(location = 0) out vec4 outRadiance;
layout(location = 1) out vec4 outAlbedo;
@@ -730,6 +769,7 @@ mat3 sunFrame;
vec3 featureAlbedo;
vec3 featureNormal;
float featureDepth;
+float firstLegEscaped = 0.0;
void addRadiance(int depth, vec3 amount) {
if (depth > 0) {
@@ -952,6 +992,7 @@ void tracePath(vec3 origin, vec3 startDirection, uint pixel, uint sampleIndex) {
bool found = intersectScene(position, direction);
bool inFog = uHasVolume && scatterInFog(position, found ? hitDistance : uFarDistance);
if (!inFog && !found) {
+ if (depth == 0) firstLegEscaped = 1.0;
addEscape(depth, previousPdf, afterMirror);
break;
}
@@ -1028,18 +1069,7 @@ ${hasSubsurface ? SUBSURFACE_LOBE : ''}
}
}
-void main() {
- ivec2 pixelCoordinate = ivec2(gl_FragCoord.xy);
- int row = pixelCoordinate.y;
- uint pixel = uint(row * uSize.x + pixelCoordinate.x);
- uint sampleIndex = uint(uSample);
- if (uHasSun) sunFrame = buildFrame(uSunDirection);
- float jitterX = hashJitter(pixel, sampleIndex, uSeed, 1u);
- float jitterY = hashJitter(pixel, sampleIndex, uSeed, 2u);
- float screenX = ((float(pixelCoordinate.x) + jitterX) / float(uSize.x) * 2.0 - 1.0) * uHalfSize.x;
- float screenY = (1.0 - (float(row) + jitterY) / float(uSize.y) * 2.0) * uHalfSize.y;
- vec3 rayDirection = normalize(uForward + uRight * screenX + uAbove * screenY);
- tracePath(uEye, rayDirection, pixel, sampleIndex);
+${texelBake ? TEXEL_MAIN : CAMERA_MAIN}
// A sample that went through a NaN or an infinity (a grazing ray, a zero pdf) counts as black, so it cannot spread through the denoiser.
if (!(all(greaterThanEqual(radiance, vec3(0.0))) && all(lessThan(radiance, vec3(1e30))))) radiance = vec3(0.0);
if (!(featureDepth >= 0.0 && featureDepth < 1e30)) featureDepth = 0.0;
@@ -1049,13 +1079,16 @@ void main() {
outRadiance = vec4(radiance, featureDepth);
outAlbedo = vec4(featureAlbedo, 0.0);
outNormal = vec4(featureNormal, 0.0);
- outStatistics = vec4(sampleLuminance, sampleLuminance * sampleLuminance, 0.0, 0.0);
+ outStatistics = vec4(sampleLuminance, sampleLuminance * sampleLuminance, firstLegEscaped, 0.0);
}
`;
-/** The kernel; `hasSubsurface` compiles in the random walk, which only scenes with a subsurface part need. */
-export function buildFragmentSource({ hasSubsurface = false } = {}) {
- return buildSource(hasSubsurface);
+/**
+ * The kernel; `hasSubsurface` compiles in the random walk, which only scenes with a subsurface part need. `texelBake`
+ * starts every path at a lightmap texel instead of the camera (see light-bake-gpu.js).
+ */
+export function buildFragmentSource({ hasSubsurface = false, texelBake = false } = {}) {
+ return buildSource(hasSubsurface, texelBake);
}
export const FRAGMENT_SOURCE = buildFragmentSource();
diff --git a/src/path-tracer-gpu.js b/src/path-tracer-gpu.js
index daa3f003..7962d618 100644
--- a/src/path-tracer-gpu.js
+++ b/src/path-tracer-gpu.js
@@ -34,10 +34,10 @@ function compileShader(gl, type, source) {
return shader;
}
-function createProgram(gl, hasSubsurface) {
+function createProgram(gl, variant) {
const program = gl.createProgram();
gl.attachShader(program, compileShader(gl, gl.VERTEX_SHADER, VERTEX_SOURCE));
- gl.attachShader(program, compileShader(gl, gl.FRAGMENT_SHADER, buildFragmentSource({ hasSubsurface })));
+ gl.attachShader(program, compileShader(gl, gl.FRAGMENT_SHADER, buildFragmentSource(variant)));
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(`The GPU path tracer program did not link: ${gl.getProgramInfoLog(program)}`);
return program;
@@ -70,7 +70,6 @@ function uploadScene(gl, program, scene) {
const materials = packMaterials(scene.materials, atlas);
const floatTables = [['uNodes', nodes], ['uTriangles', triangles], ['uMaterials', materials], ['uLights', lights.table]];
if (sceneUsesSubsurface(scene.materials)) floatTables.push(['uSubsurface', packSubsurface(scene.materials)]);
- if (sceneUsesSubsurface(scene.materials)) floatTables.push(['uSubsurface', packSubsurface(scene.materials)]);
let unit = 0;
const bind = (name) => gl.uniform1i(gl.getUniformLocation(program, name), unit++);
for (const [name, table] of floatTables) {
@@ -87,7 +86,7 @@ function uploadScene(gl, program, scene) {
createTexture(gl, unit, gl.R32F, gl.RED, gl.FLOAT, table.width, table.height, table.data);
bind(name);
}
- return { lightCount: lights.count };
+ return { lightCount: lights.count, nextUnit: unit };
}
function setSceneUniforms(gl, program, scene, camera, options, lightCount) {
@@ -193,15 +192,16 @@ function getContext() {
}
/** The kernel for a scene, compiled once per variant: a scene with a subsurface part gets the random walk, any other scene the plain kernel. */
-function getKernel(hasSubsurface) {
+function getKernel(hasSubsurface, texelBake = false) {
const { gl, programs } = getContext();
- if (!programs.has(hasSubsurface)) {
+ const key = `${hasSubsurface}:${texelBake}`;
+ if (!programs.has(key)) {
const started = performance.now();
- const program = createProgram(gl, hasSubsurface);
+ const program = createProgram(gl, { hasSubsurface, texelBake });
gl.getProgramParameter(program, gl.LINK_STATUS);
- programs.set(hasSubsurface, { program, compileSeconds: (performance.now() - started) / 1000 });
+ programs.set(key, { program, compileSeconds: (performance.now() - started) / 1000 });
}
- return programs.get(hasSubsurface);
+ return programs.get(key);
}
function releaseResources(gl) {
@@ -212,14 +212,8 @@ function releaseResources(gl) {
resources.length = 0;
}
-export async function traceOnGpu(scene, camera, options, shouldStop) {
- const { gl, gpu } = getContext();
- const { program, compileSeconds } = getKernel(sceneUsesSubsurface(scene.materials));
- const { width, height, samples } = options;
- gl.useProgram(program);
- const { lightCount } = uploadScene(gl, program, scene);
- setSceneUniforms(gl, program, scene, camera, options, lightCount);
- createTargets(gl, width, height);
+/** Draws every sample of every pixel in bands that take about DRAW_SECONDS_TARGET each, giving the page a turn now and then. */
+async function drawSamples(gl, program, width, height, samples, shouldStop) {
gl.viewport(0, 0, width, height);
gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, gl.ONE);
@@ -249,7 +243,61 @@ export async function traceOnGpu(scene, camera, options, shouldStop) {
}
}
gl.disable(gl.SCISSOR_TEST);
+}
+
+export async function traceOnGpu(scene, camera, options, shouldStop) {
+ const { gl, gpu } = getContext();
+ const { program, compileSeconds } = getKernel(sceneUsesSubsurface(scene.materials));
+ const { width, height, samples } = options;
+ gl.useProgram(program);
+ const { lightCount } = uploadScene(gl, program, scene);
+ setSceneUniforms(gl, program, scene, camera, options, lightCount);
+ createTargets(gl, width, height);
+ await drawSamples(gl, program, width, height, samples, shouldStop);
const buffers = averageBuffers(gl, width, height, samples);
releaseResources(gl);
return Object.assign(buffers, { gpu, compileSeconds });
}
+
+const TEXEL_ROW_WIDTH = 2048;
+
+/**
+ * Traces `options.samples` cosine weighted paths from every texel of a lightmap and resolves with, per texel, the mean
+ * radiance that arrives (`radiance`, three floats) and the share of first rays that left the scene (`escaped`).
+ * `texels` holds `count`, `points` and `normals` (three floats each, world space). `options.bounces` counts hits, as in
+ * the CPU bake. The scene is traced as it is: its lights, materials and environment decide the light.
+ */
+export async function traceTexelsOnGpu(scene, texels, options, shouldStop) {
+ const { gl, gpu } = getContext();
+ const { program, compileSeconds } = getKernel(sceneUsesSubsurface(scene.materials), true);
+ const { count, points, normals } = texels;
+ const { samples, seed } = options;
+ const width = Math.min(count, TEXEL_ROW_WIDTH);
+ const height = Math.ceil(count / width);
+ gl.useProgram(program);
+ const { lightCount, nextUnit } = uploadScene(gl, program, scene);
+ const camera = { eye: [0, 0, 0], forward: [0, 0, 1], right: [1, 0, 0], above: [0, 1, 0], halfWidth: 1, halfHeight: 1 };
+ setSceneUniforms(gl, program, scene, camera, { width, height, seed, bounces: options.bounces - 1, fireflyClamp: options.fireflyClamp }, lightCount);
+ const upload = (unit, name, vectors) => {
+ const padded = new Float32Array(width * height * 4);
+ for (let texel = 0; texel < count; texel++) padded.set(vectors.subarray(texel * 3, texel * 3 + 3), texel * 4);
+ createTexture(gl, unit, gl.RGBA32F, gl.RGBA, gl.FLOAT, width, height, padded);
+ gl.uniform1i(gl.getUniformLocation(program, name), unit);
+ };
+ upload(nextUnit, 'uTexelPoints', points);
+ upload(nextUnit + 1, 'uTexelNormals', normals);
+ gl.uniform1i(gl.getUniformLocation(program, 'uTexelCount'), count);
+ gl.uniform1i(gl.getUniformLocation(program, 'uSampleCount'), samples);
+ createTargets(gl, width, height);
+ await drawSamples(gl, program, width, height, samples, shouldStop);
+ const radianceSums = readTarget(gl, 0, width, height);
+ const statistics = readTarget(gl, 3, width, height);
+ releaseResources(gl);
+ const radiance = new Float32Array(count * 3);
+ const escaped = new Float32Array(count);
+ for (let texel = 0; texel < count; texel++) {
+ for (let channel = 0; channel < 3; channel++) radiance[texel * 3 + channel] = radianceSums[texel * 4 + channel] / samples;
+ escaped[texel] = statistics[texel * 4 + 2] / samples;
+ }
+ return { radiance, escaped, gpu, compileSeconds };
+}
diff --git a/tests/light-bake.test.js b/tests/light-bake.test.js
index a9995782..b2e95f6f 100644
--- a/tests/light-bake.test.js
+++ b/tests/light-bake.test.js
@@ -2,7 +2,8 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { box } from '../src/geometry.js';
import { exportGlb } from '../src/export.js';
-import { BAKE_LIMITS, MAX_BAKE_POINT_LIGHTS, MAX_BAKE_SPOT_LIGHTS, MAX_BAKE_AREA_LIGHTS, bakeLightmaps, normalizeBakeOptions } from '../src/light-bake.js';
+import { BAKE_LIMITS, MAX_BAKE_POINT_LIGHTS, MAX_BAKE_SPOT_LIGHTS, MAX_BAKE_AREA_LIGHTS, bakeLightmaps, normalizeBakeOptions, planLightmaps, MAX_BAKE_PARTS, MAX_GPU_BAKE_PARTS } from '../src/light-bake.js';
+import { bakeLightmapsAsync } from '../src/light-bake-gpu.js';
const cube = box(0, 1);
@@ -139,7 +140,8 @@ test('a part marked as generating its own geometry is skipped', () => {
});
test('options are validated with their bounds', () => {
- assert.deepEqual(normalizeBakeOptions({}), Object.fromEntries(Object.entries(BAKE_LIMITS).map(([name, limit]) => [name, limit.fallback])));
+ const fallbacks = Object.fromEntries(Object.entries(BAKE_LIMITS).map(([name, limit]) => [name, limit.fallback]));
+ assert.deepEqual(normalizeBakeOptions({}), { ...fallbacks, backend: 'cpu' });
for (const [name, bad] of [['samples', 0], ['samples', 513], ['samples', Number.NaN], ['bounces', 5], ['maxResolution', 3], ['maxResolution', 1e9], ['texelsPerUnit', 0], ['texelsPerUnit', Infinity], ['maxSeconds', 0], ['maxSeconds', '60']]) {
assert.throws(() => normalizeBakeOptions({ [name]: bad }), { name: 'RangeError', message: new RegExp(name) }, `${name} ${bad}`);
}
@@ -255,3 +257,28 @@ test('the default bounces follow most of the light that a closed room keeps, whi
assert.ok(byDefault > two * 1.05, `default ${byDefault} adds too little over 2 bounces ${two}`);
assert.equal(BAKE_LIMITS.bounces.fallback, 3);
});
+
+test('the backend option is cpu or gpu, and the synchronous bake refuses the GPU', async () => {
+ assert.equal(normalizeBakeOptions({ backend: 'gpu' }).backend, 'gpu');
+ for (const bad of ['webgpu', 'GPU', 1]) assert.throws(() => normalizeBakeOptions({ backend: bad }), { name: 'TypeError', message: /backend/ }, String(bad));
+ assert.throws(() => bakeLightmaps(smallRoom(), lamp, { ...fastOptions, backend: 'gpu' }), { name: 'TypeError', message: /light-bake-gpu/ });
+ const asynchronous = await bakeLightmapsAsync(smallRoom(), lamp, fastOptions);
+ const synchronous = bakeLightmaps(smallRoom(), lamp, fastOptions);
+ assert.equal(asynchronous.report.backend, 'cpu');
+ assert.deepEqual(Array.from(lightmapBytes(asynchronous.parts[0])), Array.from(lightmapBytes(synchronous.parts[0])));
+});
+
+test('a GPU bake needs a page with WebGL2 and does not take light linking or a sky-only run', async () => {
+ await assert.rejects(bakeLightmapsAsync(smallRoom(), lamp, { ...fastOptions, backend: 'gpu' }), /WebGL2/);
+ await assert.rejects(bakeLightmapsAsync(smallRoom(), lamp, { ...fastOptions, backend: 'gpu', skyOnly: true }), /CPU backend only/);
+ const linked = { pointLights: [{ ...lamp.pointLights[0], affects: ['floor'] }], keyColor: [0, 0, 0] };
+ await assert.rejects(bakeLightmapsAsync(smallRoom(), linked, { ...fastOptions, backend: 'gpu' }), /light linking/);
+});
+
+test('the GPU backend takes up to 1024 parts where the CPU bake takes 256', () => {
+ const crowd = Array.from({ length: MAX_BAKE_PARTS + 1 }, (_, index) => placed(`part-${index}`, [index, 0, 0], [0.5, 0.5, 0.5]));
+ assert.throws(() => planLightmaps(crowd, lamp, fastOptions), { name: 'RangeError', message: /1 to 256 parts/ });
+ assert.equal(planLightmaps(crowd, lamp, { ...fastOptions, backend: 'gpu' }).entries.length, crowd.length);
+ const tooMany = Array.from({ length: MAX_GPU_BAKE_PARTS + 1 }, (_, index) => placed(`part-${index}`, [index, 0, 0], [0.5, 0.5, 0.5]));
+ assert.throws(() => planLightmaps(tooMany, lamp, { ...fastOptions, backend: 'gpu' }), { name: 'RangeError', message: /1 to 1024 parts/ });
+});
diff --git a/tests/path-tracer-gpu-pack.test.js b/tests/path-tracer-gpu-pack.test.js
index de81fb99..30d8faa3 100644
--- a/tests/path-tracer-gpu-pack.test.js
+++ b/tests/path-tracer-gpu-pack.test.js
@@ -127,3 +127,12 @@ test('weight 0 and no block both leave the kernel without the random walk', () =
}
assert.equal(withWalk.includes('const int WALK_STEPS = 32;'), true);
});
+
+test('the texel kernel starts paths at lightmap texels, and the camera kernel does not carry its samplers', () => {
+ const texelKernel = buildFragmentSource({ texelBake: true });
+ const cameraKernel = buildFragmentSource();
+ assert.match(texelKernel, /uniform sampler2D uTexelPoints;/);
+ assert.match(texelKernel, /texelFetch\(uTexelNormals/);
+ assert.doesNotMatch(cameraKernel, /uTexelPoints/);
+ assert.match(cameraKernel, /vec3 rayDirection = normalize\(uForward/);
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 20cd6123..bd1c54a9 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -42,6 +42,7 @@ export default defineConfig({
grass: 'src/grass.js',
clutter: 'src/clutter.js',
'light-bake': 'src/light-bake.js',
+ 'light-bake-gpu': 'src/light-bake-gpu.js',
'ground-bounce': 'src/ground-bounce.js',
'floor-sky-visibility': 'src/floor-sky-visibility.js',
'path-tracer': 'src/path-tracer.js',