Skip to main content

euv_core/game/particles/
impl.rs

1use super::*;
2
3/// Default radial spark burst emitter configuration.
4impl Default for ParticleEmitterConfig {
5    /// Creates a radial neon spark burst configuration.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default particle emitter config.
10    fn default() -> Self {
11        Self {
12            base_angle: 0.0,
13            spread_rad: TAU,
14            min_speed: 60.0,
15            max_speed: 220.0,
16            min_life: 0.25,
17            max_life: 0.65,
18            start_size: 4.5,
19            end_size: 0.8,
20            start_color: Color::rgba(56, 189, 248, 255),
21            end_color: Color::rgba(99, 102, 241, 0),
22            drag: 2.2,
23        }
24    }
25}
26
27/// Default 1,024-slot lazy particle system pool.
28impl Default for ParticleSystem {
29    /// Creates a lazily allocated `ParticleSystem` configured for 1,024 pooled slots.
30    ///
31    /// # Returns
32    ///
33    /// - `Self` - Ready zero-allocation particle system.
34    fn default() -> Self {
35        Self::with_capacity(1024)
36    }
37}
38
39/// Particle emission, deterministic PRNG, and active-prefix SoA kinematics for `ParticleSystem`.
40impl ParticleSystem {
41    /// Creates a fixed-capacity `ParticleSystem` whose SoA lanes allocate lazily on first `emit_burst`.
42    ///
43    /// # Arguments
44    ///
45    /// - `usize` - Maximum concurrent particles.
46    ///
47    /// # Returns
48    ///
49    /// - `Self` - Zero-allocation particle system ready for lazy emission.
50    #[must_use]
51    pub fn with_capacity(capacity: usize) -> Self {
52        let cap: usize = capacity.max(16);
53        Self {
54            capacity: cap,
55            pos_x: vec![0.0; cap],
56            pos_y: vec![0.0; cap],
57            vel_x: vec![0.0; cap],
58            vel_y: vec![0.0; cap],
59            age: vec![0.0; cap],
60            lifetime: vec![0.0; cap],
61            drag: vec![0.0; cap],
62            start_size: vec![0.0; cap],
63            end_size: vec![0.0; cap],
64            start_color: vec![COLOR_TRANSPARENT; cap],
65            end_color: vec![COLOR_TRANSPARENT; cap],
66            min_remaining_life: f32::INFINITY,
67            cursor: 0,
68            rng_state: 0x9E37_79B9_7F4A_7C15,
69            gravity: Point::new(0.0, 0.0),
70            active_count: 0,
71        }
72    }
73
74    /// Generates a deterministic pseudo-random `f32` in `[0.0, 1.0)` advancing `state`.
75    ///
76    /// # Arguments
77    ///
78    /// - `&mut u64` - Mutable PRNG state word.
79    ///
80    /// # Returns
81    ///
82    /// - `f32` - Normalized random scalar.
83    #[inline(always)]
84    fn next_unit_f32_from(state: &mut u64) -> f32 {
85        let next: u64 = state
86            .wrapping_mul(6_364_136_223_846_793_005)
87            .wrapping_add(1_442_695_040_888_963_407);
88        *state = next;
89        ((next >> 40) as f32) * (1.0 / ((1_u32 << 24) as f32))
90    }
91
92    /// Emits `count` particles at `origin` using `config` into the compacted active prefix without heap allocations.
93    ///
94    /// # Arguments
95    ///
96    /// - `&Self` - Mutable particle system.
97    /// - `Point` - World-space emission origin.
98    /// - `usize` - Number of particles to emit.
99    /// - `ParticleEmitterConfig` - Emission parameters.
100    pub fn emit_burst(&mut self, origin: Point, count: usize, config: ParticleEmitterConfig) {
101        let Self {
102            capacity,
103            pos_x,
104            pos_y,
105            vel_x,
106            vel_y,
107            age,
108            lifetime,
109            drag,
110            start_size,
111            end_size,
112            start_color,
113            end_color,
114            min_remaining_life,
115            cursor,
116            rng_state,
117            active_count,
118            ..
119        } = self;
120        let cap: usize = *capacity;
121        if cap == 0 || count == 0 {
122            return;
123        }
124        if pos_x.len() < cap {
125            pos_x.resize(cap, 0.0);
126            pos_y.resize(cap, 0.0);
127            vel_x.resize(cap, 0.0);
128            vel_y.resize(cap, 0.0);
129            age.resize(cap, 0.0);
130            lifetime.resize(cap, 0.0);
131            drag.resize(cap, 0.0);
132            start_size.resize(cap, 0.0);
133            end_size.resize(cap, 0.0);
134            start_color.resize(cap, Color::default());
135            end_color.resize(cap, Color::default());
136        }
137        let base_angle: f32 = config.get_base_angle();
138        let spread_rad: f32 = config.get_spread_rad();
139        let min_speed: f32 = config.get_min_speed();
140        let speed_span: f32 = config.get_max_speed() - min_speed;
141        let min_life: f32 = config.get_min_life();
142        let life_span: f32 = config.get_max_life() - min_life;
143        let s_size: f32 = config.get_start_size();
144        let e_size: f32 = config.get_end_size();
145        let s_col: Color = config.get_start_color();
146        let e_col: Color = config.get_end_color();
147        let p_drag: f32 = config.get_drag();
148        let ox: f32 = origin.get_x();
149        let oy: f32 = origin.get_y();
150        let mut cur_rng: u64 = *rng_state;
151        let mut live: usize = *active_count;
152        let mut cur_slot: usize = *cursor;
153        let mut min_rem: f32 = *min_remaining_life;
154        for _ in 0..count {
155            let r_ang: f32 = Self::next_unit_f32_from(&mut cur_rng);
156            let r_spd: f32 = Self::next_unit_f32_from(&mut cur_rng);
157            let r_life: f32 = Self::next_unit_f32_from(&mut cur_rng);
158            let angle: f32 = base_angle + (r_ang - 0.5) * spread_rad;
159            let speed: f32 = min_speed + speed_span * r_spd;
160            let life: f32 = (min_life + life_span * r_life).max(0.02);
161            let slot_idx: usize = if live < cap {
162                let s: usize = live;
163                live += 1;
164                s
165            } else {
166                let s: usize = cur_slot % cap;
167                cur_slot = (s + 1) % cap;
168                s
169            };
170            let (sin_a, cos_a): (f32, f32) = angle.sin_cos();
171            pos_x[slot_idx] = ox;
172            pos_y[slot_idx] = oy;
173            vel_x[slot_idx] = cos_a * speed;
174            vel_y[slot_idx] = sin_a * speed;
175            age[slot_idx] = 0.0;
176            lifetime[slot_idx] = life;
177            drag[slot_idx] = p_drag;
178            start_size[slot_idx] = s_size;
179            end_size[slot_idx] = e_size;
180            start_color[slot_idx] = s_col;
181            end_color[slot_idx] = e_col;
182            min_rem = min_rem.min(life);
183        }
184        *rng_state = cur_rng;
185        *active_count = live;
186        *cursor = cur_slot;
187        *min_remaining_life = min_rem;
188    }
189
190    /// Advances all active particles in `[0..active_count)` via auto-vectorized SoA kinematics and swap-removes expired slots.
191    ///
192    /// # Arguments
193    ///
194    /// - `&Self` - Mutable particle system.
195    /// - `f32` - Elapsed timestep in seconds.
196    ///
197    /// # Returns
198    ///
199    /// - `usize` - Number of particles still active after the update.
200    pub fn update(&mut self, dt_secs: f32) -> usize {
201        let Self {
202            pos_x,
203            pos_y,
204            vel_x,
205            vel_y,
206            age,
207            lifetime,
208            drag,
209            start_size,
210            end_size,
211            start_color,
212            end_color,
213            min_remaining_life,
214            gravity,
215            active_count,
216            ..
217        } = self;
218        let mut n: usize = *active_count;
219        if n == 0 {
220            return 0;
221        }
222        let gx_dt: f32 = gravity.get_x() * dt_secs;
223        let gy_dt: f32 = gravity.get_y() * dt_secs;
224        let neg_dt: f32 = -dt_secs;
225        let next_min_bound: f32 = *min_remaining_life - dt_secs;
226        if next_min_bound > 0.0 {
227            let px: &mut [f32] = &mut pos_x[..n];
228            let py: &mut [f32] = &mut pos_y[..n];
229            let vx: &mut [f32] = &mut vel_x[..n];
230            let vy: &mut [f32] = &mut vel_y[..n];
231            let ag: &mut [f32] = &mut age[..n];
232            let dr: &[f32] = &drag[..n];
233            for i in 0..n {
234                ag[i] += dt_secs;
235                let damp: f32 = dr[i].mul_add(neg_dt, 1.0).clamp(0.0, 1.0);
236                let nvx: f32 = (vx[i] + gx_dt) * damp;
237                let nvy: f32 = (vy[i] + gy_dt) * damp;
238                vx[i] = nvx;
239                vy[i] = nvy;
240                px[i] = nvx.mul_add(dt_secs, px[i]);
241                py[i] = nvy.mul_add(dt_secs, py[i]);
242            }
243            *min_remaining_life = next_min_bound;
244            return n;
245        }
246        let mut i: usize = 0;
247        let mut recomputed_min_rem: f32 = f32::INFINITY;
248        while i < n {
249            let next_age: f32 = age[i] + dt_secs;
250            let life: f32 = lifetime[i];
251            if next_age >= life {
252                n -= 1;
253                if i < n {
254                    pos_x[i] = pos_x[n];
255                    pos_y[i] = pos_y[n];
256                    vel_x[i] = vel_x[n];
257                    vel_y[i] = vel_y[n];
258                    age[i] = age[n];
259                    lifetime[i] = lifetime[n];
260                    drag[i] = drag[n];
261                    start_size[i] = start_size[n];
262                    end_size[i] = end_size[n];
263                    start_color[i] = start_color[n];
264                    end_color[i] = end_color[n];
265                }
266                continue;
267            }
268            let damp: f32 = drag[i].mul_add(neg_dt, 1.0).clamp(0.0, 1.0);
269            let nvx: f32 = (vel_x[i] + gx_dt) * damp;
270            let nvy: f32 = (vel_y[i] + gy_dt) * damp;
271            age[i] = next_age;
272            vel_x[i] = nvx;
273            vel_y[i] = nvy;
274            pos_x[i] = nvx.mul_add(dt_secs, pos_x[i]);
275            pos_y[i] = nvy.mul_add(dt_secs, pos_y[i]);
276            recomputed_min_rem = recomputed_min_rem.min(life - next_age);
277            i += 1;
278        }
279        *active_count = n;
280        *min_remaining_life = recomputed_min_rem;
281        n
282    }
283
284    /// Returns a snapshot of the active particle at compacted slot `index`, or `None` if `index >= active_count`.
285    ///
286    /// # Arguments
287    ///
288    /// - `&Self` - Particle system reference.
289    /// - `usize` - Active particle index in `0..active_count`.
290    ///
291    /// # Returns
292    ///
293    /// - `Option<Particle>` - Reconstructed `Particle` record for inspection.
294    #[must_use]
295    pub fn active_particle(&self, index: usize) -> Option<Particle> {
296        let Self {
297            pos_x,
298            pos_y,
299            vel_x,
300            vel_y,
301            age,
302            lifetime,
303            drag,
304            start_size,
305            end_size,
306            start_color,
307            end_color,
308            active_count,
309            ..
310        } = self;
311        if index >= *active_count {
312            return None;
313        }
314        Some(Particle {
315            active: true,
316            position: Point::new(pos_x[index], pos_y[index]),
317            velocity: Point::new(vel_x[index], vel_y[index]),
318            age: age[index],
319            lifetime: lifetime[index],
320            start_size: start_size[index],
321            end_size: end_size[index],
322            start_color: start_color[index],
323            end_color: end_color[index],
324            drag: drag[index],
325        })
326    }
327
328    /// Clears all active particles in O(1) while retaining pre-allocated SoA lane capacities.
329    ///
330    /// # Arguments
331    ///
332    /// - `&Self` - Mutable particle system.
333    pub fn clear(&mut self) {
334        let Self {
335            active_count,
336            cursor,
337            min_remaining_life,
338            ..
339        } = self;
340        *active_count = 0;
341        *cursor = 0;
342        *min_remaining_life = f32::INFINITY;
343    }
344}