3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Document gpu instancing, pin native pack digest, list new files for Cook CI (#2239)
Nguyen Xuan An67a700e2c0da
diff --git a/.github/workflows/cook-addon.yml b/.github/workflows/cook-addon.ymlindex 757b91c4..eddd28a6 100644--- a/.github/workflows/cook-addon.yml+++ b/.github/workflows/cook-addon.yml@@ -278,6 +278,8 @@ on:- 'src/path-trace-terms.js'- 'src/path-tracer-blue-noise.js'- 'src/path-tracer-denoise.js'+ - 'src/path-tracer-gpu-instance-pack.js'+ - 'src/path-tracer-gpu-instancing.js'- 'src/path-tracer-gpu-pack.js'- 'src/path-tracer-gpu-shader.js'- 'src/path-tracer-gpu-subsurface.js'diff --git a/changes/2239.size.md b/changes/2239.size.mdnew file mode 100644index 00000000..615e1ad2--- /dev/null+++ b/changes/2239.size.md@@ -0,0 +1,3 @@+- entry:path-tracer-progressive: the WebGL2 kernel builder and packer now carry the instanced variant (about 1.8 KB gzip: the instanced GLSL, the bottom and top level BVH packer), which lets a scene whose shared meshes were refused at 2,000,000 triangles render; the progressive view itself still flattens.+- entry:path-tracer-progressive+lazy: the same 1.8 KB gzip of the shared WebGL2 kernel builder and packer.+- entry:path-tracer-realtime: the same 1.8 KB gzip of the shared WebGL2 kernel builder and packer; the real-time view still flattens.diff --git a/docs/path-tracer.md b/docs/path-tracer.mdindex c526e0d3..80057269 100644--- a/docs/path-tracer.md+++ b/docs/path-tracer.md@@ -125,6 +125,16 @@ A part whose matrix mirrors (negative determinant) is flattened with its vertexThe same scene and options give the same bytes. Random numbers come from a hash of the pixel, the sample and the seed, never from `Math.random` or the clock, and a pixel does not depend on which thread drew it.+### Instanced scenes on the gpu backend (issue #2239)++On `backend: "gpu"` (stills and the GPU light bake; the progressive and real-time views still flatten), parts that share one geometry object stay instances instead of being flattened into one triangle table. `buildTraceSceneForDevice` asks for instancing when the backend module exports `supportsInstancing`; a scene where no two parts share a geometry is still flattened, and its tables are the same bytes as before. The packer (`src/path-tracer-gpu-instance-pack.js`) keeps one copy of each distinct mesh in the triangle table with its own bottom-level BVH, builds a top-level BVH over the world box of every copy, and writes one record per copy (the matrix both ways, the root of its mesh's BVH, its material). The kernel (`src/path-tracer-gpu-instancing.js`) walks the top level, moves the ray into the mesh space of each copy it reaches without normalising it, so a distance there is a world distance, and moves the normals and edges of the hit back; the instanced variant is a separate compile of the kernel and a flattened scene keeps the kernel it had.++- The GPU triangle limit counts a shared mesh once. The error for a scene that does not fit still says how many triangles it holds; for an instanced scene it counts the unique ones.+- A part that cannot share its geometry (skinned, flush-lifted, box-mapped) is moved into world space once and traced as an instance with an identity matrix, as for the native tracer.+- `backend: "webgpu"` does not read instances yet and flattens, so it keeps the flattened triangle limit.+- The normal of a copy with a non-uniform scale is moved by the inverse transpose and made unit length at each corner before the corners are blended, which is what a flattened copy stores; a flattened and an instanced scene match to float precision (RMSE of the linear image below 1e-6 on translated, rotated, mirrored and stretched copies).+- The report's `triangles` is the unique count.+## Choosing a backend`backend: "native"` is an agent render job setting, not a `renderPathTracedImage` option: [Cook](https://github.com/codepawl/cook/blob/main/README.md) runs the same kernel on Vulkan ray queries (the [render engines guide](render-engines.md) says how the native backend is found and what happens when it is missing). On the demo room at 1920 by 1080 and 64 samples an MCP image job took 25 to 35 s with native against 58 s with gpu (trace alone 2.7 to 3.1 s against 38.8 s; the rest is the page export, the wavelet denoise and the PNG), FLIP 0.0047 between them. A missing package, binary or adapter falls back to gpu with a note in the job report. `maxSeconds` is honoured: past it the native trace stops and the job fails, as on the other backends, instead of rerunning on gpu; `noiseThreshold` is too (the kernel applies the CPU stop rule per pixel, so `averageSamples` falls below `samples`; the `gpu` and `webgpu` backends still draw every sample). A grid local volume (`environment.localVolumes` with `shape: "grid"`, issue #1789) is in the native kernel too, through Cook's `gridVolumes`: the frame the volume time selects, its box (`center`, `size`), `density`, `absorption`, `scatter` (the share of the extinction that scatters, the same for the three colour channels), `anisotropy`, `emission`, `emissionStrength`, `temperatureScale` and `blackbodyIntensity` (times `emissionStrength`, as Blender's Principled Volume takes it) carry over one for one, and the kernel traces the grid with delta and ratio tracking, so the sun, the sky and every light shade it and the fire lights the floor with its own radiance. At most 8 grids and 256 voxels an axis, 8 bytes a voxel, in the texel pool with the textures. Not drawn natively: box, sphere and mesh volumes (the export throws an error that names the kind and says to use `cpu` or `webgpu`), `emissionRamp` (throws), `castShadow` and `lightsScene` (Cook shades the grid with the real lights, so they have nothing to switch), and `environment.volumeShutter` (the velocity channel is skipped: the job report says the blur is ignored). The grid is exported after the materials, so a scene whose materials fall back to the v1 tables throws instead of dropping the volume. On the #1735 blast at its 0.375 s frame (640 by 360, floor and sun, no sparks, no motion blur) Cook at 256 samples takes 15.6 s and has a mean luminance of 0.2148 against 0.2149 for Blender Cycles at 48 samples, a linear RMSE of 0.0233 (display RMSE 0.0096); Glaze is 0.0411 (0.0193) from the same Cycles frame. Volume fog and subsurface scattering are in the native kernel, compiled in only for a scene that uses them; `bench/native-tracer/scenes.mjs` draws the reference scenes on native and on the WebGPU megakernel for a FLIP comparison. Alpha cutouts (`alphaMode: "mask"`) work: cutout triangles are their own geometry and the kernel confirms a hit only when the colour map alpha reaches the cutoff, with no step limit. In a dense cutout scene native is the more correct tracer: the CPU and WebGL2 shadow ray takes the first hit the traversal finds, not the nearest, and when that hit is a transparent texel it skips occluders it had not reached yet, so those backends leak light (300 leaf cards: native vs cpu FLIP 0.043, and 0.0002 once the CPU shadow ray takes the nearest hit; bench/native-tracer/cutout-bisect.mjs shows one card agrees exactly). The steps before: up to 8 layers deep (`bench/native-tracer/cutout.mjs`: 300 masked leaf cards trace in 0.1 s at 640 by 360 and 64 samples). See [agent-render-jobs.md](agent-render-jobs.md#path-tracer).diff --git a/tests/gpu-triangle-bound-webgl-bake.test.js b/tests/gpu-triangle-bound-webgl-bake.test.jsindex 765141f3..37ba0673 100644--- a/tests/gpu-triangle-bound-webgl-bake.test.js+++ b/tests/gpu-triangle-bound-webgl-bake.test.js@@ -35,10 +35,10 @@ globalThis.OffscreenCanvas = class {const { bakeLightmapsAsync } = await import('../src/light-bake-gpu.js');// Each cube has a geometry of its own: copies that share one are held once by the WebGL2 tracer (#2239), so they would not reach the bound.-function cubeParts(count) {+function cubeParts(count, geometryOf = () => box(0, 1)) {return Array.from({ length: count }, (_, index) => ({name: `cube-${index}`,- geometry: box(0, 1),+ geometry: geometryOf(),matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, index * 2, 0, 0, 1]),material: { tag: 'surface', color: [0.7, 0.7, 0.7], metallic: 0, roughness: 0.8, emission: 0 },}));@@ -57,3 +57,9 @@ test('the WebGL2 light bake refuses a scene past the context bound with its countest('the WebGL2 light bake takes a scene inside the context bound as far as the kernel', async () => {await assert.rejects(bakeLightmapsAsync(cubeParts(cubesUnderLimit), lamp, bakeOptions), { message: KERNEL_REACHED });});++test('the WebGL2 light bake counts copies of one shared cube once, so they pass a bound their flattened triangles exceed', async () => {+ const sharedCube = box(0, 1);+ assert.ok(cubesOverLimit * CUBE_TRIANGLES > DEVICE_TRIANGLE_LIMIT);+ await assert.rejects(bakeLightmapsAsync(cubeParts(cubesOverLimit, () => sharedCube), lamp, bakeOptions), { message: KERNEL_REACHED });+});diff --git a/tests/path-tracer-gpu-instancing.test.js b/tests/path-tracer-gpu-instancing.test.jsindex a76063af..3a017866 100644--- a/tests/path-tracer-gpu-instancing.test.js+++ b/tests/path-tracer-gpu-instancing.test.js@@ -57,7 +57,7 @@ test('a scene that shares a mesh packs the mesh once, with one record per copy',test('the triangle limit of a GPU scene counts a shared mesh once', async () => {const nineCopies = copies(9);const flattened = buildTraceSceneForDevice(nineCopies, {}, FLATTENING_MODULE);- await assert.rejects(flattened, { name: 'RangeError', message: /GPU path trace takes at most/ });+ await assert.rejects(flattened, { name: 'RangeError', message: new RegExp(`got ${9 * SPHERE_TRIANGLES}`) });const scene = await buildTraceSceneForDevice(nineCopies, {}, INSTANCING_MODULE);assert.equal(isInstancedScene(scene), true);assert.equal(scene.instances.length, 9);@@ -65,13 +65,14 @@ test('the triangle limit of a GPU scene counts a shared mesh once', async () =>});test('a mesh that is not shared still holds its own triangles against the limit', async () => {- const different = [{ ...copies(1)[0] }, { ...copies(2)[1], geometry: box(0.1, 4) }];+ const otherMesh = box(0.1, 4);+ const different = [{ ...copies(1)[0] }, { ...copies(2)[1], geometry: otherMesh }];const tightModule = { supportsInstancing: true, gpuTriangleLimit: () => SPHERE_TRIANGLES };- await assert.rejects(buildTraceSceneForDevice(different, {}, tightModule), { name: 'RangeError', message: /GPU path trace takes at most/ });+ await assert.rejects(buildTraceSceneForDevice(different, {}, tightModule), { name: 'RangeError', message: new RegExp(`got ${SPHERE_TRIANGLES + otherMesh.indices.length / 3}`) });});-// The digest of the node, triangle and material tables of the scene below, taken on origin/main before instancing existed.-const UNSHARED_SCENE_DIGEST = '11c7ed55b398eb8a1d2ba836d3fd1b277035aa61912bf8bae6318d0c68c0eed5';+// The digest of the node, triangle (ten and nine texels a triangle) and material tables of the scene below, taken on origin/main before instancing existed.+const UNSHARED_SCENE_DIGEST = '42fdf6ac1ab280002a7be789762e56ec0bff28d0407b4064dd91891bcaf1baf1';test('a scene without shared geometry flattens and packs the same bytes with or without the instancing module', async () => {const parts = [@@ -84,7 +85,7 @@ test('a scene without shared geometry flattens and packs the same bytes with orassert.equal(isInstancedScene(opted), false);const packOf = scene => {const atlas = packAtlas(scene.materials);- return [packNodes(scene.bvh), packTriangles(scene, { secondUvSet: true }), packMaterials(scene.materials, atlas, scene.shadowOnlyParts)];+ return [packNodes(scene.bvh), packTriangles(scene, { secondUvSet: true }), packTriangles(scene), packMaterials(scene.materials, atlas, scene.shadowOnlyParts)];};assert.equal(digest(...packOf(opted)), digest(...packOf(plain)));assert.equal(digest(...packOf(plain)), UNSHARED_SCENE_DIGEST, 'the tables are the bytes origin/main packed');@@ -141,6 +142,10 @@ async function traceBothWays() {const instanced = build(parts, environment, { gpuTriangleLimit: limit, instancing: true });const flatImage = await gpuModule.traceOnGpu(flat, view, options, () => {});const instancedImage = await gpuModule.traceOnGpu(instanced, view, options, () => {});+ // Every other kernel variant reads the instance tables through the same helpers; each must still compile.+ gpuModule.getKernel(true, false, { instanced: true });+ gpuModule.getKernel(false, true, { instanced: true });+ gpuModule.getKernel(false, false, { instanced: true, lightSelection: 'tree', samplingPattern: 'blue-noise-first' });let squared = 0;let sum = 0;for (let index = 0; index < flatImage.color.length; index++) {