Skip to main content

euv_engine/particle/
impl.rs

1use super::*;
2
3/// Implements deterministic pseudo-random number generation for `ParticleRng`.
4impl ParticleRng {
5    /// Creates a generator from the given seed. A zero seed is replaced with
6    /// the default seed, since xorshift degenerates at zero.
7    ///
8    /// # Arguments
9    ///
10    /// - `u64` - The seed value.
11    ///
12    /// # Returns
13    ///
14    /// - `ParticleRng` - The seeded generator.
15    pub fn with_seed(seed: u64) -> ParticleRng {
16        if seed == 0 {
17            ParticleRng::new(PARTICLE_DEFAULT_RNG_SEED)
18        } else {
19            ParticleRng::new(seed)
20        }
21    }
22
23    /// Advances the generator and returns the next 64-bit value.
24    ///
25    /// # Returns
26    ///
27    /// - `u64` - The next pseudo-random value.
28    pub fn next_u64(&mut self) -> u64 {
29        let mut state: u64 = self.get_state();
30        state ^= state >> 12;
31        state ^= state << 25;
32        state ^= state >> 27;
33        self.set_state(state);
34        state.wrapping_mul(0x2545_F491_4F6C_DD1D)
35    }
36
37    /// Returns the next pseudo-random value uniformly distributed in [0.0, 1.0).
38    ///
39    /// # Returns
40    ///
41    /// - `f64` - The next value in the unit interval.
42    pub fn next_f64(&mut self) -> f64 {
43        (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
44    }
45
46    /// Returns the next pseudo-random value uniformly distributed in [min, max).
47    ///
48    /// # Arguments
49    ///
50    /// - `f64` - The inclusive lower bound.
51    /// - `f64` - The exclusive upper bound.
52    ///
53    /// # Returns
54    ///
55    /// - `f64` - The next value in the given range.
56    pub fn range(&mut self, min: f64, max: f64) -> f64 {
57        min + (max - min) * self.next_f64()
58    }
59}
60
61/// Implements `Default` for `ParticleRng` using the default seed.
62impl Default for ParticleRng {
63    /// Constructs a default [`ParticleRng`] value.
64    ///
65    /// # Returns
66    ///
67    /// - `ParticleRng` - A default-constructed instance with the documented initial state.
68    fn default() -> ParticleRng {
69        ParticleRng::with_seed(PARTICLE_DEFAULT_RNG_SEED)
70    }
71}
72
73/// Implements `Default` for `ParticleConfig` with sensible engine defaults.
74impl Default for ParticleConfig {
75    /// Constructs a default [`ParticleConfig`] value.
76    ///
77    /// # Returns
78    ///
79    /// - `ParticleConfig` - A default-constructed instance with the documented initial state.
80    fn default() -> ParticleConfig {
81        ParticleConfig {
82            emission_rate: PARTICLE_DEFAULT_EMISSION_RATE,
83            max_particles: PARTICLE_DEFAULT_MAX_COUNT,
84            lifetime_min: PARTICLE_DEFAULT_LIFETIME_MIN,
85            lifetime_max: PARTICLE_DEFAULT_LIFETIME_MAX,
86            speed_min: PARTICLE_DEFAULT_SPEED_MIN,
87            speed_max: PARTICLE_DEFAULT_SPEED_MAX,
88            angle: PARTICLE_DEFAULT_ANGLE,
89            spread: PARTICLE_DEFAULT_SPREAD,
90            gravity: Vector2D::zero(),
91            color_start: Color::white(),
92            color_end: Color::transparent(),
93            size_start: PARTICLE_DEFAULT_SIZE_START,
94            size_end: PARTICLE_DEFAULT_SIZE_END,
95        }
96    }
97}
98
99/// Implements creation, simulation, and rendering for `ParticleEmitter`.
100impl ParticleEmitter {
101    /// Creates an active emitter at the given position with the given config.
102    ///
103    /// # Arguments
104    ///
105    /// - `Vector2D` - The world-space emission point.
106    /// - `ParticleConfig` - The emitter configuration.
107    ///
108    /// # Returns
109    ///
110    /// - `ParticleEmitter` - The new emitter.
111    pub fn create(position: Vector2D, config: ParticleConfig) -> ParticleEmitter {
112        let mut emitter: ParticleEmitter = ParticleEmitter::new(position, config);
113        emitter.set_active(true);
114        emitter
115    }
116
117    /// Creates an active emitter at the given position using the default
118    /// configuration.
119    ///
120    /// # Arguments
121    ///
122    /// - `Vector2D` - The world-space emission point.
123    ///
124    /// # Returns
125    ///
126    /// - `ParticleEmitter` - The new emitter.
127    pub fn with_defaults(position: Vector2D) -> ParticleEmitter {
128        ParticleEmitter::create(position, ParticleConfig::default())
129    }
130
131    /// Advances the emitter by the given delta time: spawns new particles
132    /// from the emission budget while active, integrates motion and gravity,
133    /// and removes expired particles.
134    ///
135    /// Integration and expiry share a single sweep over the live particles.
136    /// A read cursor integrates each particle and a write cursor compacts the
137    /// survivors downward, so the whole update costs one pass instead of the
138    /// integrate pass plus a separate `retain` pass. Survivors keep their
139    /// relative order: a dead slot is only ever refilled by swapping a live
140    /// particle into it, and the element that gets displaced lands past the
141    /// final truncation point. The compaction also moves no memory when
142    /// nothing expired, where `retain` still walks the whole vector.
143    ///
144    /// # Arguments
145    ///
146    /// - `f64` - The time elapsed since the last update, in seconds.
147    pub fn update(&mut self, delta_time: f64) {
148        let delta_time: f64 = delta_time.max(0.0);
149        let config: ParticleConfig = self.get_config();
150        if self.get_active() {
151            *self.get_mut_emit_accumulator() += config.get_emission_rate() * delta_time;
152            let mut spawn_count: usize = self.get_emit_accumulator() as usize;
153            let capacity: usize = config
154                .get_max_particles()
155                .saturating_sub(self.get_mut_particles().len());
156            spawn_count = spawn_count.min(capacity);
157            *self.get_mut_emit_accumulator() -= spawn_count as f64;
158            for _ in 0..spawn_count {
159                self.spawn_particle();
160            }
161        }
162        let gravity_step: Vector2D = config.get_gravity().scaled(delta_time);
163        let particles: &mut Vec<Particle> = self.get_mut_particles();
164        let mut survivors: usize = 0;
165        for index in 0..particles.len() {
166            let expired: bool = {
167                let particle: &mut Particle = &mut particles[index];
168                *particle.get_mut_velocity() += gravity_step;
169                let velocity: Vector2D = particle.get_velocity();
170                *particle.get_mut_position() += velocity.scaled(delta_time);
171                *particle.get_mut_age() += delta_time;
172                particle.get_age() >= particle.get_lifetime()
173            };
174            if !expired {
175                if survivors != index {
176                    particles.swap(survivors, index);
177                }
178                survivors += 1;
179            }
180        }
181        particles.truncate(survivors);
182    }
183
184    /// Spawns the given number of particles immediately, regardless of the
185    /// active flag, clamped to the remaining particle capacity.
186    ///
187    /// # Arguments
188    ///
189    /// - `usize` - The number of particles to spawn.
190    pub fn burst(&mut self, count: usize) {
191        let capacity: usize = self
192            .get_config()
193            .get_max_particles()
194            .saturating_sub(self.get_particles().len());
195        for _ in 0..count.min(capacity) {
196            self.spawn_particle();
197        }
198    }
199
200    /// Records all live particles into the given draw list as filled circles.
201    ///
202    /// Each particle's color and radius are interpolated between the
203    /// configured start and end values by its normalized age, and the
204    /// color is then snapped to the nearest entry in `PARTICLE_PALETTE`
205    /// via `quantize`. Quantizing is visually nearly identical for
206    /// gradient particles (32-bucket quantization of a smooth gradient is
207    /// imperceptible at canvas resolution) and dramatically increases
208    /// the number of particles that share the same `DrawCommand::FillCircle::color`
209    /// field, so the DrawList replay loop coalesces `set_fill_style_str`
210    /// calls across the entire batch instead of switching style for every
211    /// particle.
212    ///
213    /// # Arguments
214    ///
215    /// - `&mut DrawList` - The draw list to record commands into.
216    pub fn render(&self, draw_list: &mut DrawList) {
217        let config: ParticleConfig = self.get_config();
218        for particle in self.get_particles().iter() {
219            let t: f64 = if particle.get_lifetime() > 0.0 {
220                (particle.get_age() / particle.get_lifetime()).min(1.0)
221            } else {
222                1.0
223            };
224            let color: Color = config.get_color_start().lerp(config.get_color_end(), t);
225            let radius: f64 = Numeric::lerp(config.get_size_start(), config.get_size_end(), t);
226            if radius <= 0.0 || color.get_alpha() <= 0.0 {
227                continue;
228            }
229            let bucket: u8 = Self::quantize(&color);
230            let quantized_color: Color = PARTICLE_PALETTE[bucket as usize];
231            draw_list.fill_circle(particle.get_position(), radius, quantized_color);
232        }
233    }
234
235    /// Returns the number of currently live particles.
236    ///
237    /// # Returns
238    ///
239    /// - `usize` - The live particle count.
240    pub fn alive_count(&self) -> usize {
241        self.get_particles().len()
242    }
243
244    /// Picks the palette index nearest to the given color by squared
245    /// Euclidean distance in 4-channel RGBA space.
246    ///
247    /// Used by the render path to snap each particle's interpolated color
248    /// to one of `PARTICLE_PALETTE_SIZE` preset colors. Quantizing collapses
249    /// the smooth color gradient produced by `Color::lerp` into a small set
250    /// of buckets, so many particles share the same `DrawCommand::FillCircle::color`
251    /// and the DrawList replay loop can coalesce `set_fill_style_str` calls
252    /// across the entire batch instead of switching style for every particle.
253    ///
254    /// # Arguments
255    ///
256    /// - `&Color` - The particle color to quantize.
257    ///
258    /// # Returns
259    ///
260    /// - `u8` - The index into `PARTICLE_PALETTE` of the nearest entry. The
261    ///   result fits in `u8` because `PARTICLE_PALETTE_SIZE` is 32.
262    pub(crate) fn quantize(color: &Color) -> u8 {
263        let target_red: f64 = color.get_red();
264        let target_green: f64 = color.get_green();
265        let target_blue: f64 = color.get_blue();
266        let target_alpha: f64 = color.get_alpha();
267        let mut best_index: usize = 0;
268        let mut best_distance: f64 = f64::INFINITY;
269        for (index, candidate) in PARTICLE_PALETTE.iter().enumerate() {
270            let delta_red: f64 = candidate.get_red() - target_red;
271            let delta_green: f64 = candidate.get_green() - target_green;
272            let delta_blue: f64 = candidate.get_blue() - target_blue;
273            let delta_alpha: f64 = candidate.get_alpha() - target_alpha;
274            let distance: f64 = delta_red * delta_red
275                + delta_green * delta_green
276                + delta_blue * delta_blue
277                + delta_alpha * delta_alpha;
278            if distance < best_distance {
279                best_distance = distance;
280                best_index = index;
281            }
282        }
283        best_index as u8
284    }
285
286    /// Removes all live particles without changing the active flag.
287    pub fn clear(&mut self) {
288        self.get_mut_particles().clear();
289        self.set_emit_accumulator(0.0);
290    }
291
292    /// Spawns a single particle with randomized direction, speed, and
293    /// lifetime sampled from the configuration ranges.
294    fn spawn_particle(&mut self) {
295        let config: ParticleConfig = self.get_config();
296        let half_spread: f64 = config.get_spread() / 2.0;
297        let angle: f64 = config.get_angle() + self.get_mut_rng().range(-half_spread, half_spread);
298        let speed: f64 = self
299            .get_mut_rng()
300            .range(config.get_speed_min(), config.get_speed_max());
301        let lifetime: f64 = self
302            .get_mut_rng()
303            .range(config.get_lifetime_min(), config.get_lifetime_max())
304            .max(EPSILON);
305        let position: Vector2D = self.get_position();
306        let particle: Particle = Particle::new(
307            position,
308            Vector2D::from_angle(angle).scaled(speed),
309            0.0,
310            lifetime,
311        );
312        self.get_mut_particles().push(particle);
313    }
314}
315
316/// Forwards `ParticleEmitter::update` through the [`Updatable`] trait so
317/// emitters can participate in the same generic update loop as entities,
318/// animators, scenes, and physics worlds.
319impl Updatable for ParticleEmitter {
320    /// Advances the simulation by `delta_time` seconds.
321    ///
322    /// # Arguments
323    ///
324    /// - `f64` - Seconds elapsed since the previous update.
325    fn update(&mut self, delta_time: f64) {
326        ParticleEmitter::update(self, delta_time);
327    }
328}