Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

Hiding a volume or a light is in place; a hidden light gives no light; black lights cost nothing (ROADMAP § 1a) (#41)

Yujiaba022b3fd91b
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 7093ed2..14cbfd6 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -1902,6 +1902,31 @@ fire shot reads 6.28 / 5.56 / 3.69 as before, to the digit.
- test-render 181 pass. Not done: `Explosions` still refuses a smoke grid and says why in the old words (the voxel
line's to change, with the comparison that found it); at most 32 media a scene, as before.
+**Hiding in place, black lights (2026-11-13, after it).** `World::set_visible` rebuilt the live scene for anything but
+a particle system, so a pool parked its idle fireballs 10 km below the level and gave its idle lights a 1 mm range
+(§ 6 step 10 b). And the build placed every light whatever its visibility: hiding a light cost the rebuild and
+changed nothing (`light/hidden`: 238 for 39.8). Now, by an object's own `visible`, in place (`Changes::shown`):
+- a volume keeps its medium in the table with no shape (`MEDIUM_HIDDEN`: `medium_span` gives no crossing). Hidden
+ ones are built while the kernel has room after those shown (32 in all); no media pass runs while every medium is
+ hidden;
+- a light without a card keeps its entry in the light table, black. The kernel skips black lights first in its exact
+ loop, and they are in no group's sphere (a group of them alone holds no point), so a light parked anywhere costs
+ nothing; a hidden ancestor still rebuilds, and the build then places the lights under it black;
+- when a local light moves, or goes dark or lit, the groups are sorted again (`Tables::regroup_lights`): they were
+ sorted when the scene was built, and lights that drifted apart made their group's sphere as wide as the level.
+A rect light's card and the sun still rebuild (geometry; the sky's bake).
+
+- A fireball and a light hidden and shown every half second for 3 s (a scratch game): 6 rebuilds before (1,958 ms
+ the first, 9 ms each after), none now; the frame's CPU p50 4.70 ms, max 18 ms.
+- New tests: `light/hidden`, `light/hidden-in-place-live`, `light/shown-in-place-live`, `volume/hidden-in-place-live`,
+ `volume/shown-in-place-live`; test-render 186 pass. Bistro held still, Kabukichō's ghosting and the fire shot read
+ as before.
+- Seen on the way, not this change's: 2 s after a 5,000 cd light is hidden beside a 1,000 cd one the plane under
+ them still reads 6 % high. 45 frames after a lighting edit the long history comes back, and what is left of the
+ old light then averages out as 1 / n (NRD's fixed 30 frames would decay it for good). And 0.3 s after a fireball
+ is hidden a faint ring stays where its edge was (the upscaler's history: nothing says a medium went).
+- Not done: `Explosions` still parks (the voxel line's to change); a mesh hidden by its own `visible` still rebuilds.
+
Not done here: filters sized by hit distance, which is what would let a short history stand without noise; the
Playground and the page still open a 1280 × 720 view; the live buffers are sized by the output (about 1.7 GB at
2560 × 1440), though the traced grid rarely fills it.
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index e4de0d7..e54fced 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -46,7 +46,7 @@ runtime, and drives the engine directly, the way a UE game drives its actors:
| Engine API | `packages/scene/src/engine.ts` (`Engine`), `renderer/src/script.rs` (`__engine` natives) | Handles (u32) for geometries (typed arrays), textures (asset path, encoded image or RGBA8 pixels), material-function code, materials, objects (group / mesh / model / light / camera) and their transform, visibility, power, light / camera parameters; the environment and render settings. Descriptors are JSON-shaped (`renderer/src/desc.rs`). |
| Scene binding | `packages/scene/src/engine.ts` `SceneBinding` | Keeps the engine in step with a DSL scene. Objects report their own changes (core.ts change tracking: transforms, visibility, power, shadow flag, mesh geometry / material, add / remove), so a sync visits only what changed. Lights, cameras and materials are compared against what was last sent. |
| World | `renderer/src/world.rs` | The engine's objects, resources, environment and settings, and what changed since the last commit: parameter changes (power, light / material parameters, environment, camera) or structural ones. Asset paths must stay inside the asset root (game code is untrusted on nodes). |
-| Live commit | `renderer/src/live.rs` `LiveCore::commit`, `tables.rs` | Parameter changes rewrite GPU table entries in place (materials, lights, object power, emitter CDF, wetness / rain / fog, camera). Anything structural rebuilds the GPU scene from the world, in memory; history survives, validated per pixel. |
+| Live commit | `renderer/src/live.rs` `LiveCore::commit`, `tables.rs` | Parameter changes rewrite GPU table entries in place (materials, lights, object power, emitter CDF, wetness / rain / fog, camera), and so does hiding or showing a volume, a light without a card or a particle system that is not light-sampled by its own `visible`. Anything structural rebuilds the GPU scene from the world, in memory; history survives, validated per pixel. |
| Scene runtime | `renderer/src/script.rs` `ScriptHost` | QuickJS (rquickjs) with no I/O (no fs, network or timers). Loads a bundle (one script) or ES modules (`game.js` + `threert-runtime.js`, the cloud layout). Memory capped at 1 GiB. Time budgets: setup 120 s, event 1 s, frame 50 ms; the interrupt handler aborts overruns. The time the engine spends inside a voxel call (`voxelExplode`, `voxelEdit`, `voxelFrame`) is the engine's, not the script's: the deadline moves by it as measured, up to 250 ms an entry; past that it counts against the script, and a voxel call made after the deadline throws "interrupted" at once. A prelude adds `TextEncoder`, `structuredClone`, `atob` and `console`. |
| Node host | `packages/gameplay/src/node-host.ts` | `globalThis.__threert`: `setup(room, seed)`, `event(type, payload, ts)` (local authority: execute + commit), `commit(writes, seq)` / `setState(state, seq)` (room authority), `state()`, `frame(dt, now)`, and the editor's `outline()`, `inspect(name)`, `edit(name, path, value)`. |
| World handlers | `packages/gameplay/src/world.ts` | `on[type](world, ev)`: an event handled on this node, changing the scene at once. `WorldContext`: `scene`, `camera`, read-only `state`, `object(id)`, `time`, `now`, `random()`, `emit(type, payload)`. |
diff --git a/docs/VOXEL.md b/docs/VOXEL.md
index 835c565..55756d2 100644
--- a/docs/VOXEL.md
+++ b/docs/VOXEL.md
@@ -771,8 +771,8 @@ above.)
| What | Now | The fault at its source | Known side effects | It can go when | How to tell |
| --- | --- | --- | --- | --- | --- |
| The stand-in light | a point light at each burning fire, its intensity and colour from `FIRE_LIGHT`, measured against offline | live secondary and shadow rays have no media code: `pathtrace.wgsl` `media_shadows()` is false live (line 796), GI and reflection rays never meet a medium | offline the fire's light counts twice unless the game passes `lights: 0` (`level-destruction-fire` rendered offline has both); live, `media_train` adds the light to the radiance cache's voxels (`point_direct`, `point_sphere`): the fireball (and its smoke) is lit by it a second time; the table holds for the defaults (density, life scaled; measured by day over a floor and a wall, the fireball 0.6 of its size above it; past 8.8 m the 8.8 m values) | live rays see media: a medium's emission lights surfaces and shadows pass through it | `lights: 0`, then `tools/bench-voxel-fire.ts --only quality`: the street and the fireball's regions at least as close to offline as with the light; `voxel/fire-light` replaced by a live test of the fire's own light |
-| Idle fireballs parked | at y = −10,000, scale 1e-3, instead of hidden | `World::set_visible` (`world.rs` line 750): hiding anything but particles rebuilds the live scene | parked fireballs keep their slots among the kernel's 32 volumes, and every pixel's march still tests their boxes | hiding a volume or a light is done in place | `visible = false` instead of parking; the bench's cost runs report no rebuild after an explosion |
-| Idle lights reach 1 mm | an idle light's `distance` is 1 mm where it is parked | `light_reach` (`lib.rs` line 211): a black light without a range reaches without limit, and the kernel does not skip black lights before the group test (`pathtrace.wgsl` line 1578) | parked lights 10 km away share a group of 16 with lit ones, and groups are not sorted again when lights move (`lib.rs` line 277): the group's sphere is about 5 km wide while any fire burns (the per-light range test still works) | black lights reach nothing (or are hidden in place) and moved lights are grouped again | distance 0 on idle lights; the fire route's GPU time before any explosion within 0.1 ms of the smoke route's |
+| Idle fireballs parked | at y = −10,000, scale 1e-3, instead of hidden | `World::set_visible` (`world.rs` line 750): hiding anything but particles rebuilds the live scene | parked fireballs keep their slots among the kernel's 32 volumes, and every pixel's march still tests their boxes | **now** (2026-11-13: a volume or a light hidden by its own `visible` keeps its place in the build, in place; no media pass runs while every medium is hidden; `volume/hidden-in-place-live`, `light/hidden-in-place-live` and the two `shown`). What is left is `Explosions`' own | `visible = false` instead of parking; the bench's cost runs report no rebuild after an explosion |
+| Idle lights reach 1 mm | an idle light's `distance` is 1 mm where it is parked | `light_reach` (`lib.rs` line 211): a black light without a range reaches without limit, and the kernel does not skip black lights before the group test (`pathtrace.wgsl` line 1578) | parked lights 10 km away share a group of 16 with lit ones, and groups are not sorted again when lights move (`lib.rs` line 277): the group's sphere is about 5 km wide while any fire burns (the per-light range test still works) | **now** (2026-11-13: black lights are in no group's sphere and are skipped first; a hidden light's entry is black; the groups are sorted again when a local light moves or goes dark or lit). What is left is `Explosions`' own | distance 0 on idle lights; the fire route's GPU time before any explosion within 0.1 ms of the smoke route's |
| The smoke kept by never rebuilding | the pool's objects movable from the start; idle ones parked, not hidden (`Explosions` has no grid now: this keeps a game's own `SimulatedSmoke`) | `LiveCore::rebuild` (`live.rs` line 3474) → `load_scene` → `Gpu::upload` makes new grid textures (`gpu.rs` line 1664): the simulated state is not carried over | any other structural change in the game (an object added, a texture, an edit's fallback) wipes the smoke and the fire burning in it | a rebuild carries every simulated grid's state over | the bench's smoke check with a rebuild forced at 1 s (an object added): the smoke at 3 s as without it |
| Volumes must not overlap | `Explosions` has no smoke grid (it refuses one); the smoke is each fireball's own. Two fires close together still make two fireballs that overlap: nothing keeps them apart (no distance rule) | `media_track` (offline) and `media_march` (live) in `pathtrace.wgsl` take the media whole, in the order a ray enters them (at most 32, a 32-bit mask), not their coefficients summed along the ray; hence the rule (`core.ts` `VolumeMesh`, MATERIAL_FUNCTIONS.md) | a fire inside smoke is drawn behind all of it (measured: not seen at all at 0.2 and 0.5 s, "Why volumes must not overlap"); neighbouring fireballs hide each other in the same way; no smoke grid around explosions | **now** (2026-11-13: the kernel takes the ray a stretch at a time and sums the coefficients of the media it is in, offline and live; `volume/overlap-emission`, `-live`). What is left is `Explosions`' own: taking a grid again, in a PR of the voxel line's | puff a `SimulatedSmoke` around fireballs again (`Explosions` taking a grid) and run the comparison that found it (`bench-voxel-fire` at d7b4e4a, `--only smoke --ages 0.2,0.5`): the fire seen in its smoke offline and live; two overlapping fireballs both seen |
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 20fe2ff..5a7c159 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -129,7 +129,7 @@ struct Pixel { color: vec4<f32>, albedo: vec4<f32>, normal: vec4<f32>, emit: vec
struct Instance { m0: vec4<f32>, m1: vec4<f32>, m2: vec4<f32>, n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, info: vec4<u32>, p0: vec4<f32>, p1: vec4<f32>, p2: vec4<f32> };
@group(0) @binding(17) var<storage, read> instances: array<Instance>;
// Bounded participating media (`VolumeMesh`, gpu.rs MediumGpu; F_MEDIA), P.time.w of them: world -> local affine rows,
-// (volume function, shape: 0 box / 1 sphere, homogeneous, 1 = it changes with time: `VolumeFunction` `animated`, a
+// (volume function, shape: 0 box / 1 sphere / 2 none while its node is hidden, homogeneous, 1 = it changes with time: `VolumeFunction` `animated`, a
// simulated grid), (majorant 1/m, HG anisotropy, -, -), customData, parameters.
struct Medium { w0: vec4<f32>, w1: vec4<f32>, w2: vec4<f32>, a: vec4<u32>, b: vec4<f32>, c: vec4<f32>, p: array<vec4<f32>, 8> };
@group(0) @binding(18) var<storage, read> media: array<Medium>;
@@ -1612,8 +1612,9 @@ fn local_lights(s: Surface, lb: Lobes, v: vec3<f32>, o: vec3<f32>, x: vec3<f32>,
}
for (; i < gend; i++) {
let li = lights[i];
- // Cheap rejects before sampling the light: beyond its attenuation range (the window is zero there), or
- // entirely behind the surface.
+ // Cheap rejects before sampling the light: black (off, or hidden), beyond its attenuation range (the
+ // window is zero there), or entirely behind the surface.
+ if (all(li.color.rgb <= vec3<f32>(0.0))) { continue; }
let dc = li.pos.xyz - x;
let reach = li.color.w + select(li.dir.w, length(li.ext.xyz) + li.dir.w, u32(li.pos.w) == 3u);
if (li.color.w > 0.0 && dot(dc, dc) > reach * reach) { continue; }
@@ -2016,6 +2017,8 @@ fn medium_local(m: Medium, x: vec3<f32>) -> vec3<f32> {
fn medium_span(m: Medium, o: vec3<f32>, d: vec3<f32>) -> vec2<f32> {
let lo = medium_local(m, o);
let ld = vec3<f32>(dot(m.w0.xyz, d), dot(m.w1.xyz, d), dot(m.w2.xyz, d));
+ // (Its node hidden: scene.rs MEDIUM_HIDDEN. No ray crosses it.)
+ if (m.a.y >= 2u) { return vec2<f32>(1.0, 0.0); }
if (m.a.y == 1u) {
let a = dot(ld, ld);
let b = dot(lo, ld);
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index b27b6a5..2a3b542 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -231,6 +231,8 @@ pub struct Uploaded {
/// Vertex colours (F_VCOLOR): their byte offset in `prev_verts` (three words per triangle, room included).
pub vcolor_base: Option<u64>,
pub media_nodes: Vec<u32>,
+ /// Per medium: its node is hidden (`set_medium_hidden`). The live view runs no media pass while all are.
+ pub media_hidden: std::cell::RefCell<Vec<bool>>,
/// The model instances' kernel records (`GpuInstance`): movable ones are rewritten when they move.
pub instances: wgpu::Buffer,
/// Room for in-place geometry edits (`EditRoom`), and the binding that holds the environment CDF and the
@@ -2072,7 +2074,7 @@ impl Gpu {
self.device.poll(wgpu::PollType::wait_indefinitely())?;
timings.push(("upload_ms".into(), t0.elapsed().as_secs_f64() * 1000.0));
let bg_parts = BindParts { nodes: b_nodes, energy: b_energy, texinfo: b_texinfo, tex_view, env_view, sampler, grid_view };
- Ok(Uploaded { bg, bg_parts, tables, accum: b_accum, params: b_params, width: w, height: h, kernel, materials: b_mats, lights: b_lights, objects: b_objects, emitters: b_emit, verts: b_verts, attrs: b_attrs, prev_verts: b_prev, dynamic_first, accel, units: scene.units.clone(), particles, gpu_particles, grids, translucent, media: b_media, vcolor_base: (!scene.gpu_vcolors.is_empty()).then_some(scene.vcolor_base as u64 * 16), media_nodes: scene.media_nodes.clone(), instances: b_instances, room, cdf: b_cdf, cdf_words: env_cdf.len(), region_words, env_tex })
+ Ok(Uploaded { bg, bg_parts, tables, accum: b_accum, params: b_params, width: w, height: h, kernel, materials: b_mats, lights: b_lights, objects: b_objects, emitters: b_emit, verts: b_verts, attrs: b_attrs, prev_verts: b_prev, dynamic_first, accel, units: scene.units.clone(), particles, gpu_particles, grids, translucent, media: b_media, vcolor_base: (!scene.gpu_vcolors.is_empty()).then_some(scene.vcolor_base as u64 * 16), media_nodes: scene.media_nodes.clone(), media_hidden: std::cell::RefCell::new(scene.media.iter().map(|m| m.a[1] == crate::scene::MEDIUM_HIDDEN).collect()), instances: b_instances, room, cdf: b_cdf, cdf_words: env_cdf.len(), region_words, env_tex })
}
/// Bytes Metal allocates for an AABB BLAS over `count` boxes in `boxes` (its own size query through wgpu-hal; None
@@ -2471,6 +2473,22 @@ impl Gpu {
self.queue.write_buffer(&up.cdf, 0, bytemuck::cast_slice(cdf));
}
+ /// A volume node shown or hidden by its own `visible`, in place: its media keep their place in the table with
+ /// their shape (`shape`: the node's) or none (pathtrace.wgsl `medium_span`: no ray crosses it). False when no
+ /// medium of the build is that node's (the build left it out: a rebuild).
+ pub fn set_medium_hidden(&self, up: &Uploaded, node: u32, shape: u32, hide: bool) -> bool {
+ let size = std::mem::size_of::<crate::scene::MediumGpu>();
+ let mut hidden = up.media_hidden.borrow_mut();
+ let mut found = false;
+ for (k, _) in up.media_nodes.iter().enumerate().filter(|(_, n)| **n == node) {
+ found = true;
+ hidden[k] = hide;
+ let at = k * size + std::mem::offset_of!(crate::scene::MediumGpu, a) + 4;
+ self.queue.write_buffer(&up.media, at as u64, bytemuck::bytes_of(&if hide { crate::scene::MEDIUM_HIDDEN } else { shape }));
+ }
+ found
+ }
+
pub fn set_medium(&self, up: &Uploaded, node: u32, rows: Option<[[f32; 4]; 3]>, custom: Option<[f32; 4]>) {
// (Its grid program runs in the node's box as it is now.)
for sim in up.grids.iter().flat_map(|g| g.grids.iter()).filter(|g| g.node == node).filter_map(|g| g.sim.as_ref()) {
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index 4688cf4..1f54fb7 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -207,7 +207,7 @@ pub fn rng_seed() -> u32 {
pub const LIGHT_GROUP: usize = 16;
/// Distance beyond which a local light gives nothing (the kernel's range test in `local_lights`); f32::MAX without a
-/// range.
+/// range. (A black light gives nothing anywhere: `lights_with_groups` leaves it out.)
fn light_reach(l: &scene::GpuLight) -> f32 {
if l.color[3] <= 0.0 {
return f32::MAX;
@@ -267,22 +267,28 @@ pub fn light_order(lights: &[scene::GpuLight]) -> Vec<usize> {
}
/// The light table as uploaded: the lights, then per group of LIGHT_GROUP local lights (counted from the first local
-/// one) an entry whose `pos` is the sphere (centre, radius) holding every point its lights reach. THREERT_LIGHT_GROUPS=0:
-/// unbounded spheres, every light tested (A/B).
+/// one) an entry whose `pos` is the sphere (centre, radius) holding every point its lights reach. Black lights (off, or
+/// hidden: `scene::gpu_light_shown`) reach nothing and are in no sphere; a group of them alone has radius -1 (no point
+/// is in it). THREERT_LIGHT_GROUPS=0: unbounded spheres, every light tested (A/B).
pub fn lights_with_groups(lights: &[scene::GpuLight]) -> Vec<scene::GpuLight> {
static OFF: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let off = *OFF.get_or_init(|| std::env::var("THREERT_LIGHT_GROUPS").is_ok_and(|v| v == "0"));
let nd = lights.iter().take_while(|l| l.pos[3] == 0.0).count();
let mut out = lights.to_vec();
for g in lights[nd..].chunks(LIGHT_GROUP) {
+ let lit = |l: &&scene::GpuLight| l.color[..3].iter().any(|c| *c > 0.0);
+ if !off && !g.iter().any(|l| lit(&l)) {
+ out.push(scene::GpuLight { pos: [0.0, 0.0, 0.0, -1.0], ..Default::default() });
+ continue;
+ }
let (mut a, mut b) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
- for l in g {
+ for l in g.iter().filter(lit) {
a = a.min(Vec3::from_slice(&l.pos[..3]));
b = b.max(Vec3::from_slice(&l.pos[..3]));
}
let c = (a + b) * 0.5;
let mut r = 0.0f32;
- for l in g {
+ for l in g.iter().filter(lit) {
let reach = light_reach(l);
r = if reach == f32::MAX { f32::MAX } else { r.max(c.distance(Vec3::from_slice(&l.pos[..3])) + reach) };
}
@@ -1037,6 +1043,24 @@ mod light_lod_tests {
};
assert!(mean(&table) < 0.5 * mean(&unsorted), "groups are compact: {} vs {}", mean(&table), mean(&unsorted));
}
+
+ /// Black lights (off, or hidden) are in no group's sphere: one parked far away does not widen its group, and a
+ /// group of them alone holds no point.
+ #[test]
+ fn black_lights_reach_nothing() {
+ let at = |x: f32, lit: bool| scene::GpuLight { pos: [x, 0.0, 0.0, 1.0], color: [if lit { 1.0 } else { 0.0 }, 0.0, 0.0, 10.0], ..Default::default() };
+ // 16 lit lights within 15 m and, in their group's place, one of them black 10 km away: the sphere as without it.
+ let mut near: Vec<_> = (0..LIGHT_GROUP).map(|k| at(k as f32, true)).collect();
+ let lit = lights_with_groups(&near)[LIGHT_GROUP].pos;
+ near[3] = at(-10_000.0, false);
+ let with_black = lights_with_groups(&near)[LIGHT_GROUP].pos;
+ assert!(with_black[3] <= lit[3] && with_black[3] > 0.0, "{with_black:?} for {lit:?}");
+ // A group of black lights alone: radius -1.
+ let dark: Vec<_> = (0..LIGHT_GROUP + 2).map(|k| at(k as f32, k < LIGHT_GROUP)).collect();
+ let t = lights_with_groups(&dark);
+ assert!(t[dark.len()].pos[3] > 0.0);
+ assert_eq!(t[dark.len() + 1].pos[3], -1.0);
+ }
}
#[cfg(test)]
diff --git a/renderer/src/live.rs b/renderer/src/live.rs
index d9feecb..bdd0448 100644
--- a/renderer/src/live.rs
+++ b/renderer/src/live.rs
@@ -1668,11 +1668,22 @@ impl LiveCore {
if !changes.any() {
return Ok(false);
}
- // Particle systems shown or hidden by their own `visible`: in place when the build has them (a rain curtain
- // the weather turns off costs nothing while off), else with the rebuild.
+ // Objects shown or hidden by their own `visible`: in place when the build has them (a rain curtain the weather
+ // turns off, a pool's idle fireball and its light cost nothing while off), else with the rebuild.
if !changes.structural {
- for id in std::mem::take(&mut changes.particles_shown) {
- if !self.g.set_particles_hidden(&self.sc.up, id, !world.shown(id)) {
+ for id in std::mem::take(&mut changes.shown) {
+ let hide = !world.shown(id);
+ let done = match world.objects.get(&id).map(|o| &o.kind) {
+ Some(crate::world::Kind::Particles { .. }) => self.g.set_particles_hidden(&self.sc.up, id, hide),
+ Some(crate::world::Kind::Volume { shape, .. }) => self.g.set_medium_hidden(&self.sc.up, id, *shape, hide),
+ // (Its table entry, black while hidden: `Tables::update_light`.)
+ Some(crate::world::Kind::Light(_)) if self.sc.tables.light_index.contains_key(&id) => {
+ changes.lights.insert(id);
+ true
+ }
+ _ => false,
+ };
+ if !done {
changes.structural = true;
}
}
@@ -1876,6 +1887,9 @@ impl LiveCore {
}
let (q, up, e) = (&self.g.queue, &self.sc.up, &mut self.sc.tables);
if d.lights && !e.lights.is_empty() {
+ if d.lights_moved {
+ e.regroup_lights();
+ }
q.write_buffer(&up.lights, 0, bytemuck::cast_slice(&crate::lights_with_groups(&e.lights)));
}
if d.objects {
@@ -1938,6 +1952,7 @@ impl LiveCore {
if let (Some(idx), Some(o)) = (e.light_index.get(&id), world.objects.get(&id)) {
if let crate::world::Kind::Light(l) = &o.kind {
if let Some(mut gl) = scene::gpu_light(l, world.world_matrix(id), o.power) {
+ // (The sun: hidden with a rebuild, `World::set_visible`.)
gl.color = [colour.x, colour.y, colour.z, 0.0];
for &i in idx {
e.lights[i] = gl;
@@ -3779,7 +3794,8 @@ impl LiveCore {
let g = &self.g;
let t_submit = Instant::now();
let pipeline = g.pipeline(&self.sc.up.kernel, true);
- let media = self.sc.up.kernel.features & gpu::F_MEDIA != 0;
+ // (No media pass while every medium is hidden: a pool of idle fireballs costs the frame nothing.)
+ let media = self.sc.up.kernel.features & gpu::F_MEDIA != 0 && self.sc.up.media_hidden.borrow().iter().any(|h| !h);
let media_train = (media && self.cache.is_some()).then(|| g.media_pipeline(&self.sc.up.kernel, "media_train"));
let media_composite = media.then(|| g.media_pipeline(&self.sc.up.kernel, "media_composite"));
// This frame's sub-pixel jitter (Halton 2, 3), every camera ray's and the raster visibility pass's: 8 phases at
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index 6dab6e1..53e2b03 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -600,8 +600,8 @@ pub struct PoseGroup {
/// What groups posed models into a `PoseGroup`: model, nodes, clip, time (bits), loop.
type PoseKey = (String, Option<Vec<String>>, String, u32, bool);
-/// pathtrace.wgsl `Medium`: world -> local affine rows (the unit box / sphere's space), (function, shape, homogeneous,
-/// animated),
+/// pathtrace.wgsl `Medium`: world -> local affine rows (the unit box / sphere's space), (function, shape or
+/// `MEDIUM_HIDDEN`, homogeneous, animated),
/// (majorant 1/m, HG anisotropy, -, -), the node's customData, 32 parameter floats.
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
@@ -654,7 +654,7 @@ pub struct ParticleSystem {
pub seed: u32,
/// The node's customData (the particle function's `i.custom`).
pub custom: [f32; 4],
- /// Hidden by its own `visible` (`World::particles_hidden_built`): in the build, its pass idle until it is shown.
+ /// Hidden by its own `visible` (`World::hidden_built`): in the build, its pass idle until it is shown.
pub hidden: bool,
}
@@ -842,6 +842,16 @@ pub fn apply_shader(gm: &mut GpuMaterial, sh: &desc::ShaderRef, shaders: &HashMa
/// Analytic light of a light object with world matrix `m` (rect lights with a visible card are emitter geometry
/// instead, see `card_material`). Emission scales with the node's power.
+/// `gpu_light` of a light that may be hidden (`shown`: `World::shown`): hidden, its entry stays where it is in the
+/// table, black (the kernel skips black lights, and they are in no group's sphere: lib.rs `lights_with_groups`).
+pub fn gpu_light_shown(l: &Light, m: Mat4, power: f32, shown: bool) -> Option<GpuLight> {
+ let mut gl = gpu_light(l, m, power)?;
+ if !shown {
+ gl.color = [0.0, 0.0, 0.0, gl.color[3]];
+ }
+ Some(gl)
+}
+
pub fn gpu_light(l: &Light, m: Mat4, power: f32) -> Option<GpuLight> {
let pos = m.transform_point3(Vec3::ZERO);
let dir = m.transform_vector3(Vec3::NEG_Z).normalize();
@@ -916,6 +926,9 @@ pub fn card_material(color: [f32; 3], intensity: f32) -> GpuMaterial {
/// The most volumes a scene may show at once: the kernel loops over at most 32 media with a 32-bit mask
/// (pathtrace.wgsl `media_track`, `media_march`, `media_shadows`). A scene past it is refused, not drawn without some.
pub const MAX_MEDIA: usize = 32;
+/// A medium's shape (`MediumGpu::a[1]`: 0 box, 1 sphere) while its node is hidden: none, no ray crosses it
+/// (pathtrace.wgsl `medium_span`).
+pub const MEDIUM_HIDDEN: u32 = 2;
pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&serde_json::Value>) -> Result<Scene> {
let t0 = web_time::Instant::now();
@@ -1026,6 +1039,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let mut procs: Vec<ProcObject> = vec![];
let mut media: Vec<MediumGpu> = vec![];
let mut media_nodes: Vec<u32> = vec![];
+ // Volumes shown that the loop below has yet to place: hidden ones take what the kernel has left after them.
+ let mut media_to_show = w.objects.iter().filter(|(id, o)| matches!(o.kind, Kind::Volume { .. }) && w.shown(**id)).count();
let mut grids: Vec<GridBuild> = vec![];
let grid_programs: Vec<(String, String, String)> = w.grid_programs.iter().map(|(k, (c, h))| (k.clone(), c.clone(), h.clone())).collect();
let mut objects: Vec<[f32; 4]> = vec![];
@@ -1540,7 +1555,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
retained.dynamic.insert(*id, DynamicModel { first, mats, ..Default::default() });
}
}
- Kind::Light(l) => match (l, gpu_light(l, m, n.power)) {
+ Kind::Light(l) => match (l, gpu_light_shown(l, m, n.power, shown)) {
(_, Some(gl)) => {
lights.push(gl);
retained.light_nodes.push(*id);
@@ -1560,7 +1575,12 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
}
_ => {}
},
- Kind::Volume { function, params, shape, majorant, g, homogeneous, animated, grid } if shown => {
+ // (Hidden by its own `visible`: built while the kernel has room after the volumes shown, with no shape,
+ // so that showing it is in place: gpu.rs `set_medium_hidden`.)
+ Kind::Volume { function, params, shape, majorant, g, homogeneous, animated, grid } if shown || (w.hidden_built(*id) && media.len() + media_to_show < MAX_MEDIA) => {
+ if shown {
+ media_to_show -= 1;
+ }
let func = volume_fns.iter().position(|(k, _, _)| k == function).ok_or_else(|| anyhow!("object {}: unknown volume function {function}", n.name))? as u32;
let mut p = [0.0f32; 32];
for (k, v) in params.iter().take(32).enumerate() {
@@ -1601,7 +1621,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
if media.len() >= MAX_MEDIA {
return Err(anyhow!("object {}: more than {MAX_MEDIA} volumes shown at once (the kernel takes {MAX_MEDIA}; the rest would not be drawn)", n.name));
}
- media.push(MediumGpu { w: medium_rows(m), a: [func, *shape, *homogeneous as u32, *animated as u32], b: [majorant.max(0.0), g.clamp(-0.99, 0.99), at[0], at[1]], c: n.custom, p });
+ media.push(MediumGpu { w: medium_rows(m), a: [func, if shown { *shape } else { MEDIUM_HIDDEN }, *homogeneous as u32, *animated as u32], b: [majorant.max(0.0), g.clamp(-0.99, 0.99), at[0], at[1]], c: n.custom, p });
media_nodes.push(*id);
}
Kind::Procedural { .. } if shown => {
@@ -1611,7 +1631,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
procs.push(p);
}
}
- Kind::Particles { count, emitter, params, material, emitter_area } if (shown || w.particles_hidden_built(*id)) && *count > 0 => {
+ Kind::Particles { count, emitter, params, material, emitter_area } if (shown || w.hidden_built(*id)) && *count > 0 => {
// Quads collapsed at the node until the particle pass places them (each its own object: pivot,
// bounds and per-particle data for material functions).
let mat = *retained.materials.get(material).ok_or_else(|| anyhow!("object {}: unknown material {material}", n.name))?;
@@ -2341,5 +2361,8 @@ mod instance_tests {
let e = build_with(MAX_MEDIA as u32 + 1, 0).err().expect("33 volumes refused");
assert!(format!("{e:#}").contains("more than 32 volumes"), "{e:#}");
assert_eq!(build_with(MAX_MEDIA as u32, 4).unwrap().media.len(), MAX_MEDIA, "hidden ones do not count");
+ // Hidden by their own `visible`, they keep a place while there is room after those shown (shown in place).
+ let b = build_with(MAX_MEDIA as u32 - 2, 4).unwrap();
+ assert_eq!((b.media.len(), b.media.iter().filter(|m| m.a[1] == MEDIUM_HIDDEN).count()), (MAX_MEDIA, 2));
}
}
diff --git a/renderer/src/tables.rs b/renderer/src/tables.rs
index 0d9afcb..858c8a4 100644
--- a/renderer/src/tables.rs
+++ b/renderer/src/tables.rs
@@ -14,6 +14,8 @@ use std::collections::{HashMap, HashSet};
pub struct Dirty {
pub materials: bool,
pub lights: bool,
+ /// A local light moved, or went dark or lit: the light groups are sorted again (`Tables::regroup_lights`).
+ pub lights_moved: bool,
pub objects: bool,
/// Emitter weights changed (powers): the emitter CDF and the light tree's powers are rebuilt.
pub emitters: bool,
@@ -191,11 +193,37 @@ impl Tables {
}
let (Some(idx), Some(o)) = (self.light_index.get(&id), w.objects.get(&id)) else { return };
let Kind::Light(l) = &o.kind else { return };
- if let Some(gl) = scene::gpu_light(l, w.world_matrix(id), o.power) {
+ if let Some(gl) = scene::gpu_light_shown(l, w.world_matrix(id), o.power, w.shown(id)) {
+ // A local light somewhere else, or lit where it was dark: the groups are sorted again (`regroup_lights`).
+ let moved = idx.iter().any(|&i| self.lights[i].pos != gl.pos || (self.lights[i].color[..3] == [0.0; 3]) != (gl.color[..3] == [0.0; 3]));
for &i in idx {
self.lights[i] = gl;
}
d.lights = true;
+ d.lights_moved |= moved && gl.pos[3] != 0.0;
+ }
+ }
+
+ /// The lights in the kernel's order again (`crate::light_order`: each class in spatially compact groups), after
+ /// local lights moved: a group's sphere holds every point its lights reach, and lights that have drifted apart
+ /// make it large. `light_index` and the retained nodes follow.
+ pub fn regroup_lights(&mut self) {
+ let order = crate::light_order(&self.lights);
+ if order.iter().enumerate().all(|(k, &i)| k == i) {
+ return;
+ }
+ self.lights = order.iter().map(|&i| self.lights[i]).collect();
+ if self.retained.light_nodes.len() == order.len() {
+ self.retained.light_nodes = order.iter().map(|&i| self.retained.light_nodes[i]).collect();
+ }
+ let mut at = vec![0usize; order.len()];
+ for (k, &i) in order.iter().enumerate() {
+ at[i] = k;
+ }
+ for idx in self.light_index.values_mut() {
+ for i in idx.iter_mut() {
+ *i = at[*i];
+ }
}
}
diff --git a/renderer/src/world.rs b/renderer/src/world.rs
index 4a64b50..958c35a 100644
--- a/renderer/src/world.rs
+++ b/renderer/src/world.rs
@@ -273,9 +273,10 @@ impl Default for Settings {
#[derive(Default, Debug, Clone)]
pub struct Changes {
pub structural: bool,
- /// Particle systems (`Kind::Particles`, not light-sampled) shown or hidden by their own `visible`: in place when
- /// the build has them (live.rs `commit`, gpu.rs `set_particles_hidden`), else a rebuild.
- pub particles_shown: HashSet<u32>,
+ /// Objects shown or hidden by their own `visible` whose build can take it in place (live.rs `commit`): particle
+ /// systems that are not light-sampled (gpu.rs `set_particles_hidden`), volumes (their medium: `set_medium_hidden`)
+ /// and lights without a card (their table entry goes black). A rebuild where the build left the object out.
+ pub shown: HashSet<u32>,
pub materials: HashSet<u32>,
/// Objects whose light parameters changed.
pub lights: HashSet<u32>,
@@ -321,7 +322,7 @@ pub struct Changes {
impl Changes {
pub fn any(&self) -> bool {
- self.structural || !self.particles_shown.is_empty() || !self.new_materials.is_empty() || !self.materials.is_empty() || !self.lights.is_empty() || !self.powers.is_empty() || !self.customs.is_empty() || self.environment || self.camera || self.sun || self.exposure || !self.poses.is_empty() || !self.moved.is_empty() || !self.instanced.is_empty() || self.edits()
+ self.structural || !self.shown.is_empty() || !self.new_materials.is_empty() || !self.materials.is_empty() || !self.lights.is_empty() || !self.powers.is_empty() || !self.customs.is_empty() || self.environment || self.camera || self.sun || self.exposure || !self.poses.is_empty() || !self.moved.is_empty() || !self.instanced.is_empty() || self.edits()
}
/// Geometry edits are pending (`geometries`, `added`, `removed`).
pub fn edits(&self) -> bool {
@@ -752,8 +753,18 @@ impl World {
let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
if o.visible != visible {
o.visible = visible;
- if matches!(o.kind, Kind::Particles { emitter_area, .. } if emitter_area <= 0.0) {
- self.changes.particles_shown.insert(id);
+ // In place: what keeps its slot in the build while hidden (`hidden_built`), and lights, which always
+ // have theirs (not a rect light's card, which is geometry, nor the sun, whose colour is the sky bake's).
+ let sun = matches!(self.environment.sky, desc::Sky::Atmosphere { sun: Some(s), .. } if s == id);
+ let o = &self.objects[&id];
+ let in_place = match &o.kind {
+ Kind::Particles { emitter_area, .. } => *emitter_area <= 0.0,
+ Kind::Volume { .. } => true,
+ Kind::Light(l) => !sun && !matches!(l, desc::Light::Rect { visible: true, .. }),
+ _ => false,
+ };
+ if in_place {
+ self.changes.shown.insert(id);
} else {
self.changes.structural = true;
}
@@ -761,11 +772,17 @@ impl World {
Ok(())
}
- /// Whether the build holds particle system `id` though it is hidden: its own `visible` is false, everything above
- /// it is shown, and it is not light-sampled (a rain curtain the weather turns off): shown again in place.
- pub fn particles_hidden_built(&self, id: u32) -> bool {
+ /// Whether the build holds `id` though it is hidden: its own `visible` is false, everything above it is shown, and
+ /// it is a particle system that is not light-sampled (a rain curtain the weather turns off) or a volume (a pool's
+ /// idle fireball): shown again in place. (Volumes while the kernel has room for them: scene.rs `build`.)
+ pub fn hidden_built(&self, id: u32) -> bool {
let Some(o) = self.objects.get(&id) else { return false };
- !o.visible && matches!(o.kind, Kind::Particles { emitter_area, .. } if emitter_area <= 0.0) && o.parent.is_none_or(|p| self.shown(p))
+ let kept = match o.kind {
+ Kind::Particles { emitter_area, .. } => emitter_area <= 0.0,
+ Kind::Volume { .. } => true,
+ _ => false,
+ };
+ !o.visible && kept && o.parent.is_none_or(|p| self.shown(p))
}
pub fn set_power(&mut self, id: u32, power: f32) -> Result<()> {
@@ -1191,6 +1208,43 @@ mod tests {
assert!(w.grids.contains_key(&1) && w.grids.contains_key(&13) && !w.grids.contains_key(&10), "unused ones went, grid 1 (in use) stayed");
}
+ /// Hiding by an object's own `visible`: in place for a volume, a light without a card and a particle system that
+ /// is not light-sampled (`Changes::shown`; hidden, the build keeps a volume: `hidden_built`); a rebuild for a mesh,
+ /// a rect light with its card, the sun.
+ #[test]
+ fn hiding_a_volume_or_a_light_is_not_structural() {
+ let mut w = World::default();
+ let light = |json: serde_json::Value| Kind::Light(serde_json::from_value(json).unwrap());
+ let volume = Kind::Volume { function: "f".into(), params: vec![], shape: 1, majorant: 1.0, g: 0.0, homogeneous: false, animated: true, grid: None };
+ w.set_object(1, "fire".into(), None, volume, false, false).unwrap();
+ w.set_object(2, "lamp".into(), None, light(serde_json::json!({ "type": "point", "color": [1, 1, 1], "castShadow": true, "intensity": 100, "radius": 0.01, "range": 0 })), false, false).unwrap();
+ w.set_object(3, "card".into(), None, light(serde_json::json!({ "type": "rect", "color": [1, 1, 1], "castShadow": true, "intensity": 100, "width": 1, "height": 1, "range": 0 })), false, false).unwrap();
+ w.set_object(4, "panel".into(), None, light(serde_json::json!({ "type": "rect", "color": [1, 1, 1], "castShadow": true, "intensity": 100, "width": 1, "height": 1, "range": 0, "visible": false })), false, false).unwrap();
+ w.set_object(5, "group".into(), None, Kind::Group, false, false).unwrap();
+ assert!(w.take_changes().structural, "the first commit builds the scene");
+ for id in [1, 2, 4] {
+ w.set_visible(id, false).unwrap();
+ let c = w.take_changes();
+ assert!(!c.structural && c.shown.contains(&id) && c.any(), "{id}: hidden in place");
+ assert!(!w.shown(id));
+ w.set_visible(id, false).unwrap();
+ assert!(!w.take_changes().any(), "{id}: no change");
+ w.set_visible(id, true).unwrap();
+ let c = w.take_changes();
+ assert!(!c.structural && c.shown.contains(&id), "{id}: shown in place");
+ }
+ w.set_visible(1, false).unwrap();
+ assert!(w.hidden_built(1) && !w.hidden_built(2), "a hidden volume keeps its place in the build; a light always has one");
+ for id in [3, 5] {
+ w.set_visible(id, false).unwrap();
+ assert!(w.take_changes().structural, "{id}: a rect light's card and a group are geometry");
+ }
+ let inner = Kind::Volume { function: "f".into(), params: vec![], shape: 0, majorant: 1.0, g: 0.0, homogeneous: false, animated: false, grid: None };
+ w.set_object(6, "inner".into(), Some(5), inner, false, false).unwrap();
+ w.set_visible(6, false).unwrap();
+ assert!(!w.hidden_built(6), "under a hidden parent nothing is kept");
+ }
+
/// Wind sway: the object leans downwind about its origin by Sway::angle, the phase from its world position when it
/// has none; set_sway(None) puts it back at rest.
#[test]
diff --git a/tests/render/light-hidden-in-place-live.ts b/tests/render/light-hidden-in-place-live.ts
new file mode 100644
index 0000000..dbaaf14
--- /dev/null
+++ b/tests/render/light-hidden-in-place-live.ts
@@ -0,0 +1,34 @@
+// A light hidden in place (world.rs `set_visible`: its table entry goes black, no rebuild): two 1000 cd lights as
+// light/hidden's, both shown at first; the frame script hides one after a few frames. The plane reads the other's
+// alone. (The light is in the plane's accumulated irradiance, which follows a change over frames: with a 5000 cd
+// light hidden the plane still read 6 % over the one left 2 s later, the temporal filter's tail, not this test's
+// matter.)
+import { defineGame } from "@threert/gameplay";
+import type { PointLight } from "@threert/scene";
+import { ONE, lights } from "./light-hidden.ts";
+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "light/hidden-in-place-live", features: ["point-light", "lambert", "edits"], reference: "analytic", temporal: true,
+ metric: { kind: "radiance", region: [0.48, 0.48, 0.52, 0.52], expected: ONE, tolerance: 0.02 },
+ live: 240,
+ note: "the second light's own visible set false at frame 4: in place",
+};
+
+let elapsed = 0;
+let second: PointLight;
+export default defineGame<Record<string, never>>({
+ state: {},
+ setup: () => {
+ elapsed = 0;
+ const scene = sceneWithSky(0);
+ const [a, b] = lights(1000);
+ second = b;
+ return result(scene, camera(scene, [0, 1.5, 3], [0, 0, 0]), [a, b, plane(20, lambert(0.5))]);
+ },
+ frame(f) {
+ elapsed += f.dt;
+ if (elapsed > 3 / 60) second.visible = false;
+ },
+ handlers: {},
+});
diff --git a/tests/render/light-hidden.ts b/tests/render/light-hidden.ts
new file mode 100644
index 0000000..7ab25aa
--- /dev/null
+++ b/tests/render/light-hidden.ts
@@ -0,0 +1,31 @@
+// A hidden light gives no light: two point lights 2 m above an albedo-0.5 Lambert plane, 1000 cd shown and 5000 cd
+// hidden (`visible = false`). Directly below them the plane reads the shown one's 0.5 x 1000 / 2^2 / pi alone. (Until
+// 2026-11-13 the build placed every light whatever its visibility: 6 times that.)
+import { PointLight } from "@threert/scene";
+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+export const ONE = (0.5 * 1000) / 4 / Math.PI;
+
+export const test: TestMeta = {
+ id: "light/hidden", features: ["point-light", "lambert"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: [0.48, 0.48, 0.52, 0.52], expected: ONE, tolerance: 0.02 },
+ note: "as light/point-inverse-square, with a second, hidden light in the same place",
+};
+
+/** The two lights (the first 1000 cd, the second `cd`) over the plane. */
+export function lights(cd = 5000): [PointLight, PointLight] {
+ const mk = (cd: number) => {
+ const l = new PointLight(0xffffff, cd, 0);
+ l.radius = 0.001;
+ l.position.set(0, 2, 0);
+ return l;
+ };
+ return [mk(1000), mk(cd)];
+}
+
+export default function () {
+ const scene = sceneWithSky(0);
+ const [a, b] = lights();
+ b.visible = false;
+ return result(scene, camera(scene, [0, 1.5, 3], [0, 0, 0]), [a, b, plane(20, lambert(0.5))]);
+}
diff --git a/tests/render/light-shown-in-place-live.ts b/tests/render/light-shown-in-place-live.ts
new file mode 100644
index 0000000..0ae0fb1
--- /dev/null
+++ b/tests/render/light-shown-in-place-live.ts
@@ -0,0 +1,32 @@
+// A light shown in place: light/hidden's two lights, the 5000 cd one hidden when the scene is built (it has its entry
+// in the light table, black) and shown by the frame script after a few frames, without a rebuild. The plane reads both.
+import { defineGame } from "@threert/gameplay";
+import type { PointLight } from "@threert/scene";
+import { ONE, lights } from "./light-hidden.ts";
+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "light/shown-in-place-live", features: ["point-light", "lambert", "edits"], reference: "analytic", temporal: true,
+ metric: { kind: "radiance", region: [0.48, 0.48, 0.52, 0.52], expected: 6 * ONE, tolerance: 0.02 },
+ live: 120,
+ note: "the second light's own visible set true at frame 4: in place",
+};
+
+let elapsed = 0;
+let second: PointLight;
+export default defineGame<Record<string, never>>({
+ state: {},
+ setup: () => {
+ elapsed = 0;
+ const scene = sceneWithSky(0);
+ const [a, b] = lights();
+ second = b;
+ b.visible = false;
+ return result(scene, camera(scene, [0, 1.5, 3], [0, 0, 0]), [a, b, plane(20, lambert(0.5))]);
+ },
+ frame(f) {
+ elapsed += f.dt;
+ if (elapsed > 3 / 60) second.visible = true;
+ },
+ handlers: {},
+});
diff --git a/tests/render/volume-hidden-in-place-live.ts b/tests/render/volume-hidden-in-place-live.ts
new file mode 100644
index 0000000..684645b
--- /dev/null
+++ b/tests/render/volume-hidden-in-place-live.ts
@@ -0,0 +1,41 @@
+// A volume hidden in place (world.rs `set_visible`: its medium keeps its place in the table with no shape, no
+// rebuild): volume/box-transmittance's absorbing box before the 2-nit wall, hidden by the frame script after a few
+// frames. The wall reads its 2 nits.
+import { BoxGeometry, Mesh, MeshStandardMaterial, VolumeMesh } from "@threert/scene";
+import { defineGame } from "@threert/gameplay";
+import { UNIFORM } from "./volume-box-transmittance.ts";
+import { CENTER, camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "volume/hidden-in-place-live", features: ["volume", "edits"], reference: "analytic", temporal: true,
+ metric: { kind: "radiance", region: CENTER, expected: 2, tolerance: 0.02 },
+ live: 60,
+ note: "the box's own visible set false at frame 4: in place",
+};
+
+/** The wall and the box of volume/box-transmittance. */
+export function wallAndBox(): [Mesh, VolumeMesh] {
+ const wall = new Mesh(new BoxGeometry(8, 8, 0.1), new MeshStandardMaterial({ name: "wall", color: 0x000000, emissive: 0xffffff, emissiveIntensity: 2 }));
+ wall.position.set(0, 0, -2);
+ const box = new VolumeMesh({ volume: UNIFORM.with({ Density: 1 }), majorant: 1 });
+ box.scale.set(2, 2, 1);
+ return [wall, box];
+}
+
+let elapsed = 0;
+let box: VolumeMesh;
+export default defineGame<Record<string, never>>({
+ state: {},
+ setup: () => {
+ elapsed = 0;
+ const scene = sceneWithSky(0);
+ const [wall, b] = wallAndBox();
+ box = b;
+ return result(scene, camera(scene, [0, 0, 5], [0, 0, 0]), [wall, b]);
+ },
+ frame(f) {
+ elapsed += f.dt;
+ if (elapsed > 3 / 60) box.visible = false;
+ },
+ handlers: {},
+});
diff --git a/tests/render/volume-shown-in-place-live.ts b/tests/render/volume-shown-in-place-live.ts
new file mode 100644
index 0000000..9c8aa34
--- /dev/null
+++ b/tests/render/volume-shown-in-place-live.ts
@@ -0,0 +1,33 @@
+// A volume shown in place: volume/box-transmittance's box hidden when the scene is built (the build keeps a medium
+// for it, with no shape; it is the scene's only one, so no media pass runs until then) and shown by the frame script
+// after a few frames, without a rebuild. The wall behind it reads 2 e^-1 = 0.7358.
+import { defineGame } from "@threert/gameplay";
+import type { VolumeMesh } from "@threert/scene";
+import { wallAndBox } from "./volume-hidden-in-place-live.ts";
+import { CENTER, camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "volume/shown-in-place-live", features: ["volume", "edits"], reference: "analytic", temporal: true,
+ metric: { kind: "radiance", region: CENTER, expected: 2 * Math.exp(-1), tolerance: 0.02 },
+ live: 60,
+ note: "the box's own visible set true at frame 4: in place",
+};
+
+let elapsed = 0;
+let box: VolumeMesh;
+export default defineGame<Record<string, never>>({
+ state: {},
+ setup: () => {
+ elapsed = 0;
+ const scene = sceneWithSky(0);
+ const [wall, b] = wallAndBox();
+ box = b;
+ b.visible = false;
+ return result(scene, camera(scene, [0, 0, 5], [0, 0, 0]), [wall, b]);
+ },
+ frame(f) {
+ elapsed += f.dt;
+ if (elapsed > 3 / 60) box.visible = true;
+ },
+ handlers: {},
+});