3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Share instanced geometry in the WebGPU path tracer (#2239)
Nguyen Xuan Anafc536dcbb5b
diff --git a/.github/workflows/cook-addon.yml b/.github/workflows/cook-addon.ymlindex e9589275..39fc30c3 100644--- a/.github/workflows/cook-addon.yml+++ b/.github/workflows/cook-addon.yml@@ -295,6 +295,7 @@ on:- 'src/path-tracer-shading.js'- 'src/path-tracer-subsurface.js'- 'src/path-tracer-volume.js'+ - 'src/path-tracer-webgpu-instancing.js'- 'src/path-tracer-webgpu-kernel.js'- 'src/path-tracer-webgpu-local-volumes.js'- 'src/path-tracer-webgpu-medium.js'diff --git a/changes/2239-webgpu.md b/changes/2239-webgpu.mdnew file mode 100644index 00000000..744aed52--- /dev/null+++ b/changes/2239-webgpu.md@@ -0,0 +1 @@+- The WebGPU path tracer (`backend: "webgpu"`, megakernel) keeps parts that share one mesh as instances, like the `gpu` backend, so the triangle limit counts a shared mesh once and memory grows with the copies, not their triangles (#2239)diff --git a/docs/path-tracer.md b/docs/path-tracer.mdindex d4d882b1..0dfa7f4c 100644--- a/docs/path-tracer.md+++ b/docs/path-tracer.md@@ -102,7 +102,7 @@ The native `cycles` kernel reads an environment map as it is, as Blender CyclesAlso checked before any ray is traced: samples times pixels times bounces at most 4 billion, 400,000 triangles on the `cpu` backend, and on `gpu` and `webgpu` whatever the device holds up to 2,000,000 (`MAX_GPU_TRACE_TRIANGLES`): the triangle table takes 160 bytes a triangle (ten texels: both UV sets are kept), so a WebGL2 context with a 16384 texel `MAX_TEXTURE_SIZE` has room for 3,355,443 and one with 2048 for 419,430, and a WebGPU storage buffer of `maxStorageBufferBindingSize` bytes for that many over 160; the tracer asks the device and an oversized scene is refused with the count, the limit and what to do, the same text for a still, the real-time tracer (WebGL2 and WebGPU) and the GPU light bake (`backend: "gpu"` or `"webgpu"`; a bake with a `texelTracer` of its own keeps the default bound) (a scene exported to the native tracer takes more, see below), 1,024 parts (the CPU and WebGL tracers; a native trace takes more, see below), 32 lights, and finite numbers (positions, normals, uvs, colors) and whole-number, in-range indices in every part. A render job limits `maxSeconds` to 600: the job runs on workers without blocking the page, and its deadline is `maxSeconds` plus 60 seconds for the page and the PNG, so a trace that reaches its limit still ends before the job does.-Instances count per copy on the `cpu`, `gpu` and `webgpu` backends: they copy every placed node into one triangle buffer, so nine nodes that share three 300,000 triangle GLBs count as 2.7 million triangles, not 0.9 million. Over the bound, the error says `N triangles after expanding M instanced nodes (U unique)` and suggests fewer copies, a simpler GLB or the Glaze renderer. Only the native Cook backend with instancing counts each shared geometry once. The submit-time estimate (`scripts/agent-render-estimate.mjs`) counts every placed node the same way.+Instances count per copy on the `cpu` backend and on the progressive and real-time views (the still `gpu` and `webgpu` backends keep a shared mesh once, see "Instanced scenes on the gpu backend"): they copy every placed node into one triangle buffer, so nine nodes that share three 300,000 triangle GLBs count as 2.7 million triangles, not 0.9 million. Over the bound, the error says `N triangles after expanding M instanced nodes (U unique)` and suggests fewer copies, a simpler GLB or the Glaze renderer. Only the native Cook backend with instancing counts each shared geometry once. The submit-time estimate (`scripts/agent-render-estimate.mjs`) counts every placed node the same way.### Instanced scenes for the native tracer@@ -130,11 +130,12 @@ The same scene and options give the same bytes. Random numbers come from a hash### 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.+On `backend: "gpu"` (stills and the GPU light bake; the progressive and real-time views still flatten) and on the megakernel of `backend: "webgpu"` (stills and its light bake), 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 WebGPU megakernel reads the same tables (`src/path-tracer-webgpu-instancing.js` holds its WGSL). It keeps its ten storage bindings: the instance records follow the BVH nodes in the node buffer, behind one header vector that names the top-level root, and the parameter word `shadowSlots.w` holds the vector index of that header. A scene with no shared mesh compiles the same WGSL as before. The node buffer is bounded by one storage binding (`maxStorageBufferBindingSize`); a scene over it fails with the byte count, the instance count and "Remove copies or merge small meshes".+- The WebGPU wavefront kernel and the real-time WebGPU tracer do not read instances. The real-time tracer asks for a flattened scene and keeps the flattened triangle limit; `traceOnWebGpu` with `kernel: "wavefront"` and `prepareRealtimeKernel` refuse an instanced scene with an error that says so.- 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.diff --git a/src/path-tracer-realtime-webgpu.js b/src/path-tracer-realtime-webgpu.jsindex bc71fcfc..95047b80 100644--- a/src/path-tracer-realtime-webgpu.js+++ b/src/path-tracer-realtime-webgpu.js@@ -69,7 +69,8 @@ export async function createWebGpuRealtimeTracer(scene, resolved, suppliedCanvaspendingMotion = motion;currentParts = parts;currentEnvironment = environment;- traceScene = await buildTraceSceneForDevice(parts, environment, webGpuTracer);+ // The real-time kernel reads a flat scene only, so the module it passes does not offer instancing.+ traceScene = await buildTraceSceneForDevice(parts, environment, { gpuTriangleLimit: webGpuTracer.gpuTriangleLimit });refuseLocalVolumes(traceScene, 'the WebGPU realtime path tracer');const next = await webGpuTracer.prepareRealtimeKernel(traceScene, options, REALTIME_KERNEL_PIECES);const previousKernel = kernel;diff --git a/src/path-tracer-webgpu-instancing.js b/src/path-tracer-webgpu-instancing.jsnew file mode 100644index 00000000..3ca2500f--- /dev/null+++ b/src/path-tracer-webgpu-instancing.js@@ -0,0 +1,112 @@+// The WGSL the WebGPU megakernel adds for an instanced scene (path-tracer-gpu-instance-pack.js lays the tables out, the WebGL2+// tracer reads the same records in path-tracer-gpu-instancing.js). Copies of one mesh share its triangles and bottom-level BVH; a+// top-level BVH holds one record per copy: the world to mesh matrix, the mesh to world matrix, the root of its bottom-level BVH and+// its material. The ray of a copy is moved into mesh space without being normalised, so a distance there is the same distance in+// the world. The records live in the node buffer, after the node table, so the storage bindings stay the ten the flat scene uses.++/** Vectors per instance record: three rows of the world to mesh matrix, three columns of the mesh to world matrix, then (bottom-level root node, material, 0, 0). */+export const WEBGPU_INSTANCE_VECTORS = 7;++// The parameter word `shadowSlots.w` holds the vector index of the table header in the node buffer: its first vector names the top-level+// root node, and the instance records follow it.+export const INSTANCE_STATE = `+const INSTANCE_VECTORS: i32 = ${WEBGPU_INSTANCE_VECTORS};+var<private> nearestInstance: i32 = -1;+var<private> nearestMaterial: i32 = 0;+var<private> instanceNodeStack: array<i32, 128>;+var<private> instanceEntryStack: array<f32, 128>;++fn instanceRecord(instance: i32) -> i32 {+ return i32(params.shadowSlots.w) + 1 + instance * INSTANCE_VECTORS;+}++// An edge of the nearest triangle, moved from mesh space to the world by the columns of the instance's matrix.+fn surfaceVectorToWorld(local: vec3<f32>) -> vec3<f32> {+ let base = instanceRecord(nearestInstance);+ return nodes[base + 3].xyz * local.x + nodes[base + 4].xyz * local.y + nodes[base + 5].xyz * local.z;+}++// A vertex normal moves by the transpose of the inverse (the transpose of the three rows stored for the ray) and is unit length again+// before the corners are blended, as the flattened scene stores it.+fn normalToWorld(local: vec3<f32>) -> vec3<f32> {+ let base = instanceRecord(nearestInstance);+ let world = nodes[base].xyz * local.x + nodes[base + 1].xyz * local.y + nodes[base + 2].xyz * local.z;+ let worldLength = length(world);+ return world / select(worldLength, 1.0, worldLength == 0.0);+}`;++export const INSTANCED_TRACE_RAY = `// Walks the bottom-level BVH of one instance with the ray moved into mesh space; true when an any-hit query found a hit.+fn traceInstance(instance: i32, origin: vec3<f32>, direction: vec3<f32>, anyHit: bool) -> bool {+ let base = instanceRecord(instance);+ let rowX = nodes[base];+ let rowY = nodes[base + 1];+ let rowZ = nodes[base + 2];+ let link = nodes[base + 6];+ let localOrigin = vec3<f32>(dot(rowX.xyz, origin) + rowX.w, dot(rowY.xyz, origin) + rowY.w, dot(rowZ.xyz, origin) + rowZ.w);+ let localDirection = vec3<f32>(dot(rowX.xyz, direction), dot(rowY.xyz, direction), dot(rowZ.xyz, direction));+ let inverse = safeInverse(localDirection);+ let distanceBefore = nearestDistance;+ var stackSize = 1;+ instanceNodeStack[0] = i32(link.x);+ instanceEntryStack[0] = 0.0;+ var found = false;+ while (stackSize > 0 && !found) {+ stackSize--;+ let node = instanceNodeStack[stackSize];+ if (!(instanceEntryStack[stackSize] < nearestDistance)) { continue; }+ let header = nodes[node * 2];+ if (header.w < 0.0) {+ found = visitLeaf(node, localOrigin, localDirection, anyHit);+ continue;+ }+ let left = node + 1;+ let right = i32(header.w);+ let leftEntry = boxEntry(left, localOrigin, inverse);+ let rightEntry = boxEntry(right, localOrigin, inverse);+ let nearFirst = leftEntry <= rightEntry;+ instanceNodeStack[stackSize] = select(left, right, nearFirst);+ instanceEntryStack[stackSize] = select(leftEntry, rightEntry, nearFirst);+ instanceNodeStack[stackSize + 1] = select(right, left, nearFirst);+ instanceEntryStack[stackSize + 1] = select(rightEntry, leftEntry, nearFirst);+ stackSize += 2;+ }+ if (nearestDistance < distanceBefore) {+ nearestInstance = instance;+ nearestMaterial = i32(link.y);+ }+ return found;+}++fn traceRay(origin: vec3<f32>, direction: vec3<f32>, limit: f32, anyHit: bool) {+ nearestDistance = limit;+ nearestSlot = -1;+ nearestInstance = -1;+ let inverse = safeInverse(direction);+ var stackSize = 1;+ nodeStack[0] = i32(nodes[i32(params.shadowSlots.w)].x);+ entryStack[0] = 0.0;+ while (stackSize > 0) {+ stackSize--;+ let node = nodeStack[stackSize];+ if (!(entryStack[stackSize] < nearestDistance)) { continue; }+ let header = nodes[node * 2];+ if (header.w < 0.0) {+ let first = i32(nodes[node * 2 + 1].w);+ let last = first + i32(-header.w);+ for (var instance = first; instance < last; instance++) {+ if (traceInstance(instance, origin, direction, anyHit)) { return; }+ }+ continue;+ }+ let left = node + 1;+ let right = i32(header.w);+ let leftEntry = boxEntry(left, origin, inverse);+ let rightEntry = boxEntry(right, origin, inverse);+ let nearFirst = leftEntry <= rightEntry;+ nodeStack[stackSize] = select(left, right, nearFirst);+ entryStack[stackSize] = select(leftEntry, rightEntry, nearFirst);+ nodeStack[stackSize + 1] = select(right, left, nearFirst);+ entryStack[stackSize + 1] = select(rightEntry, leftEntry, nearFirst);+ stackSize += 2;+ }+}`;diff --git a/src/path-tracer-webgpu-kernel.js b/src/path-tracer-webgpu-kernel.jsindex f67221b9..32e73825 100644--- a/src/path-tracer-webgpu-kernel.js+++ b/src/path-tracer-webgpu-kernel.js@@ -10,13 +10,51 @@import { LIGHT_TREE_FIRST_HIT_LIGHTS, LIGHT_TREE_MINIMUM_SHARE } from './path-tracer-light-tree.js';import { PHASE_FUNCTIONS, SUBSURFACE_FUNCTIONS, VOLUME_FUNCTIONS } from './path-tracer-webgpu-medium.js';import { buildLocalVolumeFunctions } from './path-tracer-webgpu-local-volumes.js';+import { INSTANCED_TRACE_RAY, INSTANCE_STATE } from './path-tracer-webgpu-instancing.js';export const WORKGROUP_SIZE = 8;export const WAVEFRONT_WORKGROUP_SIZE = 64;/** vec4 slots of path state per path; the wavefront section below names each one. */export const PATH_STATE_VECTORS = 9;-const buildCommonSource = ({ hasVolume = false, hasLocalVolumes = false, hasGridVolume = false, hasNoiseOctaves = false, hasEmissionRamp = false, hasMeshVolume = false } = {}) => /* wgsl */ `+const NEAREST_MATERIAL = 'nearestMaterial';+const FLAT_NEAREST_MATERIAL = 'i32(triangles[nearestSlot * TRIANGLE_TEXELS].w)';++// The ray query of a scene with one triangle table and one BVH: the default, and the only one before instancing.+const FLAT_TRACE_RAY = `fn traceRay(origin: vec3<f32>, direction: vec3<f32>, limit: f32, anyHit: bool) {+ nearestDistance = limit;+ nearestSlot = -1;+ let inverse = safeInverse(direction);+ var stackSize = 1;+ nodeStack[0] = 0;+ entryStack[0] = 0.0;+ while (stackSize > 0) {+ stackSize--;+ let node = nodeStack[stackSize];+ if (!(entryStack[stackSize] < nearestDistance)) { continue; }+ let header = nodes[node * 2];+ if (header.w < 0.0) {+ if (visitLeaf(node, origin, direction, anyHit)) { return; }+ continue;+ }+ let left = node + 1;+ let right = i32(header.w);+ let leftEntry = boxEntry(left, origin, inverse);+ let rightEntry = boxEntry(right, origin, inverse);+ let nearFirst = leftEntry <= rightEntry;+ nodeStack[stackSize] = select(left, right, nearFirst);+ entryStack[stackSize] = select(leftEntry, rightEntry, nearFirst);+ nodeStack[stackSize + 1] = select(right, left, nearFirst);+ entryStack[stackSize + 1] = select(rightEntry, leftEntry, nearFirst);+ stackSize += 2;+ }+}`;++// An instanced scene (path-tracer-webgpu-instancing.js) moves the edges and normals of the hit triangle from mesh space to the world.+const buildCommonSource = ({ hasVolume = false, hasLocalVolumes = false, hasGridVolume = false, hasNoiseOctaves = false, hasEmissionRamp = false, hasMeshVolume = false, instanced = false } = {}) => {+ const worldVector = expression => (instanced ? `surfaceVectorToWorld(${expression})` : expression);+ const worldNormal = expression => (instanced ? `normalToWorld(${expression})` : expression);+ return /* wgsl */ `const PI: f32 = 3.14159265358979;const TWO_PI: f32 = 6.28318530717959;const TRIANGLE_TEXELS: i32 = 10;@@ -96,7 +134,7 @@ var<private> nearestSlot: i32;var<private> nearestU: f32;var<private> nearestV: f32;var<private> nodeStack: array<i32, 128>;-var<private> entryStack: array<f32, 128>;+var<private> entryStack: array<f32, 128>;${instanced ? INSTANCE_STATE : ''}fn safeInverseComponent(component: f32) -> f32 {if (abs(component) > 1e-20) { return 1.0 / component; }@@ -149,34 +187,7 @@ fn visitLeaf(node: i32, origin: vec3<f32>, direction: vec3<f32>, anyHit: bool) -return false;}-fn traceRay(origin: vec3<f32>, direction: vec3<f32>, limit: f32, anyHit: bool) {- nearestDistance = limit;- nearestSlot = -1;- let inverse = safeInverse(direction);- var stackSize = 1;- nodeStack[0] = 0;- entryStack[0] = 0.0;- while (stackSize > 0) {- stackSize--;- let node = nodeStack[stackSize];- if (!(entryStack[stackSize] < nearestDistance)) { continue; }- let header = nodes[node * 2];- if (header.w < 0.0) {- if (visitLeaf(node, origin, direction, anyHit)) { return; }- continue;- }- let left = node + 1;- let right = i32(header.w);- let leftEntry = boxEntry(left, origin, inverse);- let rightEntry = boxEntry(right, origin, inverse);- let nearFirst = leftEntry <= rightEntry;- nodeStack[stackSize] = select(left, right, nearFirst);- entryStack[stackSize] = select(leftEntry, rightEntry, nearFirst);- nodeStack[stackSize + 1] = select(right, left, nearFirst);- entryStack[stackSize + 1] = select(rightEntry, leftEntry, nearFirst);- stackSize += 2;- }-}+${instanced ? INSTANCED_TRACE_RAY : FLAT_TRACE_RAY}// ---- Hits ----@@ -273,8 +284,8 @@ fn mapReadsSecondUvSet(mask: f32, bit: i32) -> bool {fn fillHit(origin: vec3<f32>, direction: vec3<f32>, distance: f32) -> f32 {let base = nearestSlot * TRIANGLE_TEXELS;let cornerData = triangles[base];- let edgeOne = triangles[base + 1].xyz;- let edgeTwo = triangles[base + 2].xyz;+ let edgeOne = ${worldVector('triangles[base + 1].xyz')};+ let edgeTwo = ${worldVector('triangles[base + 2].xyz')};let normalOneData = triangles[base + 3];let normalTwoData = triangles[base + 4];let normalThreeData = triangles[base + 5];@@ -288,13 +299,13 @@ fn fillHit(origin: vec3<f32>, direction: vec3<f32>, distance: f32) -> f32 {let firstWeight = 1.0 - secondWeight - thirdWeight;hitDistance = distance;hitPoint = origin + direction * distance;- let normal = firstWeight * normalOneData.xyz + secondWeight * normalTwoData.xyz + thirdWeight * normalThreeData.xyz;+ let normal = firstWeight * ${worldNormal('normalOneData.xyz')} + secondWeight * ${worldNormal('normalTwoData.xyz')} + thirdWeight * ${worldNormal('normalThreeData.xyz')};let normalLength = length(normal);hitNormal = normal / select(normalLength, 1.0, normalLength == 0.0);let vertexColor = firstWeight * colorOneData.xyz + secondWeight * colorTwoData.xyz + thirdWeight * colorThreeData.xyz;let uv = firstWeight * vec2<f32>(normalOneData.w, colorOneData.w) + secondWeight * vec2<f32>(normalTwoData.w, colorTwoData.w) + thirdWeight * vec2<f32>(normalThreeData.w, colorThreeData.w);let secondUv = firstWeight * secondSetCorners.xy + secondWeight * secondSetCorners.zw + thirdWeight * secondSetThird;- hitMaterialIndex = i32(cornerData.w);+ hitMaterialIndex = ${instanced ? NEAREST_MATERIAL : 'i32(cornerData.w)'};let material = hitMaterialIndex * MATERIAL_TEXELS;let colorMetallic = materials[material];let emissionRoughness = materials[material + 1];@@ -339,7 +350,7 @@ fn fillHit(origin: vec3<f32>, direction: vec3<f32>, distance: f32) -> f32 {// True when the nearest hit belongs to a shadow-only part (the flag sits in texel 5 of the material); camera rays step through it.fn nearestHitIsShadowOnly() -> bool {- return materials[i32(triangles[nearestSlot * TRIANGLE_TEXELS].w) * MATERIAL_TEXELS + 5].y > 0.0;+ return materials[${instanced ? NEAREST_MATERIAL : FLAT_NEAREST_MATERIAL} * MATERIAL_TEXELS + 5].y > 0.0;}// The nearest solid hit, stepping through the transparent texels of cutout materials and, for a camera ray, shadow-only parts.@@ -376,7 +387,7 @@ fn alphaAtNearestHit() -> f32 {let second = triangles[base + 4];let third = triangles[base + 5];var uv = firstWeight * vec2<f32>(first.w, triangles[base + 6].w) + secondWeight * vec2<f32>(second.w, triangles[base + 7].w) + thirdWeight * vec2<f32>(third.w, triangles[base + 8].w);- let material = i32(triangles[base].w) * MATERIAL_TEXELS;+ let material = ${instanced ? NEAREST_MATERIAL : 'i32(triangles[base].w)'} * MATERIAL_TEXELS;let mapRectangle = materials[material + 6];if (mapRectangle.z <= 0.0) { return 1.0; }if (mapReadsSecondUvSet(materials[material + 5].z, 1)) {@@ -396,7 +407,7 @@ fn occluded(origin: vec3<f32>, direction: vec3<f32>, limit: f32) -> bool {for (var attempt = 0; attempt < ALPHA_STEP_LIMIT; attempt++) {traceRay(start, direction, remaining, anyHit);if (nearestSlot < 0) { return false; }- let material = i32(triangles[nearestSlot * TRIANGLE_TEXELS].w) * MATERIAL_TEXELS;+ let material = ${instanced ? NEAREST_MATERIAL : FLAT_NEAREST_MATERIAL} * MATERIAL_TEXELS;let cutoff = materials[material + 3].z;if (cutoff == 0.0) { return true; }if (alphaAtNearestHit() >= cutoff) { return true; }@@ -1116,6 +1127,7 @@ fn survivesRoulette(depth: i32) -> bool {return true;}`;+};const COMMON_SOURCE = buildCommonSource();// One invocation per pixel of the image.@@ -1179,7 +1191,7 @@ fn bakeTexels(@builtin(global_invocation_id) id: vec3<u32>, @builtin(num_workgro`;// `realtime` is the set of WGSL pieces of path-tracer-realtime-webgpu-kernel.js (REALTIME_KERNEL_PIECES); the real-time tracer passes them in, so other bundles do not carry them.-export const buildMegakernelSource = ({ hasVolume = false, hasLocalVolumes = false, hasGridVolume = false, hasNoiseOctaves = false, hasEmissionRamp = false, hasMeshVolume = false, hasSubsurface = false, texelBake = false, realtime = null } = {}) => buildCommonSource({ hasVolume, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasMeshVolume }) + /* wgsl */ `+export const buildMegakernelSource = ({ hasVolume = false, hasLocalVolumes = false, hasGridVolume = false, hasNoiseOctaves = false, hasEmissionRamp = false, hasMeshVolume = false, hasSubsurface = false, texelBake = false, realtime = null, instanced = false } = {}) => buildCommonSource({ hasVolume, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasMeshVolume, instanced }) + /* wgsl */ `${realtime ? realtime.declarations + realtime.addLights : `// The first hit lights from every emitter; later hits draw one, and divide by the chance of drawing it.fn addLights(depth: i32, normal: vec3<f32>) {let emitterCount = params.emittersFlagsSample.x;diff --git a/src/path-tracer-webgpu.js b/src/path-tracer-webgpu.jsindex e70f5464..64d2e9aa 100644--- a/src/path-tracer-webgpu.js+++ b/src/path-tracer-webgpu.js@@ -1,7 +1,9 @@import { buildMegakernelSource, PATH_STATE_VECTORS, WAVEFRONT_SOURCE, WAVEFRONT_WORKGROUP_SIZE, WORKGROUP_SIZE } from './path-tracer-webgpu-kernel.js';import { resolveLightSelection } from './path-tracer-light-tree.js';import { gpuTriangleCapacity, packAtlas, packEnvironment, packLightTree, packLights, packMaterials, packNodes, packSubsurface, packTriangles, sceneUsesSubsurface } from './path-tracer-gpu-pack.js';-import { MAX_GPU_TRACE_TRIANGLES, MAX_TRACE_TRIANGLES } from './path-tracer-scene.js';+import { WEBGPU_INSTANCE_VECTORS } from './path-tracer-webgpu-instancing.js';+import { packInstancedScene } from './path-tracer-gpu-instance-pack.js';+import { isInstancedScene, MAX_GPU_TRACE_TRIANGLES, MAX_TRACE_TRIANGLES, uniqueTriangleCount } from './path-tracer-scene.js';import { assertWebGpuLocalVolumes, packWebGpuLocalVolumes, webGpuVolumeFeatures } from './path-tracer-webgpu-local-volumes.js';// The WebGPU backend of the path tracer (issue #625): the same scene tables, camera, options and random numbers as the@@ -83,10 +85,10 @@ async function getSession() {}/** The WGSL and entry points of a kernel variant; a variant is one of the two kernels, with the optional parts a scene needs. */-function describeVariant({ kernel, hasVolume, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasMeshVolume, hasSubsurface, texelBake, realtime }) {+function describeVariant({ kernel, hasVolume, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasMeshVolume, hasSubsurface, texelBake, realtime, instanced = false }) {if (kernel === 'wavefront') return { code: WAVEFRONT_SOURCE, entryPoints: WAVEFRONT_ENTRY_POINTS };- if (realtime) return { code: buildMegakernelSource({ hasVolume, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasMeshVolume, hasSubsurface, realtime }), entryPoints: ['traceRealtime'] };- return { code: buildMegakernelSource({ hasVolume, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasMeshVolume, hasSubsurface, texelBake }), entryPoints: [texelBake ? 'bakeTexels' : 'main'] };+ if (realtime) return { code: buildMegakernelSource({ hasVolume, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasMeshVolume, hasSubsurface, realtime, instanced }), entryPoints: ['traceRealtime'] };+ return { code: buildMegakernelSource({ hasVolume, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasMeshVolume, hasSubsurface, texelBake, instanced }), entryPoints: [texelBake ? 'bakeTexels' : 'main'] };}async function compileKernel(current, variant) {@@ -103,14 +105,14 @@ async function compileKernel(current, variant) {}async function getKernel(current, variant) {- const key = [variant.kernel, variant.hasVolume, variant.hasLocalVolumes, variant.hasGridVolume, variant.hasNoiseOctaves, variant.hasEmissionRamp, variant.hasMeshVolume, variant.hasSubsurface, variant.texelBake, Boolean(variant.realtime)].join(':');+ const key = [variant.kernel, variant.hasVolume, variant.hasLocalVolumes, variant.hasGridVolume, variant.hasNoiseOctaves, variant.hasEmissionRamp, variant.hasMeshVolume, variant.hasSubsurface, variant.texelBake, Boolean(variant.realtime), Boolean(variant.instanced)].join(':');if (!current.kernels.has(key)) current.kernels.set(key, compileKernel(current, variant));return current.kernels.get(key);}/** The optional parts the scene needs, as the kernel variant flags. */function sceneFeatures(scene) {- return { hasVolume: Boolean(scene.volume), hasLocalVolumes: Boolean(scene.localVolumes), ...webGpuVolumeFeatures(scene.localVolumes), hasSubsurface: sceneUsesSubsurface(scene.materials), texelBake: false };+ return { hasVolume: Boolean(scene.volume), hasLocalVolumes: Boolean(scene.localVolumes), ...webGpuVolumeFeatures(scene.localVolumes), hasSubsurface: sceneUsesSubsurface(scene.materials), texelBake: false, instanced: isInstancedScene(scene) };}function createStorageBuffer(device, data, label) {@@ -124,6 +126,27 @@ function atlasWords(atlas) {return new Uint32Array(atlas.data.buffer, atlas.data.byteOffset, Math.floor(atlas.data.byteLength / 4));}+/**+ * The node and triangle tables of a scene. A flat scene has one BVH over all its triangles. An instanced scene holds each distinct mesh+ * once (path-tracer-gpu-instance-pack.js); its instance records follow the nodes in the same buffer, behind a header vector that names+ * the top-level root, so the binding count stays what the flat scene uses. `instanceHeader` is the vector index of that header, 0 for a flat scene.+ */+function packGeometryTables(device, scene) {+ if (!isInstancedScene(scene)) return { nodeTable: packNodes(scene.bvh), triangleData: packTriangles(scene, { secondUvSet: true }).data, instanceHeader: 0 };+ const packed = packInstancedScene(scene);+ const nodeFloats = packed.nodes.data.length;+ const recordFloats = scene.instances.length * WEBGPU_INSTANCE_VECTORS * 4;+ const data = new Float32Array(nodeFloats + 4 + recordFloats);+ data.set(packed.nodes.data);+ data[nodeFloats] = packed.topRoot;+ data.set(packed.instances.data.subarray(0, recordFloats), nodeFloats + 4);+ const limit = device.limits.maxStorageBufferBindingSize;+ if (data.byteLength > limit) {+ throw new RangeError(`The instanced scene needs ${data.byteLength} bytes for its BVH nodes and ${scene.instances.length} instance records, and this WebGPU adapter binds at most ${limit} bytes in one storage buffer. Remove copies or merge small meshes, or use backend "gpu".`);+ }+ return { nodeTable: { data }, triangleData: packed.triangles.data, instanceHeader: nodeFloats / 4 };+}+export function uploadScene(device, scene, requestedLightSelection = 'uniform') {const atlas = packAtlas(scene.materials);const lights = packLights(scene.lights);@@ -159,12 +182,13 @@ export function uploadScene(device, scene, requestedLightSelection = 'uniform')const materialsWithTables = new Float32Array(materialsWithSubsurface.length + localVolumeData.length);materialsWithTables.set(materialsWithSubsurface);materialsWithTables.set(localVolumeData, materialsWithSubsurface.length);- const triangleCount = scene.indices.length / 3;+ const triangleCount = uniqueTriangleCount(scene);const largeScene = triangleCount > MAX_TRACE_TRIANGLES;+ const { nodeTable, triangleData, instanceHeader } = packGeometryTables(device, scene);if (largeScene) device.pushErrorScope('out-of-memory');const buffers = [- createStorageBuffer(device, packNodes(scene.bvh).data, 'bvh nodes'),- createStorageBuffer(device, packTriangles(scene, { secondUvSet: true }).data, 'triangles'),+ createStorageBuffer(device, nodeTable.data, 'bvh nodes'),+ createStorageBuffer(device, triangleData, 'triangles'),createStorageBuffer(device, materialsWithTables, 'materials'),createStorageBuffer(device, lightsWithTree, 'lights'),createStorageBuffer(device, atlasWords(atlas), 'texture atlas'),@@ -175,7 +199,7 @@ export function uploadScene(device, scene, requestedLightSelection = 'uniform')const allocationCheck = largeScene ? device.popErrorScope().then((error) => {if (error) throw new Error(`The GPU ran out of memory while allocating the scene buffers for ${triangleCount} triangles. Simplify or drop meshes to stay near ${MAX_TRACE_TRIANGLES} triangles, or render the frame with the native Cook backend.`);}) : Promise.resolve();- return { allocationCheck, buffers, lightCount: lights.count, lightTreeBase, atlasWidth: atlas.width, subsurfaceOffset, localVolumeOffset };+ return { allocationCheck, buffers, lightCount: lights.count, lightTreeBase, atlasWidth: atlas.width, subsurfaceOffset, localVolumeOffset, instanceHeader };}/** The words of one uniform block: the 12 vectors of the megakernel parameters, then the tile and shadow slot words. */@@ -198,6 +222,7 @@ function createParameterTemplate(scene, camera, options, uploaded, emitterCount)integers.set([options.width, options.height, options.bounces, uploaded.lightCount], 36);integers.set([emitterCount, sun ? 1 : 0, environment ? 1 : 0, 0], 40);unsigned.set([options.seed >>> 0, uploaded.atlasWidth, uploaded.subsurfaceOffset, uploaded.localVolumeOffset], 44);+ unsigned[INSTANCE_HEADER_WORD] = uploaded.instanceHeader;const { volume } = scene;floats.set([...(volume?.minimum ?? [0, 0, 0]), volume?.density ?? 0], 56);floats.set([...(volume?.maximum ?? [0, 0, 0]), volume?.anisotropy ?? 0], 60);@@ -206,6 +231,8 @@ function createParameterTemplate(scene, camera, options, uploaded, emitterCount)}const SAMPLE_INDEX_WORD = 43;+// The fourth word of the shadow slot vector: the vector index of the instance table header (path-tracer-webgpu-instancing.js), 0 without instances.+const INSTANCE_HEADER_WORD = 55;const TILE_WORD = 48;const SHADOW_SLOT_WORD = 52;const SORT_FLAG_WORD = 53;@@ -298,6 +325,9 @@ export async function traceOnWebGpu(scene, camera, options, shouldStop) {if (kernel === 'wavefront' && (features.hasVolume || features.hasLocalVolumes || features.hasSubsurface)) {throw new RangeError('The WebGPU wavefront kernel does not trace volume fog, local volumes or subsurface scattering. Use the megakernel, the default.');}+ if (kernel === 'wavefront' && features.instanced) {+ throw new RangeError('The WebGPU wavefront kernel does not read instanced scenes. Build the scene without instancing, or use the megakernel, the default.');+ }assertWebGpuLocalVolumes(scene);const current = await getSession();const { device } = current;@@ -365,6 +395,9 @@ export async function traceOnWebGpu(scene, camera, options, shouldStop) {* parameter block for a camera (the caller sets the sample index and the cache words).*/export async function prepareRealtimeKernel(scene, options, realtimePieces) {+ if (isInstancedScene(scene)) {+ throw new RangeError('The WebGPU real-time tracer does not read instanced scenes yet. Build the scene for it without instancing (buildTraceSceneForDevice with a module that does not set supportsInstancing).');+ }const current = await getSession();const { device } = current;const { pipelines, compileSeconds } = await getKernel(current, { kernel: 'megakernel', ...sceneFeatures(scene), realtime: realtimePieces });@@ -456,6 +489,10 @@ export async function traceTexelsOnWebGpu(scene, texels, options, shouldStop) {return { radiance, escaped, gpu: current.gpu, compileSeconds };}+// The megakernel reads instanced scenes (path-tracer-webgpu-instancing.js): buildTraceSceneForDevice keeps copies of one mesh as instances for it.+// The wavefront kernel and the real-time tracer do not, and their callers ask for a flat scene.+export const supportsInstancing = true;+// The names path-tracer.js looks for in a backend module, the same as path-tracer-gpu.js.export { traceOnWebGpu as traceOnGpu, webGpuKernelCompileCount as gpuKernelCompileCount, webGpuTriangleLimit as gpuTriangleLimit };diff --git a/tests/gpu-triangle-bound-callers.test.js b/tests/gpu-triangle-bound-callers.test.jsindex f145c407..57d033f6 100644--- a/tests/gpu-triangle-bound-callers.test.js+++ b/tests/gpu-triangle-bound-callers.test.js@@ -46,10 +46,11 @@ const { bakeLightmapsAsync } = await import('../src/light-bake-gpu.js');const cube = box(0, 1);-function cubeParts(count) {+// The real-time tracer flattens, so its cubes may share one mesh; the light bake keeps copies of one mesh as instances (#2239), so it needs a mesh per cube to reach the bound.+function cubeParts(count, geometryOf = () => cube) {return Array.from({ length: count }, (_, index) => ({name: `cube-${index}`,- geometry: cube,+ 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 },}));@@ -76,8 +77,13 @@ test('the WebGPU real-time tracer takes a scene inside the device bound as far a});test('the GPU light bake refuses a scene past the device bound with its count', async () => {- const parts = cubeParts(cubesOverLimit);- await assert.rejects(bakeLightmapsAsync(parts, lamp, bakeOptions), refusal(tripleCount(cubesOverLimit)));+ const ownCubes = cubeParts(cubesOverLimit, () => box(0, 1));+ await assert.rejects(bakeLightmapsAsync(ownCubes, lamp, bakeOptions), refusal(tripleCount(cubesOverLimit)));+});++test('the GPU light bake counts copies of one shared cube once, so they pass a bound their flattened triangles exceed', async () => {+ assert.ok(tripleCount(cubesOverLimit) > DEVICE_TRIANGLE_LIMIT);+ await assert.rejects(bakeLightmapsAsync(cubeParts(cubesOverLimit), lamp, bakeOptions), { message: KERNEL_REACHED });});test('the GPU light bake takes a scene inside the device bound as far as the kernel', async () => {diff --git a/tests/path-tracer-webgpu-instancing.test.js b/tests/path-tracer-webgpu-instancing.test.jsnew file mode 100644index 00000000..0b34f7a3--- /dev/null+++ b/tests/path-tracer-webgpu-instancing.test.js@@ -0,0 +1,170 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import test from 'node:test';++import { icoSphere } from '../src/geometry.js';+import { packNodes } from '../src/path-tracer-gpu-pack.js';+import { buildTraceScene, buildTraceSceneForDevice, isInstancedScene } from '../src/path-tracer-scene.js';+import { WEBGPU_INSTANCE_VECTORS } from '../src/path-tracer-webgpu-instancing.js';+import { buildMegakernelSource, WAVEFRONT_SOURCE } from '../src/path-tracer-webgpu-kernel.js';+import { prepareRealtimeKernel, supportsInstancing, traceOnWebGpu, uploadScene } from '../src/path-tracer-webgpu.js';+import { withWebGpuPage } from './helpers/webgpu-page.js';++// Issue #2239: the WebGPU megakernel keeps copies of one mesh as instances (one triangle table and bottom-level BVH per mesh, a+// top-level BVH over the copies, the records in the node buffer) instead of flattening every copy into the triangle table.++const SPHERE = icoSphere(2);+const SPHERE_TRIANGLES = SPHERE.indices.length / 3;+const LIMIT = 4 * SPHERE_TRIANGLES;++function translation(x, y = 0, z = 0) {+ return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1];+}++function copies(count) {+ return Array.from({ length: count }, (_, index) => ({+ name: `copy-${index}`,+ geometry: SPHERE,+ matrix: translation(index * 3, 0.5, -index),+ material: { color: [0.2 + index * 0.1, 0.5, 0.7], roughness: 0.4 },+ }));+}++// Node has no WebGPU constants; the recording device ignores them.+globalThis.GPUBufferUsage ??= { STORAGE: 128, COPY_DST: 8 };++function digestOf(text) {+ return createHash('sha256').update(text).digest('hex');+}++// A device that keeps what is written to each buffer, so the tables the tracer uploads can be read back without a GPU.+function recordingDevice(maxStorageBufferBindingSize = 1 << 30) {+ const written = new Map();+ return {+ written,+ limits: { maxStorageBufferBindingSize },+ createBuffer: ({ label }) => ({ label }),+ pushErrorScope() {},+ popErrorScope: async () => null,+ queue: { writeBuffer: (buffer, offset, bytes) => written.set(buffer.label, new Float32Array(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength))) },+ };+}++// The digests of the default megakernel, the texel megakernel and the wavefront WGSL, taken on origin/main before instancing existed.+// A scene without shared geometry compiles exactly this text. Change them only with an intended change of the flat kernel.+const FLAT_MEGAKERNEL_DIGEST = 'c19e0e6a4a169019';+const FLAT_TEXEL_KERNEL_DIGEST = 'a85df4b363e198ba';+const FLAT_WAVEFRONT_DIGEST = 'c88c32191aab807c';++test('a scene without shared geometry compiles the WGSL origin/main compiled', () => {+ assert.equal(digestOf(buildMegakernelSource()).slice(0, 16), FLAT_MEGAKERNEL_DIGEST);+ assert.equal(digestOf(buildMegakernelSource({ texelBake: true })).slice(0, 16), FLAT_TEXEL_KERNEL_DIGEST);+ assert.equal(digestOf(WAVEFRONT_SOURCE).slice(0, 16), FLAT_WAVEFRONT_DIGEST);+ assert.equal(buildMegakernelSource({ instanced: false }), buildMegakernelSource());+ assert.doesNotMatch(buildMegakernelSource(), /instanceRecord|nearestInstance|traceInstance/);+});++test('the instanced kernel walks the bottom-level BVH of each copy and moves the hit to the world', () => {+ for (const variant of [{}, { texelBake: true }, { hasSubsurface: true, hasVolume: true }]) {+ const source = buildMegakernelSource({ ...variant, instanced: true });+ assert.match(source, /fn traceInstance\(/);+ assert.match(source, /surfaceVectorToWorld\(triangles\[base \+ 1\]\.xyz\)/);+ assert.match(source, /normalToWorld\(normalOneData\.xyz\)/);+ assert.match(source, /hitMaterialIndex = nearestMaterial;/);+ assert.doesNotMatch(source, /i32\(triangles\[nearestSlot \* TRIANGLE_TEXELS\]\.w\)/, 'the material comes from the instance, not the triangle');+ }+});++test('an instanced scene uploads each mesh once, with its instance records behind the nodes', () => {+ const scene = buildTraceScene(copies(3), {}, { instancing: true, gpuTriangleLimit: LIMIT });+ assert.equal(isInstancedScene(scene), true);+ const device = recordingDevice();+ const uploaded = uploadScene(device, scene);+ const nodes = device.written.get('bvh nodes');+ const triangles = device.written.get('triangles');+ const flatTriangles = recordingDevice();+ uploadScene(flatTriangles, buildTraceScene(copies(3), {}));+ assert.ok(triangles.length < flatTriangles.written.get('triangles').length, 'one mesh, not three copies');+ const header = uploaded.instanceHeader * 4;+ assert.ok(header > 0 && nodes[header] > 0, 'the header names a top-level root behind the bottom-level nodes');+ const records = nodes.subarray(header + 4, header + 4 + 3 * WEBGPU_INSTANCE_VECTORS * 4);+ const roots = new Set();+ const materials = [];+ for (let slot = 0; slot < 3; slot++) {+ roots.add(records[slot * WEBGPU_INSTANCE_VECTORS * 4 + 24]);+ materials.push(records[slot * WEBGPU_INSTANCE_VECTORS * 4 + 25]);+ }+ assert.equal(roots.size, 1, 'all copies start at the same bottom-level root');+ assert.deepEqual(materials.sort(), [0, 1, 2]);+});++test('a flat scene uploads the node table as it always did, with no instance header', () => {+ const scene = buildTraceScene(copies(2), {});+ const device = recordingDevice();+ const uploaded = uploadScene(device, scene);+ assert.equal(uploaded.instanceHeader, 0);+ assert.deepEqual(Array.from(device.written.get('bvh nodes')), Array.from(packNodes(scene.bvh).data));+});++test('the instance tables are bounded by one storage buffer, and the error says what to do', () => {+ const scene = buildTraceScene(copies(3), {}, { instancing: true, gpuTriangleLimit: LIMIT });+ assert.throws(() => uploadScene(recordingDevice(4096), scene), error => error instanceof RangeError && /3 instance records.*at most 4096 bytes.*Remove copies or merge small meshes/.test(error.message));+});++test('the WebGPU tracer asks for instanced scenes, and the kernels that cannot read them refuse one', async () => {+ assert.equal(supportsInstancing, true);+ const parts = copies(2);+ const instanced = await buildTraceSceneForDevice(parts, {}, { supportsInstancing, gpuTriangleLimit: () => LIMIT });+ assert.equal(isInstancedScene(instanced), true);+ await assert.rejects(traceOnWebGpu(instanced, {}, { kernel: 'wavefront' }, () => {}), { name: 'RangeError', message: /wavefront kernel does not read instanced scenes.*megakernel/ });+ await assert.rejects(prepareRealtimeKernel(instanced, {}, {}), { name: 'RangeError', message: /real-time tracer does not read instanced scenes/ });+});++async function measureInstancedAgainstFlat() {+ const { icoSphere: sphere, box: cube } = await import('/src/geometry.js');+ const { buildTraceScene: build, uniqueTriangleCount: count } = await import('/src/path-tracer-scene.js');+ const { createCamera, normalizePathTracerOptions } = await import('/src/path-tracer.js');+ const gpuModule = await import('/src/path-tracer-webgpu.js');+ const shared = sphere(2);+ const place = (x, y, z, scale) => [scale, 0, 0, 0, 0, scale, 0, 0, 0, 0, scale, 0, x, y, z, 1];+ const rotated = [0.56, 0.42, 0, 0, -0.42, 0.56, 0, 0, 0, 0, 1, 0, 0.4, 1.2, -0.2, 1];+ const parts = [+ { name: 'floor', geometry: cube(0, 1), matrix: [8, 0, 0, 0, 0, 0.2, 0, 0, 0, 0, 8, 0, 0, -0.1, 0, 1], material: { color: [0.6, 0.6, 0.6] } },+ { name: 'left', geometry: shared, matrix: place(-1.4, 0.6, 0, 0.6), material: { color: [0.9, 0.2, 0.2], roughness: 0.3 } },+ { name: 'middle', geometry: shared, matrix: rotated, material: { color: [0.2, 0.8, 0.3], metallic: 1, roughness: 0.2 } },+ { name: 'right', geometry: shared, matrix: [-0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0.5, 0, 1.5, 0.5, 0.3, 1], material: { color: [0.2, 0.3, 0.9], roughness: 0.6 } },+ ];+ const environment = { keyColor: [1, 0.95, 0.9], lightDirection: [0.4, 1, 0.3], keyIntensity: 3, pointLights: [{ position: [0, 3, 1], color: [1, 1, 1], intensity: 10, radius: 0.1 }] };+ const width = 48;+ const height = 32;+ const options = normalizePathTracerOptions({ width, height, samples: 8, bounces: 3, seed: 7, backend: 'webgpu', denoiser: 'none', threads: 1 });+ const view = createCamera({ eye: [0, 1.8, 5], target: [0, 0.6, 0], fov: 50 }, width, height);+ const limit = 1_000_000;+ const flat = build(parts, environment, { gpuTriangleLimit: limit });+ const instanced = build(parts, environment, { gpuTriangleLimit: limit, instancing: true });+ const flatImage = await gpuModule.traceOnWebGpu(flat, view, options, () => {});+ const instancedImage = await gpuModule.traceOnWebGpu(instanced, view, options, () => {});+ let squared = 0;+ let sum = 0;+ for (let index = 0; index < flatImage.color.length; index++) {+ squared += (flatImage.color[index] - instancedImage.color[index]) ** 2;+ sum += flatImage.color[index];+ }+ return {+ rmse: Math.sqrt(squared / flatImage.color.length),+ mean: sum / flatImage.color.length,+ flatTriangles: count(flat),+ instancedTriangles: count(instanced),+ instancedFlag: Array.isArray(instanced.instances),+ };+}++test('on the WebGPU megakernel an instanced scene renders what the flattened scene renders', { timeout: 240_000 }, async context => {+ await withWebGpuPage(context, async page => {+ const result = await page.evaluate(measureInstancedAgainstFlat);+ assert.equal(result.instancedFlag, true);+ assert.ok(result.instancedTriangles < result.flatTriangles);+ assert.ok(result.mean > 0.05, `the picture is not black (mean ${result.mean})`);+ assert.ok(result.rmse < result.mean * 0.001, `instanced and flattened pictures match within noise (rmse ${result.rmse}, mean ${result.mean})`);+ });+});