From fc047600b421bc60e8df325c88de200df72afa76 Mon Sep 17 00:00:00 2001 From: Nguyen Xuan An Date: Wed, 18 Nov 2026 02:08:30 +0700 Subject: [PATCH 1/2] Add a per-light bounce limit like Cycles' light max_bounces (codepawl/crucible#2015) A light input may carry maxBounces (0 to 254). The packer stores it as limit + 1 in bits 8 to 15 of LightRecord.flags; 0 keeps today's behaviour, so older inputs render the same and the record size does not change. The kernel adds a limited light's direct light, and its MIS hit from a bounced ray, only at path vertices 0..limit, so the sample and the hit share one rule. Tests: a pack test (no GPU) pins the bits, the default and the refusal of bad values; a trace test for a GPU runner pins the kernel on a wall that only the floor bounce lights. Not run here: the kernel was not compiled or traced on this machine. --- FORMAT-v2.md | 2 +- pack-input-v2.mjs | 18 +++++++ src/cycles/abi.wgsl | 3 ++ src/cycles/integrator.wgsl | 1 + src/cycles/lights.wgsl | 25 ++++++++++ tests/gpu/light-bounce-limit.test.mjs | 65 +++++++++++++++++++++++++ tests/light-bounce-limit.test.mjs | 69 +++++++++++++++++++++++++++ 7 files changed, 182 insertions(+), 1 deletion(-) create mode 100644 tests/gpu/light-bounce-limit.test.mjs create mode 100644 tests/light-bounce-limit.test.mjs diff --git a/FORMAT-v2.md b/FORMAT-v2.md index 16e4207..1e54fc1 100644 --- a/FORMAT-v2.md +++ b/FORMAT-v2.md @@ -303,7 +303,7 @@ Convention: `direction` is always the **unit emission direction pointing from th | `0` | `12` | `16` | `vec3` | `position` | World-space centre (`point`, `spot`, `area_rect`, `area_disk`; unused for `sun`) | | `12` | `4` | `4` | `u32` | `light_type` | `0=point`, `1=spot`, `2=area_rect`, `3=area_disk`, `4=sun` | | `16` | `12` | `16` | `vec3` | `radiance` | Emitted linear RGB radiance (`W/(sr·m²)` for finite-area/sun, intensity `W/sr` when `radius == 0`) | -| `28` | `4` | `4` | `u32` | `flags` | Bitmask: `1=CAST_SHADOW`, `2=MULTIPLE_IMPORTANCE`, `4=CAMERA_VISIBLE`, `8=PORTAL`, `16=NORMALIZE`, `32=SOFT_FALLOFF` (a point or spot light with a radius is an oriented disk facing the shading point, as Blender's `use_soft_falloff`; clear: the sphere) | +| `28` | `4` | `4` | `u32` | `flags` | Bitmask: `1=CAST_SHADOW`, `2=MULTIPLE_IMPORTANCE`, `4=CAMERA_VISIBLE`, `8=PORTAL`, `16=NORMALIZE`, `32=SOFT_FALLOFF` (a point or spot light with a radius is an oriented disk facing the shading point, as Blender's `use_soft_falloff`; clear: the sphere); bits `8..15`: the light's own bounce limit as `limit + 1` (Cycles `max_bounces` of the light), `0` for none. A limited light adds direct light, and is hit by a bounced ray, only at path vertices `0..limit`; the scene limit still applies on top | | `32` | `12` | `16` | `vec3` | `direction` | Unit world-space emission direction | | `44` | `4` | `4` | `f32` | `radius` | Sphere radius in metres for `point` / `spot` (`0.0` = delta emitter) | | `48` | `12` | `16` | `vec3` | `axis_u` | Unit tangent axis U for area / IES orientation | diff --git a/pack-input-v2.mjs b/pack-input-v2.mjs index eb204fd..c81f59b 100644 --- a/pack-input-v2.mjs +++ b/pack-input-v2.mjs @@ -93,6 +93,20 @@ const LIGHT_FLAG_CAMERA_VISIBLE = 4; const LIGHT_FLAG_PORTAL = 8; const LIGHT_FLAG_NORMALIZE = 16; const LIGHT_FLAG_SOFT_FALLOFF = 32; +// Bits 8..15 of `LightRecord.flags` hold a light's own bounce limit as `limit + 1`; 0 means the scene limit alone (FORMAT-v2.md section 6). +const LIGHT_BOUNCE_LIMIT_SHIFT = 8; +const MAXIMUM_LIGHT_BOUNCE_LIMIT = 254; + +function lightBounceLimitFlags(light, lightsField) { + if (light.maxBounces === undefined) { + return 0; + } + const limit = light.maxBounces; + if (!Number.isInteger(limit) || limit < 0 || limit > MAXIMUM_LIGHT_BOUNCE_LIMIT) { + throw new RangeError(`lights.${lightsField}.maxBounces must be a whole number from 0 to ${MAXIMUM_LIGHT_BOUNCE_LIMIT}, got ${JSON.stringify(limit)}. Leave it out for no limit beyond the scene's bounces.`); + } + return (limit + 1) << LIGHT_BOUNCE_LIMIT_SHIFT; +} const MATERIAL_FLAG_MULTISCATTER_GGX = 1; const MATERIAL_FLAG_THIN_WALLED = 2; @@ -1385,6 +1399,7 @@ function buildAnalyticLightEntries(lightsSection = {}) { if (sun.cameraVisible === true) { flags |= LIGHT_FLAG_CAMERA_VISIBLE; } + flags |= lightBounceLimitFlags(sun, 'sun'); const masks = lightBitMaskWords(sun.bit, sun.lightGroupMaskLo, sun.lightGroupMaskHi); const weight = Math.max(1e-6, Math.PI * luminance(sunColor)); records.push({ @@ -1433,6 +1448,7 @@ function buildAnalyticLightEntries(lightsSection = {}) { if (point.cameraVisible === true) { flags |= LIGHT_FLAG_CAMERA_VISIBLE; } + flags |= lightBounceLimitFlags(point, 'points[]'); const masks = lightBitMaskWords(point.bit, point.lightGroupMaskLo, point.lightGroupMaskHi); const maxDistance = point.range > 0 ? Number(point.range) : 1e30; const weight = Math.max(1e-6, 4 * Math.PI * luminance(color) * intensity); @@ -1497,6 +1513,7 @@ function buildAnalyticLightEntries(lightsSection = {}) { if (spot.cameraVisible === true) { flags |= LIGHT_FLAG_CAMERA_VISIBLE; } + flags |= lightBounceLimitFlags(spot, 'spots[]'); const masks = lightBitMaskWords(spot.bit, spot.lightGroupMaskLo, spot.lightGroupMaskHi); const maxDistance = spot.range > 0 ? Number(spot.range) : 1e30; const coneSolidAngle = Math.max(1e-4, 2 * Math.PI * Math.max(0, 1 - cosHalfAngle)); @@ -1575,6 +1592,7 @@ function buildAnalyticLightEntries(lightsSection = {}) { if (area.cameraVisible === true) { flags |= LIGHT_FLAG_CAMERA_VISIBLE; } + flags |= lightBounceLimitFlags(area, 'areas[]'); const masks = lightBitMaskWords(area.bit, area.lightGroupMaskLo, area.lightGroupMaskHi); const weight = Math.max(1e-6, Math.PI * luminance(color) * intensity); records.push({ diff --git a/src/cycles/abi.wgsl b/src/cycles/abi.wgsl index 15bb60b..634b248 100644 --- a/src/cycles/abi.wgsl +++ b/src/cycles/abi.wgsl @@ -95,6 +95,9 @@ const LIGHT_FLAG_PORTAL: u32 = 8u; const LIGHT_FLAG_NORMALIZE: u32 = 16u; // A point or spot light with a radius is an oriented disk facing the shading point (Blender's `use_soft_falloff`), not a sphere. const LIGHT_FLAG_SOFT_FALLOFF: u32 = 32u; +// Bits 8..15 of `LightRecord.flags`: the light's own bounce limit as `limit + 1`, `0` for none (FORMAT-v2.md section 6). +const LIGHT_BOUNCE_LIMIT_SHIFT: u32 = 8u; +const LIGHT_BOUNCE_LIMIT_MASK: u32 = 255u; // `MaterialRecord.flags` bits. const MATERIAL_FLAG_MULTISCATTER_GGX: u32 = 1u; diff --git a/src/cycles/integrator.wgsl b/src/cycles/integrator.wgsl index 866d0f9..ca02ce5 100644 --- a/src/cycles/integrator.wgsl +++ b/src/cycles/integrator.wgsl @@ -1190,6 +1190,7 @@ fn main(@builtin(global_invocation_id) global_id: vec3) { } } + lgt_path_bounce = bounce; let segment_end_t = select(surface_hit.t, volume_scatter_t, volume_scattered); let analytic_emission = lgt_eval_analytic_lights_along_segment( ray_origin, diff --git a/src/cycles/lights.wgsl b/src/cycles/lights.wgsl index 4a5f565..4c730ad 100644 --- a/src/cycles/lights.wgsl +++ b/src/cycles/lights.wgsl @@ -33,6 +33,9 @@ fn lgt_empty_sample() -> LgtDirectSample { // Shading point of the last surface bounce, kept for the MIS weight of the next hit. `lgt_mis_picked_by_tree` is false after a // volume scatter, whose direct light is picked from the flat analytic table. var lgt_mis_picked_by_tree: bool = false; +// Index of the path vertex the integrator is working at (0 at the camera hit), set once per path step. Per-light bounce limits +// read it: `lgt_bounce_limit_allows` for a light sample, `lgt_hit_vertex_bounce` for a ray that reached a light. +var lgt_path_bounce: u32 = 0u; var lgt_mis_position: vec3 = vec3(0.0); var lgt_mis_normal: vec3 = vec3(0.0, 0.0, 1.0); var lgt_mis_has_transmission: bool = false; @@ -657,6 +660,19 @@ fn lgt_sample_sun_light(light: LightRecord, rand_uv: vec2) -> LgtDirectSamp return out; } +// `LightRecord.flags` bits 8..15 hold a Cycles per-light `max_bounces` as `limit + 1`; `0` means the scene limit only. A light with +// limit L adds direct light at path vertices 0..L. +fn lgt_bounce_limit_allows(light: LightRecord, vertex_bounce: u32) -> bool { + let limit_code = (light.flags >> LIGHT_BOUNCE_LIMIT_SHIFT) & LIGHT_BOUNCE_LIMIT_MASK; + return limit_code == 0u || vertex_bounce < limit_code; +} + +// A ray that reaches a light was cast from the vertex before the one `lgt_path_bounce` names, and shares its MIS weight with that +// vertex's light sample, so both must pass the same limit. +fn lgt_hit_vertex_bounce() -> u32 { + return select(0u, lgt_path_bounce - 1u, lgt_path_bounce > 0u); +} + fn lgt_sample_analytic_light( shading_pos: vec3, receiver_lo: u32, @@ -688,6 +704,9 @@ fn lgt_sample_analytic_light_at( if (!lgt_links_match(receiver_lo, receiver_hi, light.light_group_mask_lo, light.light_group_mask_hi)) { return lgt_empty_sample(); } + if (!lgt_bounce_limit_allows(light, lgt_path_bounce)) { + return lgt_empty_sample(); + } if (light.light_type == LIGHT_TYPE_POINT || light.light_type == LIGHT_TYPE_SPOT) { return lgt_sample_point_or_spot_light(light, shading_pos, sample_uv); } @@ -1057,6 +1076,9 @@ fn lgt_eval_analytic_lights_along_segment( if (!lgt_links_match(receiver_lo, receiver_hi, light.light_group_mask_lo, light.light_group_mask_hi)) { continue; } + if (!lgt_bounce_limit_allows(light, lgt_hit_vertex_bounce())) { + continue; + } } if (light.light_type == LIGHT_TYPE_POINT || light.light_type == LIGHT_TYPE_SPOT) { @@ -1241,6 +1263,9 @@ fn lgt_eval_escaped_ray( if (!lgt_links_match(receiver_lo, receiver_hi, light.light_group_mask_lo, light.light_group_mask_hi)) { continue; } + if (!lgt_bounce_limit_allows(light, lgt_hit_vertex_bounce())) { + continue; + } } let one_minus_cos = lgt_sun_one_minus_cos(light); if (one_minus_cos <= 1.0e-12) { diff --git a/tests/gpu/light-bounce-limit.test.mjs b/tests/gpu/light-bounce-limit.test.mjs new file mode 100644 index 0000000..9069e85 --- /dev/null +++ b/tests/gpu/light-bounce-limit.test.mjs @@ -0,0 +1,65 @@ +// A light's own bounce limit against a scene whose wall gets light only after the floor has bounced it. They need the built addon and a +// Vulkan adapter with ray queries, and skip, with the reason, without them. +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { findNativeAddon, traceNative } from '../../index.mjs'; +import { buildNativeInputV2 } from '../../pack-input-v2.mjs'; +import { floorGeometry, panelGeometry, placement } from '../../tools/dispersion-scenes.mjs'; +import { pinholeCamera } from '../../tools/make-fixture-pack.mjs'; + +function skipReason() { + try { + return findNativeAddon() === null ? 'the native addon is not built (run `node build.mjs`, needs Rust and a Vulkan adapter with ray queries)' : false; + } catch (environmentError) { + return environmentError.message; + } +} +const skip = skipReason(); + +const SIZE = 16; +const SAMPLES = 256; + +function asInstance(geometry, matrix) { + return { + geometry: { positions: Float32Array.from(geometry.positions), normals: Float32Array.from(geometry.normals), indices: Uint32Array.from(geometry.indices) }, + matrix, + materialIndex: 0, + }; +} + +function centreAverage(rgba, halfExtent) { + let sum = 0; + let count = 0; + for (let row = SIZE / 2 - halfExtent; row < SIZE / 2 + halfExtent; row += 1) { + for (let column = SIZE / 2 - halfExtent; column < SIZE / 2 + halfExtent; column += 1) { + for (let channel = 0; channel < 3; channel += 1) sum += rgba[(row * SIZE + column) * 4 + channel]; + count += 3; + } + } + return sum / count; +} + +// The sun is straight overhead, so a vertical wall takes no direct sun: what it shows is the floor's light, reaching the sun at path vertex 1. +function wallBrightness(sun) { + const camera = pinholeCamera({ eye: [0, 1.5, 3], target: [0, 1.5, -1], fieldOfViewDegrees: 4, width: SIZE, height: SIZE }); + const scene = { + materials: [{ color: [0.8, 0.8, 0.8], roughness: 1 }], + instances: [asInstance(floorGeometry(30), placement({})), asInstance(panelGeometry(30, 30), placement({ translation: [0, 0, -1] }))], + lights: { sun: { direction: [0, 1, 0], color: [3, 3, 3], ...sun } }, + }; + const options = { width: SIZE, height: SIZE, samples: SAMPLES, seed: 3, bounces: 8, backgroundColor: [0, 0, 0] }; + const traced = traceNative(buildNativeInputV2(scene, camera, options), { width: SIZE, height: SIZE, samples: SAMPLES, kernel: 'cycles' }); + return centreAverage(traced.rgba, 4); +} + +test('a sun limited to 0 bounces leaves the wall the floor lights dark, and one limited to 1 still lights it', { skip }, () => { + const unlimited = wallBrightness({}); + assert.ok(unlimited > 0.05, `the wall is lit by the floor without a limit: ${unlimited}`); + assert.ok(wallBrightness({ maxBounces: 0 }) < 0.01 * unlimited, 'with a limit of 0 the sun reaches no vertex past the first'); + assert.ok(wallBrightness({ maxBounces: 1 }) > 0.5 * unlimited, 'with a limit of 1 the sun still lights the floor the wall sees'); +}); + +test('a limit above the scene bounces renders the same picture as no limit', { skip }, () => { + assert.equal(wallBrightness({ maxBounces: 254 }), wallBrightness({})); +}); diff --git a/tests/light-bounce-limit.test.mjs b/tests/light-bounce-limit.test.mjs new file mode 100644 index 0000000..84584f4 --- /dev/null +++ b/tests/light-bounce-limit.test.mjs @@ -0,0 +1,69 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { STRUCT_STRIDES_V2, buildNativeInputV2 } from '../pack-input-v2.mjs'; +import { pinholeCamera } from '../tools/make-fixture-pack.mjs'; + +const LIGHT_FLAGS_WORD_INDEX = 7; +const LIGHT_BOUNCE_LIMIT_SHIFT = 8; +const LIGHT_BOUNCE_LIMIT_MASK = 0xff; +const LOW_FLAG_MASK = 0xff; + +function packLights(lights) { + const geometry = { + positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], + normals: [0, 0, 1, 0, 0, 1, 0, 0, 1], + indices: [0, 1, 2], + }; + const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; + const scene = { + materials: [{ color: [0.5, 0.5, 0.5] }], + instances: [{ geometry, matrix: identity, materialIndex: 0 }], + lights, + }; + const camera = pinholeCamera({ eye: [0, 0, 3], target: [0, 0, 0], fieldOfViewDegrees: 40, width: 8, height: 8 }); + return buildNativeInputV2(scene, camera, { width: 8, height: 8, samples: 1, backgroundColor: [0, 0, 0] }); +} + +function lightsOf(limits) { + return { + sun: { direction: [0, 1, 0], color: [1, 1, 1], ...limits.sun }, + points: [{ position: [0, 2, 0], color: [1, 1, 1], intensity: 5, radius: 0.1, ...limits.point }], + spots: [{ position: [1, 2, 0], direction: [0, -1, 0], angle: 0.6, color: [1, 1, 1], intensity: 5, radius: 0.1, ...limits.spot }], + areas: [{ position: [2, 2, 0], direction: [0, -1, 0], width: 1, height: 1, color: [1, 1, 1], intensity: 5, ...limits.area }], + }; +} + +function lightFlagWords(input) { + const stride = STRUCT_STRIDES_V2.light; + const words = new Uint32Array(input.lights.buffer, input.lights.byteOffset, input.lights.byteLength / 4); + return [0, 1, 2, 3].map(index => words[(index * stride) / 4 + LIGHT_FLAGS_WORD_INDEX]); +} + +const limitOf = flagWord => ((flagWord >>> LIGHT_BOUNCE_LIMIT_SHIFT) & LIGHT_BOUNCE_LIMIT_MASK) - 1; + +test('a light maxBounces is stored in bits 8 to 15 of its record flags as the limit plus one', () => { + const words = lightFlagWords(packLights(lightsOf({ sun: { maxBounces: 2 }, point: { maxBounces: 0 }, spot: { maxBounces: 254 }, area: { maxBounces: 1 } }))); + assert.deepEqual(words.map(limitOf), [2, 0, 254, 1]); +}); + +test('a light without maxBounces has no limit bits, and its other flags match a light that has one', () => { + const plain = lightFlagWords(packLights(lightsOf({}))); + const limited = lightFlagWords(packLights(lightsOf({ sun: { maxBounces: 3 }, point: { maxBounces: 3 }, spot: { maxBounces: 3 }, area: { maxBounces: 3 } }))); + for (const word of plain) { + assert.equal(word >>> LIGHT_BOUNCE_LIMIT_SHIFT, 0, 'no limit bits without maxBounces'); + } + assert.deepEqual(limited.map(word => word & LOW_FLAG_MASK), plain.map(word => word & LOW_FLAG_MASK)); +}); + +test('a maxBounces that is not a whole number from 0 to 254 is refused with the accepted range', () => { + for (const badLimit of [-1, 255, 1.5, Number.NaN, '2', null]) { + for (const field of ['sun', 'point', 'spot', 'area']) { + assert.throws( + () => packLights(lightsOf({ [field]: { maxBounces: badLimit } })), + (error) => error instanceof RangeError && /maxBounces must be a whole number from 0 to 254/.test(error.message), + `${field} maxBounces ${String(badLimit)} is refused`, + ); + } + } +}); From e95e91daf84010ce8d6a0df48d823fc77444ad3e Mon Sep 17 00:00:00 2001 From: Nguyen Xuan An Date: Wed, 18 Nov 2026 02:12:06 +0700 Subject: [PATCH 2/2] Carry a light's bounce limit through the v1 input and its upgrade (codepawl/crucible#2015) --- FORMAT-v2.md | 2 +- pack-input-v2.mjs | 20 ++++++++-- pack-input.mjs | 5 ++- tests/light-bounce-limit-v1.test.mjs | 59 ++++++++++++++++++++++++++++ 4 files changed, 80 insertions(+), 6 deletions(-) create mode 100644 tests/light-bounce-limit-v1.test.mjs diff --git a/FORMAT-v2.md b/FORMAT-v2.md index 1e54fc1..b91526a 100644 --- a/FORMAT-v2.md +++ b/FORMAT-v2.md @@ -303,7 +303,7 @@ Convention: `direction` is always the **unit emission direction pointing from th | `0` | `12` | `16` | `vec3` | `position` | World-space centre (`point`, `spot`, `area_rect`, `area_disk`; unused for `sun`) | | `12` | `4` | `4` | `u32` | `light_type` | `0=point`, `1=spot`, `2=area_rect`, `3=area_disk`, `4=sun` | | `16` | `12` | `16` | `vec3` | `radiance` | Emitted linear RGB radiance (`W/(sr·m²)` for finite-area/sun, intensity `W/sr` when `radius == 0`) | -| `28` | `4` | `4` | `u32` | `flags` | Bitmask: `1=CAST_SHADOW`, `2=MULTIPLE_IMPORTANCE`, `4=CAMERA_VISIBLE`, `8=PORTAL`, `16=NORMALIZE`, `32=SOFT_FALLOFF` (a point or spot light with a radius is an oriented disk facing the shading point, as Blender's `use_soft_falloff`; clear: the sphere); bits `8..15`: the light's own bounce limit as `limit + 1` (Cycles `max_bounces` of the light), `0` for none. A limited light adds direct light, and is hit by a bounced ray, only at path vertices `0..limit`; the scene limit still applies on top | +| `28` | `4` | `4` | `u32` | `flags` | Bitmask: `1=CAST_SHADOW`, `2=MULTIPLE_IMPORTANCE`, `4=CAMERA_VISIBLE`, `8=PORTAL`, `16=NORMALIZE`, `32=SOFT_FALLOFF` (a point or spot light with a radius is an oriented disk facing the shading point, as Blender's `use_soft_falloff`; clear: the sphere); bits `8..15`: the light's own bounce limit as `limit + 1` (Cycles `max_bounces` of the light), `0` for none; a v1 input carries the code in the fourth float of the sun direction and in the last float of the last texel of every other light. A limited light adds direct light, and is hit by a bounced ray, only at path vertices `0..limit`; the scene limit still applies on top | | `32` | `12` | `16` | `vec3` | `direction` | Unit world-space emission direction | | `44` | `4` | `4` | `f32` | `radius` | Sphere radius in metres for `point` / `spot` (`0.0` = delta emitter) | | `48` | `12` | `16` | `vec3` | `axis_u` | Unit tangent axis U for area / IES orientation | diff --git a/pack-input-v2.mjs b/pack-input-v2.mjs index c81f59b..35d3b0c 100644 --- a/pack-input-v2.mjs +++ b/pack-input-v2.mjs @@ -97,15 +97,25 @@ const LIGHT_FLAG_SOFT_FALLOFF = 32; const LIGHT_BOUNCE_LIMIT_SHIFT = 8; const MAXIMUM_LIGHT_BOUNCE_LIMIT = 254; -function lightBounceLimitFlags(light, lightsField) { - if (light.maxBounces === undefined) { +/** The limit of `light.maxBounces` plus one, or 0 for a light without one. The v1 packers store this code too (sun: `sunDirection.w`, other lights: the last float of their last texel). */ +export function lightBounceLimitCode(light, lightsField) { + if (light?.maxBounces === undefined) { return 0; } const limit = light.maxBounces; if (!Number.isInteger(limit) || limit < 0 || limit > MAXIMUM_LIGHT_BOUNCE_LIMIT) { throw new RangeError(`lights.${lightsField}.maxBounces must be a whole number from 0 to ${MAXIMUM_LIGHT_BOUNCE_LIMIT}, got ${JSON.stringify(limit)}. Leave it out for no limit beyond the scene's bounces.`); } - return (limit + 1) << LIGHT_BOUNCE_LIMIT_SHIFT; + return limit + 1; +} + +function lightBounceLimitFlags(light, lightsField) { + return lightBounceLimitCode(light, lightsField) << LIGHT_BOUNCE_LIMIT_SHIFT; +} + +// The `maxBounces` a v1 input stored as a code, for the lights rebuilt from it. +function reconstructedBounceLimit(code) { + return code > 0 ? { maxBounces: Math.round(code) - 1 } : {}; } const MATERIAL_FLAG_MULTISCATTER_GGX = 1; @@ -3769,6 +3779,7 @@ export function upgradeNativeInputV1ToV2(v1Input, options = {}, carriedFields = direction: [paramF32[16], paramF32[17], paramF32[18]], color: [paramF32[20], paramF32[21], paramF32[22]], angularRadius: resolveReconstructedSunRadius(Math.acos(cosSun)), + ...reconstructedBounceLimit(paramF32[19]), }; } const lightFloats = v1Input.lights; @@ -3789,6 +3800,7 @@ export function upgradeNativeInputV1ToV2(v1Input, options = {}, carriedFields = height: lightFloats[b + 15], along: [lightFloats[b + 16], lightFloats[b + 17], lightFloats[b + 18]], intensity: lightFloats[b + 20], + ...reconstructedBounceLimit(lightFloats[b + 23]), }); } else if (type === 1) { reconstructedLights.spots.push({ @@ -3802,6 +3814,7 @@ export function upgradeNativeInputV1ToV2(v1Input, options = {}, carriedFields = intensity: lightFloats[b + 20], range: lightFloats[b + 21], softFalloff: lightFloats[b + 22] === 1, + ...reconstructedBounceLimit(lightFloats[b + 23]), }); } else { reconstructedLights.points.push({ @@ -3812,6 +3825,7 @@ export function upgradeNativeInputV1ToV2(v1Input, options = {}, carriedFields = intensity: lightFloats[b + 20], range: lightFloats[b + 21], softFalloff: lightFloats[b + 22] === 1, + ...reconstructedBounceLimit(lightFloats[b + 23]), }); } } diff --git a/pack-input.mjs b/pack-input.mjs index b121a92..b38f198 100644 --- a/pack-input.mjs +++ b/pack-input.mjs @@ -1,6 +1,6 @@ // Packs a trace scene into the tables the native kernel reads. It imports nothing from Node, so the job page can run it too. // 16 vectors: the 12 of the camera, lights and seed, the fog box and medium, and the subsurface table's first vector index. -import { PACK_REVISION, SUN_DEFAULT_HALF_ANGLE, resolveVolumeAlbedo } from './pack-input-v2.mjs'; +import { PACK_REVISION, SUN_DEFAULT_HALF_ANGLE, lightBounceLimitCode, resolveVolumeAlbedo } from './pack-input-v2.mjs'; const PARAMETER_BYTES = 16 * 16; const DEFAULT_FIREFLY_CLAMP = 20; @@ -56,7 +56,8 @@ function writeParameters(scene, camera, options, lightCount, atlasWidth, subsurf floats.set([...camera.right, 0], 8); floats.set([...camera.above, 0], 12); writeThinLens(floats, camera); - floats.set([...(sun?.direction ?? [0, 1, 0]), 0], 16); + // The fourth float is the sun's own bounce limit as `limit + 1` (0: none), which the "cycles" kernel reads after the upgrade to v2; the legacy kernel ignores it. + floats.set([...(sun?.direction ?? [0, 1, 0]), lightBounceLimitCode(sun, 'sun')], 16); floats.set([...(sun?.color ?? [0, 0, 0]), sunConeCosine(sun)], 20); floats.set([environment?.width ?? 1, environment?.height ?? 1, environment?.intensity ?? 1, environment?.total ?? 1], 24); floats.set([environment?.cosine ?? 1, environment?.sine ?? 0, scene.surfaceOffset, scene.farDistance], 28); diff --git a/tests/light-bounce-limit-v1.test.mjs b/tests/light-bounce-limit-v1.test.mjs new file mode 100644 index 0000000..5a89b60 --- /dev/null +++ b/tests/light-bounce-limit-v1.test.mjs @@ -0,0 +1,59 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { buildNativeV1Tables } from '../pack-input.mjs'; +import { STRUCT_STRIDES_V2, upgradeNativeInputV1ToV2 } from '../pack-input-v2.mjs'; + +const LIGHT_FLOATS = 24; +const LIGHT_FLAGS_WORD_INDEX = 7; +const LIGHT_BOUNCE_LIMIT_SHIFT = 8; +const SUN_LIMIT_CODE_FLOAT_INDEX = 19; +const CAMERA = { eye: [0, 0, 0], forward: [0, 0, -1], right: [1, 0, 0], above: [0, 1, 0], halfWidth: 1, halfHeight: 1 }; + +// A v1 light table of a point, a spot and an area light, each with the given limit code in its last float. +function lightTable(limitCodes) { + const data = new Float32Array(limitCodes.length * LIGHT_FLOATS); + limitCodes.forEach((code, index) => { + const base = index * LIGHT_FLOATS; + data.set([index, 2, 0, index], base); + data.set([1, 1, 1, index], base + 4); + data.set([0, -1, 0, 0.1], base + 8); + data.set([0, 0, 0, 1], base + 12); + data.set([0, 0, 0, 0.1], base + 16); + data.set([5, 0, 0, code], base + 20); + }); + return { count: limitCodes.length, table: { data } }; +} + +function packInput(sun, limitCodes) { + const pack = { + packLights: () => lightTable(limitCodes), + packEnvironment: () => null, + packTriangles: () => ({ data: new Float32Array(36) }), + packAtlas: () => ({ data: new Uint8Array(4), width: 1, height: 1 }), + packMaterials: () => ({ data: new Float32Array(16) }), + sceneUsesSubsurface: () => false, + packSubsurface: () => ({ data: new Float32Array(0) }), + }; + const scene = { materials: [{}], lights: { sun }, environment: null, surfaceOffset: 1e-4, farDistance: 100, bvh: { triangleOrder: [0] } }; + return buildNativeV1Tables(scene, CAMERA, { width: 4, height: 4, bounces: 3, seed: 7 }, pack); +} + +function upgradedFlagWords(v1Input) { + const upgraded = upgradeNativeInputV1ToV2(v1Input, { width: 4, height: 4, samples: 1 }); + const words = new Uint32Array(upgraded.lights.buffer, upgraded.lights.byteOffset, upgraded.lights.byteLength / 4); + return Array.from({ length: 4 }, (unused, index) => words[(index * STRUCT_STRIDES_V2.light) / 4 + LIGHT_FLAGS_WORD_INDEX]); +} + +test('the sun maxBounces rides in the fourth float of the sun direction as limit plus one', () => { + const parameters = (sun) => new Float32Array(packInput(sun, []).parameters.buffer, 0, 64); + assert.equal(parameters({ direction: [0, 1, 0], color: [1, 1, 1], maxBounces: 2 })[SUN_LIMIT_CODE_FLOAT_INDEX], 3); + assert.equal(parameters({ direction: [0, 1, 0], color: [1, 1, 1] })[SUN_LIMIT_CODE_FLOAT_INDEX], 0); + assert.throws(() => parameters({ direction: [0, 1, 0], color: [1, 1, 1], maxBounces: -1 }), /lights\.sun\.maxBounces must be a whole number from 0 to 254/); +}); + +test('a v1 input upgraded to v2 keeps the limit of the sun and of each point, spot and area light', () => { + const words = upgradedFlagWords(packInput({ direction: [0, 1, 0], color: [1, 1, 1], maxBounces: 2 }, [1, 0, 255])); + const limitCodes = words.map(word => (word >>> LIGHT_BOUNCE_LIMIT_SHIFT) & 0xff); + assert.deepEqual(limitCodes, [3, 1, 0, 255]); +});