3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Carry a per-light bounce limit to Cook (#2015)
Nguyen Xuan Anc37ba851b7dc
diff --git a/.github/workflows/cook-addon.yml b/.github/workflows/cook-addon.ymlindex 178f4e62..1740d307 100644--- a/.github/workflows/cook-addon.yml+++ b/.github/workflows/cook-addon.yml@@ -391,6 +391,7 @@ on:- 'tests/native-session.test.js'- 'tests/native-shadow-only.test.js'- 'tests/native-shared-material-records.test.js'+ - 'tests/native-light-bounce-limit.test.js'- 'tests/native-soft-falloff-light.test.js'- 'tests/native-surface-depth.test.js'- 'tests/native-temporal.test.js'diff --git a/changes/2015.md b/changes/2015.mdnew file mode 100644index 00000000..76b33c62--- /dev/null+++ b/changes/2015.md@@ -0,0 +1 @@+- A light takes `maxBounces` and the sun `environment.sunMaxBounces`, a per-light bounce limit like a Cycles light's `max_bounces` that the native `cycles` kernel honours; the Blender add-on writes it for lights limited below the scene (#2015)diff --git a/docs/cycles-parity.md b/docs/cycles-parity.mdindex 39adec39..59b14f70 100644--- a/docs/cycles-parity.md+++ b/docs/cycles-parity.md@@ -1092,6 +1092,8 @@ The bridge is not exact. Cycles on the exported JSON has a mean radiance of 0.17The gap is now the other way round: the export is 1.6 times brighter, not 10 times dimmer, so the sun fix is in and the sun-only gate is not met. The sun in the file has a per-light limit of 2 bounces (`cyclesSettings.max_bounces`), which the JSON format cannot carry, so the original's sun light stops at two bounces and the export's runs to eight. Capping the whole export at 2 bounces lands within 4 to 9 percent of the original `[inferred: it caps camera paths and every other light as well, which are off here, so only the sun matters; a run that clears the sun's limit in the original would settle it]`; the remainder is not explained. Cook was not measured: its native addon is not built on this machine. This does not affect the Cook against Cycles comparison above, which reads one file on both sides; it means the scene Cook was tested on is a faithful reading of the Classroom only in its camera, the 886 instances it exports, the sun and the world.+Since #2015 the format carries it: the exporter writes `environment.sunMaxBounces` (and `maxBounces` on point, spot and area lights) for every light whose own limit is below the scene's, and the native `cycles` kernel stops that light after its bounces ([lighting guide](lighting.md#a-lights-own-bounce-limit)). A light without the field runs as before, so no scene changes unless it names a limit. Not measured yet: the Classroom sun-only run against the original needs the GPU, so the "within 10 percent mean RGB" gate stays open until it is rendered.+### CommandsOn a machine with Blender 5.3, Node, `uv` and the built Cook addon (a GPU):diff --git a/docs/lighting.md b/docs/lighting.mdindex 2783beb3..93e637d6 100644--- a/docs/lighting.md+++ b/docs/lighting.md@@ -93,6 +93,12 @@ A point light casts a shadow only with `castShadow: true` (see [Local shadows](#Method: representative point, not a light-transform lookup table. The closest point of the rectangle to the shaded point stands in for the source, and the light is `intensity * cos(emission) / (d^2 + area / pi)`. The `area / pi` term keeps it finite at the surface and equals a disc source on its axis. Measured against Cycles on a white plane, a Blender area light of W watts matches `W / pi` candela, and this formula is within 1.2 percent on the axis for 1 m and 2 m squares from 0.2 m to 2 m away (measured). Off-axis error and the shape of a specular highlight are not measured: the highlight is a point highlight from the representative point, so a large panel does not give a stretched reflection. A rectangle seen from behind gives no light. An area light casts a shadow only with `castShadow: true` (see [Soft area shadows, soft sun and IES profiles](#soft-area-shadows-soft-sun-and-ies-profiles)).+## A light's own bounce limit++A point, spot or area light takes `maxBounces`, and the sun takes `environment.sunMaxBounces`: a whole number from 0 to 254 that stops the light after that many bounces, as the `max_bounces` of a Cycles light. A light with limit 2 adds direct light at the camera hit and the first two bounces, and a bounced ray that reaches it counts only from those same vertices. The scene's own bounces still apply on top. Leave it out for no limit, which is the default and draws what it always did. Anything but a whole number in range stops the build with the range to pass.++Only the native `cycles` path tracer reads it; the other tracers run every light to the scene's bounces, and `describeIgnoredFeatures` says so. The Blender add-on writes it for a light whose own limit is below the scene's, so a Blender scene with a sun limited to 2 bounces (the Classroom) exports the limit instead of a note. Cook keeps it in bits 8 to 15 of the light record's flags ([FORMAT-v2.md](https://github.com/codepawl/cook/blob/main/FORMAT-v2.md)). Cycles parity: [the Classroom sun gap](https://github.com/codepawl/crucible/blob/main/docs/cycles-parity.md).+## Light counts and frame costA frame takes at most 16 point lights, 8 spot lights and 7 area lights, and `agent-look`, the scene capabilities (`maxPointLights`, `maxSpotLights`, `maxAreaLights`) and the light bake use the same numbers. The three limits and the sun share the 32 bits of the light-linking mask, which is why the area limit is 7 and not 8: 1 + 16 + 8 + 7 fills all 32 bits. The uniform arrays are not the constraint (an area light takes four vec4 uniforms, so even 16 fit the 1,024 fragment uniform vectors of a typical GPU), so raising one limit means widening the mask for every shader, or giving bits back from another kind; neither was done. A list over its limit throws an error that names the limit, this reason and the ways around it: merge lights into a wider or brighter one, light the room with an HDRI or emissive parts, or render with `backend: native`, which takes 256 lights and ignores the mask. Every light is added in a loop in the fragment shader, so a frame costs about the same for each light whether or not it reaches a pixel; a `range` lets the loop skip a light that is out of reach.diff --git a/package-lock.json b/package-lock.jsonindex fefbfb2d..074764a0 100644--- a/package-lock.json+++ b/package-lock.json@@ -18,7 +18,7 @@"crucible-mcp": "bin/crucible-mcp.mjs"},"devDependencies": {- "@codepawlhq/cook": "git+https://github.com/codepawl/cook.git#55f2448dbb5121d82a5b125c3564403b64798d03",+ "@codepawlhq/cook": "git+https://github.com/codepawl/cook.git#e95e91daf84010ce8d6a0df48d823fc77444ad3e","@codepawlhq/crucible-denoise-oidn": "file:packages/denoise-oidn","@dimforge/rapier3d-compat": "0.21.0","@modelcontextprotocol/client": "2.4.0",@@ -181,7 +181,7 @@},"node_modules/@codepawlhq/cook": {"version": "0.2.0",- "resolved": "git+https://github.com/codepawl/cook.git#55f2448dbb5121d82a5b125c3564403b64798d03",+ "resolved": "git+https://github.com/codepawl/cook.git#e95e91daf84010ce8d6a0df48d823fc77444ad3e","integrity": "sha512-GstR1TXMXVrrvAn8DC3wzBpnGjzsulzRF8bEeUHGMN1D+6Du0ORGAIilx04FlQYSPlcnih8eyYECcuPHYjR+FA==","dev": true,"license": "MIT AND Apache-2.0 AND BSD-3-Clause",diff --git a/package.json b/package.jsonindex b9ee49bd..3f0bb0ad 100644--- a/package.json+++ b/package.json@@ -288,7 +288,7 @@},"devDependencies": {"@codepawlhq/crucible-denoise-oidn": "file:packages/denoise-oidn",- "@codepawlhq/cook": "git+https://github.com/codepawl/cook.git#55f2448dbb5121d82a5b125c3564403b64798d03",+ "@codepawlhq/cook": "git+https://github.com/codepawl/cook.git#e95e91daf84010ce8d6a0df48d823fc77444ad3e","@dimforge/rapier3d-compat": "0.21.0","@modelcontextprotocol/client": "2.4.0","@modelcontextprotocol/server": "2.4.0",diff --git a/packages/blender-addon/cook_blender/blender_conversions.py b/packages/blender-addon/cook_blender/blender_conversions.pyindex 717560dc..31b0f555 100644--- a/packages/blender-addon/cook_blender/blender_conversions.py+++ b/packages/blender-addon/cook_blender/blender_conversions.py@@ -151,10 +151,24 @@ def write_radiance_hdr(path, linear_rgb_top_first):handle.write(rgbe_bytes(linear_rgb_top_first))-def light_feature_notes(light_name, light_type, use_temperature, use_shadow, diffuse_factor, specular_factor, light_max_bounces=None, scene_max_bounces=None):- """What a light carries that Cook does not read, one sentence each. Node trees are handled by `resolve_light_nodes`.+def light_bounce_limit(light_max_bounces, scene_max_bounces):+ """The light's own Cycles `max_bounces` when it stops the light short of the scene's, else None (no per-light limit to carry).- `light_max_bounces` is the light's own Cycles limit and `scene_max_bounces` the scene's; either is None when unreadable."""+ Either value is None when unreadable. A light's limit defaults to 1024, above any scene's, so most lights carry none."""+ if light_max_bounces is None or scene_max_bounces is None or light_max_bounces >= scene_max_bounces:+ return None+ return max(0, int(light_max_bounces))+++def with_bounce_limit(entry, bounce_limit):+ """The light entry with `maxBounces` set when the light has its own limit, otherwise unchanged."""+ if bounce_limit is not None:+ entry["maxBounces"] = bounce_limit+ return entry+++def light_feature_notes(light_name, light_type, use_temperature, use_shadow, diffuse_factor, specular_factor):+ """What a light carries that Cook does not read, one sentence each. Node trees are handled by `resolve_light_nodes`."""notes = []if use_temperature:notes.append(f"light {light_name} uses a blackbody temperature; Cook uses its plain colour")@@ -162,8 +176,6 @@ def light_feature_notes(light_name, light_type, use_temperature, use_shadow, difnotes.append(f"light {light_name} has shadows off; Cook casts them")if abs(diffuse_factor - 1.0) > 1e-6 or abs(specular_factor - 1.0) > 1e-6:notes.append(f"light {light_name} has a diffuse or specular factor other than 1; Cook ignores the factors")- if light_max_bounces is not None and scene_max_bounces is not None and light_max_bounces < scene_max_bounces:- notes.append(f"light {light_name} has max bounces {light_max_bounces}, below the scene's {scene_max_bounces}; not reproduced, Cook applies one bounce limit to every light")return notesdiff --git a/packages/blender-addon/cook_blender/scene_export.py b/packages/blender-addon/cook_blender/scene_export.pyindex d981ee3b..18a89cc2 100644--- a/packages/blender-addon/cook_blender/scene_export.py+++ b/packages/blender-addon/cook_blender/scene_export.py@@ -121,27 +121,33 @@ def add_light_entry(environment, light_object, light_matrix, report):for note in conversions.light_feature_notes(light_object.name, light_data.type, getattr(light_data, "use_temperature", False), getattr(light_data, "use_shadow", True),getattr(light_data, "diffuse_factor", 1.0), getattr(light_data, "specular_factor", 1.0),- getattr(getattr(light_data, "cycles", None), "max_bounces", None), getattr(getattr(bpy.context.scene, "cycles", None), "max_bounces", None),):if note not in report["notes"]:report["notes"].append(note)position = to_yup(light_matrix.translation)emission_direction = to_yup((light_matrix.to_3x3() @ Vector((0.0, 0.0, -1.0))).normalized())+ bounce_limit = conversions.light_bounce_limit(+ getattr(getattr(light_data, "cycles", None), "max_bounces", None), getattr(getattr(bpy.context.scene, "cycles", None), "max_bounces", None),+ )if light_data.type == "SUN":if report["lightCounts"].get("SUN", 0) > 0:report["notes"].append(f"sun {light_object.name} is ignored: Cook takes one sun per scene")returnenvironment.update(conversions.sun_environment_fields(color, energy, emission_direction, light_data.angle))+ if bounce_limit is not None:+ environment["sunMaxBounces"] = bounce_limitelif light_data.type == "POINT":- environment["pointLights"].append(conversions.point_light_entry(position, color, energy, light_data.shadow_soft_size))+ environment["pointLights"].append(conversions.with_bounce_limit(conversions.point_light_entry(position, color, energy, light_data.shadow_soft_size), bounce_limit))elif light_data.type == "SPOT":- environment["spotLights"].append(conversions.spot_light_entry(position, color, energy, light_data.shadow_soft_size, emission_direction, light_data.spot_size, light_data.spot_blend))+ spot_entry = conversions.spot_light_entry(position, color, energy, light_data.shadow_soft_size, emission_direction, light_data.spot_size, light_data.spot_blend)+ environment["spotLights"].append(conversions.with_bounce_limit(spot_entry, bounce_limit))elif light_data.type == "AREA":scale = light_matrix.to_scale()local_up = to_yup((light_matrix.to_3x3() @ Vector((0.0, 1.0, 0.0))).normalized())- environment["areaLights"].append(conversions.area_light_entry(+ area_entry = conversions.area_light_entry(position, color, energy, emission_direction, local_up, light_data.shape, light_data.size, light_data.size_y, scale.x, scale.y, light_data.spread,- ))+ )+ environment["areaLights"].append(conversions.with_bounce_limit(area_entry, bounce_limit))if getattr(light_data, "normalize", True) is False:report["notes"].append(f"area light {light_object.name} has Normalize off, which the bench format cannot carry")report["lightCounts"][light_data.type] = report["lightCounts"].get(light_data.type, 0) + 1diff --git a/packages/blender-addon/tests/test_blender_conversions.py b/packages/blender-addon/tests/test_blender_conversions.pyindex a3d5fbd0..2c9aac7f 100644--- a/packages/blender-addon/tests/test_blender_conversions.py+++ b/packages/blender-addon/tests/test_blender_conversions.py@@ -123,17 +123,17 @@ class LightNoteTests(unittest.TestCase):self.assertTrue(any("blackbody" in note for note in notes))self.assertTrue(any("shadows off" in note for note in notes))- def test_light_max_bounces_below_the_scene_is_named(self):- notes = conversions.light_feature_notes("Sun", "SUN", False, True, 1.0, 1.0, 2, 12)- self.assertEqual(len(notes), 1)- self.assertIn("Sun", notes[0])- self.assertIn("max bounces 2", notes[0])- self.assertIn("not reproduced", notes[0])-- def test_light_max_bounces_at_or_above_the_scene_or_unreadable_is_silent(self):- self.assertEqual(conversions.light_feature_notes("Sun", "SUN", False, True, 1.0, 1.0, 12, 12), [])- self.assertEqual(conversions.light_feature_notes("Sun", "SUN", False, True, 1.0, 1.0, 1024, 12), [])- self.assertEqual(conversions.light_feature_notes("Sun", "SUN", False, True, 1.0, 1.0, None, 12), [])+ def test_light_max_bounces_below_the_scene_is_carried_as_the_light_limit(self):+ self.assertEqual(conversions.light_bounce_limit(2, 12), 2)+ self.assertEqual(conversions.light_bounce_limit(0, 12), 0)+ entry = conversions.with_bounce_limit(conversions.point_light_entry([0, 0, 0], [1, 1, 1], 4.0 * math.pi * 10.0, 0.1), 1)+ self.assertEqual(entry["maxBounces"], 1)++ def test_light_max_bounces_at_or_above_the_scene_or_unreadable_carries_no_limit(self):+ for light_limit, scene_limit in ((12, 12), (1024, 12), (None, 12), (2, None)):+ self.assertIsNone(conversions.light_bounce_limit(light_limit, scene_limit))+ entry = conversions.with_bounce_limit(conversions.point_light_entry([0, 0, 0], [1, 1, 1], 1.0, 0.1), None)+ self.assertNotIn("maxBounces", entry)def emission_tree(strength_input, colour_input, extra_nodes=None):diff --git a/src/path-tracer-gpu-pack.js b/src/path-tracer-gpu-pack.jsindex f23beed2..ea1bfcdd 100644--- a/src/path-tracer-gpu-pack.js+++ b/src/path-tracer-gpu-pack.js@@ -241,9 +241,13 @@ export function packSubsurface(materials) {const LIGHT_TYPES = { point: 0, spot: 1, area: 2 };+// The light's own bounce limit plus one (its `maxBounces`, already checked by buildTraceScene), or 0 for none.+const bounceLimitCode = light => (light.maxBounces === undefined ? 0 : light.maxBounces + 1);+/*** Six texels per point, spot or area light, in the order the tracer samples them. The third float of the last texel is 1 for a point or- * spot light with `softFalloff` (an oriented disk, read by the `cycles` kernel only) and 0 for every other light.+ * spot light with `softFalloff` (an oriented disk, read by the `cycles` kernel only) and 0 for every other light. The fourth float is+ * the light's own bounce limit plus one (0 for none), also read by the `cycles` kernel only.*/export function packLights(lights) {const entries = [@@ -261,13 +265,13 @@ export function packLights(lights) {data.set([...light.normal, light.width], base + 8);data.set([...light.across, light.height], base + 12);data.set([...light.along, 0], base + 16);- data.set([light.intensity, 0, 0, 0], base + 20);+ data.set([light.intensity, 0, 0, bounceLimitCode(light)], base + 20);return;}data.set([...(light.direction ?? [0, 0, 0]), light.radius], base + 8);data.set([0, 0, 0, light.cosineHalfAngle ?? 0], base + 12);data.set([0, 0, 0, light.blend ?? 0], base + 16);- data.set([light.intensity, light.range, light.softFalloff === true ? 1 : 0, 0], base + 20);+ data.set([light.intensity, light.range, light.softFalloff === true ? 1 : 0, bounceLimitCode(light)], base + 20);});return { table, count: entries.length };}diff --git a/src/path-tracer-scene.js b/src/path-tracer-scene.jsindex 0c990e62..36b3f6f1 100644--- a/src/path-tracer-scene.js+++ b/src/path-tracer-scene.js@@ -449,6 +449,21 @@ function softFalloffOf(light, label) {return light.softFalloff ? { softFalloff: true } : {};}+// The most bounces a light's own limit may name: Cook keeps it in 8 bits as the limit plus one.+const MAXIMUM_LIGHT_BOUNCES = 254;++/**+ * A light's own bounce limit, as the `max_bounces` of a Cycles light: the light adds direct light only at path vertices 0 to the limit,+ * on top of the scene's bounces. Left out, the light runs to the scene limit. Only the native cycles kernel reads it.+ */+function maxBouncesOf(value, label) {+ if (value === undefined) return {};+ if (!Number.isInteger(value) || value < 0 || value > MAXIMUM_LIGHT_BOUNCES) {+ throw new RangeError(`${label} is a whole number of bounces from 0 to ${MAXIMUM_LIGHT_BOUNCES}, got ${JSON.stringify(value)}. Leave it out for no limit beyond the scene's bounces.`);+ }+ return { maxBounces: value };+}+// Missing colour and intensity default as in the rasterizer (lighting.js); a value that is given must be usable.function lightEmission(light, label) {const color = light.color ?? [1, 1, 1];@@ -476,7 +491,7 @@ function resolveAreaLight(light, index) {}const across = rawAcrossLength < MINIMUM_ACROSS_LENGTH ? [1, 0, 0] : normalized(rawAcross);const along = [normal[1] * across[2] - normal[2] * across[1], normal[2] * across[0] - normal[0] * across[2], normal[0] * across[1] - normal[1] * across[0]];- return { bit: AREA_FIRST_BIT + index, position: light.position, ...lightEmission(light, label), width: light.width, height: light.height, normal, across, along, profile: traceProfile(light) };+ return { bit: AREA_FIRST_BIT + index, position: light.position, ...lightEmission(light, label), width: light.width, height: light.height, normal, across, along, profile: traceProfile(light), ...maxBouncesOf(light.maxBounces, `${label}.maxBounces`) };}/**@@ -530,10 +545,14 @@ function resolveLights(environment, limit = resolveLightLimit(), parts = []) {refuseLinkingBeyondMaskBits(environment, parts);}return {- sun: sunPower > 0 ? { bit: SUN_BIT, direction: normalized(environment.lightDirection ?? [0, 1, 0]), color: sunColor, angularRadius: environment.sunAngularRadius ?? SUN_ANGULAR_RADIUS } : null,- points: (environment.pointLights ?? []).map((light, index) => ({ bit: POINT_FIRST_BIT + index, position: light.position, ...lightEmission(light, `environment.pointLights[${index}]`), radius: light.radius ?? 0, range: light.range ?? 0, ...softFalloffOf(light, `environment.pointLights[${index}]`) })),+ sun: sunPower > 0 ? { bit: SUN_BIT, direction: normalized(environment.lightDirection ?? [0, 1, 0]), color: sunColor, angularRadius: environment.sunAngularRadius ?? SUN_ANGULAR_RADIUS, ...maxBouncesOf(environment.sunMaxBounces, 'environment.sunMaxBounces') } : null,+ points: (environment.pointLights ?? []).map((light, index) => ({+ bit: POINT_FIRST_BIT + index, position: light.position, ...lightEmission(light, `environment.pointLights[${index}]`), radius: light.radius ?? 0, range: light.range ?? 0, ...softFalloffOf(light, `environment.pointLights[${index}]`),+ ...maxBouncesOf(light.maxBounces, `environment.pointLights[${index}].maxBounces`),+ })),spots: (environment.spotLights ?? []).map((light, index) => ({bit: SPOT_FIRST_BIT + index, position: light.position, ...lightEmission(light, `environment.spotLights[${index}]`), radius: light.radius ?? 0, range: light.range ?? 0, ...softFalloffOf(light, `environment.spotLights[${index}]`),+ ...maxBouncesOf(light.maxBounces, `environment.spotLights[${index}].maxBounces`),direction: normalized(light.direction),cosineHalfAngle: Math.cos(light.angle),profile: traceProfile(light),diff --git a/src/path-tracer.js b/src/path-tracer.jsindex fa940988..76c0354f 100644--- a/src/path-tracer.js+++ b/src/path-tracer.js@@ -1048,6 +1048,9 @@ export function describeIgnoredFeatures(parts, environment, backend = 'cpu', { kif (fog?.density > 0 && fog.ambient) notes.add('volumeFog.ambient is not added: the fog is lit by the traced lights and sky.');const hasSoftFalloff = [...(environment?.pointLights ?? []), ...(environment?.spotLights ?? [])].some(light => light.softFalloff === true);if (hasSoftFalloff && !kernelMaterials) notes.add('softFalloff is ignored: only the native cycles kernel draws a light as an oriented disk, the other tracers draw a sphere.');+ const lightsWithOwnLimit = [...(environment?.pointLights ?? []), ...(environment?.spotLights ?? []), ...(environment?.areaLights ?? [])];+ const hasBounceLimit = environment?.sunMaxBounces !== undefined || lightsWithOwnLimit.some(light => light.maxBounces !== undefined);+ if (hasBounceLimit && !kernelMaterials) notes.add('A light maxBounces (sunMaxBounces for the sun) is ignored: only the native cycles kernel stops a light after its own bounces, the other tracers run every light to the scene bounces.');const hasPortal = (environment?.areaLights ?? []).some(light => light.portal === true);if (hasPortal && !kernelMaterials && backend === 'gpu') notes.add('Light portals (areaLights with portal: true) are ignored: only the native cycles kernel, the CPU tracer and the WebGPU tracer sample the environment through them, the other tracers draw no light from a portal.');const hasGridVolume = (environment?.localVolumes ?? []).some(volume => volume?.shape === 'grid');diff --git a/tests/light-bounce-limit.test.js b/tests/light-bounce-limit.test.jsnew file mode 100644index 00000000..29cdb955--- /dev/null+++ b/tests/light-bounce-limit.test.js@@ -0,0 +1,69 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import { box } from '../src/geometry.js';+import { describeIgnoredFeatures } from '../src/path-tracer.js';+import { packLights } from '../src/path-tracer-gpu-pack.js';+import { buildTraceScene } from '../src/path-tracer-scene.js';++const LIGHT_TEXEL_FLOATS = 24;+const BOUNCE_LIMIT_FLOAT_INDEX = 23;++function floorPart() {+ const matrix = new Float32Array([4, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 4, 0, 0, -0.05, 0, 1]);+ return { name: 'floor', geometry: box(0, 1), matrix, material: { color: [0.5, 0.5, 0.5] } };+}++function environmentWith(limits) {+ return {+ keyColor: [1, 1, 1],+ lightDirection: [0, 1, 0],+ ...limits.environment,+ pointLights: [{ position: [0, 2, 0], intensity: 5, radius: 0.3, ...limits.point }],+ spotLights: [{ position: [1, 3, 0], direction: [0, -1, 0], angle: 0.6, intensity: 5, radius: 0.2, ...limits.spot }],+ areaLights: [{ position: [2, 3, 0], direction: [0, -1, 0], width: 1, height: 1, intensity: 5, ...limits.area }],+ };+}++const buildLights = limits => buildTraceScene([floorPart()], environmentWith(limits)).lights;++test('a light maxBounces and the sun sunMaxBounces reach the resolved lights', () => {+ const lights = buildLights({ environment: { sunMaxBounces: 2 }, point: { maxBounces: 0 }, spot: { maxBounces: 1 }, area: { maxBounces: 254 } });+ assert.equal(lights.sun.maxBounces, 2);+ assert.equal(lights.points[0].maxBounces, 0);+ assert.equal(lights.spots[0].maxBounces, 1);+ assert.equal(lights.areas[0].maxBounces, 254);+});++test('a scene without a bounce limit resolves lights with no maxBounces field', () => {+ const lights = buildLights({});+ for (const light of [lights.sun, lights.points[0], lights.spots[0], lights.areas[0]]) {+ assert.equal('maxBounces' in light, false);+ }+});++test('a bounce limit that is not a whole number from 0 to 254 names the field and the range', () => {+ const badLimits = [-1, 255, 1.5, '2', null, Number.NaN];+ for (const bad of badLimits) {+ assert.throws(() => buildLights({ point: { maxBounces: bad } }), /environment\.pointLights\[0\]\.maxBounces is a whole number of bounces from 0 to 254/);+ assert.throws(() => buildLights({ spot: { maxBounces: bad } }), /environment\.spotLights\[0\]\.maxBounces is a whole number of bounces from 0 to 254/);+ assert.throws(() => buildLights({ area: { maxBounces: bad } }), /environment\.areaLights\[0\]\.maxBounces is a whole number of bounces from 0 to 254/);+ assert.throws(() => buildLights({ environment: { sunMaxBounces: bad } }), /environment\.sunMaxBounces is a whole number of bounces from 0 to 254/);+ }+});++test('the v1 light table carries the limit plus one in the last float of the last texel, and 0 without one', () => {+ const limited = packLights(buildLights({ point: { maxBounces: 0 }, spot: { maxBounces: 2 }, area: { maxBounces: 254 } }));+ const unlimited = packLights(buildLights({}));+ const codeOf = (packed, index) => packed.table.data[index * LIGHT_TEXEL_FLOATS + BOUNCE_LIMIT_FLOAT_INDEX];+ assert.deepEqual([codeOf(limited, 0), codeOf(limited, 1), codeOf(limited, 2)], [1, 3, 255]);+ assert.deepEqual([codeOf(unlimited, 0), codeOf(unlimited, 1), codeOf(unlimited, 2)], [0, 0, 0]);+});++test('a path tracer other than the native cycles kernel says it ignores a light bounce limit', () => {+ const limited = environmentWith({ point: { maxBounces: 2 } });+ assert.ok(describeIgnoredFeatures([], limited, 'cpu').some(note => /maxBounces .* is ignored/.test(note)));+ assert.ok(describeIgnoredFeatures([], { sunMaxBounces: 2 }, 'cpu').some(note => /maxBounces .* is ignored/.test(note)));+ assert.equal(describeIgnoredFeatures([], limited, 'cpu', { kernelMaterials: true }).some(note => /maxBounces/.test(note)), false);+ assert.equal(describeIgnoredFeatures([], environmentWith({}), 'cpu').some(note => /maxBounces/.test(note)), false);+});diff --git a/tests/native-light-bounce-limit.test.js b/tests/native-light-bounce-limit.test.jsnew file mode 100644index 00000000..c1f88760--- /dev/null+++ b/tests/native-light-bounce-limit.test.js@@ -0,0 +1,62 @@+import assert from 'node:assert/strict';++import { cookModule, cookTest } from './support/cook.js';+import { box } from '../src/geometry.js';+import { createCamera } from '../src/path-tracer.js';+import * as pack from '../src/path-tracer-gpu-pack.js';+import { buildTraceScene } from '../src/path-tracer-scene.js';++const cook = await cookModule();+const { STRUCT_STRIDES_V2, buildNativeInput, buildNativeInputV2, upgradeNativeInputV1ToV2 } = cook ?? {};++const LIGHT_FLAGS_WORD_INDEX = 7;+const LIGHT_BOUNCE_LIMIT_SHIFT = 8;+const LIGHT_BOUNCE_LIMIT_MASK = 0xff;++function floorPart() {+ const matrix = new Float32Array([4, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 4, 0, 0, -0.05, 0, 1]);+ return { name: 'floor', geometry: box(0, 1), matrix, material: { color: [0.5, 0.5, 0.5] } };+}++// A sun, a point, a spot and an area light, in the order Cook packs them.+function lampEnvironment(limits) {+ return {+ keyColor: [1, 1, 1],+ lightDirection: [0, 1, 0],+ ...limits.environment,+ pointLights: [{ position: [0, 2, 0], color: [1, 1, 1], intensity: 5, radius: 0.3, ...limits.point }],+ spotLights: [{ position: [1, 3, 0], direction: [0, -1, 0], angle: 0.6, intensity: 5, radius: 0.2, ...limits.spot }],+ areaLights: [{ position: [2, 3, 0], direction: [0, -1, 0], width: 1, height: 1, intensity: 5, ...limits.area }],+ };+}++const cameraDescription = { eye: [0, 1, 6], target: [0, 0, 0], fov: 45 };+const optionsOfPack = { width: 8, height: 8, samples: 1 };++// The limit each of the four light records carries: -1 for none, else the limit.+function packedLimits(v2) {+ const stride = STRUCT_STRIDES_V2.light;+ const words = new Uint32Array(v2.lights.buffer, v2.lights.byteOffset, v2.lights.byteLength / 4);+ return [0, 1, 2, 3].map(index => ((words[(index * stride) / 4 + LIGHT_FLAGS_WORD_INDEX] >>> LIGHT_BOUNCE_LIMIT_SHIFT) & LIGHT_BOUNCE_LIMIT_MASK) - 1);+}++const LIMITS = { environment: { sunMaxBounces: 2 }, point: { maxBounces: 0 }, spot: { maxBounces: 1 }, area: { maxBounces: 254 } };++cookTest('the v2 light records carry the limit of the sun and of each point, spot and area light', () => {+ const scene = buildTraceScene([floorPart()], lampEnvironment(LIMITS));+ const v2 = buildNativeInputV2(scene, createCamera(cameraDescription, 8, 8), optionsOfPack);+ assert.deepEqual(packedLimits(v2), [2, 0, 1, 254]);+});++cookTest('the v1 input a render job packs keeps the same limits through its upgrade to v2', () => {+ const scene = buildTraceScene([floorPart()], lampEnvironment(LIMITS));+ const v1 = buildNativeInput(scene, createCamera(cameraDescription, 8, 8), optionsOfPack, pack);+ assert.deepEqual(packedLimits(upgradeNativeInputV1ToV2(v1, optionsOfPack)), [2, 0, 1, 254]);+});++cookTest('lights without a limit pack as no limit in both input versions', () => {+ const scene = buildTraceScene([floorPart()], lampEnvironment({}));+ const camera = createCamera(cameraDescription, 8, 8);+ assert.deepEqual(packedLimits(buildNativeInputV2(scene, camera, optionsOfPack)), [-1, -1, -1, -1]);+ assert.deepEqual(packedLimits(upgradeNativeInputV1ToV2(buildNativeInput(scene, camera, optionsOfPack, pack), optionsOfPack)), [-1, -1, -1, -1]);+});