Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Build the Cycles light tree on the host and bind it for the cycles kernel (#895)

Nguyen Xuan Anbb0f2550c4e7
diff --git a/changes/895-light-tree.md b/changes/895-light-tree.md
new file mode 100644
index 00000000..2a8238bb
--- /dev/null
+++ b/changes/895-light-tree.md
@@ -0,0 +1 @@
+- The Cook host builds the Cycles light tree (SAOH bounding volume tree over analytic lights and emissive triangles, sun lights in one distant leaf) into FORMAT-v2 binding 7 and two new bindings 13 and 14; the kernel does not read them yet (#895)
diff --git a/packages/render-native/FORMAT-v2.md b/packages/render-native/FORMAT-v2.md
index 415e8543..75eacdb8 100644
--- a/packages/render-native/FORMAT-v2.md
+++ b/packages/render-native/FORMAT-v2.md
@@ -20,6 +20,9 @@ All integers and IEEE-754 `f32` values are **little-endian**. Every structured r
| `9` | `texture_texels` | `storage, read` | `u32` | `4` | `4` | Packed RGBA8 / RGBA32F / RG16F texel words, IES profiles, Sobol tables |
| `10` | `environment_texels` | `storage, read` | `vec4<f32>` | `16` | `16` | Linear HDRI texels followed by marginal/conditional CDF rows |
| `11` | `film_accumulation` | `storage, read_write` | `vec4<f32>` | `16` | `16` | 4 planes of `image_width * image_height` vec4s (radiance+Z, albedo, normal, moments+count) |
+| `12` | `cycles_lut` | `storage, read` | `u32` | `4` | `4` | Static LUTs, then the two pixel filter tables |
+| `13` | `light_tree_emitters` | `storage, read` | `LightTreeEmitter` | `32` | `16` | Emitters in tree order, leaf by leaf (light tree revision 1, section 7b) |
+| `14` | `light_to_tree` | `storage, read` | `u32` | `4` | `4` | Emitter slot of every unified emitter (analytic lights, then emissive triangles) |
---
@@ -303,6 +306,34 @@ Total stride: **64 bytes** (`4 × 16 B`), alignment: **16 bytes**.
| `56` | `4` | `4` | `u32` | `emitter_count_and_kind` | Bits `0..15`: leaf count; bit `16`: `0=LightRecord`, `1=EmissiveTriangleRecord`; bit `17`: distant subtree |
| `60` | `4` | `4` | `u32` | `light_group_mask_or` | Bitwise OR of subtree low-32 light-linking masks |
+Light tree revision 1 (`LIGHT_TREE_REVISION` in `light-tree-v2.mjs`; `schemaVersion` stays `2` because the tables only add data) fills this table from `buildLightTree`, a translation of the build half of Cycles 5.3 `scene/light_tree.cpp`:
+
+- **Shape.** Node 0 is the root and children are written in pre-order, so a left child is its parent index plus 1. With sun lights and local emitters (analytic lights other than the sun, plus emissive triangles) the root is an inner node: left child the local tree, right child one distant leaf holding every sun light, as Cycles does. With only one kind the root is that tree or that leaf. The environment is not an emitter of this tree. With no emitters `light_tree_node_count` is `0` and the buffer holds one zeroed node.
+- **Split.** Top-down surface area orientation heuristic: 12 centroid buckets per axis, cost `energy * box area * cone measure` (`area == 0` uses the box diagonal), regularized by `max_extent / extent`. A node splits while a split is cheaper than a leaf or while it holds more than 8 emitters; a split with no cheaper cut falls back to the middle of the list. From depth 24 on nodes split by count, which bounds the depth at 46 so a 64-bit trail always fits. Leaves list their emitters in unified-index order. Emitters are sorted by centroid with the unified index as tie break, so the output is deterministic.
+- **Counts.** At most `4194304` emitters (`LIGHT_TREE_MAX_EMITTERS`) and `65535` emitters per leaf.
+- **Node fields.** `energy` is the sum of the children's energies (leaf: the sum of its emitters). `bounds_*` is the union of the emitters' boxes with energy above zero; a distant leaf and a zero-energy node store `0`. `theta_o`, `cone_axis`, `theta_e` are the merged bounding cone (Cycles `merge`). Internal node: `left_child >= 0`, `right_or_first_emitter` is the right child. Leaf: `left_child == -1`, `right_or_first_emitter` is the first slot in `light_tree_emitters` and bits `0..15` of `emitter_count_and_kind` are the emitter count. Higher bits of that word: bit `16` the subtree has an emissive triangle, bit `17` it is the distant leaf, bit `18` it has an analytic light (internal nodes OR their children's bits, so a mixed leaf sets both 16 and 18; the per-emitter kind in section 7b is authoritative).
+- **Emitter energy.** Emissive triangle `area * mean(|radiance|)`. Area light `mean(|radiance|) * area`. Point and spot `mean(|radiance|)` for a delta light, `mean(|radiance|) * pi * radius^2` otherwise. Sun `mean(|radiance|) * solid_angle`.
+- **Emitter cone.** Point `axis = direction, theta_o = pi, theta_e = pi/2`. Spot `theta_o = 0, theta_e = min(pi/2, acos(cos_half_angle))`. Area `theta_o = 0, theta_e = atan(tan_half_spread)` (`pi/2` for the default spread). Sun `theta_o = 0, theta_e = acos(cos_half_angle)`. Emissive triangle: the kernel emits from both sides, so the double-sided cone of Cycles, an in-plane axis with `theta_o = theta_e = pi/2`.
+- **Boxes.** Point and spot: position plus or minus the radius. Area: the four corners of the rectangle (also for disks, as Cycles does). Triangle: its three vertices.
+- Each `LightRecord.tree_leaf_index` (section 6) holds the node index of the leaf that owns the light.
+
+## 7b. Light Tree Emitters — `LightTreeEmitter` (`@binding(13)`) and `light_to_tree` (`@binding(14)`)
+
+`LightTreeEmitter` stride: **32 bytes**, alignment 16 bytes. Slots are in tree order, so the emitters of a leaf are contiguous. Unified emitter index `i` is an analytic light for `i < light_count` and emissive triangle `i - light_count` otherwise; `light_to_tree[i]` is its slot. Both tables are optional in the napi input (`lightTreeEmitters`, `lightTreeEmitterCount`, `lightToTree` come together or not at all); without them the host binds a zeroed record. The kernel does not read them yet.
+
+| Byte Offset | Size (B) | WGSL Type | Field | Description |
+| ---: | ---: | :--- | :--- | :--- |
+| `0` | `4` | `f32` | `energy` | Emitter energy as above |
+| `4` | `4` | `f32` | `theta_o` | Emitter cone `theta_o` |
+| `8` | `4` | `f32` | `theta_e` | Emitter cone `theta_e` |
+| `12` | `4` | `u32` | `kind_and_depth` | Bit `0` emissive triangle, bit `1` distant, bits `8..15` leaf depth (number of valid trail bits) |
+| `16` | `4` | `u32` | `record_index` | Index into `lights` or `emissive_triangles` |
+| `20` | `4` | `u32` | `leaf_node_index` | Owning leaf node |
+| `24` | `4` | `u32` | `bit_trail_low` | Trail bits `0..31`: bit `d` is set where the path from the root goes right at depth `d` |
+| `28` | `4` | `u32` | `bit_trail_high` | Trail bits `32..63` |
+
+The emitter cone axis is not stored: it is the `direction` of the light, or the in-plane axis `-normalize(edge1)` of a triangle.
+
---
## 8. Texture Descriptors — `TextureDescriptor` (`@binding(8)`)
diff --git a/packages/render-native/light-tree-v2.mjs b/packages/render-native/light-tree-v2.mjs
new file mode 100644
index 00000000..d8baff05
--- /dev/null
+++ b/packages/render-native/light-tree-v2.mjs
@@ -0,0 +1,725 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: 2011-2022 Blender Foundation
+//
+// Host-side light tree for the Cycles-parity native kernel. A translation of the build half of Blender Cycles 5.3
+// `scene/light_tree.cpp` and `light_tree.h`: a bounding volume tree over analytic lights and emissive triangles whose
+// nodes hold a bounding box, a bounding cone (axis, theta_o, theta_e) and an energy, split with the surface area
+// orientation heuristic (12 centroid buckets, at most 8 emitters per leaf). Distant lights (the sun) form one leaf
+// outside the local tree, as in Cycles, and the environment is not an emitter of this tree.
+// Pure typed arrays, no Node-only imports. The buffer layout is documented in FORMAT-v2.md section 7.
+
+export const LIGHT_TREE_REVISION = 1;
+export const LIGHT_TREE_NODE_BYTES = 64;
+export const LIGHT_TREE_EMITTER_BYTES = 32;
+export const LIGHT_TREE_MAX_LEAF_EMITTERS = 8;
+export const LIGHT_TREE_MAX_EMITTERS = 4194304;
+export const LIGHT_TREE_BUCKET_COUNT = 12;
+export const LIGHT_TREE_MAX_DEPTH = 63;
+
+// Node `emitter_count_and_kind` bits.
+export const LIGHT_TREE_NODE_COUNT_MASK = 0xffff;
+export const LIGHT_TREE_NODE_HAS_TRIANGLE = 1 << 16;
+export const LIGHT_TREE_NODE_DISTANT = 1 << 17;
+export const LIGHT_TREE_NODE_HAS_LIGHT = 1 << 18;
+
+// Emitter `kind_and_depth` bits: bit 0 triangle, bit 1 distant, bits 8..15 depth.
+export const LIGHT_TREE_EMITTER_TRIANGLE = 1;
+export const LIGHT_TREE_EMITTER_DISTANT = 2;
+export const LIGHT_TREE_EMITTER_DEPTH_SHIFT = 8;
+
+const LIGHT_BYTES = 128;
+const EMISSIVE_TRIANGLE_BYTES = 96;
+const LIGHT_TYPE_POINT = 0;
+const LIGHT_TYPE_SPOT = 1;
+const LIGHT_TYPE_AREA_RECT = 2;
+const LIGHT_TYPE_AREA_DISK = 3;
+const LIGHT_TYPE_SUN = 4;
+const LIGHT_TREE_LEAF_MARKER = -1;
+const LEAF_FORCED_BALANCE_DEPTH = 24;
+const NO_LEAF_INDEX = 0xffffffff;
+const ANGLE_EPSILON = 5e-4;
+
+const HALF_PI = Math.PI / 2;
+
+function vectorLength(vector) {
+ return Math.hypot(vector[0], vector[1], vector[2]);
+}
+
+function dotProduct(a, b) {
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+}
+
+function normalizeOrZero(vector) {
+ const length = vectorLength(vector);
+ if (!(length > 1e-20)) {
+ return [0, 0, 0];
+ }
+ return [vector[0] / length, vector[1] / length, vector[2] / length];
+}
+
+function safeArccosine(value) {
+ return Math.acos(Math.min(1, Math.max(-1, value)));
+}
+
+function perpendicularTo(axis) {
+ const helper = Math.abs(axis[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];
+ const projected = [
+ helper[0] - axis[0] * dotProduct(helper, axis),
+ helper[1] - axis[1] * dotProduct(helper, axis),
+ helper[2] - axis[2] * dotProduct(helper, axis),
+ ];
+ return normalizeOrZero(projected);
+}
+
+// ---- Orientation cone (Cycles OrientationBounds) --------------------------------------------------------------
+
+function emptyCone() {
+ return { axis: [0, 0, 0], thetaO: 0, thetaE: 0 };
+}
+
+function isEmptyCone(cone) {
+ return cone.axis[0] === 0 && cone.axis[1] === 0 && cone.axis[2] === 0;
+}
+
+export function coneMeasure(cone) {
+ if (isEmptyCone(cone)) {
+ return 0;
+ }
+ const thetaW = Math.min(Math.PI, cone.thetaO + cone.thetaE);
+ const cosThetaO = Math.cos(cone.thetaO);
+ const sinThetaO = Math.sin(cone.thetaO);
+ return (
+ 2 * Math.PI * (1 - cosThetaO) +
+ HALF_PI *
+ (2 * thetaW * sinThetaO - Math.cos(cone.thetaO - 2 * thetaW) - 2 * cone.thetaO * sinThetaO + cosThetaO)
+ );
+}
+
+export function mergeCones(coneA, coneB) {
+ if (isEmptyCone(coneA)) {
+ return coneB;
+ }
+ if (isEmptyCone(coneB)) {
+ return coneA;
+ }
+ const [wider, narrower] = coneB.thetaO > coneA.thetaO ? [coneB, coneA] : [coneA, coneB];
+ const cosBetween = dotProduct(wider.axis, narrower.axis);
+ const thetaD = safeArccosine(cosBetween);
+ const thetaE = Math.max(wider.thetaE, narrower.thetaE);
+
+ if (wider.thetaO + ANGLE_EPSILON >= Math.min(Math.PI, thetaD + narrower.thetaO)) {
+ return { axis: wider.axis, thetaO: wider.thetaO, thetaE };
+ }
+ const oppositeAxes = cosBetween < -0.9995;
+ // Cycles keeps the midpoint theta_o for opposite axes, but an orthogonal axis then misses part of the wider cone.
+ // A quarter turn plus the larger theta_o (the narrower one pushed out by its offset from exactly opposite)
+ // contains both, so the node cone stays a true bound.
+ const thetaO = oppositeAxes
+ ? Math.max(
+ (thetaD + wider.thetaO + narrower.thetaO) * 0.5,
+ HALF_PI + Math.max(wider.thetaO, narrower.thetaO + Math.PI - thetaD)
+ )
+ : (thetaD + wider.thetaO + narrower.thetaO) * 0.5;
+ if (thetaO >= Math.PI) {
+ return { axis: wider.axis, thetaO: Math.PI, thetaE };
+ }
+ let axis;
+ if (oppositeAxes) {
+ axis = perpendicularTo(wider.axis);
+ } else {
+ const thetaR = thetaO - wider.thetaO;
+ const ortho = normalizeOrZero([
+ narrower.axis[0] - wider.axis[0] * cosBetween,
+ narrower.axis[1] - wider.axis[1] * cosBetween,
+ narrower.axis[2] - wider.axis[2] * cosBetween,
+ ]);
+ const cosR = Math.cos(thetaR);
+ const sinR = Math.sin(thetaR);
+ axis = [
+ wider.axis[0] * cosR + ortho[0] * sinR,
+ wider.axis[1] * cosR + ortho[1] * sinR,
+ wider.axis[2] * cosR + ortho[2] * sinR,
+ ];
+ }
+ return { axis, thetaO, thetaE };
+}
+
+// ---- Measure: bounding box, cone and energy (Cycles LightTreeMeasure) ----------------------------------------
+
+function emptyMeasure() {
+ return {
+ boxMin: [Infinity, Infinity, Infinity],
+ boxMax: [-Infinity, -Infinity, -Infinity],
+ cone: emptyCone(),
+ energy: 0,
+ };
+}
+
+function addMeasure(target, other) {
+ if (other.energy === 0) {
+ return;
+ }
+ for (let axis = 0; axis < 3; axis++) {
+ target.boxMin[axis] = Math.min(target.boxMin[axis], other.boxMin[axis]);
+ target.boxMax[axis] = Math.max(target.boxMax[axis], other.boxMax[axis]);
+ }
+ target.cone = mergeCones(target.cone, other.cone);
+ target.energy += other.energy;
+}
+
+function copyMeasure(measure) {
+ return {
+ boxMin: measure.boxMin.slice(),
+ boxMax: measure.boxMax.slice(),
+ cone: measure.cone,
+ energy: measure.energy,
+ };
+}
+
+function sumMeasures(a, b) {
+ const sum = copyMeasure(a);
+ addMeasure(sum, b);
+ return sum;
+}
+
+// energy * box area * cone measure, Eq. 2 of the many-light paper.
+export function measureCost(measure) {
+ if (measure.energy === 0) {
+ return 0;
+ }
+ const sizeX = measure.boxMax[0] - measure.boxMin[0];
+ const sizeY = measure.boxMax[1] - measure.boxMin[1];
+ const sizeZ = measure.boxMax[2] - measure.boxMin[2];
+ const area = 2 * (sizeX * sizeY + sizeY * sizeZ + sizeZ * sizeX);
+ const areaMeasure = area === 0 ? Math.hypot(sizeX, sizeY, sizeZ) : area;
+ return measure.energy * areaMeasure * coneMeasure(measure.cone);
+}
+
+// ---- Emitters read from the packed FORMAT-v2 tables ----------------------------------------------------------
+
+function assertFiniteNumbers(values, label, index) {
+ for (const value of values) {
+ if (!Number.isFinite(value)) {
+ throw new Error(`buildLightTree: ${label} ${index} has a non-finite value; pass finite positions, sizes and radiance.`);
+ }
+ }
+}
+
+function averageAbsolute(red, green, blue) {
+ return (Math.abs(red) + Math.abs(green) + Math.abs(blue)) / 3;
+}
+
+function lightEmitter(view, index, unifiedIndex) {
+ const floats = new Float32Array(view.buffer, view.byteOffset + index * LIGHT_BYTES, LIGHT_BYTES / 4);
+ const words = new Uint32Array(view.buffer, view.byteOffset + index * LIGHT_BYTES, LIGHT_BYTES / 4);
+ // Words 3 and 7 are integers, 26 and 27 hold an index and a leaf; only the float fields can be non-finite.
+ assertFiniteNumbers(
+ [...floats.subarray(0, 3), ...floats.subarray(4, 7), ...floats.subarray(8, 26)],
+ 'analytic light',
+ index
+ );
+ const lightType = words[3];
+ const position = [floats[0], floats[1], floats[2]];
+ const direction = normalizeOrZero([floats[8], floats[9], floats[10]]);
+ const radius = floats[11];
+ const averageRadiance = averageAbsolute(floats[4], floats[5], floats[6]);
+ const areaOrSolidAngle = floats[24];
+ const emitter = {
+ unifiedIndex,
+ isTriangle: false,
+ recordIndex: index,
+ isDistant: lightType === LIGHT_TYPE_SUN,
+ maskLow: words[30],
+ boxMin: [0, 0, 0],
+ boxMax: [0, 0, 0],
+ centroid: position,
+ cone: emptyCone(),
+ energy: 0,
+ };
+ const axis = direction[0] === 0 && direction[1] === 0 && direction[2] === 0 ? [0, 0, -1] : direction;
+ if (lightType === LIGHT_TYPE_POINT || lightType === LIGHT_TYPE_SPOT) {
+ const extent = Math.max(0, radius);
+ emitter.boxMin = position.map((value) => value - extent);
+ emitter.boxMax = position.map((value) => value + extent);
+ emitter.energy = radius > 0 ? averageRadiance * Math.PI * radius * radius : averageRadiance;
+ if (lightType === LIGHT_TYPE_POINT) {
+ emitter.cone = { axis, thetaO: Math.PI, thetaE: HALF_PI };
+ } else {
+ emitter.cone = { axis, thetaO: 0, thetaE: Math.min(HALF_PI, safeArccosine(floats[20])) };
+ }
+ } else if (lightType === LIGHT_TYPE_AREA_RECT || lightType === LIGHT_TYPE_AREA_DISK) {
+ const halfU = [0.5 * floats[15] * floats[12], 0.5 * floats[15] * floats[13], 0.5 * floats[15] * floats[14]];
+ const halfV = [0.5 * floats[19] * floats[16], 0.5 * floats[19] * floats[17], 0.5 * floats[19] * floats[18]];
+ for (let axisIndex = 0; axisIndex < 3; axisIndex++) {
+ const spread = Math.abs(halfU[axisIndex]) + Math.abs(halfV[axisIndex]);
+ emitter.boxMin[axisIndex] = position[axisIndex] - spread;
+ emitter.boxMax[axisIndex] = position[axisIndex] + spread;
+ }
+ emitter.energy = averageRadiance * areaOrSolidAngle;
+ const tanHalfSpread = floats[22];
+ const thetaE = tanHalfSpread > 0 ? Math.min(HALF_PI, Math.atan(tanHalfSpread)) : HALF_PI;
+ emitter.cone = { axis, thetaO: 0, thetaE };
+ } else if (lightType === LIGHT_TYPE_SUN) {
+ emitter.energy = averageRadiance * areaOrSolidAngle;
+ emitter.cone = { axis, thetaO: 0, thetaE: safeArccosine(floats[20]) };
+ } else {
+ throw new Error(`buildLightTree: analytic light ${index} has unknown light_type ${lightType}; pass 0 to 4.`);
+ }
+ return emitter;
+}
+
+// The kernel samples emissive triangles on both sides (abs of the cosine), so the cone is the double-sided
+// one of Cycles: any vector in the triangle plane with theta_o = pi/2.
+function triangleEmitter(view, index, unifiedIndex) {
+ const floats = new Float32Array(view.buffer, view.byteOffset + index * EMISSIVE_TRIANGLE_BYTES, EMISSIVE_TRIANGLE_BYTES / 4);
+ const words = new Uint32Array(view.buffer, view.byteOffset + index * EMISSIVE_TRIANGLE_BYTES, EMISSIVE_TRIANGLE_BYTES / 4);
+ assertFiniteNumbers(floats.subarray(0, 20), 'emissive triangle', index);
+ const origin = [floats[0], floats[1], floats[2]];
+ const edgeOne = [floats[4], floats[5], floats[6]];
+ const edgeTwo = [floats[8], floats[9], floats[10]];
+ const vertices = [
+ origin,
+ origin.map((value, axis) => value + edgeOne[axis]),
+ origin.map((value, axis) => value + edgeTwo[axis]),
+ ];
+ const emitter = {
+ unifiedIndex,
+ isTriangle: true,
+ recordIndex: index,
+ isDistant: false,
+ maskLow: words[22],
+ boxMin: [0, 1, 2].map((axis) => Math.min(vertices[0][axis], vertices[1][axis], vertices[2][axis])),
+ boxMax: [0, 1, 2].map((axis) => Math.max(vertices[0][axis], vertices[1][axis], vertices[2][axis])),
+ centroid: [0, 1, 2].map((axis) => (vertices[0][axis] + vertices[1][axis] + vertices[2][axis]) / 3),
+ cone: emptyCone(),
+ energy: floats[3] * averageAbsolute(floats[16], floats[17], floats[18]),
+ };
+ const inPlane = normalizeOrZero(edgeOne.map((value) => -value));
+ const axis = inPlane[0] === 0 && inPlane[1] === 0 && inPlane[2] === 0 ? [1, 0, 0] : inPlane;
+ emitter.cone = { axis, thetaO: HALF_PI, thetaE: HALF_PI };
+ return emitter;
+}
+
+function emitterMeasure(emitter) {
+ return {
+ boxMin: emitter.boxMin.slice(),
+ boxMax: emitter.boxMax.slice(),
+ cone: emitter.cone,
+ energy: emitter.energy,
+ };
+}
+
+// ---- Build (Cycles LightTree::recursive_build and should_split) ----------------------------------------------
+
+function createBuckets() {
+ return Array.from({ length: LIGHT_TREE_BUCKET_COUNT }, () => ({ measure: emptyMeasure(), count: 0, maskOr: 0 }));
+}
+
+function addToBucket(bucket, emitter) {
+ addMeasure(bucket.measure, emitterMeasure(emitter));
+ bucket.count += 1;
+ bucket.maskOr = (bucket.maskOr | emitter.maskLow) >>> 0;
+}
+
+function sumBuckets(a, b) {
+ return {
+ measure: sumMeasures(a.measure, b.measure),
+ count: a.count + b.count,
+ maskOr: (a.maskOr | b.maskOr) >>> 0,
+ };
+}
+
+function fillBuckets(order, start, end, dimension, centroidMin, centroidSize) {
+ const buckets = createBuckets();
+ if (centroidSize[dimension] === 0) {
+ for (let position = start; position < end; position++) {
+ addToBucket(buckets[0], order[position]);
+ }
+ return buckets;
+ }
+ const inverseExtent = 1 / centroidSize[dimension];
+ for (let position = start; position < end; position++) {
+ const emitter = order[position];
+ const rawIndex = Math.floor(
+ LIGHT_TREE_BUCKET_COUNT * (emitter.centroid[dimension] - centroidMin[dimension]) * inverseExtent
+ );
+ const bucketIndex = Math.min(LIGHT_TREE_BUCKET_COUNT - 1, Math.max(0, rawIndex));
+ addToBucket(buckets[bucketIndex], emitter);
+ }
+ return buckets;
+}
+
+function cumulativeFromLeft(buckets) {
+ const result = [buckets[0]];
+ for (let index = 1; index < LIGHT_TREE_BUCKET_COUNT - 1; index++) {
+ result.push(sumBuckets(result[index - 1], buckets[index]));
+ }
+ return result;
+}
+
+function cumulativeFromRight(buckets) {
+ const result = new Array(LIGHT_TREE_BUCKET_COUNT - 1);
+ result[LIGHT_TREE_BUCKET_COUNT - 2] = buckets[LIGHT_TREE_BUCKET_COUNT - 1];
+ for (let index = LIGHT_TREE_BUCKET_COUNT - 3; index >= 0; index--) {
+ result[index] = sumBuckets(result[index + 1], buckets[index + 1]);
+ }
+ return result;
+}
+
+function centroidBounds(order, start, end) {
+ const centroidMin = [Infinity, Infinity, Infinity];
+ const centroidMax = [-Infinity, -Infinity, -Infinity];
+ for (let position = start; position < end; position++) {
+ for (let axis = 0; axis < 3; axis++) {
+ centroidMin[axis] = Math.min(centroidMin[axis], order[position].centroid[axis]);
+ centroidMax[axis] = Math.max(centroidMax[axis], order[position].centroid[axis]);
+ }
+ }
+ return { centroidMin, centroidSize: centroidMax.map((value, axis) => value - centroidMin[axis]) };
+}
+
+// Returns { shouldSplit, middle, splitDimension, measure, maskOr }. Mirrors the quirks of the Cycles loop: the node
+// measure is summed from the buckets of dimension 0, and the total cost is only set when the centroid box has an
+// extent along x, so a set of emitters on one x plane only splits by count once it has more than a leaf's worth.
+function chooseSplit(order, start, end) {
+ const emitterCount = end - start;
+ if (emitterCount < 2) {
+ const only = order[start];
+ return {
+ shouldSplit: false,
+ middle: start,
+ splitDimension: -1,
+ measure: emitterMeasure(only),
+ maskOr: only.maskLow,
+ };
+ }
+ let middle = (start + end) >> 1;
+ const { centroidMin, centroidSize } = centroidBounds(order, start, end);
+ const maxExtent = Math.max(centroidSize[0], centroidSize[1], centroidSize[2], 0);
+ const allExtentsZero = centroidSize[0] === 0 && centroidSize[1] === 0 && centroidSize[2] === 0;
+
+ let totalCost = 0;
+ let minimumCost = Number.MAX_VALUE;
+ let splitDimension = -1;
+ let nodeMeasure = emptyMeasure();
+ let nodeMaskOr = 0;
+
+ for (let dimension = 0; dimension < 3; dimension++) {
+ if (centroidSize[dimension] === 0 && dimension !== 0) {
+ continue;
+ }
+ const buckets = fillBuckets(order, start, end, dimension, centroidMin, centroidSize);
+ const leftBuckets = cumulativeFromLeft(buckets);
+ if (dimension === 0) {
+ const whole = sumBuckets(leftBuckets[LIGHT_TREE_BUCKET_COUNT - 2], buckets[LIGHT_TREE_BUCKET_COUNT - 1]);
+ nodeMeasure = whole.measure;
+ nodeMaskOr = whole.maskOr;
+ if (allExtentsZero) {
+ break;
+ }
+ if (centroidSize[0] === 0) {
+ continue;
+ }
+ totalCost = measureCost(nodeMeasure);
+ if (totalCost === 0) {
+ break;
+ }
+ }
+ const rightBuckets = cumulativeFromRight(buckets);
+ const inverseExtent = centroidSize[dimension] === 0 ? Number.MAX_VALUE : 1 / centroidSize[dimension];
+ const regularization = maxExtent * inverseExtent;
+ for (let split = 0; split < LIGHT_TREE_BUCKET_COUNT - 1; split++) {
+ const cost = regularization * (measureCost(leftBuckets[split].measure) + measureCost(rightBuckets[split].measure));
+ if (cost < totalCost && cost < minimumCost) {
+ minimumCost = cost;
+ splitDimension = dimension;
+ middle = start + leftBuckets[split].count;
+ }
+ }
+ }
+ return {
+ shouldSplit: minimumCost < totalCost || emitterCount > LIGHT_TREE_MAX_LEAF_EMITTERS,
+ middle,
+ splitDimension,
+ measure: nodeMeasure,
+ maskOr: nodeMaskOr,
+ };
+}
+
+function partitionByCentroid(order, start, end, dimension) {
+ const slice = order.slice(start, end);
+ slice.sort((a, b) => a.centroid[dimension] - b.centroid[dimension] || a.unifiedIndex - b.unifiedIndex);
+ for (let offset = 0; offset < slice.length; offset++) {
+ order[start + offset] = slice[offset];
+ }
+}
+
+function sortLeafByIndex(order, start, end) {
+ const slice = order.slice(start, end);
+ slice.sort((a, b) => a.unifiedIndex - b.unifiedIndex);
+ for (let offset = 0; offset < slice.length; offset++) {
+ order[start + offset] = slice[offset];
+ }
+}
+
+function trailBit(depth, trailLow, trailHigh) {
+ if (depth < 32) {
+ return [(trailLow | (1 << depth)) >>> 0, trailHigh];
+ }
+ return [trailLow, (trailHigh | (1 << (depth - 32))) >>> 0];
+}
+
+function summarizeLeafFlags(order, start, end) {
+ let flags = 0;
+ for (let position = start; position < end; position++) {
+ flags |= order[position].isTriangle ? LIGHT_TREE_NODE_HAS_TRIANGLE : LIGHT_TREE_NODE_HAS_LIGHT;
+ }
+ return flags;
+}
+
+function buildSubtree(state, start, end, depth, trailLow, trailHigh) {
+ const nodeIndex = state.nodes.length;
+ const node = { measure: null, leftChild: LIGHT_TREE_LEAF_MARKER, rightOrFirst: 0, countAndKind: 0, maskOr: 0 };
+ state.nodes.push(node);
+
+ const decision = chooseSplit(state.order, start, end);
+ node.measure = decision.measure;
+ node.maskOr = decision.maskOr;
+
+ const forceBalance = depth >= LEAF_FORCED_BALANCE_DEPTH && end - start >= 2;
+ let shouldSplit = decision.shouldSplit || (forceBalance && end - start > LIGHT_TREE_MAX_LEAF_EMITTERS);
+ let middle = decision.middle;
+ if (shouldSplit && forceBalance) {
+ middle = (start + end) >> 1;
+ } else if (shouldSplit && decision.splitDimension !== -1) {
+ partitionByCentroid(state.order, start, end, decision.splitDimension);
+ }
+ if (shouldSplit && (middle <= start || middle >= end)) {
+ middle = (start + end) >> 1;
+ }
+ if (depth > LIGHT_TREE_MAX_DEPTH) {
+ shouldSplit = false;
+ }
+
+ if (!shouldSplit) {
+ sortLeafByIndex(state.order, start, end);
+ const leafCount = end - start;
+ if (leafCount > LIGHT_TREE_NODE_COUNT_MASK) {
+ throw new Error(`buildLightTree: a leaf holds ${leafCount} emitters, more than ${LIGHT_TREE_NODE_COUNT_MASK}.`);
+ }
+ node.rightOrFirst = start;
+ node.countAndKind = (leafCount | summarizeLeafFlags(state.order, start, end)) >>> 0;
+ for (let position = start; position < end; position++) {
+ const emitter = state.order[position];
+ emitter.leafIndex = nodeIndex;
+ emitter.depth = depth;
+ emitter.trailLow = trailLow;
+ emitter.trailHigh = trailHigh;
+ }
+ return nodeIndex;
+ }
+
+ const leftIndex = buildSubtree(state, start, middle, depth + 1, trailLow, trailHigh);
+ const [rightLow, rightHigh] = trailBit(depth, trailLow, trailHigh);
+ const rightIndex = buildSubtree(state, middle, end, depth + 1, rightLow, rightHigh);
+ node.leftChild = leftIndex;
+ node.rightOrFirst = rightIndex;
+ node.countAndKind = (state.nodes[leftIndex].countAndKind | state.nodes[rightIndex].countAndKind) & ~LIGHT_TREE_NODE_COUNT_MASK;
+ node.countAndKind >>>= 0;
+ node.measure = sumMeasures(state.nodes[leftIndex].measure, state.nodes[rightIndex].measure);
+ node.maskOr = (state.nodes[leftIndex].maskOr | state.nodes[rightIndex].maskOr) >>> 0;
+ return nodeIndex;
+}
+
+function buildDistantLeaf(state, start, end, depth, trailLow, trailHigh) {
+ const nodeIndex = state.nodes.length;
+ const measure = emptyMeasure();
+ let maskOr = 0;
+ for (let position = start; position < end; position++) {
+ addMeasure(measure, emitterMeasure(state.order[position]));
+ maskOr = (maskOr | state.order[position].maskLow) >>> 0;
+ }
+ sortLeafByIndex(state.order, start, end);
+ for (let position = start; position < end; position++) {
+ const emitter = state.order[position];
+ emitter.leafIndex = nodeIndex;
+ emitter.depth = depth;
+ emitter.trailLow = trailLow;
+ emitter.trailHigh = trailHigh;
+ }
+ const count = end - start;
+ if (count > LIGHT_TREE_NODE_COUNT_MASK) {
+ throw new Error(`buildLightTree: ${count} distant lights exceed the leaf limit ${LIGHT_TREE_NODE_COUNT_MASK}.`);
+ }
+ state.nodes.push({
+ measure,
+ leftChild: LIGHT_TREE_LEAF_MARKER,
+ rightOrFirst: start,
+ countAndKind: (count | LIGHT_TREE_NODE_DISTANT | LIGHT_TREE_NODE_HAS_LIGHT) >>> 0,
+ maskOr,
+ });
+ return nodeIndex;
+}
+
+// ---- Serialization ------------------------------------------------------------------------------------------
+
+function writeNode(floats, words, ints, node) {
+ const { measure } = node;
+ const hasBox = measure.energy > 0 && measure.boxMin[0] <= measure.boxMax[0];
+ const boxMin = hasBox ? measure.boxMin : [0, 0, 0];
+ const boxMax = hasBox ? measure.boxMax : [0, 0, 0];
+ const cone = measure.energy > 0 ? measure.cone : emptyCone();
+ floats[0] = boxMin[0];
+ floats[1] = boxMin[1];
+ floats[2] = boxMin[2];
+ floats[3] = measure.energy;
+ floats[4] = boxMax[0];
+ floats[5] = boxMax[1];
+ floats[6] = boxMax[2];
+ floats[7] = cone.thetaO;
+ floats[8] = cone.axis[0];
+ floats[9] = cone.axis[1];
+ floats[10] = cone.axis[2];
+ floats[11] = cone.thetaE;
+ ints[12] = node.leftChild;
+ words[13] = node.rightOrFirst;
+ words[14] = node.countAndKind;
+ words[15] = node.maskOr;
+}
+
+function serializeNodes(nodes) {
+ const bytes = new Uint8Array(Math.max(1, nodes.length) * LIGHT_TREE_NODE_BYTES);
+ for (let index = 0; index < nodes.length; index++) {
+ const offset = index * LIGHT_TREE_NODE_BYTES;
+ writeNode(
+ new Float32Array(bytes.buffer, offset, 16),
+ new Uint32Array(bytes.buffer, offset, 16),
+ new Int32Array(bytes.buffer, offset, 16),
+ nodes[index]
+ );
+ }
+ return bytes;
+}
+
+function serializeEmitters(order) {
+ const bytes = new Uint8Array(Math.max(1, order.length) * LIGHT_TREE_EMITTER_BYTES);
+ for (let slot = 0; slot < order.length; slot++) {
+ const emitter = order[slot];
+ const offset = slot * LIGHT_TREE_EMITTER_BYTES;
+ const floats = new Float32Array(bytes.buffer, offset, 8);
+ const words = new Uint32Array(bytes.buffer, offset, 8);
+ floats[0] = emitter.energy;
+ floats[1] = emitter.cone.thetaO;
+ floats[2] = emitter.cone.thetaE;
+ words[3] =
+ ((emitter.isTriangle ? LIGHT_TREE_EMITTER_TRIANGLE : 0) |
+ (emitter.isDistant ? LIGHT_TREE_EMITTER_DISTANT : 0) |
+ (emitter.depth << LIGHT_TREE_EMITTER_DEPTH_SHIFT)) >>>
+ 0;
+ words[4] = emitter.recordIndex;
+ words[5] = emitter.leafIndex;
+ words[6] = emitter.trailLow;
+ words[7] = emitter.trailHigh;
+ }
+ return bytes;
+}
+
+function assertCount(label, count) {
+ if (!Number.isInteger(count) || count < 0) {
+ throw new Error(`buildLightTree: ${label} count must be a non-negative integer, got ${count}.`);
+ }
+}
+
+function validateRecordTable(label, bytes, count, stride) {
+ if (!(bytes instanceof Uint8Array)) {
+ throw new Error(`buildLightTree: ${label} must be a Uint8Array of FORMAT-v2 records.`);
+ }
+ if (bytes.byteLength < count * stride) {
+ throw new Error(`buildLightTree: ${label} holds ${bytes.byteLength} bytes, fewer than ${count} records of ${stride} bytes.`);
+ }
+}
+
+/**
+ * Builds the light tree over the packed analytic lights and emissive triangles.
+ *
+ * @param {Uint8Array} lights packed `LightRecord` table (FORMAT-v2 section 6)
+ * @param {number} lightCount number of analytic lights
+ * @param {Uint8Array} emissiveTriangles packed `EmissiveTriangleRecord` table (section 5)
+ * @param {number} emissiveTriangleCount number of emissive triangles
+ * @returns {{nodes: Uint8Array, nodeCount: number, emitters: Uint8Array, emitterCount: number,
+ * lightToTree: Uint32Array, lightLeafIndices: Uint32Array}} `lightToTree[i]` is the emitter slot of unified
+ * emitter `i` (analytic lights first, then emissive triangles); `lightLeafIndices[i]` the leaf node of light `i`.
+ */
+export function buildLightTree(lights, lightCount, emissiveTriangles, emissiveTriangleCount) {
+ assertCount('lights', lightCount);
+ assertCount('emissiveTriangles', emissiveTriangleCount);
+ const totalEmitters = lightCount + emissiveTriangleCount;
+ if (totalEmitters > LIGHT_TREE_MAX_EMITTERS) {
+ throw new Error(
+ `buildLightTree: ${totalEmitters} emitters exceed the limit of ${LIGHT_TREE_MAX_EMITTERS}; merge emissive triangles or drop lights.`
+ );
+ }
+ validateRecordTable('lights', lights, lightCount, LIGHT_BYTES);
+ validateRecordTable('emissiveTriangles', emissiveTriangles, emissiveTriangleCount, EMISSIVE_TRIANGLE_BYTES);
+ if (totalEmitters === 0) {
+ return {
+ nodes: new Uint8Array(LIGHT_TREE_NODE_BYTES),
+ nodeCount: 0,
+ emitters: new Uint8Array(LIGHT_TREE_EMITTER_BYTES),
+ emitterCount: 0,
+ lightToTree: new Uint32Array(1),
+ lightLeafIndices: new Uint32Array(0),
+ };
+ }
+
+ const localEmitters = [];
+ const distantEmitters = [];
+ for (let index = 0; index < lightCount; index++) {
+ const emitter = lightEmitter(lights, index, index);
+ (emitter.isDistant ? distantEmitters : localEmitters).push(emitter);
+ }
+ for (let index = 0; index < emissiveTriangleCount; index++) {
+ localEmitters.push(triangleEmitter(emissiveTriangles, index, lightCount + index));
+ }
+
+ const state = { nodes: [], order: localEmitters.concat(distantEmitters) };
+ const localCount = localEmitters.length;
+ if (distantEmitters.length === 0) {
+ buildSubtree(state, 0, localCount, 0, 0, 0);
+ } else if (localCount === 0) {
+ buildDistantLeaf(state, 0, distantEmitters.length, 0, 0, 0);
+ } else {
+ const rootIndex = state.nodes.length;
+ const root = { measure: null, leftChild: 0, rightOrFirst: 0, countAndKind: 0, maskOr: 0 };
+ state.nodes.push(root);
+ const leftIndex = buildSubtree(state, 0, localCount, 1, 0, 0);
+ const rightIndex = buildDistantLeaf(state, localCount, state.order.length, 1, 1, 0);
+ root.leftChild = leftIndex;
+ root.rightOrFirst = rightIndex;
+ root.measure = sumMeasures(state.nodes[leftIndex].measure, state.nodes[rightIndex].measure);
+ root.countAndKind =
+ ((state.nodes[leftIndex].countAndKind | state.nodes[rightIndex].countAndKind) & ~LIGHT_TREE_NODE_COUNT_MASK) >>> 0;
+ root.maskOr = (state.nodes[leftIndex].maskOr | state.nodes[rightIndex].maskOr) >>> 0;
+ if (rootIndex !== 0) {
+ throw new Error('buildLightTree: the root node must be node 0.');
+ }
+ }
+
+ const lightToTree = new Uint32Array(totalEmitters);
+ const lightLeafIndices = new Uint32Array(lightCount).fill(NO_LEAF_INDEX);
+ for (let slot = 0; slot < state.order.length; slot++) {
+ const emitter = state.order[slot];
+ lightToTree[emitter.unifiedIndex] = slot;
+ if (!emitter.isTriangle) {
+ lightLeafIndices[emitter.recordIndex] = emitter.leafIndex;
+ }
+ }
+ return {
+ nodes: serializeNodes(state.nodes),
+ nodeCount: state.nodes.length,
+ emitters: serializeEmitters(state.order),
+ emitterCount: state.order.length,
+ lightToTree,
+ lightLeafIndices,
+ };
+}
diff --git a/packages/render-native/pack-input-v2.mjs b/packages/render-native/pack-input-v2.mjs
index 9304bf19..a12abc4d 100644
--- a/packages/render-native/pack-input-v2.mjs
+++ b/packages/render-native/pack-input-v2.mjs
@@ -1,6 +1,8 @@
// Packs a 67js trace scene (or upgrades a legacy v1 input) into the FORMAT-v2 binary tables read by the Cycles-parity
// native kernel (`FORMAT-v2.md` and `src/cycles/abi.wgsl`). Pure typed arrays with zero Node-only imports.
+import { buildLightTree } from './light-tree-v2.mjs';
+
export const FORMAT_V2_MAGIC = 0x36375054;
export const FORMAT_V2_VERSION = 2;
export const INVALID_INDEX_V2 = 0xffffffff;
@@ -1292,55 +1294,27 @@ function packAnalyticLightsBuffer(entries) {
};
}
-function packRootLightTreeNode(packedLights, packedEmissives) {
- const totalEmitters = packedLights.lightCount + packedEmissives.emissiveTriangleCount;
- const buffer = new Uint8Array(STRUCT_STRIDES_V2.lightTreeNode);
- if (totalEmitters === 0) {
- return { lightTreeNodes: buffer, lightTreeNodeCount: 0 };
- }
- const f32 = new Float32Array(buffer.buffer, 0, 16);
- const u32 = new Uint32Array(buffer.buffer, 0, 16);
- const i32 = new Int32Array(buffer.buffer, 0, 16);
-
- const boundsMin = [Infinity, Infinity, Infinity];
- const boundsMax = [-Infinity, -Infinity, -Infinity];
- for (const candidate of [packedLights, packedEmissives]) {
- if (!candidate.boundsMin) continue;
- for (let axis = 0; axis < 3; axis++) {
- boundsMin[axis] = Math.min(boundsMin[axis], candidate.boundsMin[axis]);
- boundsMax[axis] = Math.max(boundsMax[axis], candidate.boundsMax[axis]);
- }
- }
- if (!(boundsMin[0] <= boundsMax[0])) {
- boundsMin.fill(-1);
- boundsMax.fill(1);
+// Builds the Cycles light tree over the packed lights and emissive triangles (light-tree-v2.mjs) and records the
+// owning leaf of every analytic light in its `tree_leaf_index` field.
+function packLightTree(packedLights, packedEmissives) {
+ const tree = buildLightTree(
+ packedLights.lights,
+ packedLights.lightCount,
+ packedEmissives.emissiveTriangles,
+ packedEmissives.emissiveTriangleCount
+ );
+ const lightWords = new Uint32Array(packedLights.lights.buffer, packedLights.lights.byteOffset, packedLights.lights.byteLength / 4);
+ const wordsPerLight = STRUCT_STRIDES_V2.light / 4;
+ for (let index = 0; index < packedLights.lightCount; index++) {
+ lightWords[index * wordsPerLight + 27] = tree.lightLeafIndices[index];
}
-
- const leafCount = Math.min(0xffff, totalEmitters);
- const kindBit = packedLights.lightCount === 0 && packedEmissives.emissiveTriangleCount > 0 ? (1 << 16) : 0;
- const distantBit = packedLights.hasDistant ? (1 << 17) : 0;
-
- f32[0] = boundsMin[0];
- f32[1] = boundsMin[1];
- f32[2] = boundsMin[2];
- f32[3] = packedLights.analyticLightTotalWeight + packedEmissives.emissiveTotalWeight;
-
- f32[4] = boundsMax[0];
- f32[5] = boundsMax[1];
- f32[6] = boundsMax[2];
- f32[7] = Math.PI;
-
- f32[8] = 0;
- f32[9] = 1;
- f32[10] = 0;
- f32[11] = Math.PI;
-
- i32[12] = -1;
- u32[13] = 0;
- u32[14] = (leafCount | kindBit | distantBit) >>> 0;
- u32[15] = (packedLights.maskOr | packedEmissives.maskOr) >>> 0;
-
- return { lightTreeNodes: buffer, lightTreeNodeCount: 1 };
+ return {
+ lightTreeNodes: tree.nodes,
+ lightTreeNodeCount: tree.nodeCount,
+ lightTreeEmitters: tree.emitters,
+ lightTreeEmitterCount: tree.emitterCount,
+ lightToTree: tree.lightToTree,
+ };
}
function packEnvironmentTexelsV2(environment, options = {}) {
@@ -2233,7 +2207,7 @@ export function buildNativeInputV2(scene, camera, options = {}) {
const packedEmissives = packEmissiveTriangleBuffer(packedGeometry.emissiveList);
const analyticEntries = buildAnalyticLightEntries(scene.lights);
const packedLights = packAnalyticLightsBuffer(analyticEntries);
- const packedLightTree = packRootLightTreeNode(packedLights, packedEmissives);
+ const packedLightTree = packLightTree(packedLights, packedEmissives);
const packedEnvironment = packEnvironmentTexelsV2(scene.environment, options);
const counts = {
@@ -2274,6 +2248,9 @@ export function buildNativeInputV2(scene, camera, options = {}) {
lightCount: counts.lightCount,
lightTreeNodes: packedLightTree.lightTreeNodes,
lightTreeNodeCount: counts.lightTreeNodeCount,
+ lightTreeEmitters: packedLightTree.lightTreeEmitters,
+ lightTreeEmitterCount: packedLightTree.lightTreeEmitterCount,
+ lightToTree: packedLightTree.lightToTree,
textureDescriptors: packedTextures.textureDescriptors,
textureCount: counts.textureCount,
textureTexels: packedTextures.textureTexels,
@@ -2644,7 +2621,7 @@ export function upgradeNativeInputV1ToV2(v1Input, options = {}) {
const packedEmissives = packEmissiveTriangleBuffer(emissiveList);
const analyticEntries = buildAnalyticLightEntries(reconstructedLights);
const packedLights = packAnalyticLightsBuffer(analyticEntries);
- const packedLightTree = packRootLightTreeNode(packedLights, packedEmissives);
+ const packedLightTree = packLightTree(packedLights, packedEmissives);
const packedEnvironment = packEnvironmentTexelsV2(reconstructedEnv, options);
const mergedOptions = {
@@ -2694,6 +2671,9 @@ export function upgradeNativeInputV1ToV2(v1Input, options = {}) {
lightCount: counts.lightCount,
lightTreeNodes: packedLightTree.lightTreeNodes,
lightTreeNodeCount: counts.lightTreeNodeCount,
+ lightTreeEmitters: packedLightTree.lightTreeEmitters,
+ lightTreeEmitterCount: packedLightTree.lightTreeEmitterCount,
+ lightToTree: packedLightTree.lightToTree,
textureDescriptors: packedTextures.textureDescriptors,
textureCount: counts.textureCount,
textureTexels: packedTextures.textureTexels,
diff --git a/packages/render-native/package.json b/packages/render-native/package.json
index 6982806c..929e7ee7 100644
--- a/packages/render-native/package.json
+++ b/packages/render-native/package.json
@@ -11,6 +11,7 @@
"index.mjs",
"pack-input.mjs",
"pack-input-v2.mjs",
+ "light-tree-v2.mjs",
"FORMAT-v2.md",
"build.mjs",
"build.rs",
diff --git a/packages/render-native/src/cycles/abi.wgsl b/packages/render-native/src/cycles/abi.wgsl
index 5e3f2e94..792c7633 100644
--- a/packages/render-native/src/cycles/abi.wgsl
+++ b/packages/render-native/src/cycles/abi.wgsl
@@ -357,6 +357,21 @@ struct LightTreeNode {
light_group_mask_or: u32,
}
+// 32 bytes (2 x 16 B), alignment 16 B. One emitter of the light tree, in tree order (FORMAT-v2 section 7b).
+// `kind_and_depth`: bit 0 emissive triangle, bit 1 distant, bits 8..15 depth. `record_index` indexes `lights` or
+// `emissive_triangles`. `bit_trail_low` / `bit_trail_high` hold one bit per tree level, set where the path to the
+// emitter goes right.
+struct LightTreeEmitter {
+ energy: f32,
+ theta_o: f32,
+ theta_e: f32,
+ kind_and_depth: u32,
+ record_index: u32,
+ leaf_node_index: u32,
+ bit_trail_low: u32,
+ bit_trail_high: u32,
+}
+
// 32 bytes (2 x 16 B), alignment 16 B.
struct TextureDescriptor {
@align(16) data_offset: u32,
@@ -530,6 +545,8 @@ struct ClosureSample {
@group(0) @binding(10) var<storage, read> environment_texels: array<vec4<f32>>;
@group(0) @binding(11) var<storage, read_write> film_accumulation: array<vec4<f32>>;
@group(0) @binding(12) var<storage, read> cycles_lut: array<u32>;
+@group(0) @binding(13) var<storage, read> light_tree_emitters: array<LightTreeEmitter>;
+@group(0) @binding(14) var<storage, read> light_to_tree: array<u32>;
// ---------------------------------------------------------------------------------------------------------------------
// Cross-lane closure interface contract (defined in Lane L4 `src/cycles/closure.wgsl`, called by Lane L3 integrator)
diff --git a/packages/render-native/src/cycles/mod.rs b/packages/render-native/src/cycles/mod.rs
index 868c5a94..77a44928 100644
--- a/packages/render-native/src/cycles/mod.rs
+++ b/packages/render-native/src/cycles/mod.rs
@@ -393,6 +393,9 @@ mod specialization_tests {
light_count: (lights.len() / LIGHT_RECORD_STRIDE) as u32,
light_tree_nodes: Uint8Array::new(vec![0u8; 64]),
light_tree_node_count: 1,
+ light_tree_emitters: None,
+ light_tree_emitter_count: None,
+ light_to_tree: None,
texture_descriptors: Uint8Array::new(vec![0u8; 32]),
texture_count: 1,
texture_texels: Uint32Array::new(vec![0u32; 4]),
diff --git a/packages/render-native/src/host/session.rs b/packages/render-native/src/host/session.rs
index ae58b128..8dc30cdd 100644
--- a/packages/render-native/src/host/session.rs
+++ b/packages/render-native/src/host/session.rs
@@ -198,6 +198,9 @@ const MATERIAL_RECORD_BYTES: usize = 256;
const EMISSIVE_TRIANGLE_RECORD_BYTES: usize = 96;
const LIGHT_RECORD_BYTES: usize = 128;
const LIGHT_TREE_NODE_BYTES: usize = 64;
+const LIGHT_TREE_EMITTER_BYTES: usize = 32;
+/// Buffers bound at 2..=10; the light tree emitter and light-to-tree buffers follow them for bindings 13 and 14.
+const CYCLES_SCENE_BUFFER_COUNT: usize = 9;
const TEXTURE_DESCRIPTOR_BYTES: usize = 32;
const CYCLES_SAMPLE_OFFSET_BYTE_OFFSET: u64 = 16;
const LOBE_PROBE_WORKGROUP_SIZE: u32 = 64;
@@ -302,6 +305,8 @@ fn create_cycles_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayo
layout_entries.extend((2..=10).map(|binding| storage_entry(binding, true)));
layout_entries.push(storage_entry(11, false)); // film_accumulation (read_write)
layout_entries.push(storage_entry(12, true)); // cycles_lut (read-only: static LUTs, then the two pixel filter tables)
+ layout_entries.push(storage_entry(13, true)); // light_tree_emitters
+ layout_entries.push(storage_entry(14, true)); // light_to_tree
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("cycles path tracer"),
entries: &layout_entries,
@@ -386,7 +391,7 @@ fn create_cycles_bind_group(
wgpu::BindGroupEntry { binding: 0, resource: parameters.as_entire_binding() },
wgpu::BindGroupEntry { binding: 1, resource: tlas.as_binding() },
];
- for (offset, buffer) in buffers.iter().enumerate() {
+ for (offset, buffer) in buffers[..CYCLES_SCENE_BUFFER_COUNT].iter().enumerate() {
entries.push(wgpu::BindGroupEntry {
binding: 2 + offset as u32,
resource: buffer.as_entire_binding(),
@@ -400,6 +405,12 @@ fn create_cycles_bind_group(
binding: 12,
resource: lut_buffer.as_entire_binding(),
});
+ for (offset, buffer) in buffers[CYCLES_SCENE_BUFFER_COUNT..].iter().enumerate() {
+ entries.push(wgpu::BindGroupEntry {
+ binding: 13 + offset as u32,
+ resource: buffer.as_entire_binding(),
+ });
+ }
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("cycles path tracer"),
layout: bind_group_layout,
@@ -553,6 +564,38 @@ fn validate_record_buffer(label: &str, bytes: &[u8], count: u32, stride: usize)
Ok(())
}
+/// The emitter table and the emitter-to-slot table come together or not at all, and the slot table must cover
+/// every analytic light and emissive triangle of the input.
+fn validate_light_tree_tables(input: &NativeTraceInputV2) -> Result<()> {
+ let (emitters, emitter_count, light_to_tree) = match (
+ &input.light_tree_emitters,
+ input.light_tree_emitter_count,
+ &input.light_to_tree,
+ ) {
+ (None, None, None) => return Ok(()),
+ (Some(emitters), Some(emitter_count), Some(light_to_tree)) => (emitters, emitter_count, light_to_tree),
+ _ => {
+ return Err(failure(
+ "lightTreeEmitters, lightTreeEmitterCount and lightToTree must all be present or all absent. Pack them together with packTraceSceneV2.",
+ ))
+ }
+ };
+ validate_record_buffer("lightTreeEmitters", emitters, emitter_count, LIGHT_TREE_EMITTER_BYTES)?;
+ let unified_count = input.light_count as u64 + input.emissive_triangle_count as u64;
+ if emitter_count as u64 != unified_count {
+ return Err(failure(format!(
+ "lightTreeEmitterCount is {emitter_count} but the input has {unified_count} lights and emissive triangles. The tree must hold every emitter once."
+ )));
+ }
+ if (light_to_tree.len() as u64) < unified_count.max(1) {
+ return Err(failure(format!(
+ "lightToTree holds {} entries, fewer than the {unified_count} emitters of the input.",
+ light_to_tree.len()
+ )));
+ }
+ Ok(())
+}
+
pub(crate) fn prepare_cycles_scene(
input: &NativeTraceInputV2,
shader_source: String,
@@ -597,6 +640,7 @@ pub(crate) fn prepare_cycles_scene(
input.texture_count,
TEXTURE_DESCRIPTOR_BYTES,
)?;
+ validate_light_tree_tables(input)?;
// Use cached device; open once per process.
let (device, queue, adapter_name, backend_name, features) = get_cached_device()?;
@@ -777,6 +821,8 @@ pub(crate) fn run_cycles_lobe_probe(options: &ProbeCyclesLobeOptions, shader_sou
storage_buffer(&device, "probe texture descriptors", descriptor_slice),
storage_buffer(&device, "probe texture texels", bytemuck::cast_slice(texel_slice)),
storage_buffer(&device, "dummy environment texels", &[0u8; 16]),
+ storage_buffer(&device, "dummy light tree emitters", &[0u8; LIGHT_TREE_EMITTER_BYTES]),
+ storage_buffer(&device, "dummy light to tree", &[0u8; 4]),
];
let accumulation = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("lobe probe accumulation"),
diff --git a/packages/render-native/src/host/textures.rs b/packages/render-native/src/host/textures.rs
index 6613aee7..6e21c76f 100644
--- a/packages/render-native/src/host/textures.rs
+++ b/packages/render-native/src/host/textures.rs
@@ -68,6 +68,24 @@ pub(crate) fn upload_scene_buffers(
}
}
+const EMPTY_LIGHT_TREE_EMITTER: [u8; 32] = [0u8; 32];
+const EMPTY_LIGHT_TO_TREE: [u32; 1] = [0u32; 1];
+
+/// The emitter table of an input, or one zeroed record for an input packed without a light tree.
+fn light_tree_emitter_bytes(input: &NativeTraceInputV2) -> &[u8] {
+ match &input.light_tree_emitters {
+ Some(bytes) if !bytes.is_empty() => bytes,
+ _ => &EMPTY_LIGHT_TREE_EMITTER,
+ }
+}
+
+fn light_to_tree_words(input: &NativeTraceInputV2) -> &[u32] {
+ match &input.light_to_tree {
+ Some(words) if !words.is_empty() => words,
+ _ => &EMPTY_LIGHT_TO_TREE,
+ }
+}
+
pub(crate) fn upload_cycles_scene_buffers(
device: &wgpu::Device,
input: &NativeTraceInputV2,
@@ -81,7 +99,7 @@ pub(crate) fn upload_cycles_scene_buffers(
parameter_bytes[12..16].copy_from_slice(&height.to_le_bytes());
parameter_bytes[24..28].copy_from_slice(&total_samples.to_le_bytes());
- // Bindings 2..=10 in FORMAT-v2 order.
+ // Bindings 2..=10 in FORMAT-v2 order, then the light tree tables for bindings 13 and 14.
let buffers = vec![
storage_buffer(device, "cycles instances", &input.instances),
storage_buffer(device, "cycles triangles", &input.triangles),
@@ -92,6 +110,9 @@ pub(crate) fn upload_cycles_scene_buffers(
storage_buffer(device, "cycles texture descriptors", &input.texture_descriptors),
storage_buffer(device, "cycles texture texels", bytemuck::cast_slice(&input.texture_texels)),
storage_buffer(device, "cycles environment texels", bytemuck::cast_slice(&input.environment_texels)),
+ // Bound at 13 and 14 by `create_cycles_bind_group`: the light tree emitters and the emitter-to-slot table.
+ storage_buffer(device, "cycles light tree emitters", light_tree_emitter_bytes(input)),
+ storage_buffer(device, "cycles light to tree", bytemuck::cast_slice(light_to_tree_words(input))),
];
let accumulation = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("cycles film accumulation"),
diff --git a/packages/render-native/src/lib.rs b/packages/render-native/src/lib.rs
index 0ffe5796..86d61f9b 100644
--- a/packages/render-native/src/lib.rs
+++ b/packages/render-native/src/lib.rs
@@ -53,6 +53,11 @@ pub struct NativeTraceInputV2 {
pub light_count: u32,
pub light_tree_nodes: Uint8Array,
pub light_tree_node_count: u32,
+ /// Emitters in tree order (FORMAT-v2 section 7b); absent in inputs packed before the light tree landed.
+ pub light_tree_emitters: Option<Uint8Array>,
+ pub light_tree_emitter_count: Option<u32>,
+ /// Emitter slot of every unified emitter (analytic lights first, then emissive triangles).
+ pub light_to_tree: Option<Uint32Array>,
pub texture_descriptors: Uint8Array,
pub texture_count: u32,
pub texture_texels: Uint32Array,
diff --git a/tests/native-light-tree.test.js b/tests/native-light-tree.test.js
new file mode 100644
index 00000000..53d6a596
--- /dev/null
+++ b/tests/native-light-tree.test.js
@@ -0,0 +1,496 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { buildNativeInputV2 } from '../packages/render-native/index.mjs';
+import {
+ LIGHT_TREE_EMITTER_BYTES,
+ LIGHT_TREE_MAX_EMITTERS,
+ LIGHT_TREE_NODE_BYTES,
+ buildLightTree,
+ coneMeasure,
+ mergeCones,
+} from '../packages/render-native/light-tree-v2.mjs';
+import { createCamera } from '../src/path-tracer.js';
+
+const LIGHT_BYTES = 128;
+const TRIANGLE_BYTES = 96;
+const TYPE_POINT = 0;
+const TYPE_SPOT = 1;
+const TYPE_AREA_RECT = 2;
+const TYPE_SUN = 4;
+const LEAF_LIMIT = 8;
+
+function createRandom(seed) {
+ let state = seed >>> 0;
+ return () => {
+ state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
+ return state / 4294967296;
+ };
+}
+
+function randomDirection(random) {
+ const z = random() * 2 - 1;
+ const angle = random() * Math.PI * 2;
+ const ring = Math.sqrt(1 - z * z);
+ return [ring * Math.cos(angle), ring * Math.sin(angle), z];
+}
+
+function writeLight(bytes, index, light) {
+ const floats = new Float32Array(bytes.buffer, index * LIGHT_BYTES, LIGHT_BYTES / 4);
+ const words = new Uint32Array(bytes.buffer, index * LIGHT_BYTES, LIGHT_BYTES / 4);
+ floats.set(light.position, 0);
+ words[3] = light.type;
+ floats.set(light.radiance, 4);
+ floats.set(light.direction, 8);
+ floats[11] = light.radius ?? 0;
+ floats.set(light.axisU ?? [1, 0, 0], 12);
+ floats[15] = light.sizeU ?? 0;
+ floats.set(light.axisV ?? [0, 1, 0], 16);
+ floats[19] = light.sizeV ?? 0;
+ floats[20] = light.cosHalfAngle ?? 0;
+ floats[22] = light.tanHalfSpread ?? 0;
+ floats[24] = light.areaOrSolidAngle ?? 0;
+ words[30] = light.maskLow ?? 1;
+}
+
+function makeLights(count, seed, { includeSun = false } = {}) {
+ const random = createRandom(seed);
+ const bytes = new Uint8Array(Math.max(1, count) * LIGHT_BYTES);
+ for (let index = 0; index < count; index++) {
+ const position = [random() * 40 - 20, random() * 10, random() * 40 - 20];
+ const radiance = [0.2 + random() * 5, 0.2 + random() * 5, 0.2 + random() * 5];
+ const direction = randomDirection(random);
+ const choice = includeSun && index === count - 1 ? 3 : Math.floor(random() * 3);
+ if (choice === 0) {
+ writeLight(bytes, index, { position, type: TYPE_POINT, radiance, direction, radius: random() * 0.3 });
+ } else if (choice === 1) {
+ writeLight(bytes, index, {
+ position, type: TYPE_SPOT, radiance, direction, radius: 0.05, cosHalfAngle: Math.cos(0.2 + random()),
+ });
+ } else if (choice === 2) {
+ const width = 0.5 + random();
+ const height = 0.5 + random();
+ writeLight(bytes, index, {
+ position, type: TYPE_AREA_RECT, radiance, direction, sizeU: width, sizeV: height, areaOrSolidAngle: width * height,
+ });
+ } else {
+ writeLight(bytes, index, {
+ position, type: TYPE_SUN, radiance, direction, cosHalfAngle: Math.cos(0.005), areaOrSolidAngle: 6.8e-5,
+ });
+ }
+ }
+ return bytes;
+}
+
+function makeTriangles(count, seed) {
+ const random = createRandom(seed);
+ const bytes = new Uint8Array(Math.max(1, count) * TRIANGLE_BYTES);
+ for (let index = 0; index < count; index++) {
+ const floats = new Float32Array(bytes.buffer, index * TRIANGLE_BYTES, TRIANGLE_BYTES / 4);
+ const words = new Uint32Array(bytes.buffer, index * TRIANGLE_BYTES, TRIANGLE_BYTES / 4);
+ const origin = [random() * 40 - 20, random() * 10, random() * 40 - 20];
+ const edgeOne = [random() - 0.5, random() - 0.5, random() - 0.5];
+ const edgeTwo = [random() - 0.5, random() - 0.5, random() - 0.5];
+ const cross = [
+ edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1],
+ edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2],
+ edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0],
+ ];
+ const crossLength = Math.hypot(...cross);
+ floats.set(origin, 0);
+ floats[3] = 0.5 * crossLength;
+ floats.set(edgeOne, 4);
+ floats.set(edgeTwo, 8);
+ floats.set(cross.map((value) => value / crossLength), 12);
+ floats.set([1 + random() * 4, 1 + random() * 4, 1 + random() * 4], 16);
+ words[22] = 1;
+ }
+ return bytes;
+}
+
+function readNode(tree, index) {
+ const offset = index * LIGHT_TREE_NODE_BYTES;
+ const floats = new Float32Array(tree.nodes.buffer, offset, 16);
+ const words = new Uint32Array(tree.nodes.buffer, offset, 16);
+ const ints = new Int32Array(tree.nodes.buffer, offset, 16);
+ return {
+ boxMin: [floats[0], floats[1], floats[2]],
+ energy: floats[3],
+ boxMax: [floats[4], floats[5], floats[6]],
+ thetaO: floats[7],
+ axis: [floats[8], floats[9], floats[10]],
+ thetaE: floats[11],
+ leftChild: ints[12],
+ rightOrFirst: words[13],
+ count: words[14] & 0xffff,
+ isDistant: (words[14] & (1 << 17)) !== 0,
+ maskOr: words[15],
+ isLeaf: ints[12] < 0,
+ };
+}
+
+function readEmitter(tree, slot) {
+ const offset = slot * LIGHT_TREE_EMITTER_BYTES;
+ const floats = new Float32Array(tree.emitters.buffer, offset, 8);
+ const words = new Uint32Array(tree.emitters.buffer, offset, 8);
+ return {
+ energy: floats[0],
+ thetaO: floats[1],
+ thetaE: floats[2],
+ isTriangle: (words[3] & 1) !== 0,
+ isDistant: (words[3] & 2) !== 0,
+ depth: words[3] >>> 8,
+ recordIndex: words[4],
+ leafIndex: words[5],
+ trailLow: words[6],
+ trailHigh: words[7],
+ };
+}
+
+function normalize(vector) {
+ const length = Math.hypot(...vector);
+ return vector.map((value) => value / length);
+}
+
+function angleBetween(a, b) {
+ const dot = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+ return Math.acos(Math.min(1, Math.max(-1, dot)));
+}
+
+// The geometry of one emitter as the test reads it back from the packed records.
+function describeEmitter(lights, triangles, lightCount, unifiedIndex) {
+ if (unifiedIndex < lightCount) {
+ const floats = new Float32Array(lights.buffer, unifiedIndex * LIGHT_BYTES, LIGHT_BYTES / 4);
+ const position = [floats[0], floats[1], floats[2]];
+ const type = new Uint32Array(lights.buffer, unifiedIndex * LIGHT_BYTES, 4)[3];
+ const direction = normalize([floats[8], floats[9], floats[10]]);
+ if (type === TYPE_SUN) {
+ return { axis: direction, normal: null, boxMin: null, boxMax: null };
+ }
+ let extent = [floats[11], floats[11], floats[11]];
+ if (type === TYPE_AREA_RECT) {
+ extent = [0, 1, 2].map(
+ (axis) => 0.5 * floats[15] * Math.abs(floats[12 + axis]) + 0.5 * floats[19] * Math.abs(floats[16 + axis])
+ );
+ }
+ return {
+ axis: direction,
+ normal: type === TYPE_AREA_RECT || type === TYPE_SPOT ? direction : null,
+ normalSlack: 2e-3,
+ boxMin: position.map((value, axis) => value - extent[axis]),
+ boxMax: position.map((value, axis) => value + extent[axis]),
+ };
+ }
+ const triangleIndex = unifiedIndex - lightCount;
+ const floats = new Float32Array(triangles.buffer, triangleIndex * TRIANGLE_BYTES, TRIANGLE_BYTES / 4);
+ const origin = [floats[0], floats[1], floats[2]];
+ const vertices = [
+ origin,
+ origin.map((value, axis) => value + floats[4 + axis]),
+ origin.map((value, axis) => value + floats[8 + axis]),
+ ];
+ return {
+ axis: normalize([-floats[4], -floats[5], -floats[6]]),
+ normal: [floats[12], floats[13], floats[14]],
+ // A double-sided triangle cone is centred on an in-plane axis, so its normal is a quarter turn from it.
+ normalSlack: Math.PI / 2 + 2e-3,
+ boxMin: [0, 1, 2].map((axis) => Math.min(...vertices.map((vertex) => vertex[axis]))),
+ boxMax: [0, 1, 2].map((axis) => Math.max(...vertices.map((vertex) => vertex[axis]))),
+ };
+}
+
+function boxInside(innerMin, innerMax, outerMin, outerMax, slack = 1e-4) {
+ return [0, 1, 2].every(
+ (axis) => innerMin[axis] >= outerMin[axis] - slack && innerMax[axis] <= outerMax[axis] + slack
+ );
+}
+
+// Walks the whole tree and returns every leaf with the chain of ancestors above it.
+function collectLeaves(tree) {
+ const leaves = [];
+ const visit = (nodeIndex, ancestors, depth, trailLow) => {
+ const node = readNode(tree, nodeIndex);
+ if (node.isLeaf) {
+ leaves.push({ nodeIndex, node, ancestors, depth, trailLow });
+ return;
+ }
+ visit(node.leftChild, [...ancestors, nodeIndex], depth + 1, trailLow);
+ visit(node.rightOrFirst, [...ancestors, nodeIndex], depth + 1, (trailLow | (1 << depth)) >>> 0);
+ };
+ visit(0, [], 0, 0);
+ return leaves;
+}
+
+function checkTreeInvariants(tree, lights, triangles, lightCount, triangleCount) {
+ const totalEmitters = lightCount + triangleCount;
+ const leaves = collectLeaves(tree);
+ const seenUnified = new Set();
+ const seenSlots = new Set();
+
+ for (const leaf of leaves) {
+ assert.ok(leaf.node.count >= 1, 'a leaf holds at least one emitter');
+ if (!leaf.node.isDistant) {
+ assert.ok(leaf.node.count <= LEAF_LIMIT || leaf.depth >= 24, `leaf ${leaf.nodeIndex} holds ${leaf.node.count} emitters`);
+ }
+ let energySum = 0;
+ for (let offset = 0; offset < leaf.node.count; offset++) {
+ const slot = leaf.node.rightOrFirst + offset;
+ assert.ok(!seenSlots.has(slot), `slot ${slot} appears in two leaves`);
+ seenSlots.add(slot);
+ const emitter = readEmitter(tree, slot);
+ assert.equal(emitter.leafIndex, leaf.nodeIndex, 'emitter points at its leaf');
+ assert.equal(emitter.depth, leaf.depth, 'emitter depth is its leaf depth');
+ assert.equal(emitter.trailLow, leaf.trailLow, 'trail bits describe the path from the root');
+ assert.equal(emitter.trailHigh, 0);
+ const unifiedIndex = emitter.isTriangle ? lightCount + emitter.recordIndex : emitter.recordIndex;
+ assert.ok(!seenUnified.has(unifiedIndex), `emitter ${unifiedIndex} appears in two leaves`);
+ seenUnified.add(unifiedIndex);
+ assert.equal(tree.lightToTree[unifiedIndex], slot, 'light_to_tree inverts the emitter order');
+ energySum += emitter.energy;
+
+ const geometry = describeEmitter(lights, triangles, lightCount, unifiedIndex);
+ for (const ancestorIndex of [leaf.nodeIndex, ...leaf.ancestors.slice().reverse()]) {
+ const ancestor = readNode(tree, ancestorIndex);
+ if (geometry.boxMin && !ancestor.isDistant) {
+ assert.ok(
+ boxInside(geometry.boxMin, geometry.boxMax, ancestor.boxMin, ancestor.boxMax),
+ `emitter ${unifiedIndex} lies inside the box of node ${ancestorIndex}`
+ );
+ }
+ assert.ok(
+ Math.min(Math.PI, angleBetween(ancestor.axis, geometry.axis) + emitter.thetaO) <= ancestor.thetaO + 2e-3,
+ `node ${ancestorIndex} cone contains the cone of emitter ${unifiedIndex}`
+ );
+ assert.ok(ancestor.thetaE >= emitter.thetaE - 1e-6, `node ${ancestorIndex} keeps the widest theta_e`);
+ if (geometry.normal) {
+ assert.ok(
+ angleBetween(ancestor.axis, geometry.normal) <= ancestor.thetaO + geometry.normalSlack,
+ `node ${ancestorIndex} cone reaches the normal of emitter ${unifiedIndex}`
+ );
+ }
+ }
+ }
+ assert.ok(
+ Math.abs(leaf.node.energy - energySum) <= 1e-5 * Math.max(1, energySum),
+ `leaf ${leaf.nodeIndex} energy is the sum of its emitters`
+ );
+ }
+ assert.equal(seenUnified.size, totalEmitters, 'every emitter is in exactly one leaf');
+ assert.equal(seenSlots.size, totalEmitters);
+
+ for (let nodeIndex = 0; nodeIndex < tree.nodeCount; nodeIndex++) {
+ const node = readNode(tree, nodeIndex);
+ if (node.isLeaf) {
+ continue;
+ }
+ const left = readNode(tree, node.leftChild);
+ const right = readNode(tree, node.rightOrFirst);
+ assert.ok(
+ Math.abs(node.energy - (left.energy + right.energy)) <= 1e-5 * Math.max(1, node.energy),
+ `node ${nodeIndex} energy equals the sum of its children`
+ );
+ assert.equal(node.maskOr, (left.maskOr | right.maskOr) >>> 0);
+ for (const child of [left, right]) {
+ if (!child.isDistant && child.energy > 0) {
+ assert.ok(boxInside(child.boxMin, child.boxMax, node.boxMin, node.boxMax), `child box inside the box of node ${nodeIndex}`);
+ }
+ }
+ }
+}
+
+
+test('every emitter is in exactly one leaf and the node invariants hold for lights and triangles', () => {
+ const lights = makeLights(60, 11);
+ const triangles = makeTriangles(140, 12);
+ const tree = buildLightTree(lights, 60, triangles, 140);
+ assert.equal(tree.emitterCount, 200);
+ assert.ok(tree.nodeCount > 1);
+ assert.equal(tree.nodes.byteLength, tree.nodeCount * LIGHT_TREE_NODE_BYTES);
+ assert.equal(tree.emitters.byteLength, 200 * LIGHT_TREE_EMITTER_BYTES);
+ checkTreeInvariants(tree, lights, triangles, 60, 140);
+});
+
+test('sun lights form one distant leaf on the right of the root, outside the local tree', () => {
+ const lights = makeLights(40, 21, { includeSun: true });
+ const tree = buildLightTree(lights, 40, makeTriangles(30, 22), 30);
+ checkTreeInvariants(tree, lights, makeTriangles(30, 22), 40, 30);
+ const root = readNode(tree, 0);
+ assert.ok(!root.isLeaf);
+ const distant = readNode(tree, root.rightOrFirst);
+ assert.ok(distant.isLeaf && distant.isDistant);
+ assert.equal(distant.count, 1);
+ const sun = readEmitter(tree, distant.rightOrFirst);
+ assert.ok(sun.isDistant);
+ assert.equal(sun.recordIndex, 39);
+ assert.equal(sun.depth, 1);
+ assert.equal(sun.trailLow, 1);
+ const lightLeaf = new Uint32Array(lights.buffer, 39 * LIGHT_BYTES, 32)[27];
+ assert.equal(lightLeaf, 0, 'the packed record is untouched by the builder');
+ assert.equal(tree.lightLeafIndices[39], root.rightOrFirst);
+});
+
+test('a scene with only a sun is one distant leaf and an empty scene has no nodes', () => {
+ const sunOnly = makeLights(1, 3, { includeSun: true });
+ const tree = buildLightTree(sunOnly, 1, new Uint8Array(TRIANGLE_BYTES), 0);
+ assert.equal(tree.nodeCount, 1);
+ assert.ok(readNode(tree, 0).isDistant);
+
+ const empty = buildLightTree(new Uint8Array(LIGHT_BYTES), 0, new Uint8Array(TRIANGLE_BYTES), 0);
+ assert.equal(empty.nodeCount, 0);
+ assert.equal(empty.emitterCount, 0);
+ assert.equal(empty.nodes.byteLength, LIGHT_TREE_NODE_BYTES);
+});
+
+test('the same input gives byte-identical output, also from copied buffers', () => {
+ const lights = makeLights(120, 31, { includeSun: true });
+ const triangles = makeTriangles(300, 32);
+ const first = buildLightTree(lights, 120, triangles, 300);
+ const second = buildLightTree(lights.slice(), 120, triangles.slice(), 300);
+ assert.deepEqual(first.nodes, second.nodes);
+ assert.deepEqual(first.emitters, second.emitters);
+ assert.deepEqual(first.lightToTree, second.lightToTree);
+});
+
+test('co-located emitters and emitters on one plane still build balanced trees within the leaf limit', () => {
+ const lights = new Uint8Array(100 * LIGHT_BYTES);
+ for (let index = 0; index < 100; index++) {
+ writeLight(lights, index, {
+ position: [1, 2, 3], type: TYPE_POINT, radiance: [1, 1, 1], direction: [0, 0, -1], radius: 0.1,
+ });
+ }
+ const colocated = buildLightTree(lights, 100, new Uint8Array(TRIANGLE_BYTES), 0);
+ checkTreeInvariants(colocated, lights, new Uint8Array(TRIANGLE_BYTES), 100, 0);
+
+ const planar = new Uint8Array(100 * LIGHT_BYTES);
+ for (let index = 0; index < 100; index++) {
+ writeLight(planar, index, {
+ position: [5, index % 10, Math.floor(index / 10)], type: TYPE_POINT, radiance: [1, 1, 1], direction: [0, 0, -1],
+ });
+ }
+ const planarTree = buildLightTree(planar, 100, new Uint8Array(TRIANGLE_BYTES), 0);
+ checkTreeInvariants(planarTree, planar, new Uint8Array(TRIANGLE_BYTES), 100, 0);
+});
+
+test('a tight spatial cluster of lights splits from a far one so the tree separates them', () => {
+ const lights = new Uint8Array(20 * LIGHT_BYTES);
+ for (let index = 0; index < 20; index++) {
+ const cluster = index < 10 ? 0 : 1000;
+ writeLight(lights, index, {
+ position: [cluster + (index % 10) * 0.01, 0, 0], type: TYPE_POINT, radiance: [1, 1, 1], direction: [0, 0, -1], radius: 0.01,
+ });
+ }
+ const tree = buildLightTree(lights, 20, new Uint8Array(TRIANGLE_BYTES), 0);
+ const root = readNode(tree, 0);
+ const left = readNode(tree, root.leftChild);
+ const right = readNode(tree, root.rightOrFirst);
+ assert.ok(left.boxMax[0] < 1 || right.boxMax[0] < 1, 'one child holds only the near cluster');
+ assert.ok(left.boxMin[0] > 100 || right.boxMin[0] > 100, 'the other holds only the far cluster');
+});
+
+test('cone merge contains both inputs and the measure grows with the cone', () => {
+ const coneA = { axis: [1, 0, 0], thetaO: 0.2, thetaE: 0.3 };
+ const coneB = { axis: [0, 1, 0], thetaO: 0.1, thetaE: 0.5 };
+ const merged = mergeCones(coneA, coneB);
+ for (const cone of [coneA, coneB]) {
+ assert.ok(Math.min(Math.PI, angleBetween(merged.axis, cone.axis) + cone.thetaO) <= merged.thetaO + 1e-9);
+ }
+ assert.equal(merged.thetaE, 0.5);
+ assert.ok(coneMeasure(merged) > coneMeasure(coneA));
+ assert.equal(coneMeasure({ axis: [0, 0, 0], thetaO: 0, thetaE: 0 }), 0);
+ const opposite = mergeCones({ axis: [1, 0, 0], thetaO: 0, thetaE: 0 }, { axis: [-1, 0, 0], thetaO: 0, thetaE: 0 });
+ assert.ok(Math.abs(Math.hypot(...opposite.axis) - 1) < 1e-9);
+ assert.ok(opposite.thetaO >= Math.PI / 2 - 1e-9);
+
+ const nearlyOpposite = [
+ { axis: [1, 0, 0], thetaO: 0.3, thetaE: 0 },
+ { axis: normalize([-1, 0.02, 0]), thetaO: 0.1, thetaE: 0 },
+ ];
+ const nearlyOppositeMerge = mergeCones(nearlyOpposite[0], nearlyOpposite[1]);
+ for (const cone of nearlyOpposite) {
+ const reach = Math.min(Math.PI, angleBetween(nearlyOppositeMerge.axis, cone.axis) + cone.thetaO);
+ assert.ok(reach <= nearlyOppositeMerge.thetaO + 1e-9, 'a near-opposite merge still contains both cones');
+ }
+});
+
+test('500 lights build in bounded time and 5000 emitters stay within the invariants', () => {
+ const lights = makeLights(500, 41);
+ const started = performance.now();
+ const tree = buildLightTree(lights, 500, new Uint8Array(TRIANGLE_BYTES), 0);
+ const elapsedMilliseconds = performance.now() - started;
+ assert.ok(elapsedMilliseconds < 5000, `500 lights took ${elapsedMilliseconds.toFixed(0)} ms`);
+ checkTreeInvariants(tree, lights, new Uint8Array(TRIANGLE_BYTES), 500, 0);
+
+ const bigLights = makeLights(1000, 42);
+ const bigTriangles = makeTriangles(4000, 43);
+ const bigTree = buildLightTree(bigLights, 1000, bigTriangles, 4000);
+ checkTreeInvariants(bigTree, bigLights, bigTriangles, 1000, 4000);
+});
+
+test('the boundary rejects bad counts, short buffers, non-finite values and unknown light types', () => {
+ const lights = makeLights(2, 51);
+ const triangles = makeTriangles(1, 52);
+ assert.throws(() => buildLightTree(lights, -1, triangles, 1), /non-negative integer/);
+ assert.throws(() => buildLightTree(lights, 2.5, triangles, 1), /non-negative integer/);
+ assert.throws(() => buildLightTree(lights, 3, triangles, 1), /fewer than 3 records of 128 bytes/);
+ assert.throws(() => buildLightTree(lights, 2, triangles, 2), /fewer than 2 records of 96 bytes/);
+ assert.throws(() => buildLightTree([], 0, triangles, 1), /Uint8Array/);
+ assert.throws(
+ () => buildLightTree(lights, 2, triangles, LIGHT_TREE_MAX_EMITTERS),
+ new RegExp(`exceed the limit of ${LIGHT_TREE_MAX_EMITTERS}`)
+ );
+ const broken = lights.slice();
+ new Float32Array(broken.buffer, 0, 1)[0] = Number.NaN;
+ assert.throws(() => buildLightTree(broken, 2, triangles, 1), /analytic light 0 has a non-finite value/);
+ const unknownType = lights.slice();
+ new Uint32Array(unknownType.buffer, 0, 4)[3] = 9;
+ assert.throws(() => buildLightTree(unknownType, 2, triangles, 1), /unknown light_type 9/);
+});
+
+test('buildNativeInputV2 packs the tree, fills tree_leaf_index and keeps counts consistent', () => {
+ const camera = createCamera({ eye: [0, 0, 6], target: [0, 0, 0], fov: 50 }, 16, 16);
+ const quad = {
+ positions: new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]),
+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
+ uvs: new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]),
+ colors: new Float32Array(12).fill(1),
+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
+ };
+ const v2 = buildNativeInputV2(
+ {
+ materials: [{ color: [0.8, 0.8, 0.8] }, { color: [1, 1, 1], emission: 5 }],
+ instances: [
+ { geometry: quad, matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], materialIndex: 0 },
+ { geometry: quad, matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 3, 0, 1], materialOverride: 1 },
+ ],
+ lights: {
+ points: [
+ { position: [2, 2, 2], intensity: 10, radius: 0.1 },
+ { position: [-3, 1, 0], intensity: 4 },
+ ],
+ sun: { color: [1, 1, 1], direction: [0, 1, 0.2] },
+ },
+ },
+ camera,
+ { width: 16, height: 16, samples: 1 }
+ );
+ assert.equal(v2.lightCount, 3);
+ assert.equal(v2.emissiveTriangleCount, 2);
+ assert.equal(v2.lightTreeEmitterCount, 5);
+ assert.ok(v2.lightTreeNodeCount >= 3);
+ assert.equal(v2.lightTreeNodes.byteLength, v2.lightTreeNodeCount * LIGHT_TREE_NODE_BYTES);
+ assert.equal(v2.lightTreeEmitters.byteLength, 5 * LIGHT_TREE_EMITTER_BYTES);
+ assert.equal(v2.lightToTree.length, 5);
+ const tree = {
+ nodes: v2.lightTreeNodes,
+ nodeCount: v2.lightTreeNodeCount,
+ emitters: v2.lightTreeEmitters,
+ lightToTree: v2.lightToTree,
+ };
+ checkTreeInvariants(tree, v2.lights, v2.emissiveTriangles, 3, 2);
+ for (let index = 0; index < 3; index++) {
+ const leafIndex = new Uint32Array(v2.lights.buffer, v2.lights.byteOffset + index * LIGHT_BYTES, 32)[27];
+ const slot = v2.lightToTree[index];
+ assert.equal(leafIndex, readEmitter(tree, slot).leafIndex, `light ${index} tree_leaf_index names its leaf`);
+ }
+ const kp = new Uint32Array(v2.kernelParams.buffer, v2.kernelParams.byteOffset, 80);
+ assert.equal(kp[26], v2.lightTreeNodeCount, 'kernel params carry the node count');
+});