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}
42
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub enum EmitterKind {
45    /// Upward-drifting plume that widens with height.
46    Embers,
47}
48
49/// A particle emitter placed in the image.
50#[derive(Clone, Debug, PartialEq)]
51pub struct Emitter {
52    pub kind: EmitterKind,
53    /// Origin in pixels.
54    pub origin_x: f64,
55    pub origin_y: f64,
56    /// Pixels per normalised unit (the image height).
57    pub unit: f64,
58    /// Multiplies every particle's level (dimmer in daylight).
59    pub intensity: f64,
60    pub embers: Vec<Ember>,
61}
62
63/// The ember set for a seed. Independent of size and theme, so the hero time is too.
64pub fn ember_set(seed: u64) -> Vec<Ember> {
65    let mut rng = Rng::stream(seed, "particles");
66    let count = rng.range_u32(44, 72);
67    (0..count)
68        .map(|_| {
69            let life_ms = LIVES_MS[rng.weighted_index(&[1, 2, 3, 2])];
70            Ember {
71                life_ms,
72                phase_ms: rng.below(life_ms),
73                x0: rng.range_f64(-0.010, 0.010),
74                drift: rng.range_f64(-0.075, 0.075),
75                rise: rng.range_f64(0.16, 0.38),
76                wobble: rng.range_f64(0.002, 0.012),
77                wobble_cycles: f64::from(rng.range_u32(1, 3)),
78                wobble_phase: rng.unit(),
79                max_level: f64::from(rng.range_u32(4, 6)),
80                glyph_bias: rng.below(2),
81            }
82        })
83        .collect()
84}
85
86/// Offset of an ember at time `t`, in units of height, plus glyph and level.
87fn ember_state(e: &Ember, t_ms: u64) -> Option<(f64, f64, u8, f64)> {
88    let life = u64::from(e.life_ms);
89    let age = (t_ms + u64::from(e.phase_ms)) % life;
90    let p = age as f64 / life as f64;
91    if p >= 0.96 {
92        return None;
93    }
94    let dy = -e.rise * p;
95    let wob = e.wobble * p * sin(TAU * (e.wobble_cycles * p + e.wobble_phase));
96    let dx = e.x0 + e.drift * pow(p, 1.5) + wob;
97    let level = e.max_level * pow(1.0 - p, 0.8);
98    let stage = ((p * 4.0) as u32 + e.glyph_bias).min(EMBERS.len() as u32 - 1);
99    Some((dx, dy, EMBERS[stage as usize], level))
100}
101
102impl Emitter {
103    /// All live particles at time `t`, in pixels.
104    pub fn sample(&self, t_ms: u64) -> Vec<Particle> {
105        match self.kind {
106            EmitterKind::Embers => self
107                .embers
108                .iter()
109                .filter_map(|e| ember_state(e, t_ms))
110                .filter_map(|(dx, dy, glyph, level)| {
111                    let lv = (level * self.intensity).round();
112                    if lv < 1.0 {
113                        return None;
114                    }
115                    Some(Particle {
116                        x: self.origin_x + dx * self.unit,
117                        y: self.origin_y + dy * self.unit,
118                        glyph,
119                        level: lv.min(6.0) as u8,
120                    })
121                })
122                .collect(),
123        }
124    }
125}
126
127/// Picks the hero time: among candidate frames in the first 10 s, the one whose
128/// particles are most evenly spread (lowest sum of squared bucket counts).
129/// Ties go to the earliest frame. Depends only on the seed.
130pub fn hero_time(embers: &[Ember]) -> u64 {
131    let mut best = (u64::MAX, 0u64);
132    let mut buckets: Vec<(i64, i64)> = Vec::with_capacity(embers.len());
133    for k in 0..HERO_CANDIDATES {
134        let t = k * HERO_STEP_MS;
135        buckets.clear();
136        for e in embers {
137            if let Some((dx, dy, _, _)) = ember_state(e, t) {
138                buckets.push((
139                    (dx / HERO_BUCKET).floor() as i64,
140                    (dy / HERO_BUCKET).floor() as i64,
141                ));
142            }
143        }
144        buckets.sort_unstable();
145        let mut score = 0u64;
146        let mut i = 0;
147        while i < buckets.len() {
148            let mut j = i;
149            while j < buckets.len() && buckets[j] == buckets[i] {
150                j += 1;
151            }
152            let n = (j - i) as u64;
153            score += n * n;
154            i = j;
155        }
156        if score < best.0 {
157            best = (score, t);
158        }
159    }
160    best.1
161}
162
163/// Particle presets attached to an anchor of the character (activity effects).
164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165pub enum Preset {
166    /// Magic: sparks flying out from a point (a wand tip).
167    Sparkles,
168    /// Faint wisps rising from a point (a mug, a kettle).
169    Steam,
170}
171
172impl Preset {
173    pub fn from_id(id: &str) -> Option<Self> {
174        match id {
175            "sparkles" => Some(Preset::Sparkles),
176            "steam" => Some(Preset::Steam),
177            _ => None,
178        }
179    }
180}
181
182/// A preset particle: offset from its anchor in sprite pixels (y down), glyph, level 1-6.
183#[derive(Clone, Copy, Debug, PartialEq)]
184pub struct PresetParticle {
185    pub dx: f64,
186    pub dy: f64,
187    pub glyph: u8,
188    pub level: u8,
189}
190
191/// Particles of a preset at time `t`. Seeded and periodic in [`LOOP_MS`], like the
192/// embers, so GIF loops stay seamless.
193pub fn preset_particles(preset: Preset, seed: u64, t_ms: u64) -> Vec<PresetParticle> {
194    use crate::glyphs::id;
195    let (label, count, lives): (&str, u32, &[u32]) = match preset {
196        Preset::Sparkles => ("fx_sparkles", 9, &[1000, 1500, 2000]),
197        Preset::Steam => ("fx_steam", 5, &[2000, 3000]),
198    };
199    let mut rng = Rng::stream(seed, label);
200    let mut out = Vec::new();
201    for _ in 0..count {
202        let life = *rng.choose(lives);
203        let phase = rng.below(life);
204        let a = rng.unit();
205        let b = rng.unit();
206        let c = rng.unit();
207        let p = ((t_ms + u64::from(phase)) % u64::from(life)) as f64 / f64::from(life);
208        match preset {
209            Preset::Sparkles => {
210                // Out from the tip in a random direction, fading.
211                let ang = TAU * a;
212                let dist = (1.0 + 5.0 * b) * p;
213                let level = (6.0 * (1.0 - p)).round() as u8;
214                if level == 0 {
215                    continue;
216                }
217                let glyph = [id('*'), id('+'), id('\''), id('.')][((p * 4.0) as usize).min(3)];
218                out.push(PresetParticle {
219                    dx: dist * sin(ang + TAU / 4.0),
220                    dy: -dist * sin(ang) - 1.5 * p,
221                    glyph,
222                    level,
223                });
224            }
225            Preset::Steam => {
226                // Rising and swaying, faint.
227                let rise = (8.0 + 6.0 * b) * p;
228                let sway = 1.2 * sin(TAU * (p + c)) * p;
229                let level = (4.0 * (1.0 - p) + 0.5).round() as u8;
230                if level == 0 || p < 0.08 {
231                    continue;
232                }
233                let glyph = [id('\''), id('~'), id('`'), id('.')][((p * 4.0) as usize).min(3)];
234                out.push(PresetParticle {
235                    dx: sway + 0.5 * (a - 0.5),
236                    dy: -rise - 1.0,
237                    glyph,
238                    level,
239                });
240            }
241        }
242    }
243    out
244}
245
246#[cfg(test)]
247mod preset_tests {
248    use super::*;
249
250    #[test]
251    fn presets_loop_and_vary() {
252        for preset in [Preset::Sparkles, Preset::Steam] {
253            assert_eq!(
254                preset_particles(preset, 3, 700),
255                preset_particles(preset, 3, 700 + LOOP_MS)
256            );
257            assert_ne!(
258                preset_particles(preset, 3, 700),
259                preset_particles(preset, 3, 1900)
260            );
261            assert!(
262                !preset_particles(preset, 3, 0).is_empty()
263                    || !preset_particles(preset, 3, 500).is_empty()
264            );
265        }
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272
273    #[test]
274    fn particles_loop_seamlessly() {
275        let e = Emitter {
276            kind: EmitterKind::Embers,
277            origin_x: 100.0,
278            origin_y: 200.0,
279            unit: 1000.0,
280            intensity: 1.0,
281            embers: ember_set(5),
282        };
283        assert_eq!(e.sample(1234), e.sample(1234 + LOOP_MS));
284        assert_eq!(e.sample(0), e.sample(LOOP_MS * 3));
285    }
286
287    #[test]
288    fn hero_time_is_stable_and_in_range() {
289        let set = ember_set(5);
290        let t = hero_time(&set);
291        assert_eq!(t, hero_time(&ember_set(5)));
292        assert!(t < HERO_STEP_MS * HERO_CANDIDATES);
293    }
294}