Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Pass the first transparent surface at a limit of 0 and charge the camera path's transparent count to shadow rays, as Cycles does (#894)

Nguyen Xuan Anbf4a3991b6c2
diff --git a/changes/894-transparent-bounces.md b/changes/894-transparent-bounces.md
new file mode 100644
index 00000000..61f46598
--- /dev/null
+++ b/changes/894-transparent-bounces.md
@@ -0,0 +1 @@
+- The Cook `cycles` kernel passes the first transparent surface at a transparent bounce limit of 0 and gives shadow rays only the transparent limit the camera path has left, both as Cycles does (#894)
diff --git a/packages/render-native/src/cycles/integrator.wgsl b/packages/render-native/src/cycles/integrator.wgsl
index 4ec6fe39..bb08898e 100644
--- a/packages/render-native/src/cycles/integrator.wgsl
+++ b/packages/render-native/src/cycles/integrator.wgsl
@@ -286,6 +286,7 @@ fn int_trace_shadow(
self_triangle: u32,
target_instance: u32,
target_triangle: u32,
+ path_transparent_bounces: u32,
) -> vec3<f32> {
let step_eps = max(kernel_params.ray_epsilon, 1.0e-6);
let shadow_t_max = select(1.0e30, max(max_distance - step_eps, 0.0), max_distance < 1.0e29);
@@ -293,7 +294,10 @@ fn int_trace_shadow(
if (shadow_t_max > 0.0 && kernel_params.instance_count > 0u && kernel_params.triangle_count > 0u) {
var current_t_min = 0.0;
- var transparent_hits = 0u;
+ // `integrate_shadow_max_transparent_hits` (kernel/integrator/intersect_shadow.h) allows
+ // max(transparent_max_bounce - transparent_bounce, 0) transparent hits: the transparent
+ // surfaces the camera path already passed count against the same limit as the shadow ray's.
+ var transparent_hits = path_transparent_bounces;
for (var step = 0u; step <= INT_MAX_PATH_STEPS; step += 1u) {
if (current_t_min >= shadow_t_max) {
break;
@@ -582,6 +586,7 @@ fn int_accumulate_direct_sample(
medium_sigma: vec3<f32>,
in_medium: bool,
bounce: u32,
+ transparent_bounces: u32,
radiance: ptr<function, vec3<f32>>,
) {
if (sample.valid == 0u || sample.pdf <= 0.0) {
@@ -615,6 +620,7 @@ fn int_accumulate_direct_sample(
(*point).triangle_index,
sample.target_instance,
sample.target_triangle,
+ transparent_bounces,
);
}
if (visibility.x <= 0.0 && visibility.y <= 0.0 && visibility.z <= 0.0) {
@@ -653,6 +659,7 @@ fn int_accumulate_volume_direct_sample(
incident_dir: vec3<f32>,
throughput: vec3<f32>,
bounce: u32,
+ transparent_bounces: u32,
radiance: ptr<function, vec3<f32>>,
) {
if (sample.valid == 0u || sample.pdf <= 0.0) {
@@ -674,6 +681,7 @@ fn int_accumulate_volume_direct_sample(
INVALID_INDEX,
sample.target_instance,
sample.target_triangle,
+ transparent_bounces,
);
}
*radiance += int_clamp_contribution(unshadowed * visibility, i32(bounce));
@@ -823,12 +831,12 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
if (SCENE_HAS_ANALYTIC_LIGHTS && kernel_params.light_count > 0u) {
smp_seek(&rng, step, SMP_SLOT_VOLUME_ANALYTIC_PICK);
let light_samp = lgt_sample_analytic_light(scatter_pos, 0xFFFFFFFFu, 0xFFFFFFFFu, smp_next_1d(&rng), smp_next_2d(&rng));
- int_accumulate_volume_direct_sample(light_samp, scatter_pos, ray_dir, throughput, bounce, &sample_radiance);
+ int_accumulate_volume_direct_sample(light_samp, scatter_pos, ray_dir, throughput, bounce, transparent_bounces, &sample_radiance);
}
if (SCENE_HAS_ENV_IMPORTANCE && kernel_params.env_width > 0u && kernel_params.env_height > 0u && kernel_params.background_mis_weight > 0.0) {
smp_seek(&rng, step, SMP_SLOT_VOLUME_ENVIRONMENT);
let env_samp = lgt_sample_environment(smp_next_4d(&rng));
- int_accumulate_volume_direct_sample(env_samp, scatter_pos, ray_dir, throughput, bounce, &sample_radiance);
+ int_accumulate_volume_direct_sample(env_samp, scatter_pos, ray_dir, throughput, bounce, transparent_bounces, &sample_radiance);
}
var phase_pdf = 0.0;
@@ -931,7 +939,11 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
if (terminate_on_hit) {
if (closure.lobe_count > 0u && closure.lobes[0].lobe_type == LOBE_TRANSPARENT && closure.total_sample_weight > 0.0) {
- if (kernel_params.max_transparent_bounces > 0u && transparent_bounces < kernel_params.max_transparent_bounces) {
+ // `path_state_next` (kernel/integrator/path_state.h) counts the transparent surface it passes and sets
+ // PATH_RAY_TERMINATE_ON_NEXT_SURFACE once the count reaches transparent_max_bounce, so the first
+ // surface is always passed, also with a limit of 0. The break on terminate_on_next_surface above ends
+ // the path at the next surface and the count never exceeds the limit here.
+ {
let trans_prob = clamp(closure.lobes[0].sample_weight / closure.total_sample_weight, 0.0, 1.0);
smp_seek(&rng, step, SMP_SLOT_TRANSPARENT);
if (trans_prob > 0.0 && smp_next_1d(&rng) < trans_prob) {
@@ -992,7 +1004,7 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
direct_sample = lgt_sample_environment(smp_next_4d(&rng));
}
}
- int_accumulate_direct_sample(direct_sample, &closure, &point, wo, throughput, medium_sigma, in_medium, bounce, &sample_radiance);
+ int_accumulate_direct_sample(direct_sample, &closure, &point, wo, throughput, medium_sigma, in_medium, bounce, transparent_bounces, &sample_radiance);
}
smp_seek(&rng, step, SMP_SLOT_SURFACE_BSDF);
@@ -1002,9 +1014,8 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
}
if (bsdf_sample.sampled_lobe_type == LOBE_TRANSPARENT) {
- if (kernel_params.max_transparent_bounces == 0u || transparent_bounces >= kernel_params.max_transparent_bounces) {
- break;
- }
+ // As above: `path_state_next` passes the transparent surface and then terminates on the next surface
+ // when the count reaches transparent_max_bounce, with a limit of 0 as well (its FIXME note).
transparent_bounces += 1u;
if (transparent_bounces >= kernel_params.max_transparent_bounces) {
terminate_on_next_surface = true;
diff --git a/tests/native-transparent-bounces.test.js b/tests/native-transparent-bounces.test.js
new file mode 100644
index 00000000..156e760c
--- /dev/null
+++ b/tests/native-transparent-bounces.test.js
@@ -0,0 +1,102 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadReferenceScene } from '../bench/cycles-parity/scene-bridge.mjs';
+import { buildTraceSceneWithManyLights } from '../bench/cycles-parity/trace-scene-many-lights.mjs';
+import { buildNativeInputV2, findNativeAddon, traceNative } from '../packages/render-native/index.mjs';
+import { createCamera } from '../src/path-tracer.js';
+
+const hasAddon = findNativeAddon() !== null;
+const skipWithoutAddon = hasAddon ? false : 'the native addon is not built';
+
+const WIDTH = 240;
+const HEIGHT = 135;
+const SAMPLES = 512;
+
+// Means measured from Blender 5.3.0 Cycles (OptiX, 960 x 540, 4096 samples, box filter) on the `transparent-bounces` reference scene
+// at Transparent Max Bounces 0, 1 and 2 (docs/cycles-parity.md, "Transparent bounce limits"). Cycles seeds 1 and 2 agree to five
+// digits (a relMSE floor below 1e-6). The tolerance is 0.5 percent: Cook sits 0.1 to 0.2 percent above Cycles at 4096 samples with
+// every limit, and the failures it has to catch are far larger: before the fix Cook missed
+// 3 to 11 percent of the image mean at a limit of 0 and was 1 to 2 percent too bright behind one layer at a limit of 2.
+const CYCLES_IMAGE_MEAN_AT_LIMIT_0_AND_1 = [0.54387, 0.19923, 0.16623];
+const CYCLES_IMAGE_MEAN_AT_LIMIT_2 = [0.60846, 0.30715, 0.229];
+const CYCLES_SKY_BEHIND_ONE_LAYER_AT_LIMIT_0_AND_1 = [0.61574, 0.30679, 0.27764];
+const CYCLES_BACKDROP_BEHIND_ONE_LAYER_AT_LIMIT_2 = [0.506, 0.24495, 0.21766];
+const RELATIVE_TOLERANCE = 0.005;
+
+const LEFT_STRIP = [0.08, 0.28];
+const SKY_ROWS = [0.03, 0.2];
+const BACKDROP_ROWS = [0.4, 0.6];
+
+async function traceLimit(transparentBounces) {
+ const { traceSource } = await loadReferenceScene('transparent-bounces');
+ const traceScene = buildTraceSceneWithManyLights(traceSource.parts, traceSource.environment);
+ const camera = createCamera(traceSource.camera, WIDTH, HEIGHT);
+ const input = buildNativeInputV2(traceScene, camera, {
+ width: WIDTH,
+ height: HEIGHT,
+ samples: SAMPLES,
+ bounces: 8,
+ transparentBounces,
+ seed: 1,
+ parts: traceSource.parts,
+ });
+ return traceNative(input, { width: WIDTH, height: HEIGHT, samples: SAMPLES, bounces: 8, seed: 1, kernel: 'cycles' }).rgba;
+}
+
+function meanOfRegion(rgba, columns, rows) {
+ const sum = [0, 0, 0];
+ const columnStart = Math.floor(WIDTH * columns[0]);
+ const columnStop = Math.floor(WIDTH * columns[1]);
+ const rowStart = Math.floor(HEIGHT * rows[0]);
+ const rowStop = Math.floor(HEIGHT * rows[1]);
+ for (let row = rowStart; row < rowStop; row++) {
+ for (let column = columnStart; column < columnStop; column++) {
+ for (let channel = 0; channel < 3; channel++) {
+ sum[channel] += rgba[(row * WIDTH + column) * 4 + channel];
+ }
+ }
+ }
+ const pixelCount = (columnStop - columnStart) * (rowStop - rowStart);
+ return sum.map(value => value / pixelCount);
+}
+
+function assertWithinTolerance(actual, expected, label) {
+ actual.forEach((value, channel) => {
+ const relativeError = Math.abs(value / expected[channel] - 1);
+ assert.ok(
+ relativeError <= RELATIVE_TOLERANCE,
+ `${label}, channel ${channel}: Cook ${value.toFixed(5)} against Cycles ${expected[channel]} is ${(relativeError * 100).toFixed(2)} percent off`,
+ );
+ });
+}
+
+test('a transparent limit of 0 lets the path through the first layer, as Cycles does', { skip: skipWithoutAddon }, async () => {
+ const limitZero = await traceLimit(0);
+ assertWithinTolerance(meanOfRegion(limitZero, [0, 1], [0, 1]), CYCLES_IMAGE_MEAN_AT_LIMIT_0_AND_1, 'image mean at limit 0');
+ assertWithinTolerance(
+ meanOfRegion(limitZero, LEFT_STRIP, SKY_ROWS),
+ CYCLES_SKY_BEHIND_ONE_LAYER_AT_LIMIT_0_AND_1,
+ 'sky seen through one layer at limit 0',
+ );
+});
+
+test('a transparent limit of 1 matches Cycles and a limit of 0 renders the same picture', { skip: skipWithoutAddon }, async () => {
+ const limitZero = await traceLimit(0);
+ const limitOne = await traceLimit(1);
+ assertWithinTolerance(meanOfRegion(limitOne, [0, 1], [0, 1]), CYCLES_IMAGE_MEAN_AT_LIMIT_0_AND_1, 'image mean at limit 1');
+ assertWithinTolerance(
+ meanOfRegion(limitZero, [0, 1], [0, 1]),
+ meanOfRegion(limitOne, [0, 1], [0, 1]),
+ 'image mean at limit 0 against limit 1',
+ );
+});
+
+test('shadow rays spend what is left of the limit after the camera path passed layers', { skip: skipWithoutAddon }, async () => {
+ const limitTwo = await traceLimit(2);
+ assertWithinTolerance(meanOfRegion(limitTwo, [0, 1], [0, 1]), CYCLES_IMAGE_MEAN_AT_LIMIT_2, 'image mean at limit 2');
+ assertWithinTolerance(
+ meanOfRegion(limitTwo, LEFT_STRIP, BACKDROP_ROWS),
+ CYCLES_BACKDROP_BEHIND_ONE_LAYER_AT_LIMIT_2,
+ 'backdrop seen through one layer at limit 2',
+ );
+});