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.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
A particle system is a mesh and an instance (#259)
Yujiab4b34d46b414
diff --git a/docs/MATERIAL_FUNCTIONS.md b/docs/MATERIAL_FUNCTIONS.mdindex 6ead6e1..e5ed0ab 100644--- a/docs/MATERIAL_FUNCTIONS.md+++ b/docs/MATERIAL_FUNCTIONS.md@@ -146,10 +146,11 @@ vec4(0)); <code> return o; }`:| `custom` | the material function's `i.custom` for this particle; `i.op` / `i.ob` are its center and bounds |Parameters are `$Name`, as in material functions. A particle function has no state: it is a function of time, the camera-and its random numbers, so every client places the same particles and a frame can be re-rendered. Each particle is two-dynamic triangles and an object of its own; a compute pass (`renderer/shaders/particles.wgsl`) writes them (positions,-shading normal and tangent from `u` / `v`), last frame's positions (motion vectors) and the BLAS input, then the dynamic-BLASes and the TLAS are rebuilt. Moving the node moves `i.pivot`. Offline renders+and its random numbers, so every client places the same particles and a frame can be re-rendered. A particle system is+a mesh of its own, a quad a particle, and one instance of it; each particle has an object of its own. A compute pass+(`renderer/shaders/particles.wgsl`) writes the mesh's vertices (positions, shading normal and tangent from `u` / `v`)+and last frame's positions (motion vectors), then the system's BLAS and the TLAS are built again. Moving the node+moves `i.pivot`. Offline rendersplace the particles once, at the scene time. Particles need hardware ray tracing (with software traversal they staycollapsed at the pivot) and cast no shadow by default.@@ -191,8 +192,8 @@ sparks.customData = [f.state.boomAt, 0, 0, 0];A particle node whose material is `transparent` (three.js's flag) is drawn by the translucency pass instead(`renderer/shaders/translucent.wgsl`), as UE draws translucent materials:-- **Outside the scene.** Its triangles are in no acceleration structure the path tracer uses, only in their own. They- cast no shadow and show in no reflection, refraction or GI (UE's default for translucency; docs/ROADMAP.md, Known+- **Outside the scene.** Its mesh is in no acceleration structure the path tracer uses, only in the pass's own (an+ instance of it a system). They cast no shadow and show in no reflection, refraction or GI (UE's default for translucency; docs/ROADMAP.md, Knownparity gaps).- **Over the image.** Per output pixel, after the temporal filter (live) or over the converged image (offline), a raygoes as far as the opaque surface the pixel shows. Then:diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 9cbfdd7..eb608a4 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -2879,6 +2879,27 @@ Mutations: 26. 25 failed a test there was; one, a texture put on a shelf too lowFound by review: a translucent particle's material given another function kept the kernel's old dispatch for thetranslucency pass, which has its particles' functions alone; the kernel is made again where those are others.+**A particle system is a mesh and an instance (2026-11-24).** Particles were world-space triangles of their own+kind: two a particle among the scene's dynamic triangles (the translucent ones after everything else, in a BLAS of+their own), a row a triangle, their emitters by a nominal area in the triangles' attributes, every size fixed when+the scene was uploaded. Now a system is what any geometry that deforms is: a mesh of the pool (a quad a particle,+four vertices), one instance, a BLAS of its own built again after the particle passes. Stateless and stateful+systems, those the lights are sampled by (their triangles are the instance's emitters) and translucent ones (an+instance of the translucency pass's TLAS each) alike; a particle keeps its own object, which a hit finds from its+instance's and its triangle. The world-space form is gone from the build, the layout, the passes and the kernel.+The cost is a BLAS build and a TLAS instance a system, where all systems shared four BLASes at most. A frame's GPU+time on Bistro with opaque particles added (1280 x 720, an M5 Pro; runs alternated): 16 systems of 1024+particles, 21.25 to 21.48 ms for 21.15 to 21.63 (no difference); 256 systems of 64, 21.44 to 21.55 ms for 21.07 to+21.11 (+0.41 ms, 1.9 %: 0.16 ms of it in the trace).+Not changed: a system that comes or goes, a particle function or program, still rebuild the scene.+Tests: the build's five kinds of system (`a_particle_system_is_a_mesh_of_quads_and_an_instance`); a particle's+previous positions and the motion at its pixels beside another system; `translucent/systems` (two translucent+systems, their order reversed between the image's sides).+Mutations: 28 (the build and the layout, the passes' previous positions, the kernel's object of a particle, the+builds after the passes, the translucency pass). One had no test, a pass's first frame taking the build's+positions for its previous ones, and has its assertion now, for both passes; the others failed a test there was,+one of them by the renderer stopping.+**Volumes and density grids come in place (2026-11-23, after it).** A volume that came, went or was set againwhile a game ran, a still volume's first move, a volume function, a new density grid and a grid program each hadthe scene built again. On Bistro (as above), the frame the edit landed in:diff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 9a299c7..e02b07c 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -1430,7 +1430,7 @@ and in the merged layout alike, **and the same 23 fail on main's build, with the`hidden-in-place-live`, `instance-data`, `lit-normal`, `lit-orientation`, `motion-repose`, `node-custom`,`quad-placement`, `shown-in-place-live` (13; `particles/burst-not-yet` expects nothing drawn and passes);`gpu-particles/beside-particles`, `plane`, `voxels`, `voxels-live`, `voxels-side` (5); `translucent/depth`,- `translucent/order` (translucent particles);+ `translucent/order`, `translucent/systems` (translucent particles);- `volume/lighting`, `volume/lighting-offline` (6 for 1): their subject is one translucent particle in front of a6-nit wall, so these two are the same missing particles: the region reads the wall;- `surface/windows` (0.3934 for 0.4234): not explained. Its scene is one plane with the library's facade windows@@ -1618,9 +1618,9 @@ Vertices and indices, one layout for hardware and software traversal (`renderer/the section has the material and where the section's triangles and emitters start; its instance's record hasits object and whether its mesh deforms (`INST_DEFORMS`). A light sample is told its emitter's section by thelight list's record (64 bytes). The record a pixel is left to `finish` by has 16 bits for it (`MESH_SECTIONS`).-- **Rows** (`Stream::Triangles`, four words). A triangle no instance places (a light's card, a particle's, a- flattened scene's) has one: its material, its object, its flags, its emitter + 1. They are all the GPU holds: the- world-space triangles', then the translucent particles'.+- **Rows** (`Stream::Triangles`, four words). A triangle no instance places (a light's card, a flattened scene's)+ has one: its material, its object, its flags, its emitter + 1. They are all the GPU holds: the world-space+ triangles'.- **Software traversal's leaves** (`leaves`, binding 2; `indexed::Leaf`). A tree keeps its triangles itself, as anacceleration structure does: 48 bytes each, in the triangles' order, (v0, id), (v1 - v0, id), (v2 - v0, -). Acandidate's test reads nothing else. The ids: a world-space triangle's flags; a mesh's section, and its index in@@ -1629,7 +1629,16 @@ Vertices and indices, one layout for hardware and software traversal (`renderer/- **A hit reads** its triangle's indices and its three vertices' records (`tri_data(triangle, instance, part)`).- **What shares.** Corners equal bit for bit in position, normal, UV and tangent are one vertex: the stillworld-space triangles among themselves, each mesh within itself, a skinned mesh by its model's corners. Triangles- the CPU or a pass writes whole (those that move in world space, particles) keep three vertices each.+ the CPU writes whole (those that move in world space) keep three vertices each.+- **Particle systems.** A system is a mesh of the pool, four vertices and two triangles a particle, and one+ instance that places nothing (`scene::particle_mesh`, `INST_PARTICLES`): its pass writes the vertices in the+ world and their previous positions, and its BLAS is built again after the passes, with the TLAS+ (`Gpu::build_particles`). A particle has an object of its own, from the instance's on: a hit's is its+ triangle's index in the mesh / 2 past it (kernel feature `F_PART`). A system the lights are sampled by has an+ emitter a triangle among its instance's, weighed by half the particle's nominal area and taken again from the+ vertices every frame. A translucent system's instance is hidden from the scene's TLAS and is an instance of+ the translucency pass's own. The same whatever `THREERT_INSTANCING` says; under software traversal the passes+ do not run.- **Tangents.** A vertex's own: the tangent at a hit is its triangle's three vertices' there, the hand its firstvertex's, placed by its instance (`hit_tangent`; read only where a frame is asked, by a normal map or afunction). A model's file gives them; a primitive of a file that has UVs and no tangents has them made where itdiff --git a/packages/scene/src/core.ts b/packages/scene/src/core.tsindex 91f0563..c45007f 100644--- a/packages/scene/src/core.ts+++ b/packages/scene/src/core.ts@@ -1501,7 +1501,7 @@ export interface ParticleBinding {/*** `count` particles that `emitter` places every frame (GPU), drawn with `material` (alpha-tested materials give soft* streaks and sprites; the material function reads each particle's `i.custom`). Particles cast no shadow by default.- * Hardware ray tracing only (they are dynamic triangles).+ * Hardware ray tracing only (a GPU pass places them every frame).*/export class Particles extends Object3D {override type = "Particles";@@ -1583,7 +1583,7 @@ export interface ParticleCollide {* `spawn` (the game's own, e.g. debris turned to dust), changed by `program`, collided as `collide` says, and drawn as* camera-facing quads with `material` (lit; emissive materials glow, with `emitterArea` as for `Particles`). Each* particle's colour is the material function's `i.custom`. When more are born than there is room for, the oldest slots- * are reused. Hardware ray tracing only (they are dynamic triangles); particles cast no shadow by default.+ * are reused. Hardware ray tracing only (a GPU pass places them every frame); particles cast no shadow by default.*/export class GpuParticles extends Object3D {override type = "GpuParticles";diff --git a/renderer/shaders/gpu_particles.wgsl b/renderer/shaders/gpu_particles.wgslindex 3fbc113..2023329 100644--- a/renderer/shaders/gpu_particles.wgsl+++ b/renderer/shaders/gpu_particles.wgsl@@ -50,9 +50,9 @@ struct PP {grid_n: vec4<u32>,};-// a: (first triangle in the GPU order, capacity, first object, program); b: (seed, first dynamic triangle, this frame's-// first emitted slot, emitted count); c: pivot, w = collision flags (1 plane, 2 voxels); d: (plane height, restitution,-// friction, -); e: (first spawn, spawned count, frame number, -); p: parameters.+// a: (its mesh's first vertex (four a particle), capacity, first object, program); b: (seed, where its vertices'+// previous positions begin, this frame's first emitted slot, emitted count); c: pivot, w = collision flags (1 plane, 2 voxels); d:+// (plane height, restitution, friction, -); e: (first spawn, spawned count, frame number, -); p: parameters.struct System { a: vec4<u32>, b: vec4<u32>, c: vec4<f32>, d: vec4<f32>, e: vec4<u32>, p: array<vec4<f32>, 8> };// (`TriAttr`: records.wgsl.)@@ -139,20 +139,15 @@ fn collide(s_in: PState, dt: f32, flags: f32, d: vec4<f32>) -> PState {return s;}-// One triangle of a quad, from its first vertex `v` on (particles.wgsl `put_tri`, opaque particles only).-fn put_tri(v: u32, dyn_first: u32, a: vec3<f32>, b: vec3<f32>, c: vec3<f32>, n: vec3<f32>, tg: vec3<f32>) {- let corners = array<vec3<f32>, 3>(a, b, c);- let first = PPS.env.x > 0.5;- for (var k = 0u; k < 3u; k++) {- let i = (v + k) * 3u;- vertices[i] = vec4<f32>(corners[k], vertices[i].w);- vertices[i + 1u] = vec4<f32>(n, vertices[i + 1u].w);- vertices[i + 2u] = vec4<f32>(tg, 1.0);- let j = v + k - dyn_first;- let now = vec4<f32>(corners[k], 0.0);- prev_verts[j * 3u] = select(last[j], now, first);- last[j] = now;- }+// One vertex of a system's mesh (particles.wgsl `put_vertex`).+fn put_vertex(v: u32, j: u32, p: vec3<f32>, n: vec3<f32>, tg: vec3<f32>) {+ let i = v * 3u;+ vertices[i] = vec4<f32>(p, vertices[i].w);+ vertices[i + 1u] = vec4<f32>(n, vertices[i + 1u].w);+ vertices[i + 2u] = vec4<f32>(tg, 1.0);+ let now = vec4<f32>(p, 0.0);+ prev_verts[j * 3u] = select(last[j], now, PPS.env.x > 0.5);+ last[j] = now;}@compute @workgroup_size(64, 1, 1)@@ -224,9 +219,12 @@ fn gpu_particles(@builtin(global_invocation_id) gid: vec3<u32>) {let area = length(uxv);let n = select(to_cam, uxv / area, area > 1e-12);let tg = select(vec3<f32>(1.0, 0.0, 0.0), normalize(u), dot(u, u) > 1e-24);- let t = sys.a.x + 6u * k;- put_tri(t, sys.b.y, c00, c10, c11, n, tg);- put_tri(t + 3u, sys.b.y, c00, c11, c01, n, tg);+ let t = sys.a.x + 4u * k;+ let j = sys.b.y + 4u * k;+ put_vertex(t, j, c00, n, tg);+ put_vertex(t + 1u, j + 1u, c10, n, tg);+ put_vertex(t + 2u, j + 2u, c11, n, tg);+ put_vertex(t + 3u, j + 3u, c01, n, tg);let oi = (sys.a.z + k) * OBJECT_STRIDE;objects[oi] = vec4<f32>(s.pos, objects[oi].w);objects[oi + 1u] = vec4<f32>(vec3<f32>(4.0 * half), objects[oi + 1u].w);diff --git a/renderer/shaders/particles.wgsl b/renderer/shaders/particles.wgslindex 182d963..6f1609f 100644--- a/renderer/shaders/particles.wgsl+++ b/renderer/shaders/particles.wgsl@@ -1,9 +1,9 @@// Particle pass (gpu.rs `ParticleGpu`): every frame, before the trace, each particle system's particle function places-// its particles. A particle is a quad of two dynamic triangles (scene.rs `ParticleSystem`) and its own object (pivot,-// bounds, per-particle data for material functions). The pass writes the kernel's triangle data (positions and shading-// attributes), last frame's positions as `prev_verts` (motion vectors; from its own copy `last`, since a repose-// re-uploads the dynamic tail from the CPU), the BLAS input vertices and the objects; the dynamic BLASes are rebuilt-// after it.+// its particles. A particle is a quad of its system's mesh (scene.rs `ParticleSystem`: four vertices) and its own+// object (pivot, bounds, per-particle data for material functions). The pass writes the vertices (positions and+// shading attributes; the systems' BLASes are built from them after it), last frame's positions as `prev_verts`+// (motion vectors; from its own copy `last`, since a repose re-uploads the dynamic tail from the CPU) and the+// objects.//// A particle function is a WGSL body (`ParticleFunction` in @threert/scene) run per particle:// fn pf_<name>(i: PIn, p: array<vec4<f32>, 8>) -> POut { var o = POut(...); <code> return o; }@@ -41,8 +41,8 @@ struct PP {// (`TriAttr`: records.wgsl.)-// a: (its first vertex (six a particle), count, first object, function); b: (seed, the first vertex that moves,-// translucent (1: its triangles are the translucency pass's), -); c: the node's pivot, w: 1 collapse every particle (the system was just hidden), 2 its first run since it+// a: (its mesh's first vertex (four a particle), count, first object, function); b: (seed, where its vertices'+// previous positions begin (the instance's, `scene::Instance::prev`), -, -); c: the node's pivot, w: 1 collapse every particle (the system was just hidden), 2 its first run since it// was shown (no last frame: motion vectors 0) (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> };@@ -53,7 +53,7 @@ struct System { a: vec4<u32>, b: vec4<u32>, c: vec4<f32>, p: array<vec4<f32>, 8>@group(0) @binding(2) var<storage, read_write> vertices: array<vec4<f32>>;@group(0) @binding(3) var<storage, read_write> prev_verts: array<vec4<f32>>;@group(0) @binding(5) var<storage, read_write> objects: array<vec4<f32>>;-// This pass's last positions of the dynamic tail's particle vertices (the previous positions' indexing).+// This pass's last positions of the particles' vertices (the previous positions' indexing).@group(0) @binding(7) var<storage, read_write> last: array<vec4<f32>>;// vec4s an object in `objects` (scene.rs `object_stride`: 4 in a scene with instance colours), the pipeline's constant.@@ -71,25 +71,17 @@ fn unit(h: u32) -> f32 { return f32(h >> 8u) * (1.0 / 16777216.0); }fn particle_function(f: u32, i: PIn, p: array<vec4<f32>, 8>) -> POut { return POut(i.pivot, vec3<f32>(0.0), vec3<f32>(0.0), false, vec4<f32>(0.0)); }// @particle-functions-end-// One triangle of a quad, from its first vertex `v` on (three vertices a triangle): positions, the last frame's as-// the previous positions, shading normal and tangent (as scene.rs tri_attr). The dynamic groups' BLAS is built from-// the positions, the translucent triangles' own too. Translucent triangles (`trans`) have no motion vectors (the pass-// draws them over the image each frame).-fn put_tri(v: u32, dyn_first: u32, trans: bool, a: vec3<f32>, b: vec3<f32>, c: vec3<f32>, n: vec3<f32>, tg: vec3<f32>, first: bool) {- let corners = array<vec3<f32>, 3>(a, b, c);- for (var k = 0u; k < 3u; k++) {- let i = (v + k) * 3u;- // (The w's hold the uv, left as built.)- vertices[i] = vec4<f32>(corners[k], vertices[i].w);- vertices[i + 1u] = vec4<f32>(n, vertices[i + 1u].w);- vertices[i + 2u] = vec4<f32>(tg, 1.0);- if (!trans) {- let j = v + k - dyn_first;- let now = vec4<f32>(corners[k], 0.0);- prev_verts[j * 3u] = select(last[j], now, first);- last[j] = now;- }- }+// One vertex of a system's mesh (`v`; `j`: where its previous position is kept): its position, the last frame's as+// the previous position, its normal and tangent.+fn put_vertex(v: u32, j: u32, p: vec3<f32>, n: vec3<f32>, tg: vec3<f32>, first: bool) {+ let i = v * 3u;+ // (The w's hold the uv, left as built.)+ vertices[i] = vec4<f32>(p, vertices[i].w);+ vertices[i + 1u] = vec4<f32>(n, vertices[i + 1u].w);+ vertices[i + 2u] = vec4<f32>(tg, 1.0);+ let now = vec4<f32>(p, 0.0);+ prev_verts[j * 3u] = select(last[j], now, first);+ last[j] = now;}@compute @workgroup_size(64, 1, 1)@@ -115,7 +107,7 @@ fn particles(@builtin(global_invocation_id) gid: vec3<u32>) {o.u = vec3<f32>(0.0);o.v = vec3<f32>(0.0);}- // Two triangles, uv (0, 1) (1, 1) (1, 0) and (0, 1) (1, 0) (0, 0) as the scene build gave them.+ // The quad's corners, uv (0, 1) (1, 1) (1, 0) (0, 0) as the scene build gave them.let c00 = o.center - o.u - o.v;let c10 = o.center + o.u - o.v;let c11 = o.center + o.u + o.v;@@ -125,11 +117,14 @@ fn particles(@builtin(global_invocation_id) gid: vec3<u32>) {let area = length(uxv);let n = select(vec3<f32>(0.0, 0.0, 1.0), uxv / area, area > 1e-12);let tg = select(vec3<f32>(1.0, 0.0, 0.0), normalize(o.u), dot(o.u, o.u) > 1e-24);- let t = s.a.x + 6u * k;- let trans = s.b.z == 1u;let first = PPS.env.z > 0.5 || s.c.w > 1.5;- put_tri(t, s.b.y, trans, c00, c10, c11, n, tg, first);- put_tri(t + 3u, s.b.y, trans, c00, c11, c01, n, tg, first);+ // Its mesh's quad: the corners in the order the build indexed them.+ let t = s.a.x + 4u * k;+ let j = s.b.y + 4u * k;+ put_vertex(t, j, c00, n, tg, first);+ put_vertex(t + 1u, j + 1u, c10, n, tg, first);+ put_vertex(t + 2u, j + 2u, c11, n, tg, first);+ put_vertex(t + 3u, j + 3u, c01, n, tg, first);let oi = (s.a.z + k) * OBJECT_STRIDE;objects[oi] = vec4<f32>(o.center, objects[oi].w);objects[oi + 1u] = vec4<f32>(2.0 * (abs(o.u) + abs(o.v)), objects[oi + 1u].w);diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgslindex e25b285..7211a94 100644--- a/renderer/shaders/pathtrace.wgsl+++ b/renderer/shaders/pathtrace.wgsl@@ -71,6 +71,7 @@ fn approx(a: u32) -> bool { return (APPROX & a) != 0u; }// Features the scene uses (gpu::F_*): the rest is compiled out, so plain scenes pay nothing for them.override FEAT: u32 = 0xffffffffu;const F_MASKED: u32 = 1u;+const F_PART: u32 = 1024u; // a particle system's mesh among the instances: a hit's object is its particle's (`tri_data`)const F_FOG: u32 = 64u;const F_VOLUME: u32 = 128u;const F_TEX: u32 = 256u;@@ -299,9 +300,10 @@ fn inst_sign(r: Instance) -> f32 { return select(1.0, -1.0, (bitcast<u32>(r.n1.wfn inst_normal(r: Instance, n: vec4<f32>) -> vec4<f32> {return vec4<f32>(normalize(vec3<f32>(dot(r.n0.xyz, n.xyz), dot(r.n1.xyz, n.xyz), dot(r.n2.xyz, n.xyz))), n.w);}-// A model-space triangle's `x` as its instance has it: the instance's object (the record's `info`).+// A model-space triangle's `x` as its instance has it: the instance's object (the record's `info`), and for a+// particle system's mesh the particle's past it (`tri_data` has which; 0 for every other mesh).fn inst_x(info: vec4<u32>, x: vec4<f32>) -> vec4<f32> {- return vec4<f32>(x.x, bitcast<f32>(info.y), x.z, x.w);+ return vec4<f32>(x.x, bitcast<f32>(info.y + bitcast<u32>(x.y)), x.z, x.w);}// An instance's rows (scene.rs `Row`): four words a section of its mesh, from the record's info.w on. The material// with its class bits, the section's first triangle, its first emitter (NO_EMITTER: it does not emit). Which section@@ -310,6 +312,8 @@ fn inst_x(info: vec4<u32>, x: vec4<f32>) -> vec4<f32> {const INST_CUTOUT: u32 = 16u;const INST_GLASS: u32 = 32u;const INST_DEFORMS: u32 = 64u;+// The instance's mesh is a particle system's: two triangles and an object a particle, from the record's object on.+const INST_PARTICLES: u32 = 128u;const ROW_MATERIAL: u32 = 0xffffffu;const ROW_CUTOUT: u32 = 0x1000000u;const ROW_GLASS: u32 = 0x2000000u;@@ -333,7 +337,7 @@ fn tri_indices(ti: u32) -> vec3<u32> {let k = P.word_first[1].x + ti * 3u;return vec3<u32>(words[k], words[k + 1u], words[k + 2u]);}-// The row of a triangle no instance places (a light's card, a particle's, a scene's that is flattened), four words:+// The row of a triangle no instance places (a light's card, a scene's that is flattened), four words:// its material, its object, its flags (TRI_*), its emitter entry + 1. A mesh's triangle has none: which section of// its mesh it is in is its hit's to say (`Hit.part`), and the rest is its instance's.fn tri_row(row: u32) -> vec4<u32> {@@ -356,7 +360,14 @@ struct TriData { a: TriAttr, v0: vec3<f32>, e1: vec3<f32>, e2: vec3<f32>, vi: vefn tri_data(ti: u32, inst: u32, part: u32) -> TriData {var base = 0u;var row = vec4<u32>(part, 0u, 0u, 0u);- if (has(F_INST) && inst != NO_INST) { base = instance_at(inst).info.z; } else { row = tri_row(part); }+ if (has(F_INST) && inst != NO_INST) {+ let r = instance_at(inst);+ base = r.info.z;+ // A particle system's mesh: which particle the triangle is (two each, from the mesh's first).+ if (has(F_PART) && (bitcast<u32>(r.n1.w) & INST_PARTICLES) != 0u) { row.y = (ti - r.info.x) >> 1u; }+ } else {+ row = tri_row(part);+ }let i = (tri_indices(ti) + vec3<u32>(base)) * VERTEX_VEC4;let p0 = vertices[i.x];let p1 = vertices[i.y];diff --git a/renderer/shaders/records.wgsl b/renderer/shaders/records.wgslindex 0f4e5b1..6067407 100644--- a/renderer/shaders/records.wgsl+++ b/renderer/shaders/records.wgsl@@ -3,7 +3,7 @@// `live_source`, build.rs).// A triangle's shading attributes as a hit reads them of its three vertices (pathtrace.wgsl `tri_data`): normals (w:-// uv parts), uv parts (w: material index, bits), x: (a spare word, object (bits), a particle's area, its emitter+// uv parts), uv parts (w: material index, bits), x: (a spare word, object (bits), a spare word, its emitter// entry + 1 (bits; 0: it is not light-sampled)). (Its tangents are read where a frame is asked, `hit_tangent`; its// texel density is computed where it is hit, `mesh_density`.) A triangle of a mesh with sections: uv.w its section,// x.w its index in it (its instance's row has the material and where the section's emitters start: `material_of`,diff --git a/renderer/shaders/translucent.wgsl b/renderer/shaders/translucent.wgslindex c1ef125..cf33c00 100644--- a/renderer/shaders/translucent.wgsl+++ b/renderer/shaders/translucent.wgsl@@ -2,9 +2,10 @@// ------------------------------------------------------------------------------------------------// Translucency pass (gpu.rs `Translucent`; hardware RT only, appended to the kernel module after the trace).//-// Particles drawn with a `transparent` material are in the kernel's triangle tables (after everything else, from-// TPS.size.z) but in none of the scene's acceleration structures: they cast no shadow and show in no reflection or GI-// (UE's default for translucency). This pass draws them, per output pixel, over the opaque image:+// Particles drawn with a `transparent` material are in none of the scene's acceleration structures: they cast no+// shadow and show in no reflection or GI (UE's default for translucency). They have a TLAS of their own, `tacc`: an+// instance of it a system's mesh, its custom data the instance's record as in the scene's. This pass draws them,+// per output pixel, over the opaque image:// - depth: the particle ray stops at the opaque surface the pixel sees (live: the traced first hits under the pixel;// offline: a ray), so nothing behind a wall shows;// - overlap: ordered blending, the TL_LAYERS nearest particle hits sorted by distance, front to back;@@ -15,7 +16,7 @@// accumulates (colour, transmittance) per sample, laid over the converged image.@if(hwrt) struct TP {- size: vec4<u32>, // output width, height, first translucent triangle, mode (0 offline: accumulate; 1 live: over the image)+ size: vec4<u32>, // output width, height, -, mode (0 offline: accumulate; 1 live: over the image)view: vec4<u32>, // live: traced width, height (the opaque first hits); training budget (points per frame); 1 = at the traced resolutionmisc: vec4<f32>, // live: share of hit pixels that train the volume voxels, 1 = train only (THREERT_TL_HIDE: what is behind), -, -};@@ -54,15 +55,18 @@return t;}-// Material of a translucent particle at triangle ti (barycentrics b): colour, opacity and emission after maps and its-// material function.-@if(hwrt) fn particle_material(ti: u32, b: vec2<f32>, view: vec3<f32>, lod: f32) -> MatOut {- // (Its row: the translucent triangles' rows follow the other rows, from `P.word_first[1].w` on.)- let row = P.word_first[1].w + ti - TPS.size.z;- let td = tri_data(ti, NO_INST, row);- let a = td.a;- // (A particle's triangle is in the world: no instance.)- let m = material_at(material_of(a, NO_INST));+// Material of a translucent particle at a hit of `tacc` (its primitive, its instance's custom data, barycentrics b):+// colour, opacity and emission after maps and its material function.+@if(hwrt) fn particle_material(prim: u32, custom: u32, b: vec2<f32>, view: vec3<f32>, lod: f32) -> MatOut {+ // Its system's mesh: the triangles from the instance's record's first, one section; its particle's object from+ // the instance's first.+ let inst = hit_inst(custom);+ let rec = instance_at(inst);+ let ti = rec.info.x + prim;+ let td = tri_data(ti, inst, 0u);+ var a = td.a;+ a.x = inst_x(rec.info, a.x);+ let m = material_at(material_of(a, inst));let uv = mesh_uv(a, m, b.x, b.y);let tl = mesh_lod(mesh_density(td.e1, td.e2, a, m), 1.0, 1.0) + lod - LOD_BIAS;var r = mat_base(m);@@ -73,7 +77,7 @@}r.emissive = emission(m, uv, tl) * obj_power(a);if (has(F_FUNC) && m.tex1.w > 0) {- r = translucent_material_function(m.tex1.w - 1, mat_in_at(ti, NO_INST, row, b.x, b.y, view, lod), m, r);+ r = translucent_material_function(m.tex1.w - 1, mat_in_at(ti, inst, 0u, b.x, b.y, view, lod), m, r);}return r;}@@ -115,6 +119,7 @@ fn translucent(@builtin(global_invocation_id) gid: vec3<u32>) {// The nearest TL_LAYERS hits, by distance.var lt: array<f32, TL_LAYERS>;var lp: array<u32, TL_LAYERS>;+ var lc: array<u32, TL_LAYERS>;var lb: array<vec2<f32>, TL_LAYERS>;var n = 0u;var rq: ray_query;@@ -129,11 +134,13 @@ fn translucent(@builtin(global_invocation_id) gid: vec3<u32>) {if (k == 0u || lt[k - 1u] <= c.t) { break; }lt[k] = lt[k - 1u];lp[k] = lp[k - 1u];+ lc[k] = lc[k - 1u];lb[k] = lb[k - 1u];k -= 1u;}lt[k] = c.t;lp[k] = c.primitive_index;+ lc[k] = c.instance_custom_data;lb[k] = c.barycentrics;n = min(n + 1u, TL_LAYERS);}@@ -148,8 +155,7 @@ fn translucent(@builtin(global_invocation_id) gid: vec3<u32>) {var train = live && rng1(rng_dim(D_CACHE)) < TPS.misc.x;let foot = 2.0 * P.cam_pos.w / f32(h);for (var k = 0u; k < n; k++) {- let ti = TPS.size.z + lp[k];- let r = particle_material(ti, lb[k], -d, log2(max(lt[k] * foot, 1e-7)));+ let r = particle_material(lp[k], lc[k], lb[k], -d, log2(max(lt[k] * foot, 1e-7)));let alpha = clamp(r.opacity, 0.0, 1.0);if (alpha <= 0.0) { continue; }let x = o + d * lt[k];diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rsindex f40d251..f7db396 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -554,8 +554,8 @@ pub struct ParticleGpu {max_count: u32,/// Not run yet: the first run's motion vectors are zero (no last frame).fresh: std::cell::Cell<bool>,- /// Some systems are opaque (in the scene's dynamic BLASes, rebuilt every frame).- opaque: bool,+ /// The systems' own meshes (`scene::ParticleSystem::mesh`): each one's BLAS is built again after the pass.+ meshes: Vec<u32>,/// Per system: its particle count, whether the translucency pass draws it, and its state when hidden or shown in/// place (`set_particles_hidden`): `Shown`; `Collapse` (this frame's pass collapses its quads), `Collapsed` (zero/// its count next frame), `Idle`; `Showing` (this frame's pass is its first: no motion vectors), `ShowRan` (clear@@ -583,12 +583,10 @@ pub const VOLUME_TRAIN_CAP: u32 = 8192;/// particle pass writes (`vertices` from `first_vertex`, three a triangle), from triangle `first` in the kernel's/// tables; the translucency pass's parameters and volume training points (translucent.wgsl).pub struct Translucent {- blas: wgpu::Blas,pub tlas: wgpu::Tlas,- size: wgpu::BlasTriangleGeometrySizeDescriptor,- vertices: wgpu::Buffer,- first_vertex: u32,- pub first: u32,+ /// The systems' meshes (`scene::ParticleSystem::mesh`), an instance of the TLAS each: their BLASes are built with+ /// the other particle meshes' after the pass (`Gpu::build_particles`).+ meshes: Vec<u32>,pub params: wgpu::Buffer,pub points: wgpu::Buffer,pub count: wgpu::Buffer,@@ -613,17 +611,6 @@ impl Uploaded {}}-impl Translucent {- /// Rebuilds the BLAS from the particle pass's vertices, and the TLAS.- fn build(&self, e: &mut wgpu::CommandEncoder) {- let entry = wgpu::BlasBuildEntry {- blas: &self.blas,- geometry: wgpu::BlasGeometries::TriangleGeometries(vec![wgpu::BlasTriangleGeometry { size: &self.size, vertex_buffer: &self.vertices, first_vertex: self.first_vertex, vertex_stride: VERTEX_STRIDE, index_buffer: None, first_index: None, transform_buffer: None, transform_buffer_offset: None }]),- };- e.build_acceleration_structures([entry].iter(), [&self.tlas]);- }-}-/// translucent.wgsl's entry points: the pass, volume training (live).#[derive(Clone)]pub struct TranslucentPipelines {@@ -904,6 +891,8 @@ pub struct GpuParticlesGpu {fresh: std::cell::Cell<bool>,grid_o: [f32; 4],grid_n: [u32; 4],+ /// The systems' own meshes (as `ParticleGpu`'s).+ meshes: Vec<u32>,}/// gpu_particles.wgsl with the scene's particle programs (`fn pe_` / `pu_<name>`) and their dispatch.@@ -1898,7 +1887,7 @@ impl Kernel {pub fn new(scene: &Scene, groups: [usize; GROUPS]) -> Kernel {// (The translucency pass's functions: those of its particles' materials.)- let used: std::collections::BTreeSet<i32> = scene.trans_attrs.iter().filter_map(|a| scene.materials.get(a.uv[3].to_bits() as usize)).map(|m| m.tex1[3] - 1).filter(|&f| f >= 0).collect();+ let used: std::collections::BTreeSet<i32> = scene.translucent_mats().iter().filter_map(|&m| scene.materials.get(m as usize)).map(|m| m.tex1[3] - 1).filter(|&f| f >= 0).collect();let functions = Kernel::material_functions(&scene.shaders, &used);let volume_functions = Kernel::volume_functions_of(&scene.volume_fns);let mut geometry_functions = String::new();@@ -1943,6 +1932,8 @@ pub const A_LIVE: u32 = 31;// Kernel features (`override FEAT` in pathtrace.wgsl).pub const F_MASKED: u32 = 1;+/// A particle system's mesh among the instances (`scene::INST_PARTICLES`): a hit on one has its particle's object.+pub const F_PART: u32 = 1024;pub const F_FOG: u32 = 64;pub const F_VOLUME: u32 = 128;pub const F_TEX: u32 = 256;@@ -2080,7 +2071,9 @@ pub fn instance_features(scene: &Scene) -> u32 {let iglass = if mixed_glass { F_IGLASS } else { 0 };let masked = any_row(crate::scene::ROW_CUTOUT);let deform = if scene.meshes.iter().any(|m| m.deforms) { F_DEFORM } else { 0 };- media | particles | ifunc | iglass | deform | F_INST | if masked { F_MASKED } else { 0 } | if scene.units.is_some() { F_UNITS } else { 0 }+ // (Hardware traversal's: the particle passes run with it alone, and software traversal has such a mesh flat.)+ let part = if scene.units.is_none() && !(scene.particles.is_empty() && scene.gpu_particles.is_empty()) { F_PART } else { 0 };+ media | particles | ifunc | iglass | deform | part | F_INST | if masked { F_MASKED } else { 0 } | if scene.units.is_some() { F_UNITS } else { 0 }}/// `features` from the parts parameter edits change (the materials; `environment`: `environment_features`), and the@@ -2689,11 +2682,6 @@ impl Gpu {let st = wgpu::BufferUsages::STORAGE;// (COPY_SRC: the live view's in-place edits grow these past their room by a copy, live/edits.rs `edit_geometry`.)let edit = st | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC;- let dynamic_first: usize = groups[..4].iter().sum();- // A particle's triangle's first vertex: three vertices a triangle, from the first vertex that moves (a dynamic- // world-space triangle) or the first translucent one.- let (moving, translucent, trans_first) = (scene.indexed.dynamic.0, scene.indexed.translucent, scene.trans_first);- let vertex_of = move |tri: u32, trans: bool| if trans { translucent + (tri - trans_first) * 3 } else { moving + (tri - dynamic_first as u32) * 3 };// The vertices, with room for three a triangle of the edit room; and those that move, as they are (their// previous frame's).let ix = &scene.indexed;@@ -2805,10 +2793,13 @@ impl Gpu {// INSTANCE_BIT | record; shadow casters mask 1).// Per mesh: its geometries, one a section (`InstMesh::parts`): first triangle, count.let mesh_parts: Vec<Vec<(u32, u32)>> = scene.meshes.iter().map(|m| m.parts(&scene.sections).into_iter().map(|(at, count)| (m.first + at, count)).collect()).collect();+ // (A translucent particle system's is not flagged opaque: the translucency pass asks for every hit.)+ let layered: std::collections::HashSet<usize> = scene.particles.iter().filter(|p| p.translucent).map(|p| p.mesh as usize).collect();let mesh_sizes: Vec<Vec<wgpu::BlasTriangleGeometrySizeDescriptor>> = mesh_parts.iter().zip(&ix.meshes)- .map(|(parts, &(_, vertices))| {+ .enumerate()+ .map(|(mesh, (parts, &(_, vertices)))| {parts.iter().map(|&(_, count)| wgpu::BlasTriangleGeometrySizeDescriptor {@@ -2816,7 +2807,7 @@ impl Gpu {vertex_count: vertices.max(1),index_format: Some(wgpu::IndexFormat::Uint32),index_count: Some(count * 3),- flags: wgpu::AccelerationStructureGeometryFlags::OPAQUE,+ flags: if layered.contains(&mesh) { wgpu::AccelerationStructureGeometryFlags::empty() } else { wgpu::AccelerationStructureGeometryFlags::OPAQUE },}).collect()})@@ -2974,24 +2965,23 @@ impl Gpu {let bg_parts = BindParts { nodes: b_nodes, leaves: b_leaves, tex_view, env_view, sampler, grid_view };let bg = self.scene_bind_group(&SceneBuffers { params: &b_params, vertices: &b_vertices, heap: &heap, words: &words, prev_vertices: &b_prev, accum: &b_accum, parts: &bg_parts, accel: accel.as_ref(), uniform: uniform.as_ref() });let kernel = Kernel { approx: self.approx, ..Kernel::new(scene, groups) };- // Translucent particles (hardware RT): their own BLAS + TLAS, rebuilt after the particle pass.+ // Translucent particles (hardware RT): the translucency pass's own TLAS, built again after the particle pass:+ // an instance of it a system's mesh, the instance's record in its custom data as in the scene's TLAS.+ let layered: Vec<(u32, u32)> = scene.particles.iter().filter(|p| p.translucent).filter_map(|p| scene.instances.iter().position(|i| i.mesh == p.mesh).map(|r| (p.mesh, r as u32))).collect();let translucent = match &accel {- Some(_) if !scene.trans_tris.is_empty() => {- let n = scene.trans_tris.len() as u32;- let size = wgpu::BlasTriangleGeometrySizeDescriptor { vertex_format: wgpu::VertexFormat::Float32x3, vertex_count: n * 3, index_format: None, index_count: None, flags: wgpu::AccelerationStructureGeometryFlags::empty() };- let blas = d.create_blas(- &wgpu::CreateBlasDescriptor { label: Some("translucent"), flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE, update_mode: wgpu::AccelerationStructureUpdateMode::Build },- wgpu::BlasGeometrySizeDescriptors::Triangles { descriptors: vec![size.clone()] },- );- let mut tlas = d.create_tlas(&wgpu::CreateTlasDescriptor { label: Some("translucent"), max_instances: 1, flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE, update_mode: wgpu::AccelerationStructureUpdateMode::Build });- tlas[0] = Some(wgpu::TlasInstance::new(&blas, [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], 0, 0xff));+ Some(a) if !layered.is_empty() => {+ let mut tlas = d.create_tlas(&wgpu::CreateTlasDescriptor { label: Some("translucent"), max_instances: layered.len() as u32, flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE, update_mode: wgpu::AccelerationStructureUpdateMode::Build });+ for (k, &(mesh, record)) in layered.iter().enumerate() {+ tlas[k] = Some(wgpu::TlasInstance::new(&a.meshes[mesh as usize], [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], INSTANCE_BIT | record, 0xff));+ }let params = d.create_buffer(&wgpu::BufferDescriptor { label: Some("translucent params"), size: 48, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });let points = d.create_buffer(&wgpu::BufferDescriptor { label: Some("volume points"), size: VOLUME_TRAIN_CAP as u64 * 16, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false });let count = d.create_buffer(&wgpu::BufferDescriptor { label: Some("volume point count"), size: 16, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });- let t = Translucent { blas, tlas, size, vertices: b_vertices.clone(), first_vertex: ix.translucent, first: scene.trans_first, params, points, count };- // Built once now (collapsed quads): bind groups may use the TLAS before the first particle pass.+ let t = Translucent { tlas, meshes: layered.iter().map(|l| l.0).collect(), params, points, count };+ // Built once now (collapsed quads): bind groups may use the TLAS before the first particle pass. (The+ // systems' meshes with their TLAS, in one build.)let mut enc = d.create_command_encoder(&Default::default());- t.build(&mut enc);+ enc.build_acceleration_structures(mesh_entries(a, &t.meshes).iter(), [&t.tlas]);self.queue.submit([enc.finish()]);Some(t)}@@ -3018,7 +3008,8 @@ impl Gpu {let mut p = [0.0f32; 32];p.copy_from_slice(&ps.params);// (A system hidden at build runs nothing: its quads stay collapsed at the node.)- ParticleSystemGpu { a: [vertex_of(ps.final_first, ps.translucent), if ps.hidden { 0 } else { ps.count }, ps.object, ps.func], b: [ps.seed, ix.dynamic.0, ps.translucent as u32, 0], c: [o[0], o[1], o[2], 0.0], p, d: ps.custom }+ // (Its mesh's first vertex: four a particle.)+ ParticleSystemGpu { a: [ix.meshes[ps.mesh as usize].0, if ps.hidden { 0 } else { ps.count }, ps.object, ps.func], b: [ps.seed, ix.meshes[ps.mesh as usize].0 - ix.dynamic.0, 0, 0], c: [o[0], o[1], o[2], 0.0], p, d: ps.custom }}).collect();// COPY_DST: pivot updates (`set_particle_pivot`).@@ -3028,11 +3019,11 @@ impl Gpu {let written = ParticleTargets { vertices: &b_vertices, prev_vertices: &b_prev, heap: &heap };let pbg = particle_bind_group(d, &pipeline, "particles", &[(0, ¶ms), (1, &b_sys), (7, &last)], &written);let nodes = scene.particles.iter().map(|p| p.seed).collect();- let opaque = scene.particles.iter().any(|p| !p.translucent);+ let meshes = scene.particles.iter().map(|p| p.mesh).collect();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, last, 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 })+ Some(ParticleGpu { pipeline, stamp, bg: pbg, params, table: b_sys, last, 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), meshes, counts, translucent: translucent_sys, hidden })}_ => None,};@@ -3048,7 +3039,7 @@ impl Gpu {.map(|ps| {let c = &ps.collide;let flags = u32::from(c.plane.is_some()) | if c.voxels { 2 } else { 0 };- GpuParticleSystemGpu { a: [vertex_of(ps.final_first, false), ps.capacity, ps.object, ps.program], b: [ps.seed, ix.dynamic.0, 0, 0], c: [ps.pivot[0], ps.pivot[1], ps.pivot[2], flags as f32], d: [c.plane.unwrap_or(0.0), c.restitution, c.friction, 0.0], e: [0; 4], p: ps.params }+ GpuParticleSystemGpu { a: [ix.meshes[ps.mesh as usize].0, ps.capacity, ps.object, ps.program], b: [ps.seed, ix.meshes[ps.mesh as usize].0 - ix.dynamic.0, 0, 0], c: [ps.pivot[0], ps.pivot[1], ps.pivot[2], flags as f32], d: [c.plane.unwrap_or(0.0), c.restitution, c.friction, 0.0], e: [0; 4], p: ps.params }}).collect();let table = buf("gpu particle systems", bytemuck::cast_slice(&systems), edit);@@ -3071,7 +3062,7 @@ impl Gpu {let sm = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("stamp"), source: wgpu::ShaderSource::Wgsl(STAMP_WGSL.into()) });let sp = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("stamp"), layout: None, module: &sm, entry_point: Some("stamp"), compilation_options: Default::default(), cache: self.cache() });let sbg = d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("stamp"), layout: &sp.get_bind_group_layout(0), entries: &[e(0, &b_vertices), wgpu::BindGroupEntry { binding: 1, resource: a.tlas.as_binding() }] });- Some(GpuParticlesGpu { pipeline, stamp: (sp, sbg), bg, params, table, last, state, spawns, grid, systems: std::cell::RefCell::new(systems), host: std::cell::RefCell::new(host), nodes: scene.gpu_particles.iter().map(|p| p.node).collect(), max_cap: scene.gpu_particles.iter().map(|p| p.capacity).max().unwrap_or(0), frame: std::cell::Cell::new(0), fresh: std::cell::Cell::new(true), grid_o, grid_n })+ Some(GpuParticlesGpu { pipeline, stamp: (sp, sbg), bg, params, table, last, state, spawns, grid, systems: std::cell::RefCell::new(systems), host: std::cell::RefCell::new(host), nodes: scene.gpu_particles.iter().map(|p| p.node).collect(), max_cap: scene.gpu_particles.iter().map(|p| p.capacity).max().unwrap_or(0), frame: std::cell::Cell::new(0), fresh: std::cell::Cell::new(true), grid_o, grid_n, meshes: scene.gpu_particles.iter().map(|p| p.mesh).collect() })}_ => None,};@@ -3250,9 +3241,9 @@ impl Gpu {}}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.)+ // (The stateful GPU particles leave what they placed to this pass when there are stateless ones.)if up.gpu_particles.is_some() {- self.rebuild_dynamic(accel, e);+ self.build_particles(up, accel, false, e);}return;}@@ -3276,12 +3267,8 @@ impl Gpu {if let Some((q, i)) = blas_ts {stamp(e, wgpu::ComputePassTimestampWrites { query_set: q, beginning_of_pass_write_index: None, end_of_pass_write_index: Some(i) });}- if p.opaque {- self.rebuild_dynamic(accel, e);- }- if let Some(t) = &up.translucent {- t.build(e);- }+ // (The stateful particles leave what they placed to this pass.)+ self.build_particles(up, accel, true, e);if let Some((q, i)) = blas_ts {stamp(e, wgpu::ComputePassTimestampWrites { query_set: q, beginning_of_pass_write_index: Some(i + 1), end_of_pass_write_index: None });}@@ -3380,13 +3367,26 @@ impl Gpu {if let Some((q, i)) = blas_ts {stamp(e, wgpu::ComputePassTimestampWrites { query_set: q, beginning_of_pass_write_index: None, end_of_pass_write_index: Some(i) });}- self.rebuild_dynamic(accel, e);+ self.build_particles(up, accel, false, e);if let Some((q, i)) = blas_ts {stamp(e, wgpu::ComputePassTimestampWrites { query_set: q, beginning_of_pass_write_index: Some(i + 1), end_of_pass_write_index: None });}}}+ /// What the particle passes placed, above the triangles, in a frame's encoder: the BLASes of the systems' meshes+ /// and the TLAS (the translucency pass's too). `stateless`: the stateless systems' too (not when every one of+ /// them is idle).+ fn build_particles(&self, up: &Uploaded, accel: &Accel, stateless: bool, e: &mut wgpu::CommandEncoder) {+ let own = up.particles.as_ref().filter(|_| stateless);+ let meshes: Vec<u32> = own.iter().flat_map(|p| &p.meshes).chain(up.gpu_particles.iter().flat_map(|p| &p.meshes)).copied().collect();+ // (The translucent systems' meshes are among the stateless ones': their own TLAS with the scene's.)+ let layered = up.translucent.as_ref().filter(|_| stateless).map(|t| &t.tlas);+ if !meshes.is_empty() {+ e.build_acceleration_structures(mesh_entries(accel, &meshes).iter(), std::iter::once(&accel.tlas).chain(layered));+ }+ }+/// A grid's data (four f32 a cell) into the atlas, from layer `z0`.fn write_grid(&self, atlas: &wgpu::Texture, z0: u32, dims: [u32; 3], data: &[f32]) {let halves = grid_halves(data);@@ -3541,6 +3541,11 @@ impl Gpu {found}+ /// Whether a particle system's mesh is among the instances (they move every frame: motion vectors).+ pub fn particle_meshes(up: &Uploaded) -> bool {+ up.particles.is_some() || up.gpu_particles.is_some()+ }+/// 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))@@ -3923,9 +3928,6 @@ impl Gpu {if let Some(a) = &mut up.accel {(a.vertices, a.indices, a.index_first) = (up.vertices.clone(), up.words.buffer.clone(), (up.words.at(Stream::Indices) / 4) as u32);}- if let Some(t) = &mut up.translucent {- t.vertices = up.vertices.clone();- }up.bg = self.scene_bind_group(&SceneBuffers { params: &up.params, vertices: &up.vertices, heap: &up.heap, words: &up.words, prev_vertices: &up.prev_vertices, accum: &up.accum, parts: &up.bg_parts, accel: up.accel.as_ref(), uniform: up.uniform.as_ref() });if up.accel.is_none() {return;@@ -4128,12 +4130,6 @@ impl Gpu {}}- /// The dynamic groups' BLASes and the TLAS, in a frame's encoder (the particle passes: their triangles are placed- /// by the GPU every frame).- pub fn rebuild_dynamic(&self, accel: &Accel, e: &mut wgpu::CommandEncoder) {- e.build_acceleration_structures(dynamic_entries(accel).iter(), [&accel.tlas]);- }-#[cfg(not(target_arch = "wasm32"))]/// Offline translucency: the pass (translucent.wgsl) `spp` times at random points in each pixel, each with a fresh/// lighting estimate per hit; the mean (colour, transmittance) per pixel. Empty without translucent particles.@@ -4145,7 +4141,7 @@ impl Gpu {let sums = d.create_buffer(&wgpu::BufferDescriptor { label: Some("translucent sums"), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });// (Drawn at full resolution: the reduced image's buffer is bound and not read.)let tbg = self.translucent_bind_group(t, &sums, &self.translucent_low(1, 1));- let tp = TranslucentParams { size: [w, h, t.first, 0], view: [w, h, 0, 0], misc: [0.0; 4] };+ let tp = TranslucentParams { size: [w, h, 0, 0], view: [w, h, 0, 0], misc: [0.0; 4] };self.queue.write_buffer(&t.params, 0, bytemuck::bytes_of(&tp));let n = spp.max(1);for s in 0..n {@@ -4210,8 +4206,9 @@ impl Gpu {}if up.particles.is_some() {let mut e = d.create_command_encoder(&Default::default());+ // (What the stateful systems placed: the stateless pass above built before they ran.)if let Some(a) = &up.accel {- self.rebuild_dynamic(a, &mut e);+ self.build_particles(&up, a, false, &mut e);}self.queue.submit([e.finish()]);}@@ -4356,7 +4353,7 @@ mod tests {("F_GLASS", F_GLASS), ("F_COAT", F_COAT), ("F_HUGE", F_HUGE), ("F_INST", F_INST), ("F_MEDIA", F_MEDIA), ("F_PEMIT", F_PEMIT),("F_HMEDIA", F_HMEDIA), ("F_PROC", F_PROC), ("F_TINT", F_TINT), ("F_UNLIT", F_UNLIT), ("F_BACKGROUND", F_BACKGROUND),("F_VCOLOR", F_VCOLOR), ("F_AERIAL", F_AERIAL), ("F_GRID", F_GRID), ("F_LISTS", F_LISTS), ("F_IFUNC", F_IFUNC), ("F_IGLASS", F_IGLASS),- ("F_DEFORM", F_DEFORM),+ ("F_DEFORM", F_DEFORM), ("F_PART", F_PART),];let mut seen = 0u32;for (name, bit) in all {diff --git a/renderer/src/indexed.rs b/renderer/src/indexed.rsindex 86cb5d8..55dd8a7 100644--- a/renderer/src/indexed.rs+++ b/renderer/src/indexed.rs@@ -1,7 +1,8 @@//! The scene's geometry as the GPU holds it: vertices kept once, a triangle three indices and a row. The build still//! makes triangles with corners of their own (`Scene::tris`, `attrs`); what they share is found here, scope by scope:-//! a mesh's triangles share within the mesh, the still world-space triangles among themselves, and what a pass or the-//! CPU writes whole each frame (the dynamic world-space triangles, particles) has three vertices a triangle.+//! a mesh's triangles share within the mesh, the still world-space triangles among themselves, what the CPU writes+//! whole each frame (the dynamic world-space triangles) has three vertices a triangle, and a particle system's+//! mesh four a quad.use crate::scene::GpuTriAttr;use glam::Vec3A;@@ -13,7 +14,7 @@ use std::hash::Hash;pub type Vertex = [[f32; 4]; 3];pub const VERTEX_BYTES: usize = std::mem::size_of::<Vertex>();-/// The row of a triangle no instance places (a light's card, a particle's, a flattened scene's): its material, its+/// The row of a triangle no instance places (a light's card, a flattened scene's): its material, its/// object, its flags (`scene::TRI_*`), its emitter entry + 1. A mesh's triangle needs none on the GPU: a ray's hit/// says which section of its mesh it is in, and the rest is its instance's. (The build has one for every triangle,/// a mesh's with its section and its index there: `Indexed::rows`.)@@ -135,6 +136,21 @@ pub fn apart(tris: &[[Vec3A; 3]], attrs: &[GpuTriAttr]) -> Scope {s}+/// A particle system's quads (two triangles each, the second the first's first and third corners and its own+/// third) as four vertices a quad, in the order the particle pass writes them.+pub fn quads(tris: &[[Vec3A; 3]], attrs: &[GpuTriAttr]) -> Scope {+ let mut s = Scope::default();+ for (q, (t, a)) in tris.chunks_exact(2).zip(attrs.chunks_exact(2)).enumerate() {+ for (k, c) in [(0, 0), (0, 1), (0, 2), (1, 2)] {+ let (p, (n, uv, tangent)) = (t[k][c], corner(&a[k], c));+ s.vertices.push([[p.x, p.y, p.z, uv[0]], [n[0], n[1], n[2], uv[1]], tangent]);+ }+ let v = q as u32 * 4;+ s.indices.extend([[v, v + 1, v + 2], [v, v + 2, v + 3]]);+ }+ s+}+/// Triangles written whole as their vertices alone (their indices do not change): `corners`, three a triangle, and/// their attributes; the vertices, as `apart` has them.pub fn apart_vertices(corners: &[[f32; 3]], attrs: &[GpuTriAttr]) -> Vec<Vertex> {@@ -159,16 +175,12 @@ pub struct Indexed {pub rows: Vec<TriRow>,/// Software traversal: every triangle as its tree's leaf has it. Empty under hardware traversal.pub leaves: Vec<Leaf>,- /// The meshes' first triangle: those before it are in world space. And the translucent particles' first (they- /// lie after the meshes') and how many.+ /// The meshes' first triangle: those before it are in world space.pub pool_first: u32,- pub translucent_tris: (u32, u32),/// By mesh (`Scene::meshes`): its first vertex and how many it has.pub meshes: Vec<(u32, u32)>,/// The world-space triangles' vertices: the first so many (the still ones', then those that move).pub flat: u32,- /// The translucent particles' first vertex (three a triangle, after every mesh's).- pub translucent: u32,/// By skin source (`Scene::skin_sources`): the model's vertices a mesh of it is skinned from (`source_vertices`)/// and its triangles' indices, which every mesh of the source has. Empty: no mesh is skinned from it.pub skins: Vec<(Vec<crate::skin::SkinCorner>, Vec<[u32; 3]>)>,@@ -178,11 +190,9 @@ pub struct Indexed {}impl Indexed {- /// The rows the GPU holds: the world-space triangles', then the translucent particles' (found from `pool_first`- /// on: the meshes' triangles lie between and have none).- pub fn gpu_rows(&self) -> Vec<TriRow> {- let (first, n) = (self.translucent_tris.0 as usize, self.translucent_tris.1 as usize);- self.rows[..(self.pool_first as usize).min(self.rows.len())].iter().chain(self.rows.get(first..first + n).unwrap_or(&[])).copied().collect()+ /// The rows the GPU holds: the world-space triangles' (a mesh's triangles have none).+ pub fn gpu_rows(&self) -> &[TriRow] {+ &self.rows[..(self.pool_first as usize).min(self.rows.len())]}/// A scope's vertices after those there are, its triangles after those there are, their indices raised by `by`diff --git a/renderer/src/lib.rs b/renderer/src/lib.rsindex 2cf9695..5e1ddbc 100644--- a/renderer/src/lib.rs+++ b/renderer/src/lib.rs@@ -86,7 +86,7 @@ pub struct Prepared {pub light_tree: Option<ltree::LightTree>,/// Material -> runs of its flattened static triangles (first, end in the traversal order, object): a material/// that starts emitting gets emitter entries in place from its runs (live/edits.rs `add_material_emitters`).- /// `moving_mats`: the materials of dynamic world-space triangles (`Tables::moving_mats`).+ /// `moving_mats`: the materials of dynamic world-space triangles and of particle systems (`Tables::moving_mats`).pub mat_runs: std::collections::HashMap<u32, Vec<[u32; 3]>>,pub moving_mats: std::collections::HashSet<u32>,/// The flattened triangles' build indices in traversal order (`Scene::tris` order: positions for new entries).@@ -107,14 +107,13 @@ pub fn emitter_tri(k: usize, tri_verts: &[[f32; 4]], a: &scene::GpuTriAttr, mate}let v = |j: usize| Vec3::new(tri_verts[k * 3 + j][0], tri_verts[k * 3 + j][1], tri_verts[k * 3 + j][2]);let (e1, e2) = (v(1), v(2));- let nominal = a.x[2] > 0.0;- let area = if nominal { a.x[2] } else { 0.5 * e1.cross(e2).length() };+ let area = 0.5 * e1.cross(e2).length();if !(area * lum > 0.0) {return None;}let c = v(0) + (e1 + e2) / 3.0;let moves = tri_verts[k * 3][3].to_bits() & scene::TRI_DYNAMIC != 0;- Some(EmitterTri { tri: k as u32, mat, obj: a.x[1].to_bits(), area, c: c.to_array(), moves, nominal, in_tree: false, inst: NO_INST, part: 0 })+ Some(EmitterTri { tri: k as u32, mat, obj: a.x[1].to_bits(), area, c: c.to_array(), moves, nominal: false, in_tree: false, inst: NO_INST, part: 0 })}/// An emissive triangle of the emitter CDF: triangle (traversal order), material, object, area.@@ -192,16 +191,19 @@ impl GpuEmitterTri {/// `InstMesh::emitters`): one a numbered/// triangle, in the numbers' order, each with its triangle as the instance places it. `tris`: the mesh's, in model/// space; `first`: its first triangle in the triangles' table; `numbered(k)`: triangle k's number, material and-/// section, if it emits; `record`: the instance's. A triangle of no area: no weight (area 0). A hidden instance's (an instanced+/// section, if it emits; `record`: the instance's; `nominal`: the area a triangle is weighed by where the mesh is a+/// particle system's (`scene::ParticleSystem::emitter_area`, half of it: the pass places the triangle, of whatever+/// size). A triangle of no area: no weight (area 0). A hidden instance's (an instanced/// object's copy not shown) keep their mesh's own area: its object has no power, so they weigh nothing, and the light/// tree has them (`switchable_power`) for when the copy is shown.-pub fn instance_emitters(inst: &scene::Instance, record: u32, tris: &[[glam::Vec3A; 3]], first: u32, numbered: &dyn Fn(usize) -> Option<(usize, u32, u32)>, count: usize, materials: &[scene::GpuMaterial], moves: bool) -> Vec<(EmitterTri, [glam::Vec3A; 3])> {+pub fn instance_emitters(inst: &scene::Instance, record: u32, tris: &[[glam::Vec3A; 3]], first: u32, numbered: &dyn Fn(usize) -> Option<(usize, u32, u32)>, count: usize, materials: &[scene::GpuMaterial], moves: bool, nominal: Option<f32>) -> Vec<(EmitterTri, [glam::Vec3A; 3])> {let dead = EmitterTri { tri: first, mat: 0, obj: inst.object, area: 0.0, c: [0.0; 3], moves, nominal: false, in_tree: false, inst: record, part: 0 };let mut out = vec![(dead, [glam::Vec3A::ZERO; 3]); count];for (k, t) in tris.iter().enumerate() {let Some((slot, mat, part)) = numbered(k) else { continue };let (area, c, w) = placed_emitter(inst, t, mat, materials);- out[slot] = (EmitterTri { tri: first + k as u32, mat, area, c, part, ..dead }, w);+ // (A particle system's: weighed by its nominal area, whatever size its pass gives it.)+ out[slot] = (EmitterTri { tri: first + k as u32, mat, area: nominal.unwrap_or(area), c, part, nominal: nominal.is_some(), ..dead }, w);}out}@@ -668,21 +670,8 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mutlet layout = scene::proc_layout(&sc.procs, !hwrt);sc.proc_records = sc.procs.iter().zip(&layout.headers).map(|(p, &h)| p.gpu(h)).collect();sc.proc_layout = (!sc.procs.is_empty()).then_some(layout);- // Translucent particles (hardware RT): after the pool, in no group (only the translucency pass traces them).- sc.trans_first = (tri_verts.len() / 3) as u32;- if hwrt {- for (t, a) in sc.trans_tris.iter().zip(&sc.trans_attrs) {- let [a0, b, c] = *t;- let (e1, e2): (Vec3A, Vec3A) = (b - a0, c - a0);- tri_verts.push([a0.x, a0.y, a0.z, f32::from_bits(0)]);- tri_verts.push([e1.x, e1.y, e1.z, 0.0]);- tri_verts.push([e2.x, e2.y, e2.z, 0.0]);- attrs.push(*a);- }- }sc.attrs = attrs;- // Vertex colours (scene.rs `tri_colors`), with the triangles: the flattened ones in traversal order, the pool, the- // translucent particles (white).+ // Vertex colours (scene.rs `tri_colors`), with the triangles: the flattened ones in traversal order, the pool.sc.gpu_vcolors = if sc.vcolors.is_empty() && sc.pool_vcolors.is_empty() {vec![]} else {@@ -694,24 +683,12 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mutv};// Posed models: where each of their triangles landed (they are re-skinned in place, hardware RT only).- if hwrt && (sc.retained.dynamics_mut().next().is_some() || !sc.particles.is_empty() || !sc.gpu_particles.is_empty()) {+ if hwrt && sc.retained.dynamics_mut().next().is_some() {let first_dynamic: usize = groups[..4].iter().sum();let finals: std::collections::HashMap<u32, u32> = bvh.order[first_dynamic..].iter().enumerate().map(|(k, &i)| (i, (first_dynamic + k) as u32)).collect();for d in sc.retained.dynamics_mut() {d.finals = (0..d.mats.len() as u32).map(|j| finals[&(d.first + j)]).collect();}- // A particle system's triangles stay together (one group, the order within a group is the build order).- for ps in sc.particles.iter_mut().filter(|p| !p.translucent) {- ps.final_first = finals[&ps.first];- debug_assert!((0..ps.count * 2).all(|j| finals[&(ps.first + j)] == ps.final_first + j));- }- for ps in sc.gpu_particles.iter_mut() {- ps.final_first = finals[&ps.first];- debug_assert!((0..ps.capacity * 2).all(|j| finals[&(ps.first + j)] == ps.final_first + j));- }- }- for ps in sc.particles.iter_mut().filter(|p| p.translucent) {- ps.final_first = sc.trans_first + ps.first;}timings.push(("bvh_ms".into(), t.elapsed().as_secs_f64() * 1000.0));@@ -730,6 +707,8 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut// (And the instances hidden at the build, `Instance::masked`: where they stand when they are shown is theirs to// bound then, in the light tree's moving subtree.)let moving = sc.retained.moving_records();+ // (The particle systems the lights are sampled by: half a quad's nominal area a triangle.)+ let nominal: std::collections::HashMap<u32, f32> = sc.particles.iter().map(|p| (p.mesh, p.emitter_area)).chain(sc.gpu_particles.iter().map(|p| (p.mesh, p.emitter_area))).filter(|(_, a)| *a > 0.0).map(|(m, a)| (m, a * 0.5)).collect();for r in 0..sc.instances.len() {let m = sc.meshes[sc.instances[r].mesh as usize];// (With sections: the emitters of its sections whose material emits, a section after another; each one's row@@ -743,13 +722,14 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut}let first = emitter_tris.len() as u32;sc.instances[r].first_emitter = first;+ let area = nominal.get(&sc.instances[r].mesh).copied();for (k, start) in starts.iter().enumerate() {sc.rows[at + k][2] = start.map_or(scene::NO_EMITTER, |s| first + s);}let (a, b) = (m.first as usize, (m.first + m.count) as usize);let attrs = &sc.attrs[pool_first + a..pool_first + b];let numbered = |k: usize| scene::section_slot(&attrs[k], &rows, &starts);- for (e, w) in instance_emitters(&sc.instances[r], r as u32, &sc.pool_tris[a..b], (pool_first + a) as u32, &numbered, count as usize, &sc.materials, moving.contains(&(r as u32)) || sc.instances[r].masked) {+ for (e, w) in instance_emitters(&sc.instances[r], r as u32, &sc.pool_tris[a..b], (pool_first + a) as u32, &numbered, count as usize, &sc.materials, moving.contains(&(r as u32)) || sc.instances[r].masked || area.is_some(), area) {gpu_emitter_tris.push(GpuEmitterTri::of(&e, w, 0));emitter_tris.push(e);}@@ -773,6 +753,11 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut_ => runs.push([k as u32, k as u32 + 1, obj]),}}+ // (Nor a particle system's material: its triangles are its pass's.)+ // (Not a translucent system's, which has no emitter and no class: its material's function changes in place.)+ for i in sc.instances.iter().filter(|i| i.bits & scene::INST_PARTICLES != 0 && !i.hidden) {+ moving_mats.insert(scene::row_material(&sc.rows[i.rows as usize]));+ }let tri_order = bvh.order[..pool_first.min(bvh.order.len())].to_vec();// Many static emitters: a light tree samples them by importance at the shading point (`ltree`); each one's path// code with its triangle in the list (emit_mis). THREERT_LTREE=0: the CDF alone (A/B).@@ -929,8 +914,6 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mutsc.gpu_instances[r].n[2][3] = f32::from_bits(i.prev);}params.word_first[1][2] = sc.indexed.dynamic.0;- // (Hardware traversal: the translucent particles' rows follow the world-space triangles'.)- params.word_first[1][3] = sc.indexed.pool_first;Prepared { tri_verts, groups, nodes, emitters, gpu_emitter_tris, emitter_runs, env, env_cdf, params, energy, emitter_tris, light_tree, env_nee_floor, mat_runs, moving_mats, tri_order }}@@ -953,6 +936,8 @@ fn index_geometry(sc: &scene::Scene, order: &[u32], tri_verts: &[[f32; 4]], groulet source_of: std::collections::HashMap<u32, u32> = sc.retained.skinned.iter().filter(|k| k.mesh != u32::MAX).map(|k| (k.mesh, k.source)).collect();let mut meshes: Vec<usize> = (0..sc.meshes.len()).filter(|&m| sc.meshes[m].count > 0).collect();meshes.sort_by_key(|&m| sc.meshes[m].first);+ // (A particle system's mesh: quads the pass writes.)+ let quads: std::collections::HashSet<u32> = sc.particles.iter().map(|p| p.mesh).chain(sc.gpu_particles.iter().map(|p| p.mesh)).collect();// (A skinned mesh with its source: the model's vertices are found with its first mesh.)let scopes: Vec<(indexed::Scope, Option<u32>)> = meshes.par_iter()@@ -962,6 +947,7 @@ fn index_geometry(sc: &scene::Scene, order: &[u32], tri_verts: &[[f32; 4]], groulet (tris, attrs) = (&sc.pool_tris[r.clone()], &sc.attrs[pool_first + r.start..pool_first + r.end]);match source_of.get(&(m as u32)).copied().filter(|&s| im.deforms && sc.skin_sources[s as usize].len() == tris.len()) {Some(s) => (indexed::shared_skinned(&sc.skin_sources[s as usize], tris, attrs), Some(s)),+ None if quads.contains(&(m as u32)) => (indexed::quads(tris, attrs), None),None => (indexed::shared(tris, attrs), None),}})@@ -986,13 +972,6 @@ fn index_geometry(sc: &scene::Scene, order: &[u32], tri_verts: &[[f32; 4]], grouif no_still {out.indices.push([0; 3]);}- // The translucent particles' (what `tri_verts` has after the pool: under hardware traversal).- if out.indices.len() < sc.attrs.len() {- let first = out.indices.len();- out.translucent = out.vertices.len() as u32;- out.translucent_tris = (first as u32, sc.trans_tris.len() as u32);- out.push(indexed::apart(&sc.trans_tris, &sc.attrs[first..]), out.translucent);- }assert_eq!((out.indices.len(), tri_verts.len()), (sc.attrs.len(), sc.attrs.len() * 3), "a row of indices a triangle");// A row a triangle. One no instance places: its material, its object, its flags, its emitter + 1. A mesh's: its// section and its index in it (whether it deforms is its instance's to say: `scene::INST_DEFORMS`).@@ -1781,7 +1760,7 @@ mod units_tests {let x = &sc.indexed;assert_eq!((x.indices.len(), x.rows.len()), (sc.attrs.len(), sc.attrs.len()), "{what}");// (A pool triangle's mesh: its vertices count from the mesh's first.)- let pool_first = sc.attrs.len() - sc.pool_tris.len() - sc.trans_tris.len() * usize::from(hwrt) - usize::from(sc.units.is_some() && sc.tris.is_empty());+ let pool_first = sc.attrs.len() - sc.pool_tris.len() - usize::from(sc.units.is_some() && sc.tris.is_empty());let base = |k: usize| sc.meshes.iter().zip(&x.meshes).find(|(m, _)| m.count > 0 && (pool_first + m.first as usize..pool_first + (m.first + m.count) as usize).contains(&k)).map_or(0, |(_, v)| v.0);let bits = |v: &[f32]| v.iter().map(|f| f.to_bits()).collect::<Vec<_>>();for (k, a) in sc.attrs.iter().enumerate() {@@ -1825,6 +1804,93 @@ mod units_tests {}}+ /// An opaque particle system is a mesh of its own and one instance of it: two triangles and four vertices a+ /// particle (a quad's corners once each, in the order the pass writes them), among the vertices that move; the+ /// instance places nothing and has the system's first object. One the lights are not sampled by has a row that+ /// keeps its material's emission out of the light list; one they are sampled by has an emitter a triangle, its+ /// instance's, weighed by half the particle's nominal area. Stateless and stateful systems alike. A translucent+ /// system's instance is hidden from the scene's acceleration structure (the translucency pass has it). An+ /// opaque particle system's material is not one whose emitters an edit makes in place. Under software traversal (the passes do+ /// not run there) no kernel asks for a particle's object. No GPU.+ #[test]+ fn a_particle_system_is_a_mesh_of_quads_and_an_instance() {+ let mut w = world(true);+ w.set_material(7, serde_json::from_value(serde_json::json!({ "name": "spark", "color": [0, 0, 0], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1, 0.5, 0.2], "emissiveIntensity": 20, "doubleSided": true })).unwrap());+ w.set_particle_fn("rise", "fn pf_rise(i: PIn, p: array<vec4<f32>, 8>) -> POut { return POut(i.pivot + vec3<f32>(f32(i.index), i.time, 0.0), vec3<f32>(0.1, 0.0, 0.0), vec3<f32>(0.0, 0.1, 0.0), true, vec4<f32>(0.0)); }".into(), String::new());+ for (id, count, emitter_area) in [(40, 3, 0.0), (41, 2, 0.09)] {+ w.set_object(id, format!("sparks{id}"), None, Kind::Particles { count, emitter: "rise".into(), params: vec![], material: 7, emitter_area }, true, false).unwrap();+ w.set_transform(id, Vec3::new(0.3, 0.2, 1.0), Quat::IDENTITY, Vec3::ONE).unwrap();+ }+ // (A translucent system, of a transparent material.)+ w.set_material(8, serde_json::from_value(serde_json::json!({ "name": "smoke", "color": [0.5, 0.5, 0.5], "opacity": 0.5, "transparent": true, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true })).unwrap());+ w.set_object(44, "smoke".into(), None, Kind::Particles { count: 2, emitter: "rise".into(), params: vec![], material: 8, emitter_area: 0.0 }, true, false).unwrap();+ // (Stateful systems too: one of each kind.)+ w.set_particle_program("puff", "fn pe_puff(i: EIn, p: array<vec4<f32>, 8>) -> PState { return PState(i.pivot, vec3<f32>(0.0), 0.0, 1.0, vec4<f32>(1.0), 0.1); }".into(), "fn pu_puff(s: PState, i: UIn, p: array<vec4<f32>, 8>) -> PState { return s; }".into(), String::new());+ for (id, capacity, emitter_area) in [(42, 5, 0.0), (43, 1, 0.04)] {+ w.set_object(id, format!("puffs{id}"), None, Kind::GpuParticles { capacity, program: "puff".into(), params: vec![], material: 7, emitter_area, rate: 1.0, collide: Default::default() }, true, false).unwrap();+ }+ for (what, hwrt, units) in [("units", false, true), ("hardware traversal", true, false)] {+ let mut sc = scene::build(&w, std::path::Path::new(".."), &default_presets_dir(), None).unwrap();+ let p = prepare_as(hwrt, units, &mut sc, &mut vec![]);+ let (own, sampled) = (&sc.particles[0], &sc.particles[1]);+ let (stateful, stateful_sampled) = (&sc.gpu_particles[0], &sc.gpu_particles[1]);+ assert_eq!((stateful.capacity, stateful_sampled.capacity), (5, 1), "{what}: the stateful systems, as the stateless");+ assert!(sc.instances.iter().filter(|i| i.bits & scene::INST_PARTICLES != 0).count() == 5 && sc.tri_flags.iter().all(|f| f & scene::TRI_DYNAMIC == 0), "{what}: five systems, an instance each, none a world-space triangle");+ assert!(p.moving_mats.contains(&sc.retained.materials[&7]), "{what}: the particles' material is its passes'");+ assert_eq!((own.count, sampled.count), (3, 2));+ let part = gpu::instance_features(&sc) & gpu::F_PART;+ if !hwrt {+ assert_eq!(part, 0, "{what}: no kernel asks for a particle's object");+ continue;+ }+ assert_ne!(part, 0, "{what}: the kernel asks for a particle's object");+ let (m, v) = (sc.meshes[own.mesh as usize], sc.indexed.meshes[own.mesh as usize]);+ assert_eq!((m.count, m.deforms, m.sect_count, v.1), (6, true, 1, 12), "{what}: two triangles and four vertices a particle");+ let pool_first = sc.attrs.len() - sc.pool_tris.len();+ let tris = &sc.indexed.indices[pool_first + m.first as usize..][..6];+ assert_eq!(tris, [[0, 1, 2], [0, 2, 3], [4, 5, 6], [4, 6, 7], [8, 9, 10], [8, 10, 11]], "{what}: a quad's corners once each");+ let uv = |k: u32| [sc.indexed.vertices[(v.0 + k) as usize][0][3], sc.indexed.vertices[(v.0 + k) as usize][1][3]];+ assert_eq!([uv(4), uv(5), uv(6), uv(7)], [[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]], "{what}: in the order the pass writes them");+ assert!(v.0 >= sc.indexed.dynamic.0 && v.0 + v.1 <= sc.indexed.dynamic.0 + sc.indexed.dynamic.1, "{what}: among the vertices that move");+ let of: Vec<&scene::Instance> = sc.instances.iter().filter(|i| i.mesh == own.mesh).collect();+ assert_eq!(of.len(), 1, "{what}: one instance");+ let i = of[0];+ assert_eq!((i.world, i.object, i.bits & scene::INST_PARTICLES, i.prev), (glam::Mat4::IDENTITY, own.object, scene::INST_PARTICLES, v.0 - sc.indexed.dynamic.0), "{what}: it places nothing; the first particle's object; where its previous positions are");+ let row = sc.rows[i.rows as usize];+ assert_eq!((row[2], row[3]), (scene::NO_EMITTER, scene::ROW_UNSAMPLED), "{what}: its emission is not in the light list");+ assert!(p.emitter_tris.iter().all(|e| e.inst == NO_INST || sc.instances[e.inst as usize].mesh != own.mesh), "{what}: no emitter of it");+ // The stateful system: a mesh of five quads after the first's, its own instance and objects.+ let (m2, v2) = (sc.meshes[stateful.mesh as usize], sc.indexed.meshes[stateful.mesh as usize]);+ assert_eq!((m2.count, m2.deforms, v2.1), (10, true, 20), "{what}: the stateful system's quads");+ let i2 = sc.instances.iter().find(|i| i.mesh == stateful.mesh).expect("its instance");+ assert_eq!((i2.object, i2.bits & scene::INST_PARTICLES), (stateful.object, scene::INST_PARTICLES), "{what}: its first particle's object");+ assert!(stateful.object >= own.object + 3 || own.object >= stateful.object + 5, "{what}: the systems' objects apart");+ // The ones the lights are sampled by: an emitter a triangle, the instance's, from its row's first on, in+ // the triangles' order, weighed by half the particle's nominal area.+ for (mesh, count, area) in [(sampled.mesh, 2u32, 0.045f32), (stateful_sampled.mesh, 1, 0.02)] {+ let r = sc.instances.iter().position(|i| i.mesh == mesh).expect("its instance");+ let (i, m) = (&sc.instances[r], sc.meshes[mesh as usize]);+ let row = sc.rows[i.rows as usize];+ assert_eq!((row[2], row[3], i.bits & scene::INST_PARTICLES), (i.first_emitter, 0, scene::INST_PARTICLES), "{what}: its row has its first emitter");+ let mine = &p.emitter_tris[row[2] as usize..][..(count * 2) as usize];+ for (k, e) in mine.iter().enumerate() {+ assert_eq!((e.inst, e.part, e.tri, e.nominal, e.moves, e.area, e.obj), (r as u32, 0, (pool_first as u32 + m.first) + k as u32, true, true, area, i.object), "{what}: emitter {k} of the system");+ }+ assert_eq!(p.emitter_runs.particles.iter().filter(|run| run[0] <= row[2] && row[2] + count * 2 <= run[0] + run[1]).count(), 1, "{what}: its emitters are taken again from its vertices every frame");+ }+ assert_eq!(p.emitter_tris.iter().filter(|e| e.nominal).count(), 6, "{what}: no other emitter by a nominal area");+ // The translucent system: a mesh and an instance too, the instance out of the scene's acceleration+ // structure (the translucency pass has it); no world-space translucent triangle; its material is the+ // translucency pass's, and one an edit may change in place.+ let smoke = &sc.particles[2];+ let i3 = sc.instances.iter().find(|i| i.mesh == smoke.mesh).expect("its instance");+ assert!(smoke.translucent && i3.hidden && i3.bits & scene::INST_PARTICLES != 0 && sc.rows[i3.rows as usize][3] == scene::ROW_UNSAMPLED, "{what}: the translucent system's instance");+ assert_eq!((sc.meshes[smoke.mesh as usize].count, i3.object), (4, smoke.object), "{what}: its quads are its mesh's");+ assert_eq!((sc.translucent_mats(), p.moving_mats.contains(&sc.retained.materials[&8])), (vec![sc.retained.materials[&8]], false), "{what}: its material");+ assert!(sc.instances.iter().filter(|i| i.bits & scene::INST_PARTICLES != 0 && i.mesh != smoke.mesh).all(|i| !i.hidden), "{what}: the opaque systems' instances are the scene's");+ }+ }+/// The same with no still triangle at all: the still tree is then the leaf of one triangle (bvh.rs `EMPTY`), and/// that triangle must be one no ray meets, not the first of the units' (a mesh's, in its model space). First seen/// on a GPU: `geometry/instanced`, two planes, darker towards a triangle standing at the origin.diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rsindex b028c3d..bf69df6 100644--- a/renderer/src/live/edits.rs+++ b/renderer/src/live/edits.rs@@ -461,7 +461,7 @@ pub(super) fn place_instance(cx: &mut Placing, record: usize, inst: &mut scene::starts.get(s as usize).copied().flatten().map(|x| ((x + i) as usize, of[s as usize], s))};let (a, b) = (im.first as usize, (im.first + im.count) as usize);- let made = crate::instance_emitters(inst, record as u32, &cx.pool_tris[a..b], (cx.edit.pool_first + a) as u32, &numbered, n, &cx.tables.materials, moves);+ let made = crate::instance_emitters(inst, record as u32, &cx.pool_tris[a..b], (cx.edit.pool_first + a) as u32, &numbered, n, &cx.tables.materials, moves, None);for (j, (e, w)) in made.into_iter().enumerate() {cx.new_emitters.push(((first + j) as u32, crate::GpuEmitterTri::of(&e, w, 0)));match cx.tables.emitter_tris.get_mut(first + j) {@@ -1864,7 +1864,7 @@ impl LiveCore {};let first_tri = edit.pool_first + im.first as usize;let (b0, b1) = (im.first as usize, (im.first + im.count) as usize);- for (e, w) in crate::instance_emitters(&instances[r], r as u32, &pool_tris[b0..b1], first_tri as u32, &numbered, n as usize, &tables.materials, moving.contains(&(r as u32))) {+ for (e, w) in crate::instance_emitters(&instances[r], r as u32, &pool_tris[b0..b1], first_tri as u32, &numbered, n as usize, &tables.materials, moving.contains(&(r as u32)), None) {new.push((tables.emitter_tris.len() as u32, crate::GpuEmitterTri::of(&e, w, 0)));tables.emitter_tris.push(e);}@@ -2150,7 +2150,7 @@ impl LiveCore {let at = sc.tables.emitter_tris.len();(inst.first_emitter, row[2]) = (at as u32, at as u32);let (a, b) = (mesh.first as usize, (mesh.first + mesh.count) as usize);- let made = crate::instance_emitters(inst, r as u32, &sc.pool_tris[a..b], (sc.edit.pool_first + a) as u32, &|k| Some((k, mat, 0)), mesh.count as usize, &sc.tables.materials, true);+ let made = crate::instance_emitters(inst, r as u32, &sc.pool_tris[a..b], (sc.edit.pool_first + a) as u32, &|k| Some((k, mat, 0)), mesh.count as usize, &sc.tables.materials, true, None);for (j, (e, w)) in made.into_iter().enumerate() {self.pending_emitters.push(((at + j) as u32, crate::GpuEmitterTri::of(&e, w, 0)));sc.tables.emitter_tris.push(e);@@ -3346,7 +3346,7 @@ impl LiveCore {let first = tables.emitter_tris.len();(inst.first_emitter, row[2]) = (first as u32, first as u32);let (a, b) = (im.first as usize, (im.first + im.count) as usize);- let made = crate::instance_emitters(&inst, (r0 + i) as u32, &pool_tris[a..b], (edit.pool_first + a) as u32, &|k| Some((k, mat, 0)), im.count as usize, &tables.materials, true);+ let made = crate::instance_emitters(&inst, (r0 + i) as u32, &pool_tris[a..b], (edit.pool_first + a) as u32, &|k| Some((k, mat, 0)), im.count as usize, &tables.materials, true, None);for (j, (e, w)) in made.into_iter().enumerate() {new_emitters.push(((first + j) as u32, crate::GpuEmitterTri::of(&e, w, 0)));tables.emitter_tris.push(e);diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rsindex e7ab913..b53179c 100644--- a/renderer/src/live/frame.rs+++ b/renderer/src/live/frame.rs@@ -411,7 +411,7 @@ impl LiveCore {}let tile_at = (((halton(self.frame % 64 + 1, 2) * 8.0) as u32).min(7), ((halton(self.frame % 64 + 1, 3) * 8.0) as u32).min(7));// Something moves (triangles re-transformed, instances' transforms): the kernel writes motion vectors.- let moving = !self.sc.dynamic.1.is_empty() || self.sc.moving_instances;+ let moving = !self.sc.dynamic.1.is_empty() || self.sc.moving_instances || gpu::Gpu::particle_meshes(&self.sc.up);for k in 0..spp.max(1) {let mut p = self.sc.base;p.motion[1] = reconstruction.raw_signal() as u32 as f32;@@ -599,7 +599,7 @@ impl LiveCore {let target = if lp.misc2[2] > 0.0 || lp.dof[0] > 0.0 { &self.targets.buf("sb").buffer } else { &self.targets.buf("fa").buffer };// Below full resolution the particles are drawn per traced pixel, then laid over the output (`translucent_up`).let low = (iw, ih) != (w, h);- let tp = gpu::TranslucentParams { size: [w, h, t.first, 1], view: [iw, ih, gpu::VOLUME_TRAIN_CAP, low as u32], misc: [VOLUME_TRAIN_SHARE, translucent_hidden(self.frame) as u32 as f32, 0.0, 0.0] };+ let tp = gpu::TranslucentParams { size: [w, h, 0, 1], view: [iw, ih, gpu::VOLUME_TRAIN_CAP, low as u32], misc: [VOLUME_TRAIN_SHARE, translucent_hidden(self.frame) as u32 as f32, 0.0, 0.0] };g.queue.write_buffer(&t.params, 0, bytemuck::bytes_of(&tp));(pipes, g.translucent_bind_group(t, target, self.targets.translucent_low.as_ref().expect("made at the frame's start")), &t.count)});diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rsindex f1f49a9..b7ad424 100644--- a/renderer/src/live/inplace_tests.rs+++ b/renderer/src/live/inplace_tests.rs@@ -613,14 +613,19 @@ fn a_moved_card_beside_another_is_written_where_it_lies() {}}-/// A particle that drifts: its vertices' previous positions are the pass's last (the motion vectors at its pixels-/// are its step back), and the pass leaves its vertices' UVs as the build made them.+/// A particle that drifts, beside a system that stands still: its vertices' previous positions are the pass's last+/// (the motion vectors at its pixels are its step back, and nothing else moves), and the pass leaves the vertices'+/// UVs as the build made them.#[test]fn a_particle_that_moves_has_its_last_positions_and_keeps_its_uvs() {let presets = crate::default_presets_dir();let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54));let mut w = world();w.set_particle_fn("drift", "fn pf_drift(i: PIn, p: array<vec4<f32>, 8>) -> POut { return POut(vec3<f32>(-0.6 + 0.6 * i.time, 0.5, 1.0), vec3<f32>(0.3, 0.0, 0.0), vec3<f32>(0.0, 0.3, 0.0), true, vec4<f32>(0.0)); }".into(), String::new());+ // (Another system before it, two quads that stand still: the drifting one's vertices and their previous positions+ // are not the scene's first that move.)+ w.set_particle_fn("still", "fn pf_still(i: PIn, p: array<vec4<f32>, 8>) -> POut { return POut(vec3<f32>(-0.6 + 0.5 * f32(i.index), -0.5, 1.0), vec3<f32>(0.1, 0.0, 0.0), vec3<f32>(0.0, 0.1, 0.0), true, vec4<f32>(0.0)); }".into(), String::new());+ w.set_object(17, "still".into(), None, Kind::Particles { count: 2, emitter: "still".into(), params: vec![], material: 1, emitter_area: 0.0 }, true, false).unwrap();w.set_object(18, "drift".into(), None, Kind::Particles { count: 1, emitter: "drift".into(), params: vec![], material: 1, emitter_area: 0.01 }, true, false).unwrap();let mut live = match open(&w) {Ok(c) if c.g.hwrt => c,@@ -628,7 +633,7 @@ fn a_particle_that_moves_has_its_last_positions_and_keeps_its_uvs() {Err(e) => return eprintln!("skipped: {e}"),};w.take_changes();- // (The vertices that move: the particle's six.)+ // (The vertices that move: four a particle, the systems' meshes.)let vertices = |c: &LiveCore| -> (Vec<[f32; 3]>, Vec<[f32; 2]>) {let (first, n) = (c.sc.dynamic_verts.0 as u64, c.sc.dynamic_verts.1 as u64);let size = crate::indexed::VERTEX_BYTES as u64;@@ -636,11 +641,17 @@ fn a_particle_that_moves_has_its_last_positions_and_keeps_its_uvs() {(v.iter().map(|v| [v[0][0], v[0][1], v[0][2]]).collect(), v.iter().map(|v| [v[0][3], v[1][3]]).collect())};let built = vertices(&live);- assert!(built.1.len() == 6 && built.1.iter().any(|uv| uv[0] != 0.0) && built.1.iter().any(|uv| uv[1] != 0.0), "the particle's six vertices, with the build's UVs ({:?})", built.1);+ assert!(built.1.len() == 12 && built.1.chunks(4).all(|q| q == [[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]]), "four vertices a particle (its mesh's quad, in the order the pass writes it), with the build's UVs: {:?}", built.1);live.fixed_dt = Some(1.0 / 60.0);- for _ in 0..4 {+ for k in 0..4 {live.advance_time(1.0 / 60.0);live.render(1, |_, _| {});+ // (A pass's first run has no last frame: the previous positions are the positions, and nothing moves.)+ if k == 0 {+ let m = &live.targets.kernel.motion;+ let moved = read_back::<f32>(&live, &m.buffer, m.offset, m.size).chunks_exact(4).filter(|p| p[3] > 0.5 && Vec3::new(p[0], p[1], p[2]).length() > 1e-4).count();+ assert_eq!(moved, 0, "the first frame: no pixel moves");+ }}let now = vertices(&live);assert!(now.0 != built.0 && now.1 == built.1, "the pass moved the vertices and left their UVs ({:?} -> {:?})", built.1, now.1);@@ -658,6 +669,10 @@ fn a_gpu_particle_that_moves_has_its_last_positions_and_keeps_its_uvs() {let mut w = world();let emit = "fn pe_drift(i: EIn, p: array<vec4<f32>, 8>) -> PState { var s: PState; s.pos = i.at; s.life = 1000.0; s.color = i.color; s.size = 0.3; s.vel = vec3<f32>(0.6, 0.0, 0.0); return s; }";w.set_particle_program("drift", emit.into(), "fn pu_drift(s: PState, i: UIn, p: array<vec4<f32>, 8>) -> PState { return s; }".into(), String::new());+ // (Another system before it, two quads that stand still: the drifting one's vertices and their previous positions+ // are not the scene's first that move.)+ w.set_particle_fn("still", "fn pf_still(i: PIn, p: array<vec4<f32>, 8>) -> POut { return POut(vec3<f32>(-0.6 + 0.5 * f32(i.index), -0.5, 1.0), vec3<f32>(0.1, 0.0, 0.0), vec3<f32>(0.0, 0.1, 0.0), true, vec4<f32>(0.0)); }".into(), String::new());+ w.set_object(17, "still".into(), None, Kind::Particles { count: 2, emitter: "still".into(), params: vec![], material: 1, emitter_area: 0.0 }, true, false).unwrap();w.set_object(18, "drift".into(), None, Kind::GpuParticles { capacity: 1, program: "drift".into(), params: vec![], material: 1, emitter_area: 0.01, rate: 0.0, collide: Default::default() }, true, false).unwrap();let mut live = match open(&w) {Ok(c) if c.g.hwrt => c,@@ -675,11 +690,17 @@ fn a_gpu_particle_that_moves_has_its_last_positions_and_keeps_its_uvs() {(v.iter().map(|v| [v[0][0], v[0][1], v[0][2]]).collect(), v.iter().map(|v| [v[0][3], v[1][3]]).collect())};let built = vertices(&live);- assert!(built.1.len() == 6 && built.1.iter().any(|uv| uv[0] != 0.0) && built.1.iter().any(|uv| uv[1] != 0.0), "the particle's six vertices, with the build's UVs ({:?})", built.1);+ assert!(built.1.len() == 12 && built.1.chunks(4).all(|q| q == [[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]]), "four vertices a particle (its mesh's quad, in the order the pass writes it), with the build's UVs: {:?}", built.1);live.fixed_dt = Some(1.0 / 60.0);- for _ in 0..6 {+ for k in 0..6 {live.advance_time(1.0 / 60.0);live.render(1, |_, _| {});+ // (A pass's first run has no last frame: the previous positions are the positions, and nothing moves.)+ if k == 0 {+ let m = &live.targets.kernel.motion;+ let moved = read_back::<f32>(&live, &m.buffer, m.offset, m.size).chunks_exact(4).filter(|p| p[3] > 0.5 && Vec3::new(p[0], p[1], p[2]).length() > 1e-4).count();+ assert_eq!(moved, 0, "the first frame: no pixel moves");+ }}let now = vertices(&live);assert!(now.0 != built.0 && now.1 == built.1, "the pass moved the vertices and left their UVs ({:?} -> {:?})", built.1, now.1);diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rsindex f7582b5..0ca0de9 100644--- a/renderer/src/live/load.rs+++ b/renderer/src/live/load.rs@@ -254,9 +254,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Plet fixed_features = (!sc.textures.is_empty(), !sc.shaders.is_empty(), prep.groups);let shaders = sc.shaders.clone();let volume_fns = sc.volume_fns.clone();- let mut translucent_mats: Vec<u32> = sc.trans_attrs.iter().map(|a| a.uv[3].to_bits()).collect();- translucent_mats.sort_unstable();- translucent_mats.dedup();+ let translucent_mats = sc.translucent_mats();let translucent_used = translucent_mats.iter().filter_map(|&m| sc.materials.get(m as usize)).map(|m| m.tex1[3] - 1).filter(|&f| f >= 0).collect();// (The light tree is the tables' by now: its nodes from there.)let up = g.upload(&sc, &targets.accum, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, crate::ltree::nodes_of(tables.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;diff --git a/renderer/src/scene.rs b/renderer/src/scene.rsindex fd39e99..4517a3b 100644--- a/renderer/src/scene.rs+++ b/renderer/src/scene.rs@@ -94,13 +94,20 @@ pub const MESH_SECTIONS: usize = 1 << 16;/// An instance's row for a section of its mesh, as the kernel reads it (the words' heap, heap.rs `Stream::Rows`):/// the material with the class bits `ROW_*`, the section's first triangle in the triangles' table, its first emitter in-/// the light list (`NO_EMITTER`: it does not emit), and a word to spare.+/// the light list (`NO_EMITTER`: it does not emit), and a word the kernel does not read (`ROW_UNSAMPLED`).pub type Row = [u32; 4];pub const ROW_MATERIAL: u32 = 0xff_ffff;/// The material is alpha-tested; it is glass (shadow rays pass).pub const ROW_CUTOUT: u32 = 1 << 24;pub const ROW_GLASS: u32 = 1 << 25;pub const NO_EMITTER: u32 = u32::MAX;+/// In a row's last word: the section's triangles are not in the light list although its material may emit (a+/// particle system the lights are not sampled by: its emission reaches surfaces by their BSDF rays alone).+pub const ROW_UNSAMPLED: u32 = 1;+/// Whether a row's section is in the light list.+fn row_emits(r: &Row, materials: &[GpuMaterial]) -> bool {+ r[3] & ROW_UNSAMPLED == 0 && materials.get(row_material(r) as usize).is_some_and(emissive)+}/// The row of a section drawn with material `mat`; where its triangles and its emitters are is set where the tables/// are laid out (lib.rs `prepare`, the live edits).@@ -129,7 +136,7 @@ pub fn rows_bits(rows: &[Row]) -> u32 {/// How many emitters an instance with these rows has in the light list: every triangle of its sections whose/// material emits, a section after another, a section's in its triangles' order (`section_emitters`).pub fn rows_emitters(sections: &[Section], rows: &[Row], materials: &[GpuMaterial]) -> u32 {- sections.iter().zip(rows).filter(|(_, r)| materials.get(row_material(r) as usize).is_some_and(emissive)).map(|(s, _)| s.count).sum()+ sections.iter().zip(rows).filter(|(_, r)| row_emits(r, materials)).map(|(s, _)| s.count).sum()}/// A triangle's place among its instance's emitters, its material and its section, from its attributes (its@@ -147,7 +154,7 @@ pub fn section_emitters(sections: &[Section], rows: &[Row], materials: &[GpuMate.iter().zip(rows).map(|(s, r)| {- materials.get(row_material(r) as usize).is_some_and(emissive).then(|| {+ row_emits(r, materials).then(|| {at += s.count;at - s.count})@@ -288,8 +295,11 @@ pub const INST_CUTOUT: u32 = 16;pub const INST_GLASS: u32 = 32;/// Its mesh deforms (a posed skinned model's): its motion is its vertices' too (`Instance::prev`).pub const INST_DEFORMS: u32 = 64;+/// Its mesh is a particle system's (`ParticleSystem::mesh`): a quad a particle, and an object a particle from the+/// record's on (a hit's object is its triangle's index in the mesh / 2 past it).+pub const INST_PARTICLES: u32 = 128;/// Every bit of n1.w that is the instance's own, not a unit's.-pub const INST_BITS: u32 = INST_MIRRORED | INST_CUTOUT | INST_GLASS | INST_DEFORMS;+pub const INST_BITS: u32 = INST_MIRRORED | INST_CUTOUT | INST_GLASS | INST_DEFORMS | INST_PARTICLES;/// Whether a placement mirrors what it places (a negative determinant).pub fn mirrors(w: Mat4) -> bool {@@ -537,7 +547,7 @@ pub struct GpuTriAttr {pub n2: [f32; 4], // normal2, w = uv1.xpub uv: [f32; 4], // uv1.y, uv2.x, uv2.y, material (bits)pub t: [f32; 4], // its first corner's tangent (dP/du), w = the frame's hand (0: the triangle has no tangents)- pub x: [f32; 4], // -, object index (bits), a particle's area, its emitter entry + 1 (bits; 0: not light-sampled)+ pub x: [f32; 4], // -, object index (bits), -, its emitter entry + 1 (bits; 0: not light-sampled)pub t1: [f32; 4], // its second corner's tangentpub t2: [f32; 4], // its third corner's}@@ -707,7 +717,7 @@ pub struct Scene {pub gpu_instances: Vec<GpuInstance>,/// Where engine handles landed in the GPU tables, for edits without a rebuild (`LiveCore::commit`).pub retained: Retained,- /// Particle systems (dynamic triangles a GPU pass places every frame) and the particle functions they run:+ /// Particle systems (a mesh each, whose vertices a GPU pass places every frame) and the particle functions they run:/// (name, WGSL code, helpers).pub particles: Vec<ParticleSystem>,pub particle_fns: Vec<(String, String, String)>,@@ -738,14 +748,21 @@ pub struct Scene {/// Software traversal's units (`prepare`: the instances it keeps as instances; units.rs), None under hardware/// traversal and for a scene without any.pub units: Option<crate::units::Units>,- /// Translucent particles' triangles (`transparent` material): in the kernel's triangle tables after everything- /// else (`trans_first`, set by `prepare`), in no traversal group: only the translucency pass sees them.- pub trans_tris: Vec<[Vec3A; 3]>,- pub trans_attrs: Vec<GpuTriAttr>,- pub trans_first: u32,}impl Scene {+ /// The materials of the translucent particle systems (the translucency pass's: its kernel has their functions+ /// alone), each once, in order.+ pub fn translucent_mats(&self) -> Vec<u32> {+ let mut m: Vec<u32> = vec![];+ for p in self.particles.iter().filter(|p| p.translucent) {+ m.extend(self.instances.iter().filter(|i| i.mesh == p.mesh).map(|i| row_material(&self.rows[i.rows as usize])));+ }+ m.sort_unstable();+ m.dedup();+ m+ }+/// vec4s an object in `objects` (`object_stride`).pub fn object_stride(&self) -> usize {object_stride(self.tinted)@@ -1100,22 +1117,23 @@ pub fn medium_rows(m: glam::Mat4) -> [[f32; 4]; 3] {[inv.row(0).to_array(), inv.row(1).to_array(), inv.row(2).to_array()]}-/// `count` particles, each a quad (two triangles from `first`, build order; `final_first` in the GPU order after-/// `prepare`, hardware RT) and its own object (from `object`: pivot, bounds, per-particle data), placed every frame by-/// particle function `func` with `params` (8 vec4).+/// `count` particles, each a quad and its own object (from `object`: pivot, bounds, per-particle data), placed every+/// frame by particle function `func` with `params` (8 vec4). The quads are a mesh of the system's own, which one+/// instance places as the pass writes it.#[derive(Clone, Debug)]pub struct ParticleSystem {- /// Drawn by the translucency pass: `first` / `final_first` index the translucent triangles (`Scene::trans_tris`,- /// from `trans_first` on the GPU).+ /// Its mesh among the instanced ones: four vertices and two triangles a particle, written by the pass in the+ /// world (its instance does not place it).+ pub mesh: u32,+ /// A particle's nominal area where the lights are sampled by the system (m²; 0: they are not).+ pub emitter_area: f32,+ /// Drawn by the translucency pass: its instance is hidden from the scene's acceleration structure and is in+ /// that pass's.pub translucent: bool,- pub first: u32,- pub final_first: u32,pub count: u32,pub object: u32,pub func: u32,pub params: [f32; 32],- /// Triangle flags (kept in the kernel's vertex data).- pub flags: u32,/// Seed of the particles' fixed random numbers (the node).pub seed: u32,/// The node's customData (the particle function's `i.custom`).@@ -1124,13 +1142,13 @@ pub struct ParticleSystem {pub hidden: bool,}-/// A `GpuParticles` node as built: its quads (`first` in build order, `final_first` in the GPU's), its objects (and+/// A `GpuParticles` node as built: its quads (a mesh of its own, `mesh`, as `ParticleSystem::mesh`), its objects (and/// states) from `object`, its program and parameters, emission and collision.#[derive(Clone, Debug)]pub struct GpuParticleSystem {+ pub mesh: u32,+ pub emitter_area: f32,pub node: u32,- pub first: u32,- pub final_first: u32,pub capacity: u32,pub object: u32,pub program: u32,@@ -1599,7 +1617,6 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&selet mut particles: Vec<ParticleSystem> = vec![];let mut gpu_particles: Vec<GpuParticleSystem> = vec![];let particle_programs: Vec<(String, String, String, String)> = w.particle_programs.iter().map(|(k, (e, u, h))| (k.clone(), e.clone(), u.clone(), h.clone())).collect();- let (mut trans_tris, mut trans_attrs): (Vec<[Vec3A; 3]>, Vec<GpuTriAttr>) = (vec![], vec![]);let particle_fns: Vec<(String, String, String)> = w.particle_fns.iter().map(|(k, (c, h))| (k.clone(), c.clone(), h.clone())).collect();let volume_fns: Vec<(String, String, String)> = w.volume_fns.iter().map(|(k, (c, h))| (k.clone(), c.clone(), h.clone())).collect();let geometry_fns: Vec<(String, String, String)> = w.geometry_fns.iter().map(|(k, (c, h))| (k.clone(), c.clone(), h.clone())).collect();@@ -2165,73 +2182,49 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se}}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).+ // A particle system is geometry as any other: a mesh of its own in the pool, a quad a particle, and one+ // instance of it; each particle its own object (pivot, bounds and per-particle data for material+ // functions). The quads are collapsed at the node until the particle pass writes their vertices where+ // the particles are (the instance places nothing), and the mesh's BLAS is built again after the pass.+ // (Whatever THREERT_INSTANCING says: a system has no flattened form.)let mat = *retained.materials.get(material).ok_or_else(|| anyhow!("object {}: unknown material {material}", n.name))?;let func = particle_fns.iter().position(|(k, _, _)| k == emitter).ok_or_else(|| anyhow!("object {}: unknown particle function {emitter}", n.name))? as u32;let pivot = m.transform_point3(Vec3::ZERO);- let p = Vec3A::from(pivot);let object = (objects.len() / stride) as u32;- let corners = [[Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0)], [Vec2::new(0.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)]];let translucent = w.materials.get(material).is_some_and(|m| m.transparent);- let first = if translucent { trans_tris.len() as u32 } else { first };- for k in 0..*count {- for uv in corners {- let mut a = tri_attr([Vec3::Z; 3], uv, Some([(Vec3::X, 1.0); 3]), mat);- a.x[1] = f32::from_bits(object + k);- // Light sampling by a nominal area (half a quad per triangle; lib.rs prepare, emit_mis); -1: a- // particle not light-sampled (its emission reaches surfaces by their BSDF rays alone).- a.x[2] = if translucent { 0.0 } else if *emitter_area > 0.0 { emitter_area * 0.5 } else { -1.0 };- if translucent {- trans_tris.push([p; 3]);- trans_attrs.push(a);- } else {- tris.push([p; 3]);- tri_flags.push(flags | TRI_DYNAMIC);- attrs.push(a);- }- }- objects.extend_from_slice(&object_row(pivot, n.power, Vec3::ZERO, n.custom, [1.0; 3])[..stride]);- }let mut pf = [0.0f32; 32];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, hidden: !shown });- if !translucent {- tri_nodes.push((n.name.clone(), first, tris.len() as u32));+ for _ in 0..*count {+ objects.extend_from_slice(&object_row(pivot, n.power, Vec3::ZERO, n.custom, [1.0; 3])[..stride]);}+ let mesh = particle_mesh(*count, pivot.into(), mat, object, !translucent && *emitter_area > 0.0, n, &materials, &mut Pool { tris: &mut pool_tris, attrs: &mut pool_attrs, meshes: &mut meshes, sections: &mut sections, instances: &mut instances, rows: &mut rows });+ // (A translucent system is the translucency pass's: its instance is in that pass's acceleration+ // structure, not in the scene's.)+ instances.last_mut().expect("the system's instance").hidden = translucent;+ particles.push(ParticleSystem { mesh, emitter_area: *emitter_area, translucent, count: *count, object, func, params: pf, seed: *id, custom: n.custom, hidden: !shown });}Kind::GpuParticles { capacity, program, params, material, emitter_area, rate, collide } if shown && *capacity > 0 => {- // As `Particles`: quads collapsed at the node, each its own object, until the pass places them.+ // As `Particles`: a mesh of quads collapsed at the node and one instance, each particle its own object.let mat = *retained.materials.get(material).ok_or_else(|| anyhow!("object {}: unknown material {material}", n.name))?;let prog = particle_programs.iter().position(|(k, ..)| k == program).ok_or_else(|| anyhow!("object {}: unknown particle program {program}", n.name))? as u32;let pivot = m.transform_point3(Vec3::ZERO);- let p = Vec3A::from(pivot);let object = (objects.len() / stride) as u32;- let corners = [[Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0)], [Vec2::new(0.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)]];- for k in 0..*capacity {- for uv in corners {- let mut a = tri_attr([Vec3::Z; 3], uv, Some([(Vec3::X, 1.0); 3]), mat);- a.x[1] = f32::from_bits(object + k);- a.x[2] = if *emitter_area > 0.0 { emitter_area * 0.5 } else { -1.0 };- tris.push([p; 3]);- tri_flags.push(flags | TRI_DYNAMIC);- attrs.push(a);- }- objects.extend_from_slice(&object_row(pivot, n.power, Vec3::ZERO, n.custom, [1.0; 3])[..stride]);- }let mut pf = [0.0f32; 32];for (k, v) in params.iter().take(32).enumerate() {pf[k] = *v;}- gpu_particles.push(GpuParticleSystem { node: *id, first, final_first: first, capacity: *capacity, object, program: prog, params: pf, seed: *id, pivot: pivot.to_array(), rate: *rate, collide: collide.clone() });- tri_nodes.push((n.name.clone(), first, tris.len() as u32));+ for _ in 0..*capacity {+ objects.extend_from_slice(&object_row(pivot, n.power, Vec3::ZERO, n.custom, [1.0; 3])[..stride]);+ }+ let mesh = particle_mesh(*capacity, pivot.into(), mat, object, *emitter_area > 0.0, n, &materials, &mut Pool { tris: &mut pool_tris, attrs: &mut pool_attrs, meshes: &mut meshes, sections: &mut sections, instances: &mut instances, rows: &mut rows });+ gpu_particles.push(GpuParticleSystem { mesh, emitter_area: *emitter_area, node: *id, capacity: *capacity, object, program: prog, params: pf, seed: *id, pivot: pivot.to_array(), rate: *rate, collide: collide.clone() });}Kind::Camera(c) if st.camera == Some(*id) => camera = Some(camera_data(m, c)),_ => {}}- if tris.len() as u32 > first && !matches!(n.kind, Kind::Particles { .. } | Kind::GpuParticles { .. } | Kind::Instanced { .. }) {+ if tris.len() as u32 > first && !matches!(n.kind, Kind::Instanced { .. }) {// Object pivot + world bounds (UE ObjectPositionWS / ObjectBounds) for material functions, and the object's// power (scales everything it emits).let (mut lo, mut hi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));@@ -2346,9 +2339,6 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seproc_layout: None,proc_records: vec![],units: None,- trans_tris,- trans_attrs,- trans_first: 0,pool_tris,pool_attrs,meshes,@@ -2710,6 +2700,41 @@ pub fn mesh_class(g: &GpuMaterial) -> u32 {/// emitters of a mesh that deforms).pub const FLAT: usize = 3;+/// The build's arrays a mesh of the pool and its instance are added to.+pub struct Pool<'a> {+ pub tris: &'a mut Vec<[Vec3A; 3]>,+ pub attrs: &'a mut Vec<GpuTriAttr>,+ pub meshes: &'a mut Vec<InstMesh>,+ pub sections: &'a mut Vec<Section>,+ pub instances: &'a mut Vec<Instance>,+ pub rows: &'a mut Vec<Row>,+}++/// A particle system's mesh and its one instance (`ParticleSystem::mesh`): `count` quads collapsed at `pivot` until+/// the pass places them, one section of material `mat`; the instance places nothing (the pass writes the vertices+/// in the world), has the system's first object (`object`: one a particle) and, unless the lights are sampled by+/// the system (`sampled`), a row that keeps the material's emission out of the light list. The mesh.+fn particle_mesh(count: u32, pivot: Vec3A, mat: u32, object: u32, sampled: bool, n: &world::Object, materials: &[GpuMaterial], pool: &mut Pool) -> u32 {+ let corners = [[Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0)], [Vec2::new(0.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)]];+ let first = pool.tris.len() as u32;+ for k in 0..count {+ for (j, uv) in corners.into_iter().enumerate() {+ pool.tris.push([pivot; 3]);+ pool.attrs.push(section_attr([Vec3::Z; 3], uv, Some([(Vec3::X, 1.0); 3]), 0, k * 2 + j as u32));+ }+ }+ pool.meshes.push(InstMesh { deforms: true, sect_first: pool.sections.len() as u32, sect_count: 1, ..own_inst_mesh(&pool.tris[first as usize..], first) });+ let mesh = pool.meshes.len() as u32 - 1;+ pool.sections.push(Section { first: 0, count: count * 2, slot: 0 });+ let mut mine = [row_of(mat, materials)];+ if !sampled {+ mine[0][3] = ROW_UNSAMPLED;+ }+ pool.instances.push(Instance { mesh, world: Mat4::IDENTITY, object, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: pool.rows.len() as u32, bits: rows_bits(&mine) | INST_PARTICLES, prev: 0, verts: 0 });+ pool.rows.extend(mine);+ mesh+}+/// The `InstMesh` of triangles at pool index `first`, with their bounds; its sections are the caller's to set.pub fn own_inst_mesh(tris: &[[Vec3A; 3]], first: u32) -> InstMesh {let (mut lo, mut hi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));diff --git a/tests/render/translucent-systems.ts b/tests/render/translucent-systems.tsnew file mode 100644index 0000000..dae8da6--- /dev/null+++ b/tests/render/translucent-systems.ts@@ -0,0 +1,36 @@+// Translucency pass, several systems: two translucent particle systems of two quads each, A (emitting 2 nits, its+// node's power 2: 4 nits) and B (black), both half opaque, over a 2-nit wall. On the left A's quad is in front of+// B's, on the right B's in front of A's: front to back, left = 0.5 * 4 + 0.5 * (0.5 * 0 + 0.5 * 2) = 2.5 and+// right = 0.5 * 0 + 0.5 * (0.5 * 4 + 0.5 * 2) = 1.5. A hit taken for the other system's (its material, its node's+// power) reads the same on both sides.+import { BoxGeometry, Mesh, MeshStandardMaterial, ParticleFunction, Particles } from "@threert/scene";+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";++export const test: TestMeta = {+ id: "translucent/systems", features: ["particles", "translucency"], reference: "analytic", temporal: false,+ metric: { kind: "ratio", a: [0.25, 0.4, 0.35, 0.6], b: [0.65, 0.4, 0.75, 0.6], expected: 2.5 / 1.5, tolerance: 0.02 },+ note: "quads 1 x 1 m at z = 1 and z = 0 behind one another as the camera at z = 5 sees them (30 deg vertical fov), wall at z = -1",+};++// Particle 0 on the left, 1 on the right; $Swap 0: the left one near, the right one far; 1: the other way round.+const PAIRS = new ParticleFunction("test_tl_systems", {+ params: { Swap: 0 },+ code: `+ let left = i.index == 0u;+ let near = left != ($Swap > 0.5);+ o.center = vec3<f32>(select(1.0, -1.0, left) * select(0.9524, 0.762, near), 0.0, select(0.0, 1.0, near));+ o.u = vec3<f32>(0.5, 0.0, 0.0);+ o.v = vec3<f32>(0.0, 0.5, 0.0);`,+});++export default function () {+ const scene = sceneWithSky(0);+ 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, -1);+ const glow = new MeshStandardMaterial({ name: "tl-a", transparent: true, opacity: 0.5, color: 0x000000, emissive: 0xffffff, emissiveIntensity: 2 });+ const black = new MeshStandardMaterial({ name: "tl-b", transparent: true, opacity: 0.5, color: 0x000000 });+ const b = new Particles({ count: 2, emitter: PAIRS.with({ Swap: 1 }), material: black });+ const a = new Particles({ count: 2, emitter: PAIRS.with({ Swap: 0 }), material: glow });+ a.power = 2;+ return result(scene, camera(scene, [0, 0, 5], [0, 0, 0]), [wall, b, a]);+}