Skip to main content

euv_core/game/engine3d/niagara/
impl.rs

1use super::*;
2
3/// Default glowing neon spark emitter preset for `NiagaraEmitterConfig3D`.
4impl Default for NiagaraEmitterConfig3D {
5    /// Creates a glowing neon spark burst configuration.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default 3D Niagara emitter configuration.
10    fn default() -> Self {
11        Self {
12            origin: Vec3::new(0.0, 0.5, 0.0),
13            base_velocity: Vec3::new(0.0, 2.2, 2.5),
14            velocity_spread: 1.6,
15            min_lifetime: 0.35,
16            max_lifetime: 0.95,
17            start_size_m: 0.22,
18            end_size_m: 0.04,
19            start_color: Color::rgba(56, 189, 248, 235),
20            end_color: Color::rgba(168, 85, 247, 0),
21            drag: 1.4,
22            turbulence: 1.8,
23            restitution: 0.45,
24            emissive_boost: 1.4,
25        }
26    }
27}
28
29/// Default 2,048-slot `NiagaraSystem3D`.
30impl Default for NiagaraSystem3D {
31    /// Creates a pre-allocated 2,048-slot `NiagaraSystem3D` with Earth gravity.
32    ///
33    /// # Returns
34    ///
35    /// - `Self` - Ready zero-allocation 3D particle system.
36    fn default() -> Self {
37        Self::with_capacity(NIAGARA_DEFAULT_CAPACITY)
38    }
39}
40
41/// SoA 3D particle emission, curl-noise kinematics, floor collision, and depth-tested billboard compositing for `NiagaraSystem3D`.
42impl NiagaraSystem3D {
43    /// Constructs a pre-allocated `NiagaraSystem3D` sized for `capacity` live 3D particles with zero runtime heap allocations.
44    ///
45    /// # Arguments
46    ///
47    /// - `usize` - Maximum concurrent 3D particle slots (`>= 16`).
48    ///
49    /// # Returns
50    ///
51    /// - `Self` - Pre-allocated 3D Niagara particle pool.
52    #[must_use]
53    pub fn with_capacity(capacity: usize) -> Self {
54        let cap: usize = capacity.max(16);
55        Self {
56            capacity: cap,
57            active_count: 0,
58            gravity: Vec3::new(0.0, -9.81, 0.0),
59            sim_time_secs: 0.0,
60            ring_cursor: 0,
61            rng_state: 0xD1B5_4A32_D192_ED03,
62            pos_x: vec![0.0; cap],
63            pos_y: vec![0.0; cap],
64            pos_z: vec![0.0; cap],
65            vel_x: vec![0.0; cap],
66            vel_y: vec![0.0; cap],
67            vel_z: vec![0.0; cap],
68            age: vec![0.0; cap],
69            lifetime: vec![0.0; cap],
70            start_size: vec![0.0; cap],
71            end_size: vec![0.0; cap],
72            drag: vec![0.0; cap],
73            turbulence: vec![0.0; cap],
74            restitution: vec![0.0; cap],
75            emissive_boost: vec![0.0; cap],
76            start_color: vec![COLOR_TRANSPARENT; cap],
77            end_color: vec![COLOR_TRANSPARENT; cap],
78        }
79    }
80
81    /// Generates a deterministic pseudo-random `f32` in `[-1.0, 1.0)` advancing `state`.
82    ///
83    /// # Arguments
84    ///
85    /// - `&mut u64` - Mutable PRNG state word.
86    ///
87    /// # Returns
88    ///
89    /// - `f32` - Signed pseudo-random scalar in `[-1.0, 1.0)`.
90    #[cfg_attr(not(target_arch = "wasm32"), inline)]
91    fn next_signed_f32(state: &mut u64) -> f32 {
92        let next: u64 = state
93            .wrapping_mul(NIAGARA_RNG_MULT)
94            .wrapping_add(NIAGARA_RNG_INC);
95        *state = next;
96        let unit: f32 = ((next >> 40) as f32) * (1.0 / ((1_u32 << 24) as f32));
97        unit * 2.0 - 1.0
98    }
99
100    /// Emits `count` 3D particles configured by `config` directly into the compacted SoA pool with zero heap allocations.
101    ///
102    /// # Arguments
103    ///
104    /// - `usize` - Number of particles to emit.
105    /// - `&NiagaraEmitterConfig3D` - Emission origin, velocity, lifetime, and optical configuration.
106    pub fn emit_burst(&mut self, count: usize, config: &NiagaraEmitterConfig3D) {
107        let cap: usize = self.get_capacity();
108        if cap == 0 || count == 0 {
109            return;
110        }
111        let orig: Vec3 = config.get_origin();
112        let base_v: Vec3 = config.get_base_velocity();
113        let spread: f32 = config.get_velocity_spread().max(0.0);
114        let min_life: f32 = config.get_min_lifetime().max(0.04);
115        let life_span: f32 = (config.get_max_lifetime() - min_life).max(0.0);
116        let s_size: f32 = config.get_start_size_m().max(0.01);
117        let e_size: f32 = config.get_end_size_m().max(0.005);
118        let s_col: Color = config.get_start_color();
119        let e_col: Color = config.get_end_color();
120        let drag_v: f32 = config.get_drag().max(0.0);
121        let turb_v: f32 = config.get_turbulence().max(0.0);
122        let rest_v: f32 = config.get_restitution().clamp(0.0, 0.95);
123        let boost_v: f32 = config.get_emissive_boost().clamp(0.0, 4.0);
124        let Self {
125            active_count,
126            ring_cursor,
127            rng_state,
128            pos_x,
129            pos_y,
130            pos_z,
131            vel_x,
132            vel_y,
133            vel_z,
134            age,
135            lifetime,
136            start_size,
137            end_size,
138            drag,
139            turbulence,
140            restitution,
141            emissive_boost,
142            start_color,
143            end_color,
144            ..
145        } = self;
146        let mut live: usize = *active_count;
147        let mut cursor: usize = *ring_cursor;
148        let mut rng: u64 = *rng_state;
149        for _ in 0..count {
150            let slot: usize = if live < cap {
151                let assigned: usize = live;
152                live += 1;
153                assigned
154            } else {
155                let assigned: usize = cursor % cap;
156                cursor = (assigned + 1) % cap;
157                assigned
158            };
159            let rx: f32 = Self::next_signed_f32(&mut rng);
160            let ry: f32 = Self::next_signed_f32(&mut rng);
161            let rz: f32 = Self::next_signed_f32(&mut rng);
162            let r_life: f32 = (Self::next_signed_f32(&mut rng) * 0.5 + 0.5).clamp(0.0, 1.0);
163            pos_x[slot] = orig.get_x();
164            pos_y[slot] = orig.get_y();
165            pos_z[slot] = orig.get_z();
166            vel_x[slot] = base_v.get_x() + rx * spread;
167            vel_y[slot] = base_v.get_y() + ry * spread;
168            vel_z[slot] = base_v.get_z() + rz * spread;
169            age[slot] = 0.0;
170            lifetime[slot] = min_life + life_span * r_life;
171            start_size[slot] = s_size;
172            end_size[slot] = e_size;
173            drag[slot] = drag_v;
174            turbulence[slot] = turb_v;
175            restitution[slot] = rest_v;
176            emissive_boost[slot] = boost_v;
177            start_color[slot] = s_col;
178            end_color[slot] = e_col;
179        }
180        *active_count = live;
181        *ring_cursor = cursor;
182        *rng_state = rng;
183    }
184
185    /// Advances all active 3D particles by `dt_secs` with gravity, drag, curl-noise turbulence, and ground bounce, returning remaining active count.
186    ///
187    /// # Arguments
188    ///
189    /// - `f32` - Simulation timestep in seconds.
190    /// - `f32` - Ground plane Y elevation in meters for bounce collision.
191    ///
192    /// # Returns
193    ///
194    /// - `usize` - Remaining active particle count.
195    pub fn update(&mut self, dt_secs: f32, ground_y: f32) -> usize {
196        let safe_dt: f32 = dt_secs.clamp(0.0, 0.1);
197        if safe_dt <= 0.0 || self.get_active_count() == 0 {
198            return self.get_active_count();
199        }
200        let sim_t: f32 = self.get_sim_time_secs() + safe_dt;
201        self.set_sim_time_secs(sim_t);
202        let grav: Vec3 = self.get_gravity();
203        let gx_dt: f32 = grav.get_x() * safe_dt;
204        let gy_dt: f32 = grav.get_y() * safe_dt;
205        let gz_dt: f32 = grav.get_z() * safe_dt;
206        let Self {
207            active_count,
208            pos_x,
209            pos_y,
210            pos_z,
211            vel_x,
212            vel_y,
213            vel_z,
214            age,
215            lifetime,
216            start_size,
217            end_size,
218            drag,
219            turbulence,
220            restitution,
221            emissive_boost,
222            start_color,
223            end_color,
224            ..
225        } = self;
226        let mut live: usize = *active_count;
227        let mut idx: usize = 0;
228        while idx < live {
229            let next_age: f32 = age[idx] + safe_dt;
230            if next_age >= lifetime[idx] {
231                live -= 1;
232                if idx < live {
233                    pos_x[idx] = pos_x[live];
234                    pos_y[idx] = pos_y[live];
235                    pos_z[idx] = pos_z[live];
236                    vel_x[idx] = vel_x[live];
237                    vel_y[idx] = vel_y[live];
238                    vel_z[idx] = vel_z[live];
239                    age[idx] = age[live];
240                    lifetime[idx] = lifetime[live];
241                    start_size[idx] = start_size[live];
242                    end_size[idx] = end_size[live];
243                    drag[idx] = drag[live];
244                    turbulence[idx] = turbulence[live];
245                    restitution[idx] = restitution[live];
246                    emissive_boost[idx] = emissive_boost[live];
247                    start_color[idx] = start_color[live];
248                    end_color[idx] = end_color[live];
249                }
250                continue;
251            }
252            age[idx] = next_age;
253            let px: f32 = pos_x[idx];
254            let py: f32 = pos_y[idx];
255            let pz: f32 = pos_z[idx];
256            let turb: f32 = turbulence[idx];
257            let (tx, ty, tz): (f32, f32, f32) = if turb > 1.0e-4 {
258                let phase_x: f32 = py * 1.7 + sim_t * 3.1;
259                let phase_y: f32 = pz * 1.7 - sim_t * 2.7;
260                let phase_z: f32 = px * 1.7 + sim_t * 2.3;
261                (
262                    phase_x.sin() * turb * safe_dt,
263                    phase_y.cos() * turb * 0.5 * safe_dt,
264                    phase_z.sin() * turb * safe_dt,
265                )
266            } else {
267                (0.0, 0.0, 0.0)
268            };
269            let damp: f32 = (1.0 - drag[idx] * safe_dt).clamp(0.0, 1.0);
270            let mut nvx: f32 = (vel_x[idx] + gx_dt + tx) * damp;
271            let mut nvy: f32 = (vel_y[idx] + gy_dt + ty) * damp;
272            let mut nvz: f32 = (vel_z[idx] + gz_dt + tz) * damp;
273            let npx: f32 = nvx.mul_add(safe_dt, px);
274            let mut npy: f32 = nvy.mul_add(safe_dt, py);
275            let npz: f32 = nvz.mul_add(safe_dt, pz);
276            if npy < ground_y {
277                npy = ground_y;
278                if nvy < 0.0 {
279                    nvy = -nvy * restitution[idx];
280                    nvx *= 0.84;
281                    nvz *= 0.84;
282                }
283            }
284            pos_x[idx] = npx;
285            pos_y[idx] = npy;
286            pos_z[idx] = npz;
287            vel_x[idx] = nvx;
288            vel_y[idx] = nvy;
289            vel_z[idx] = nvz;
290            idx += 1;
291        }
292        *active_count = live;
293        live
294    }
295
296    /// Clears all live 3D particles in O(1) while retaining pre-allocated SoA capacities.
297    pub fn clear(&mut self) {
298        self.set_active_count(0);
299        let Self { ring_cursor, .. } = self;
300        *ring_cursor = 0;
301    }
302
303    /// Projects and depth-tests all active 3D Niagara particles onto `rgba_out` using the reverse-Z `depth_buffer`, returning rendered particle count.
304    ///
305    /// # Arguments
306    ///
307    /// - `&Mat4` - Active frame view-projection matrix.
308    /// - `f32` - Projected viewport focal length in pixels.
309    /// - `(usize, usize)` - Target framebuffer `(width, height)` in pixels.
310    /// - `&[f32]` - Reverse-Z `1/w` depth buffer (`0.0` = sky, larger = nearer).
311    /// - `&mut [u8]` - Target RGBA8 framebuffer updated with depth-tested glowing billboards.
312    ///
313    /// # Returns
314    ///
315    /// - `usize` - Number of visible 3D particles composited onto the framebuffer.
316    pub fn composite_depth_tested(
317        &self,
318        view_proj: &Mat4,
319        focal_px: f32,
320        dims: (usize, usize),
321        depth_buffer: &[f32],
322        rgba_out: &mut [u8],
323    ) -> usize {
324        let (width, height): (usize, usize) = dims;
325        let live: usize = self.get_active_count();
326        if live == 0
327            || width == 0
328            || height == 0
329            || depth_buffer.len() < width * height
330            || rgba_out.len() < width * height * 4
331        {
332            return 0;
333        }
334        let w_f: f32 = width as f32;
335        let h_f: f32 = height as f32;
336        let w_max: i32 = (width as i32) - 1;
337        let h_max: i32 = (height as i32) - 1;
338        let mut drawn: usize = 0;
339        let Self {
340            pos_x,
341            pos_y,
342            pos_z,
343            age,
344            lifetime,
345            start_size,
346            end_size,
347            emissive_boost,
348            start_color,
349            end_color,
350            ..
351        } = self;
352        for idx in 0..live {
353            let world_pt: Vec3 = Vec3::new(pos_x[idx], pos_y[idx], pos_z[idx]);
354            let clip: [f32; 4] = view_proj.mul_point4(world_pt);
355            if clip[3] <= NIAGARA_NEAR_CLIP_M {
356                continue;
357            }
358            let inv_w: f32 = 1.0 / clip[3];
359            let sx: f32 = (clip[0] * inv_w * 0.5 + 0.5) * w_f;
360            let sy: f32 = (0.5 - clip[1] * inv_w * 0.5) * h_f;
361            let life_t: f32 = (age[idx] / lifetime[idx].max(1.0e-4)).clamp(0.0, 1.0);
362            let world_rad: f32 = start_size[idx] + (end_size[idx] - start_size[idx]) * life_t;
363            let px_rad: f32 =
364                (world_rad * focal_px * inv_w).clamp(1.0, NIAGARA_MAX_BILLBOARD_RADIUS_PX);
365            let x0: i32 = ((sx - px_rad).floor() as i32).max(0);
366            let x1: i32 = ((sx + px_rad).ceil() as i32).min(w_max);
367            let y0: i32 = ((sy - px_rad).floor() as i32).max(0);
368            let y1: i32 = ((sy + px_rad).ceil() as i32).min(h_max);
369            if x0 > x1 || y0 > y1 {
370                continue;
371            }
372            let c0: Color = start_color[idx];
373            let c1: Color = end_color[idx];
374            let keep: f32 = 1.0 - life_t;
375            let boost: f32 = emissive_boost[idx];
376            let cr: f32 = ((c0.get_red() as f32) * keep + (c1.get_red() as f32) * life_t) * boost;
377            let cg: f32 =
378                ((c0.get_green() as f32) * keep + (c1.get_green() as f32) * life_t) * boost;
379            let cb: f32 = ((c0.get_blue() as f32) * keep + (c1.get_blue() as f32) * life_t) * boost;
380            let base_alpha: f32 =
381                (((c0.get_alpha() as f32) * keep + (c1.get_alpha() as f32) * life_t) / 255.0)
382                    .clamp(0.0, 1.0);
383            if base_alpha <= 0.01 {
384                continue;
385            }
386            let inv_r2: f32 = 1.0 / (px_rad * px_rad).max(1.0);
387            let mut wrote_any: bool = false;
388            for py in y0..=y1 {
389                let dy: f32 = (py as f32) + 0.5 - sy;
390                let dy2: f32 = dy * dy;
391                let row_off: usize = (py as usize) * width;
392                for px in x0..=x1 {
393                    let dx: f32 = (px as f32) + 0.5 - sx;
394                    let q2: f32 = (dx * dx + dy2) * inv_r2;
395                    if q2 >= 1.0 {
396                        continue;
397                    }
398                    let pix_idx: usize = row_off + (px as usize);
399                    if inv_w < depth_buffer[pix_idx] {
400                        continue;
401                    }
402                    let falloff: f32 = (1.0 - q2) * (1.0 - q2);
403                    let alpha: f32 = (base_alpha * falloff).clamp(0.0, 1.0);
404                    let inv_a: f32 = 1.0 - alpha;
405                    let off: usize = pix_idx * 4;
406                    let nr: f32 = ((rgba_out[off] as f32) * inv_a + cr * alpha).clamp(0.0, 255.0);
407                    let ng: f32 =
408                        ((rgba_out[off + 1] as f32) * inv_a + cg * alpha).clamp(0.0, 255.0);
409                    let nb: f32 =
410                        ((rgba_out[off + 2] as f32) * inv_a + cb * alpha).clamp(0.0, 255.0);
411                    rgba_out[off] = nr as u8;
412                    rgba_out[off + 1] = ng as u8;
413                    rgba_out[off + 2] = nb as u8;
414                    wrote_any = true;
415                }
416            }
417            if wrote_any {
418                drawn += 1;
419            }
420        }
421        drawn
422    }
423}