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.

Particle systems hidden in place: a node's own visible no longer rebuilds the scene, and a hidden system costs nothing

Evan (Yifeng) Wangaa6bf7f12749
diff --git a/renderer/shaders/particles.wgsl b/renderer/shaders/particles.wgsl
index 818fc65..e2d888d 100644
--- a/renderer/shaders/particles.wgsl
+++ b/renderer/shaders/particles.wgsl
@@ -44,7 +44,8 @@ struct TriAttr { n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, uv: vec4<f32>, t:
// a: (first triangle in the GPU order, count, first object, function); b: (seed, first dynamic triangle, translucent
// (1: its triangles are the translucency pass's, `tblas` from the first translucent triangle), first translucent
-// triangle); c: the node's pivot; p: parameters; d: the node's customData.
+// triangle); c: the node's pivot, w > 0: collapse every particle (the system was just hidden: gpu.rs
+// `set_particles_hidden`); p: parameters; d: the node's customData.
struct System { a: vec4<u32>, b: vec4<u32>, c: vec4<f32>, p: array<vec4<f32>, 8>, d: vec4<f32> };
@group(0) @binding(0) var<uniform> PPS: PP;
@@ -132,7 +133,7 @@ fn particles(@builtin(global_invocation_id) gid: vec3<u32>) {
i.pivot = s.c.xyz;
i.custom = s.d;
var o = particle_function(s.a.w, i, s.p);
- if (!o.visible) {
+ if (!o.visible || s.c.w > 0.5) {
o.u = vec3<f32>(0.0);
o.v = vec3<f32>(0.0);
}
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index 0910dd5..d707b2e 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -232,6 +232,21 @@ pub struct ParticleGpu {
fresh: std::cell::Cell<bool>,
/// Some systems are opaque (in the scene's dynamic BLASes, rebuilt every frame).
opaque: bool,
+ /// Per system: its particle count, whether the translucency pass draws it, and its state when hidden in place
+ /// (`set_particles_hidden`): `Shown`, `Collapse` (this frame's pass collapses its quads), `Collapsed` (zero its
+ /// count next frame), `Idle`.
+ counts: Vec<u32>,
+ translucent: Vec<bool>,
+ hidden: std::cell::RefCell<Vec<Hidden>>,
+}
+
+/// A particle system's state as hidden in place (`ParticleGpu::hidden`).
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+enum Hidden {
+ Shown,
+ Collapse,
+ Collapsed,
+ Idle,
}
/// Volume training points per frame at most (translucent.wgsl `volume_train`).
@@ -1620,7 +1635,8 @@ impl Gpu {
let o = &scene.objects[ps.object as usize * scene.object_stride()];
let mut p = [0.0f32; 32];
p.copy_from_slice(&ps.params);
- ParticleSystemGpu { a: [ps.final_first, ps.count, ps.object, ps.func], b: [ps.seed, dynamic_first as u32, ps.translucent as u32, scene.trans_first], c: [o[0], o[1], o[2], 0.0], p, d: ps.custom }
+ // (A system hidden at build runs nothing: its quads stay collapsed at the node.)
+ ParticleSystemGpu { a: [ps.final_first, if ps.hidden { 0 } else { ps.count }, ps.object, ps.func], b: [ps.seed, dynamic_first as u32, ps.translucent as u32, scene.trans_first], c: [o[0], o[1], o[2], 0.0], p, d: ps.custom }
})
.collect();
// COPY_DST: pivot updates (`set_particle_pivot`).
@@ -1635,7 +1651,10 @@ impl Gpu {
});
let nodes = scene.particles.iter().map(|p| p.seed).collect();
let opaque = scene.particles.iter().any(|p| !p.translucent);
- Some(ParticleGpu { pipeline, stamp, bg: pbg, params, table: b_sys, nodes, systems: systems.len() as u32, max_count: scene.particles.iter().map(|p| p.count).max().unwrap_or(0), fresh: std::cell::Cell::new(true), opaque })
+ let counts = scene.particles.iter().map(|p| p.count).collect();
+ let translucent_sys = scene.particles.iter().map(|p| p.translucent).collect();
+ let hidden = std::cell::RefCell::new(scene.particles.iter().map(|p| if p.hidden { Hidden::Idle } else { Hidden::Shown }).collect());
+ Some(ParticleGpu { pipeline, stamp, bg: pbg, params, table: b_sys, nodes, systems: systems.len() as u32, max_count: scene.particles.iter().map(|p| p.count).max().unwrap_or(0), fresh: std::cell::Cell::new(true), opaque, counts, translucent: translucent_sys, hidden })
}
_ => None,
};
@@ -1806,6 +1825,28 @@ impl Gpu {
#[allow(clippy::too_many_arguments)]
pub fn run_particles(&self, up: &Uploaded, cam: [f32; 3], fwd: [f32; 3], time: f32, dt: f32, rain: f32, wetness: f32, e: &mut wgpu::CommandEncoder, pass_ts: Option<(&wgpu::QuerySet, u32)>, blas_ts: Option<(&wgpu::QuerySet, u32)>) {
let (Some(p), Some(accel)) = (&up.particles, &up.accel) else { return };
+ // Systems hidden in place: collapsed by last frame's pass, now idle (count 0); every system idle: no pass, no
+ // BLAS builds (their quads stay collapsed).
+ {
+ let mut hidden = p.hidden.borrow_mut();
+ for (k, h) in hidden.iter_mut().enumerate() {
+ match *h {
+ Hidden::Collapse => *h = Hidden::Collapsed,
+ Hidden::Collapsed => {
+ self.write_particle_count(p, k, 0, false);
+ *h = Hidden::Idle;
+ }
+ _ => {}
+ }
+ }
+ if hidden.iter().all(|h| *h == Hidden::Idle) {
+ // (The stateful GPU particles leave the dynamic BLAS rebuild to this pass when there are stateless ones.)
+ if up.gpu_particles.is_some() {
+ self.rebuild_dynamic(accel, e);
+ }
+ return;
+ }
+ }
let first = if p.fresh.replace(false) { 1.0 } else { 0.0 };
let v = [cam[0], cam[1], cam[2], time, fwd[0], fwd[1], fwd[2], dt, rain, wetness, first, 0.0];
self.queue.write_buffer(&p.params, 0, bytemuck::cast_slice(&v));
@@ -1987,15 +2028,48 @@ impl Gpu {
}
}
- /// A particle node moved: its systems' pivot (`i.pivot`).
+ /// A particle node moved: its systems' pivot (`i.pivot`; c.w, the collapse flag, kept).
pub fn set_particle_pivot(&self, up: &Uploaded, node: u32, pivot: [f32; 3]) {
let Some(p) = &up.particles else { return };
for (k, _) in p.nodes.iter().enumerate().filter(|(_, n)| **n == node) {
let at = (k * std::mem::size_of::<ParticleSystemGpu>() + 32) as u64;
- self.queue.write_buffer(&p.table, at, bytemuck::cast_slice(&[pivot[0], pivot[1], pivot[2], 0.0]));
+ self.queue.write_buffer(&p.table, at, bytemuck::cast_slice(&pivot));
}
}
+ /// System `k`'s particle count and collapse flag in the table (a.y, c.w).
+ fn write_particle_count(&self, p: &ParticleGpu, k: usize, count: u32, collapse: bool) {
+ let at = (k * std::mem::size_of::<ParticleSystemGpu>()) as u64;
+ self.queue.write_buffer(&p.table, at + 4, bytemuck::bytes_of(&count));
+ self.queue.write_buffer(&p.table, at + 44, bytemuck::bytes_of(&if collapse { 1.0f32 } else { 0.0 }));
+ }
+
+ /// A particle node shown or hidden by its own `visible`, in place: hidden, its systems' next pass collapses their
+ /// quads and then they run nothing (`run_particles`); shown, they run again. False when no system of the build is
+ /// that node's (the build left it out: a rebuild).
+ pub fn set_particles_hidden(&self, up: &Uploaded, node: u32, hide: bool) -> bool {
+ let Some(p) = &up.particles else { return false };
+ let mut hidden = p.hidden.borrow_mut();
+ let mut found = false;
+ for (k, _) in p.nodes.iter().enumerate().filter(|(_, n)| **n == node) {
+ found = true;
+ let shown = hidden[k] == Hidden::Shown;
+ if hide && shown {
+ self.write_particle_count(p, k, p.counts[k], true);
+ hidden[k] = Hidden::Collapse;
+ } else if !hide && !shown {
+ self.write_particle_count(p, k, p.counts[k], false);
+ hidden[k] = Hidden::Shown;
+ }
+ }
+ found
+ }
+
+ /// Whether the translucency pass has anything to draw: a translucent system shown (or collapsing).
+ pub fn translucent_particles_live(&self, up: &Uploaded) -> bool {
+ up.particles.as_ref().is_none_or(|p| p.translucent.iter().zip(p.hidden.borrow().iter()).any(|(t, h)| *t && *h != Hidden::Idle))
+ }
+
/// A particle node's customData changed: its systems' `i.custom`.
pub fn set_particle_custom(&self, up: &Uploaded, node: u32, custom: [f32; 4]) {
let Some(p) = &up.particles else { return };
diff --git a/renderer/src/live.rs b/renderer/src/live.rs
index 7ec315e..99abe1a 100644
--- a/renderer/src/live.rs
+++ b/renderer/src/live.rs
@@ -1500,6 +1500,15 @@ 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.
+ 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)) {
+ changes.structural = true;
+ }
+ }
+ }
// New materials without textures: entries after the scene's, before the edits that place objects drawn with
// them (and the GPU's table with them, grown if it is full).
if !changes.new_materials.is_empty() && !changes.structural {
@@ -3605,7 +3614,8 @@ impl LiveCore {
let bg = &self.sc.bgs[(self.frame % 2) as usize];
// Translucent particles: drawn over the composed image right after the specular filter composes it (into fb when
// depth of field / motion blur follow, else fa; live.wgsl spec_filter), then their volume voxels trained.
- let tl = self.sc.up.translucent.as_ref().map(|t| {
+ // (Nothing to draw while every translucent particle system is hidden in place.)
+ let tl = self.sc.up.translucent.as_ref().filter(|_| g.translucent_particles_live(&self.sc.up)).map(|t| {
let pipes = g.translucent_pipelines(&self.sc.up.kernel, true);
let target = if lp.misc2[2] > 0.0 || lp.dof[0] > 0.0 { &self.targets.fb } else { &self.targets.fa };
// Below full resolution the particles are drawn per traced pixel, then laid over the output (`translucent_up`).
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index 401fc03..f91add3 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -648,6 +648,8 @@ 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.
+ pub hidden: bool,
}
/// A `GpuParticles` node as built: its quads (`first` in build order, `final_first` in the GPU's), its objects (and
@@ -1571,7 +1573,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 && *count > 0 => {
+ Kind::Particles { count, emitter, params, material, emitter_area } if (shown || w.particles_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))?;
@@ -1604,7 +1606,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
for (k, v) in params.iter().take(32).enumerate() {
pf[k] = *v;
}
- particles.push(ParticleSystem { translucent, first, final_first: first, count: *count, object, func, params: pf, flags: flags | TRI_DYNAMIC, seed: *id, custom: n.custom });
+ particles.push(ParticleSystem { translucent, first, final_first: first, count: *count, object, func, params: pf, flags: flags | TRI_DYNAMIC, seed: *id, custom: n.custom, hidden: !shown });
if !translucent {
tri_nodes.push((n.name.clone(), first, tris.len() as u32));
}
diff --git a/renderer/src/world.rs b/renderer/src/world.rs
index 7f9980a..1706095 100644
--- a/renderer/src/world.rs
+++ b/renderer/src/world.rs
@@ -271,6 +271,9 @@ 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>,
pub materials: HashSet<u32>,
/// Objects whose light parameters changed.
pub lights: HashSet<u32>,
@@ -316,7 +319,7 @@ pub struct Changes {
impl Changes {
pub fn any(&self) -> bool {
- self.structural || !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.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()
}
/// Geometry edits are pending (`geometries`, `added`, `removed`).
pub fn edits(&self) -> bool {
@@ -747,11 +750,22 @@ impl World {
let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
if o.visible != visible {
o.visible = visible;
- self.changes.structural = true;
+ if matches!(o.kind, Kind::Particles { emitter_area, .. } if emitter_area <= 0.0) {
+ self.changes.particles_shown.insert(id);
+ } else {
+ self.changes.structural = true;
+ }
}
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 {
+ 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))
+ }
+
pub fn set_power(&mut self, id: u32, power: f32) -> Result<()> {
let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
if o.power != power {
diff --git a/tests/render/particles-hidden-in-place-live.ts b/tests/render/particles-hidden-in-place-live.ts
new file mode 100644
index 0000000..a2b6d78
--- /dev/null
+++ b/tests/render/particles-hidden-in-place-live.ts
@@ -0,0 +1,45 @@
+// Particles hidden in place (world.rs `set_visible` on a particle node that is not light-sampled, gpu.rs `set_particles_hidden`):
+// two systems of one 1 x 1 m quad emitting 5 nits over a black sky, the left one always shown; the right one starts
+// shown and is hidden by the frame script after a few frames, without a rebuild. Right / left 0.
+import { MeshStandardMaterial, ParticleFunction, Particles } from "@threert/scene";
+import { defineGame } from "@threert/gameplay";
+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "particles/hidden-in-place-live", features: ["particles", "edits"], reference: "analytic", temporal: true,
+ metric: { kind: "ratio", a: [0.66, 0.42, 0.8, 0.58], b: [0.2, 0.42, 0.34, 0.58], expected: 0, tolerance: 0.01 },
+ live: 60,
+ note: "a particle system hidden in place (its own visible, no rebuild) draws nothing: right / left 0",
+};
+
+const AT = new ParticleFunction("test_place_vis", {
+ params: { X: 0 },
+ code: `
+ o.center = vec3<f32>($X, 0.0, 0.0);
+ o.u = vec3<f32>(0.5, 0.0, 0.0);
+ o.v = vec3<f32>(0.0, 0.0, -0.5);`,
+});
+
+let elapsed = 0;
+let flipped = false;
+let right: Particles;
+export default defineGame<Record<string, never>>({
+ state: {},
+ setup: () => {
+ elapsed = 0;
+ flipped = false;
+ const scene = sceneWithSky(0);
+ const mat = new MeshStandardMaterial({ name: "glow", color: 0x000000, emissive: 0xffffff, emissiveIntensity: 5 });
+ const left = new Particles({ count: 1, emitter: AT.with({ X: -1 }), material: mat });
+ right = new Particles({ count: 1, emitter: AT.with({ X: 1 }), material: mat });
+ right.visible = true;
+ return result(scene, camera(scene, [0, 4.5, 0.001], [0, 0, 0]), [left, right]);
+ },
+ frame(f) {
+ elapsed += f.dt;
+ if (flipped || elapsed <= 3 / 60) return;
+ flipped = true;
+ right.visible = false;
+ },
+ handlers: {},
+});
diff --git a/tests/render/particles-shown-in-place-live.ts b/tests/render/particles-shown-in-place-live.ts
new file mode 100644
index 0000000..1d2f0b2
--- /dev/null
+++ b/tests/render/particles-shown-in-place-live.ts
@@ -0,0 +1,45 @@
+// Particles shown in place (world.rs `set_visible` on a particle node that is not light-sampled, gpu.rs `set_particles_hidden`):
+// two systems of one 1 x 1 m quad emitting 5 nits over a black sky, the left one always shown; the right one starts
+// hidden (in the build, idle) and is shown by the frame script after a few frames, without a rebuild. Right / left 1.
+import { MeshStandardMaterial, ParticleFunction, Particles } from "@threert/scene";
+import { defineGame } from "@threert/gameplay";
+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "particles/shown-in-place-live", features: ["particles", "edits"], reference: "analytic", temporal: true,
+ metric: { kind: "ratio", a: [0.66, 0.42, 0.8, 0.58], b: [0.2, 0.42, 0.34, 0.58], expected: 1, tolerance: 0.02 },
+ live: 60,
+ note: "a particle system hidden at build, shown in place: it draws as the other, right / left 1",
+};
+
+const AT = new ParticleFunction("test_place_vis", {
+ params: { X: 0 },
+ code: `
+ o.center = vec3<f32>($X, 0.0, 0.0);
+ o.u = vec3<f32>(0.5, 0.0, 0.0);
+ o.v = vec3<f32>(0.0, 0.0, -0.5);`,
+});
+
+let elapsed = 0;
+let flipped = false;
+let right: Particles;
+export default defineGame<Record<string, never>>({
+ state: {},
+ setup: () => {
+ elapsed = 0;
+ flipped = false;
+ const scene = sceneWithSky(0);
+ const mat = new MeshStandardMaterial({ name: "glow", color: 0x000000, emissive: 0xffffff, emissiveIntensity: 5 });
+ const left = new Particles({ count: 1, emitter: AT.with({ X: -1 }), material: mat });
+ right = new Particles({ count: 1, emitter: AT.with({ X: 1 }), material: mat });
+ right.visible = false;
+ return result(scene, camera(scene, [0, 4.5, 0.001], [0, 0, 0]), [left, right]);
+ },
+ frame(f) {
+ elapsed += f.dt;
+ if (flipped || elapsed <= 3 / 60) return;
+ flipped = true;
+ right.visible = true;
+ },
+ handlers: {},
+});