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#[cfg(test)]
164mod tests {
165    use super::*;
166
167    #[test]
168    fn particles_loop_seamlessly() {
169        let e = Emitter {
170            kind: EmitterKind::Embers,
171            origin_x: 100.0,
172            origin_y: 200.0,
173            unit: 1000.0,
174            intensity: 1.0,
175            embers: ember_set(5),
176        };
177        assert_eq!(e.sample(1234), e.sample(1234 + LOOP_MS));
178        assert_eq!(e.sample(0), e.sample(LOOP_MS * 3));
179    }
180
181    #[test]
182    fn hero_time_is_stable_and_in_range() {
183        let set = ember_set(5);
184        let t = hero_time(&set);
185        assert_eq!(t, hero_time(&ember_set(5)));
186        assert!(t < HERO_STEP_MS * HERO_CANDIDATES);
187    }
188}