Skip to main content

clairlune_scene/
particles.rs

1//! Seeded, periodic particles. Each particle's state is a pure function of
2//! `t mod life`, and every life divides the loop length, so animations loop
3//! seamlessly (needed for GIF export, free for live mode).
4
5use crate::glyphs::EMBERS;
6use crate::math::{TAU, pow, sin};
7use crate::rng::Rng;
8
9/// Loop length shared by all periodic elements in M1.
10pub const LOOP_MS: u64 = 6000;
11/// Particle lifetimes. Each divides [`LOOP_MS`].
12const LIVES_MS: [u32; 4] = [1000, 1500, 2000, 3000];
13/// Hero-time search: candidates every 500 ms in the first 10 s.
14const HERO_STEP_MS: u64 = 500;
15const HERO_CANDIDATES: u64 = 20;
16/// Clustering bucket size in units of image height.
17const HERO_BUCKET: f64 = 0.03;
18
19/// One ember, in units of image height, relative to the emitter origin.
20#[derive(Clone, Copy, Debug, PartialEq)]
21pub struct Ember {
22    life_ms: u32,
23    phase_ms: u32,
24    x0: f64,
25    drift: f64,
26    rise: f64,
27    wobble: f64,
28    wobble_cycles: f64,
29    wobble_phase: f64,
30    max_level: f64,
31    glyph_bias: u32,
32}
33
34/// A particle sample in pixels with an ink level `1..=6`.
35#[derive(Clone, Copy, Debug, PartialEq)]
36pub struct Particle {
37    pub x: f64,
38    pub y: f64,
39    pub glyph: u8,
40    pub level: u8,
41    /// Drawn in ink colour (snow, rain, dust) instead of ember colour.
42    pub ink: bool,
43}
44
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum EmitterKind {
47    /// Upward-drifting plume that widens with height.
48    Embers,
49    /// Screen-wide weather particles.
50    Weather(WeatherKind),
51}
52
53/// A particle emitter placed in the image.
54#[derive(Clone, Debug, PartialEq)]
55pub struct Emitter {
56    pub kind: EmitterKind,
57    /// Origin in pixels.
58    pub origin_x: f64,
59    pub origin_y: f64,
60    /// Pixels per normalised unit (the image height).
61    pub unit: f64,
62    /// Multiplies every particle's level (dimmer in daylight).
63    pub intensity: f64,
64    pub embers: Vec<Ember>,
65    /// Weather particles (empty for embers).
66    pub drops: Vec<Drop>,
67    /// Image size in pixels, for screen-space weather.
68    pub size: (f64, f64),
69}
70
71/// The ember set for a seed. Independent of size and theme, so the hero time is too.
72pub fn ember_set(seed: u64) -> Vec<Ember> {
73    let mut rng = Rng::stream(seed, "particles");
74    let count = rng.range_u32(44, 72);
75    (0..count)
76        .map(|_| {
77            let life_ms = LIVES_MS[rng.weighted_index(&[1, 2, 3, 2])];
78            Ember {
79                life_ms,
80                phase_ms: rng.below(life_ms),
81                x0: rng.range_f64(-0.010, 0.010),
82                drift: rng.range_f64(-0.075, 0.075),
83                rise: rng.range_f64(0.16, 0.38),
84                wobble: rng.range_f64(0.002, 0.012),
85                wobble_cycles: f64::from(rng.range_u32(1, 3)),
86                wobble_phase: rng.unit(),
87                max_level: f64::from(rng.range_u32(4, 6)),
88                glyph_bias: rng.below(2),
89            }
90        })
91        .collect()
92}
93
94/// Offset of an ember at time `t`, in units of height, plus glyph and level.
95fn ember_state(e: &Ember, t_ms: u64) -> Option<(f64, f64, u8, f64)> {
96    let life = u64::from(e.life_ms);
97    let age = (t_ms + u64::from(e.phase_ms)) % life;
98    let p = age as f64 / life as f64;
99    if p >= 0.96 {
100        return None;
101    }
102    let dy = -e.rise * p;
103    let wob = e.wobble * p * sin(TAU * (e.wobble_cycles * p + e.wobble_phase));
104    let dx = e.x0 + e.drift * pow(p, 1.5) + wob;
105    let level = e.max_level * pow(1.0 - p, 0.8);
106    let stage = ((p * 4.0) as u32 + e.glyph_bias).min(EMBERS.len() as u32 - 1);
107    Some((dx, dy, EMBERS[stage as usize], level))
108}
109
110impl Emitter {
111    /// All live particles at time `t`, in pixels.
112    pub fn sample(&self, t_ms: u64) -> Vec<Particle> {
113        match self.kind {
114            EmitterKind::Embers => self
115                .embers
116                .iter()
117                .filter_map(|e| ember_state(e, t_ms))
118                .filter_map(|(dx, dy, glyph, level)| {
119                    let lv = (level * self.intensity).round();
120                    if lv < 1.0 {
121                        return None;
122                    }
123                    Some(Particle {
124                        x: self.origin_x + dx * self.unit,
125                        y: self.origin_y + dy * self.unit,
126                        glyph,
127                        level: lv.min(6.0) as u8,
128                        ink: false,
129                    })
130                })
131                .collect(),
132            EmitterKind::Weather(kind) => self
133                .drops
134                .iter()
135                .map(|d| {
136                    let (x, y, glyph, level) = drop_state(kind, d, t_ms);
137                    Particle {
138                        x: x * self.size.0,
139                        y: y * self.size.1,
140                        glyph,
141                        level,
142                        ink: kind.ink(),
143                    }
144                })
145                .collect(),
146        }
147    }
148}
149
150/// Picks the hero time: among candidate frames in the first 10 s, the one whose
151/// particles are most evenly spread (lowest sum of squared bucket counts).
152/// Ties go to the earliest frame. Depends only on the seed.
153pub fn hero_time(embers: &[Ember]) -> u64 {
154    let mut best = (u64::MAX, 0u64);
155    let mut buckets: Vec<(i64, i64)> = Vec::with_capacity(embers.len());
156    for k in 0..HERO_CANDIDATES {
157        let t = k * HERO_STEP_MS;
158        buckets.clear();
159        for e in embers {
160            if let Some((dx, dy, _, _)) = ember_state(e, t) {
161                buckets.push((
162                    (dx / HERO_BUCKET).floor() as i64,
163                    (dy / HERO_BUCKET).floor() as i64,
164                ));
165            }
166        }
167        buckets.sort_unstable();
168        let mut score = 0u64;
169        let mut i = 0;
170        while i < buckets.len() {
171            let mut j = i;
172            while j < buckets.len() && buckets[j] == buckets[i] {
173                j += 1;
174            }
175            let n = (j - i) as u64;
176            score += n * n;
177            i = j;
178        }
179        if score < best.0 {
180            best = (score, t);
181        }
182    }
183    best.1
184}
185
186/// Screen-wide weather (PLAN.md section 4.2, step 6). Every motion completes a
187/// whole number of cycles per [`LOOP_MS`], so weather loops seamlessly.
188#[derive(Clone, Copy, Debug, PartialEq, Eq)]
189pub enum WeatherKind {
190    Snow,
191    Rain,
192    Fireflies,
193    Leaves,
194    Dust,
195}
196
197impl WeatherKind {
198    /// The kind for a recipe's weather id (`none` and `stars` have no particles).
199    pub fn from_id(id: &str) -> Option<Self> {
200        match id {
201            "snow" => Some(WeatherKind::Snow),
202            "rain" => Some(WeatherKind::Rain),
203            "fireflies" => Some(WeatherKind::Fireflies),
204            "leaves" => Some(WeatherKind::Leaves),
205            "dust" => Some(WeatherKind::Dust),
206            _ => None,
207        }
208    }
209
210    /// Ink-coloured (cool) or ember-coloured (warm, glowing).
211    pub fn ink(self) -> bool {
212        matches!(
213            self,
214            WeatherKind::Snow | WeatherKind::Rain | WeatherKind::Dust
215        )
216    }
217}
218
219/// One weather particle, in normalised screen coordinates.
220#[derive(Clone, Copy, Debug, PartialEq)]
221pub struct Drop {
222    x0: f64,
223    y0: f64,
224    /// Whole vertical (or horizontal, for dust) wraps per loop.
225    wraps: u32,
226    sway: f64,
227    cycles: u32,
228    phase: f64,
229    glyph: u8,
230    level: u8,
231}
232
233/// The weather particles for a seed; the count scales with the aspect ratio.
234pub fn weather_set(kind: WeatherKind, seed: u64, aspect: f64) -> Vec<Drop> {
235    use crate::glyphs::id;
236    let mut rng = Rng::stream(seed, "weather_particles");
237    let per = match kind {
238        WeatherKind::Snow => 70.0,
239        WeatherKind::Rain => 110.0,
240        WeatherKind::Fireflies => 14.0,
241        WeatherKind::Leaves => 22.0,
242        WeatherKind::Dust => 40.0,
243    };
244    let count = (per * aspect).round() as u32;
245    (0..count)
246        .map(|_| {
247            let x0 = rng.unit();
248            let y0 = rng.unit();
249            let phase = rng.unit();
250            let big = rng.chance(1, 4);
251            match kind {
252                WeatherKind::Snow => Drop {
253                    x0,
254                    y0,
255                    wraps: rng.range_u32(1, 2),
256                    sway: rng.range_f64(0.003, 0.010),
257                    cycles: rng.range_u32(1, 3),
258                    phase,
259                    glyph: if big {
260                        id('*')
261                    } else {
262                        *rng.choose(&[id('.'), id('\''), id('`')])
263                    },
264                    level: if big { 5 } else { rng.range_u32(2, 4) as u8 },
265                },
266                WeatherKind::Rain => Drop {
267                    x0,
268                    y0,
269                    wraps: rng.range_u32(6, 9),
270                    sway: 0.0,
271                    cycles: 1,
272                    phase,
273                    glyph: *rng.choose(&[id('/'), id('|'), id('\'')]),
274                    level: rng.range_u32(2, 3) as u8,
275                },
276                WeatherKind::Fireflies => Drop {
277                    x0,
278                    // Low in the scene, among the terrain.
279                    y0: 0.45 + 0.5 * y0,
280                    wraps: rng.range_u32(1, 3),
281                    sway: rng.range_f64(0.01, 0.03),
282                    cycles: rng.range_u32(1, 2),
283                    phase,
284                    glyph: id('.'),
285                    level: 0,
286                },
287                WeatherKind::Leaves => Drop {
288                    x0,
289                    y0,
290                    wraps: 1,
291                    sway: rng.range_f64(0.01, 0.03),
292                    cycles: rng.range_u32(2, 3),
293                    phase,
294                    glyph: *rng.choose(&[id(','), id('`'), id('\'')]),
295                    level: rng.range_u32(2, 4) as u8,
296                },
297                WeatherKind::Dust => Drop {
298                    x0,
299                    y0: 0.3 + 0.65 * y0,
300                    wraps: 1,
301                    sway: rng.range_f64(0.002, 0.008),
302                    cycles: rng.range_u32(1, 2),
303                    phase,
304                    glyph: *rng.choose(&[id('.'), id('`')]),
305                    level: rng.range_u32(1, 2) as u8,
306                },
307            }
308        })
309        .collect()
310}
311
312fn frac(x: f64) -> f64 {
313    x - x.floor()
314}
315
316/// Position (normalised), glyph and level of a weather particle at `t`.
317fn drop_state(kind: WeatherKind, d: &Drop, t_ms: u64) -> (f64, f64, u8, u8) {
318    use crate::glyphs::id;
319    let u = (t_ms % LOOP_MS) as f64 / LOOP_MS as f64;
320    let wave = |cycles: u32, phase: f64| sin(TAU * (f64::from(cycles) * u + phase));
321    match kind {
322        WeatherKind::Snow | WeatherKind::Leaves => (
323            frac(d.x0 + d.sway * wave(d.cycles, d.phase)),
324            frac(d.y0 + f64::from(d.wraps) * u),
325            d.glyph,
326            d.level,
327        ),
328        WeatherKind::Rain => (d.x0, frac(d.y0 + f64::from(d.wraps) * u), d.glyph, d.level),
329        WeatherKind::Fireflies => {
330            // Wander on a small closed curve and pulse.
331            let glow = 0.5 + 0.5 * wave(d.wraps, d.phase * 2.0);
332            let level = (1.0 + 4.0 * glow).round() as u8;
333            (
334                frac(d.x0 + d.sway * wave(d.cycles, d.phase)),
335                d.y0 + 0.5 * d.sway * wave(d.cycles + 1, d.phase + 0.25),
336                if level >= 4 { id('*') } else { d.glyph },
337                level,
338            )
339        }
340        WeatherKind::Dust => (
341            frac(d.x0 + f64::from(d.wraps) * u),
342            d.y0 + d.sway * wave(d.cycles, d.phase),
343            d.glyph,
344            d.level,
345        ),
346    }
347}
348
349/// Particle presets attached to an anchor of the character (activity effects).
350#[derive(Clone, Copy, Debug, PartialEq, Eq)]
351pub enum Preset {
352    /// Magic: sparks flying out from a point (a wand tip).
353    Sparkles,
354    /// Faint wisps rising from a point (a mug, a kettle).
355    Steam,
356    /// Music notes floating up and sideways (a guitar).
357    Notes,
358}
359
360impl Preset {
361    pub fn from_id(id: &str) -> Option<Self> {
362        match id {
363            "sparkles" => Some(Preset::Sparkles),
364            "steam" => Some(Preset::Steam),
365            "notes" => Some(Preset::Notes),
366            _ => None,
367        }
368    }
369}
370
371/// A preset particle: offset from its anchor in sprite pixels (y down), glyph, level 1-6.
372#[derive(Clone, Copy, Debug, PartialEq)]
373pub struct PresetParticle {
374    pub dx: f64,
375    pub dy: f64,
376    pub glyph: u8,
377    pub level: u8,
378}
379
380/// Particles of a preset at time `t`. Seeded and periodic in [`LOOP_MS`], like the
381/// embers, so GIF loops stay seamless.
382pub fn preset_particles(preset: Preset, seed: u64, t_ms: u64) -> Vec<PresetParticle> {
383    use crate::glyphs::id;
384    let (label, count, lives): (&str, u32, &[u32]) = match preset {
385        Preset::Sparkles => ("fx_sparkles", 9, &[1000, 1500, 2000]),
386        Preset::Steam => ("fx_steam", 5, &[2000, 3000]),
387        Preset::Notes => ("fx_notes", 4, &[1500, 2000, 3000]),
388    };
389    let mut rng = Rng::stream(seed, label);
390    let mut out = Vec::new();
391    for _ in 0..count {
392        let life = *rng.choose(lives);
393        let phase = rng.below(life);
394        let a = rng.unit();
395        let b = rng.unit();
396        let c = rng.unit();
397        let p = ((t_ms + u64::from(phase)) % u64::from(life)) as f64 / f64::from(life);
398        match preset {
399            Preset::Sparkles => {
400                // Out from the tip in a random direction, fading.
401                let ang = TAU * a;
402                let dist = (1.0 + 5.0 * b) * p;
403                let level = (6.0 * (1.0 - p)).round() as u8;
404                if level == 0 {
405                    continue;
406                }
407                let glyph = [id('*'), id('+'), id('\''), id('.')][((p * 4.0) as usize).min(3)];
408                out.push(PresetParticle {
409                    dx: dist * sin(ang + TAU / 4.0),
410                    dy: -dist * sin(ang) - 1.5 * p,
411                    glyph,
412                    level,
413                });
414            }
415            Preset::Steam => {
416                // Rising and swaying, faint.
417                let rise = (8.0 + 6.0 * b) * p;
418                let sway = 1.2 * sin(TAU * (p + c)) * p;
419                let level = (4.0 * (1.0 - p) + 0.5).round() as u8;
420                if level == 0 || p < 0.08 {
421                    continue;
422                }
423                let glyph = [id('\''), id('~'), id('`'), id('.')][((p * 4.0) as usize).min(3)];
424                out.push(PresetParticle {
425                    dx: sway + 0.5 * (a - 0.5),
426                    dy: -rise - 1.0,
427                    glyph,
428                    level,
429                });
430            }
431            Preset::Notes => {
432                // Up and out to one side, swaying, fading.
433                let side = if a < 0.5 { -1.0 } else { 1.0 };
434                let rise = (6.0 + 5.0 * b) * p;
435                let level = (5.0 * (1.0 - p) + 0.5).round() as u8;
436                if level == 0 {
437                    continue;
438                }
439                out.push(PresetParticle {
440                    dx: side * (1.0 + 3.0 * p) + 0.8 * sin(TAU * (2.0 * p + c)),
441                    dy: -rise - 1.0,
442                    glyph: crate::glyphs::NOTES[(b * 2.0) as usize % 2],
443                    level,
444                });
445            }
446        }
447    }
448    out
449}
450
451#[cfg(test)]
452mod weather_tests {
453    use super::*;
454
455    #[test]
456    fn weather_loops_and_moves() {
457        for kind in [
458            WeatherKind::Snow,
459            WeatherKind::Rain,
460            WeatherKind::Fireflies,
461            WeatherKind::Leaves,
462            WeatherKind::Dust,
463        ] {
464            let e = Emitter {
465                kind: EmitterKind::Weather(kind),
466                origin_x: 0.0,
467                origin_y: 0.0,
468                unit: 1.0,
469                intensity: 1.0,
470                embers: Vec::new(),
471                drops: weather_set(kind, 9, 16.0 / 9.0),
472                size: (1920.0, 1080.0),
473            };
474            assert!(!e.drops.is_empty());
475            assert_eq!(e.sample(1234), e.sample(1234 + LOOP_MS), "{kind:?}");
476            assert_ne!(e.sample(0), e.sample(700), "{kind:?} should move");
477        }
478    }
479}
480
481#[cfg(test)]
482mod preset_tests {
483    use super::*;
484
485    #[test]
486    fn presets_loop_and_vary() {
487        for preset in [Preset::Sparkles, Preset::Steam, Preset::Notes] {
488            assert_eq!(
489                preset_particles(preset, 3, 700),
490                preset_particles(preset, 3, 700 + LOOP_MS)
491            );
492            assert_ne!(
493                preset_particles(preset, 3, 700),
494                preset_particles(preset, 3, 1900)
495            );
496            assert!(
497                !preset_particles(preset, 3, 0).is_empty()
498                    || !preset_particles(preset, 3, 500).is_empty()
499            );
500        }
501    }
502}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507
508    #[test]
509    fn particles_loop_seamlessly() {
510        let e = Emitter {
511            kind: EmitterKind::Embers,
512            origin_x: 100.0,
513            origin_y: 200.0,
514            unit: 1000.0,
515            intensity: 1.0,
516            embers: ember_set(5),
517            drops: Vec::new(),
518            size: (0.0, 0.0),
519        };
520        assert_eq!(e.sample(1234), e.sample(1234 + LOOP_MS));
521        assert_eq!(e.sample(0), e.sample(LOOP_MS * 3));
522    }
523
524    #[test]
525    fn hero_time_is_stable_and_in_range() {
526        let set = ember_set(5);
527        let t = hero_time(&set);
528        assert_eq!(t, hero_time(&ember_set(5)));
529        assert!(t < HERO_STEP_MS * HERO_CANDIDATES);
530    }
531}