3D engine that AI agents drive
Give the irradiance grid its own texture unit and smooth its coefficients (#506)
Nguyen Xuan An69181aa15e78
diff --git a/docs/light-bake.md b/docs/light-bake.mdindex b0fbf514..b2b669c9 100644--- a/docs/light-bake.md+++ b/docs/light-bake.md@@ -78,7 +78,7 @@ An open scene with a floor gets the light the floor bounces without a bake and w`bake: { preset: 'standard', irradianceGrid: true }` (or a node count from 8 to 48 along the longest side; `true` is 24) bakes a grid of diffuse light instead of lightmaps. `src/irradiance-grid.js` (a lazy module that loads with the bake) places a node every cell of the parts' bounds, and for each node traces the light that surfaces send toward it along the six axis directions with the bake's gatherer (emission and direct light at every hit, `bounces` reflections, about a quarter of the preset's samples). The six values become first order spherical harmonics per colour channel, stored in one RGBA16F 3D texture (three texels per node). A lit surface reads it with one trilinear lookup and its normal, so the warm light a sunlit floor sends up to the walls and the ceiling costs no ray per frame. A ray that leaves the scene adds nothing, so the sky stays with the environment map, and the grid replaces lightmaps for the scene. Probes still run.-Nodes inside a solid (most rays hit the back of a face) are filled from their neighbours, and the lookup moves half a cell along the normal. A wall thinner than a cell can still leak light, and the grid is static: it is traced again when the parts, the lights or the bake change, and a part that moves does not move its bounce. The report is `bake.irradianceGrid` (`size`, `cellSize`, `nodes`, `solidNodes`, `seconds`). The sampler takes texture unit 12, which the splat layers also use, so a scene with both is not supported yet.+Nodes inside a solid (most rays hit the back of a face) are filled from their neighbours, and the lookup moves half a cell along the normal. A wall thinner than a cell can still leak light, and the grid is static: it is traced again when the parts, the lights or the bake change, and a part that moves does not move its bounce. The report is `bake.irradianceGrid` (`size`, `cellSize`, `nodes`, `solidNodes`, `seconds`). The sampler has its own texture unit, 16, so it works beside splat layers. A 3x3x3 [1 2 1] filter over the valid nodes' coefficients removes the low-frequency noise of the few samples each node gets.## Reflection probesdiff --git a/src/irradiance-grid.js b/src/irradiance-grid.jsindex b85abb16..995ee7c1 100644--- a/src/irradiance-grid.js+++ b/src/irradiance-grid.js@@ -23,7 +23,10 @@ const FILL_PASSES = 12;const COEFFICIENTS_PER_NODE = 12;// The grid is one 3D texture: node (x, y, z) takes three texels along x, one per colour channel, each holding the channel's// constant term and its x, y and z terms.-const TEXTURE_UNIT = 12;+// Unit 16, past the 16 the renderer's other samplers use (splat layers take 11 to 14, local shadows 15). A unit index is limited by+// MAX_COMBINED_TEXTURE_IMAGE_UNITS (at least 32 in WebGL2), not by the 16 samplers a fragment shader may declare.+export const IRRADIANCE_GRID_TEXTURE_UNIT = 16;+const TEXTURE_UNIT = IRRADIANCE_GRID_TEXTURE_UNIT;function buildValidityDirections() {const directions = [];@@ -141,6 +144,48 @@ function fillInvalidNodes(data, valid, size) {}}+// A [1 2 1] x [1 2 1] x [1 2 1] filter over the coefficients of valid neighbours removes the low-frequency noise of the few+// samples each node gets, at the cost of a little blur across a wall. Nodes inside solids keep their filled values.+function smoothNodes(data, valid, size) {+ const [width, height, depth] = size;+ const source = Float32Array.from(data);+ const weights = [1, 2, 1];+ for (let node = 0; node < valid.length; node++) {+ if (!valid[node]) {+ continue;+ }+ const x = node % width;+ const y = Math.floor(node / width) % height;+ const z = Math.floor(node / (width * height));+ const sum = new Float64Array(COEFFICIENTS_PER_NODE);+ let total = 0;+ for (let dz = -1; dz <= 1; dz++) {+ for (let dy = -1; dy <= 1; dy++) {+ for (let dx = -1; dx <= 1; dx++) {+ const nx = x + dx;+ const ny = y + dy;+ const nz = z + dz;+ if (nx < 0 || ny < 0 || nz < 0 || nx >= width || ny >= height || nz >= depth) {+ continue;+ }+ const neighbour = nx + width * (ny + height * nz);+ if (!valid[neighbour]) {+ continue;+ }+ const weight = weights[dx + 1] * weights[dy + 1] * weights[dz + 1];+ for (let slot = 0; slot < COEFFICIENTS_PER_NODE; slot++) {+ sum[slot] += weight * source[neighbour * COEFFICIENTS_PER_NODE + slot];+ }+ total += weight;+ }+ }+ }+ for (let slot = 0; slot < COEFFICIENTS_PER_NODE; slot++) {+ data[node * COEFFICIENTS_PER_NODE + slot] = sum[slot] / total;+ }+ }+}+/*** Traces the grid. For each node, the cosine weighted light arriving along the six axis directions (the bake's gatherer:* emission and direct light at every hit, bounced over `bounces` reflections) becomes a first order fit per colour channel:@@ -200,6 +245,7 @@ export function traceIrradianceGrid(parts, lighting, { resolution = DEFAULT_GRID}}fillInvalidNodes(data, valid, layout.size);+ smoothNodes(data, valid, layout.size);return { ...layout, data, nodes: nodeCount, solidNodes, seconds: (performance.now() - started) / 1000 };}diff --git a/tests/irradiance-grid.test.js b/tests/irradiance-grid.test.jsindex 5ff487ec..7ac372a9 100644--- a/tests/irradiance-grid.test.js+++ b/tests/irradiance-grid.test.js@@ -4,7 +4,7 @@ import test from 'node:test';import { box } from '../src/geometry.js';import { createAgentScene } from '../src/agent-scene.js';import { normalizeAgentBake } from '../src/agent-bake.js';-import { evaluateIrradianceGrid, normalizeIrradianceGrid, placeIrradianceGrid, traceIrradianceGrid } from '../src/irradiance-grid.js';+import { IRRADIANCE_GRID_TEXTURE_UNIT, evaluateIrradianceGrid, normalizeIrradianceGrid, placeIrradianceGrid, traceIrradianceGrid } from '../src/irradiance-grid.js';import { createFragmentShader } from '../src/shaders.js';const cube = box(0, 1);@@ -103,3 +103,13 @@ test('a recipe with bake.irradianceGrid skips lightmaps, reports the grid and giconst parts = scene.getParts?.() ?? scene.parts;assert.ok(parts.every(part => part.material.irradianceGrid && !part.material.lightMap));});++test('a scene with splat layers and the grid keeps the two on different texture units', async () => {+ const { SPLAT_UNITS } = await import('../src/shader-registry.js');+ await import('../src/splat-shader.js');+ const taken = [...Object.values(SPLAT_UNITS), 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15];+ assert.ok(!taken.includes(IRRADIANCE_GRID_TEXTURE_UNIT), 'the grid sampler has its own unit');+ const source = createFragmentShader(['splat', 'irradianceGrid']);+ assert.match(source, /irradianceGridDiffuse/);+ assert.match(source, /splatColor/);+});