Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion FORMAT-v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ Convention: `direction` is always the **unit emission direction pointing from th
| `0` | `12` | `16` | `vec3<f32>` | `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<f32>` | `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 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<f32>` | `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<f32>` | `axis_u` | Unit tangent axis U for area / IES orientation |
Expand Down
32 changes: 32 additions & 0 deletions pack-input-v2.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,30 @@ 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;

/** 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;
}

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;
const MATERIAL_FLAG_THIN_WALLED = 2;
Expand Down Expand Up @@ -1385,6 +1409,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({
Expand Down Expand Up @@ -1433,6 +1458,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);
Expand Down Expand Up @@ -1497,6 +1523,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));
Expand Down Expand Up @@ -1575,6 +1602,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({
Expand Down Expand Up @@ -3751,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;
Expand All @@ -3771,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({
Expand All @@ -3784,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({
Expand All @@ -3794,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]),
});
}
}
Expand Down
5 changes: 3 additions & 2 deletions pack-input.mjs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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);
Expand Down
3 changes: 3 additions & 0 deletions src/cycles/abi.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions src/cycles/integrator.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -1190,6 +1190,7 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
}
}

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,
Expand Down
25 changes: 25 additions & 0 deletions src/cycles/lights.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -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<private> 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<private> lgt_path_bounce: u32 = 0u;
var<private> lgt_mis_position: vec3<f32> = vec3<f32>(0.0);
var<private> lgt_mis_normal: vec3<f32> = vec3<f32>(0.0, 0.0, 1.0);
var<private> lgt_mis_has_transmission: bool = false;
Expand Down Expand Up @@ -657,6 +660,19 @@ fn lgt_sample_sun_light(light: LightRecord, rand_uv: vec2<f32>) -> 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<f32>,
receiver_lo: u32,
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down
65 changes: 65 additions & 0 deletions tests/gpu/light-bounce-limit.test.mjs
Original file line number Diff line number Diff line change
@@ -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({}));
});
59 changes: 59 additions & 0 deletions tests/light-bounce-limit-v1.test.mjs
Original file line number Diff line number Diff line change
@@ -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]);
});
Loading
Loading