1use crate::glyphs::EMBERS;
6use crate::math::{TAU, pow, sin};
7use crate::rng::Rng;
8
9pub const LOOP_MS: u64 = 6000;
11const LIVES_MS: [u32; 4] = [1000, 1500, 2000, 3000];
13
14pub const CALM_PACE: u8 = 1;
20const CALM_LIVES_MS: [u32; 3] = [2000, 3000, 6000];
22const HERO_STEP_MS: u64 = 500;
24const HERO_CANDIDATES: u64 = 20;
25const HERO_BUCKET: f64 = 0.03;
27
28#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq)]
30pub struct Ember {
31 life_ms: u32,
32 phase_ms: u32,
33 x0: f64,
34 drift: f64,
35 rise: f64,
36 wobble: f64,
37 wobble_cycles: f64,
38 wobble_phase: f64,
39 max_level: f64,
40 glyph_bias: u32,
41}
42
43#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq)]
45pub struct Particle {
46 pub x: f64,
47 pub y: f64,
48 pub glyph: u8,
49 pub level: u8,
50 pub ink: bool,
52}
53
54#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
55pub enum EmitterKind {
56 Embers,
58 Weather(WeatherKind),
60}
61
62#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)]
64pub struct Emitter {
65 pub kind: EmitterKind,
66 pub origin_x: f64,
68 pub origin_y: f64,
69 pub unit: f64,
71 pub intensity: f64,
73 pub embers: Vec<Ember>,
74 pub drops: Vec<Drop>,
76 pub size: (f64, f64),
78 #[serde(default)]
80 pub pace: u8,
81}
82
83pub fn ember_set(seed: u64, pace: u8) -> Vec<Ember> {
86 if pace >= CALM_PACE {
87 return calm_ember_set(seed);
88 }
89 let mut rng = Rng::stream(seed, "particles");
90 let count = rng.range_u32(44, 72);
91 (0..count)
92 .map(|_| {
93 let life_ms = LIVES_MS[rng.weighted_index(&[1, 2, 3, 2])];
94 Ember {
95 life_ms,
96 phase_ms: rng.below(life_ms),
97 x0: rng.range_f64(-0.010, 0.010),
98 drift: rng.range_f64(-0.075, 0.075),
99 rise: rng.range_f64(0.16, 0.38),
100 wobble: rng.range_f64(0.002, 0.012),
101 wobble_cycles: f64::from(rng.range_u32(1, 3)),
102 wobble_phase: rng.unit(),
103 max_level: f64::from(rng.range_u32(4, 6)),
104 glyph_bias: rng.below(2),
105 }
106 })
107 .collect()
108}
109
110fn calm_ember_set(seed: u64) -> Vec<Ember> {
113 let mut rng = Rng::stream(seed, "particles_calm");
114 let count = rng.range_u32(36, 56);
115 (0..count)
116 .map(|_| {
117 let life_ms = CALM_LIVES_MS[rng.weighted_index(&[1, 3, 2])];
118 Ember {
119 life_ms,
120 phase_ms: rng.below(life_ms),
121 x0: rng.range_f64(-0.010, 0.010),
122 drift: rng.range_f64(-0.035, 0.035),
123 rise: rng.range_f64(0.07, 0.16),
124 wobble: rng.range_f64(0.002, 0.008),
125 wobble_cycles: f64::from(rng.range_u32(1, 2)),
126 wobble_phase: rng.unit(),
127 max_level: f64::from(rng.range_u32(4, 6)),
128 glyph_bias: rng.below(2),
129 }
130 })
131 .collect()
132}
133
134fn ember_state(e: &Ember, t_ms: u64) -> Option<(f64, f64, u8, f64)> {
136 let life = u64::from(e.life_ms);
137 let age = (t_ms % life + u64::from(e.phase_ms)) % life;
139 let p = age as f64 / life as f64;
140 if p >= 0.96 {
141 return None;
142 }
143 let dy = -e.rise * p;
144 let wob = e.wobble * p * sin(TAU * (e.wobble_cycles * p + e.wobble_phase));
145 let dx = e.x0 + e.drift * pow(p, 1.5) + wob;
146 let level = e.max_level * pow(1.0 - p, 0.8);
147 let stage = ((p * 4.0) as u32 + e.glyph_bias).min(EMBERS.len() as u32 - 1);
148 Some((dx, dy, EMBERS[stage as usize], level))
149}
150
151impl Emitter {
152 pub fn is_sound(&self) -> bool {
155 self.embers.iter().all(|e| e.life_ms > 0)
156 && self
157 .drops
158 .iter()
159 .all(|d| usize::from(d.glyph) < crate::glyphs::GLYPHS.len() && d.cycles < u32::MAX)
160 }
161
162 pub fn sample(&self, t_ms: u64) -> Vec<Particle> {
164 match self.kind {
165 EmitterKind::Embers => self
166 .embers
167 .iter()
168 .filter_map(|e| ember_state(e, t_ms))
169 .filter_map(|(dx, dy, glyph, level)| {
170 let lv = (level * self.intensity).round();
171 if lv < 1.0 {
172 return None;
173 }
174 Some(Particle {
175 x: self.origin_x + dx * self.unit,
176 y: self.origin_y + dy * self.unit,
177 glyph,
178 level: lv.min(6.0) as u8,
179 ink: false,
180 })
181 })
182 .collect(),
183 EmitterKind::Weather(kind) => self
184 .drops
185 .iter()
186 .filter_map(|d| {
187 let (x, y, glyph, level) = if self.pace >= CALM_PACE {
188 calm_drop_state(kind, d, t_ms)?
189 } else {
190 drop_state(kind, d, t_ms)
191 };
192 Some(Particle {
193 x: x * self.size.0,
194 y: y * self.size.1,
195 glyph,
196 level,
197 ink: kind.ink(),
198 })
199 })
200 .collect(),
201 }
202 }
203}
204
205pub fn hero_time(embers: &[Ember]) -> u64 {
209 let mut best = (u64::MAX, 0u64);
210 let mut buckets: Vec<(i64, i64)> = Vec::with_capacity(embers.len());
211 for k in 0..HERO_CANDIDATES {
212 let t = k * HERO_STEP_MS;
213 buckets.clear();
214 for e in embers {
215 if let Some((dx, dy, _, _)) = ember_state(e, t) {
216 buckets.push((
217 (dx / HERO_BUCKET).floor() as i64,
218 (dy / HERO_BUCKET).floor() as i64,
219 ));
220 }
221 }
222 buckets.sort_unstable();
223 let mut score = 0u64;
224 let mut i = 0;
225 while i < buckets.len() {
226 let mut j = i;
227 while j < buckets.len() && buckets[j] == buckets[i] {
228 j += 1;
229 }
230 let n = (j - i) as u64;
231 score += n * n;
232 i = j;
233 }
234 if score < best.0 {
235 best = (score, t);
236 }
237 }
238 best.1
239}
240
241#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
244pub enum WeatherKind {
245 Snow,
246 Rain,
247 Fireflies,
248 Leaves,
249 Dust,
250 Petals,
252 Fog,
254 Blizzard,
256 Ash,
258 Sparkle,
260 Confetti,
262 Birds,
264 Butterflies,
266 Seeds,
268 ShootingStars,
270 Spray,
273 Sandstorm,
275 Tumbleweed,
277 Cinders,
279 SkyLanterns,
281 Fireworks,
283 Spores,
285 Wisps,
287 Bats,
289 Spindrift,
291 Dragonflies,
293}
294
295impl WeatherKind {
296 pub fn from_id(id: &str) -> Option<Self> {
298 match id {
299 "snow" => Some(WeatherKind::Snow),
300 "rain" => Some(WeatherKind::Rain),
301 "fireflies" => Some(WeatherKind::Fireflies),
302 "leaves" => Some(WeatherKind::Leaves),
303 "dust" => Some(WeatherKind::Dust),
304 "petals" => Some(WeatherKind::Petals),
305 "fog" => Some(WeatherKind::Fog),
306 "blizzard" => Some(WeatherKind::Blizzard),
307 "ash" => Some(WeatherKind::Ash),
308 "sparkle" => Some(WeatherKind::Sparkle),
309 "confetti" => Some(WeatherKind::Confetti),
310 "birds" => Some(WeatherKind::Birds),
311 "butterflies" => Some(WeatherKind::Butterflies),
312 "seeds" => Some(WeatherKind::Seeds),
313 "shooting_stars" => Some(WeatherKind::ShootingStars),
314 "spray" => Some(WeatherKind::Spray),
315 "sandstorm" => Some(WeatherKind::Sandstorm),
316 "tumbleweed" => Some(WeatherKind::Tumbleweed),
317 "cinders" => Some(WeatherKind::Cinders),
318 "sky_lanterns" => Some(WeatherKind::SkyLanterns),
319 "fireworks" => Some(WeatherKind::Fireworks),
320 "spores" => Some(WeatherKind::Spores),
321 "wisps" => Some(WeatherKind::Wisps),
322 "bats" => Some(WeatherKind::Bats),
323 "spindrift" => Some(WeatherKind::Spindrift),
324 "dragonflies" => Some(WeatherKind::Dragonflies),
325 _ => None,
326 }
327 }
328
329 pub fn ink(self) -> bool {
331 matches!(
332 self,
333 WeatherKind::Snow
334 | WeatherKind::Rain
335 | WeatherKind::Dust
336 | WeatherKind::Fog
337 | WeatherKind::Blizzard
338 | WeatherKind::Ash
339 | WeatherKind::Sparkle
340 | WeatherKind::Birds
341 | WeatherKind::Seeds
342 | WeatherKind::ShootingStars
343 | WeatherKind::Spray
344 | WeatherKind::Sandstorm
345 | WeatherKind::Tumbleweed
346 | WeatherKind::Bats
347 | WeatherKind::Spindrift
348 )
349 }
350
351 pub fn shows_at(self, tod: crate::recipe::TimeOfDay) -> bool {
354 use crate::recipe::TimeOfDay as T;
355 let dark = matches!(tod, T::Dusk | T::DeepDusk | T::Night);
356 match self {
357 WeatherKind::Fireflies
358 | WeatherKind::ShootingStars
359 | WeatherKind::SkyLanterns
360 | WeatherKind::Fireworks
361 | WeatherKind::Wisps
362 | WeatherKind::Bats => dark,
363 WeatherKind::Birds | WeatherKind::Butterflies | WeatherKind::Dragonflies => !dark,
364 _ => true,
365 }
366 }
367}
368
369#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq)]
371pub struct Drop {
372 pub(crate) x0: f64,
373 pub(crate) y0: f64,
374 pub(crate) wraps: u32,
376 pub(crate) sway: f64,
377 pub(crate) cycles: u32,
378 pub(crate) phase: f64,
379 pub(crate) glyph: u8,
380 pub(crate) level: u8,
381 #[serde(default)]
384 pub(crate) fall: f64,
385}
386
387fn calm_life_ms(kind: WeatherKind) -> u64 {
389 match kind {
390 WeatherKind::Rain => 2000,
391 _ => 6000,
392 }
393}
394
395pub fn weather_set(kind: WeatherKind, seed: u64, aspect: f64, pace: u8) -> Vec<Drop> {
397 if let Some(drops) = crate::local_weather::set(kind, seed, aspect) {
398 return drops;
399 }
400 let mut drops = old_weather_set(kind, seed, aspect);
401 if pace >= CALM_PACE {
402 let mut rng = Rng::stream(seed, "weather_fall");
405 for d in &mut drops {
406 d.fall = match kind {
407 WeatherKind::Snow => rng.range_f64(0.10, 0.22),
408 WeatherKind::Rain => rng.range_f64(0.18, 0.30),
409 WeatherKind::Leaves => rng.range_f64(0.12, 0.24),
410 WeatherKind::Dust => rng.range_f64(0.06, 0.12),
411 WeatherKind::Petals => rng.range_f64(0.14, 0.26),
412 WeatherKind::Fog => rng.range_f64(0.03, 0.07),
413 WeatherKind::Blizzard => rng.range_f64(0.25, 0.4),
414 WeatherKind::Ash => rng.range_f64(0.06, 0.14),
415 WeatherKind::Confetti => rng.range_f64(0.16, 0.28),
416 WeatherKind::Birds => rng.range_f64(0.12, 0.2),
417 WeatherKind::Butterflies => rng.range_f64(0.04, 0.08),
418 WeatherKind::Seeds => rng.range_f64(0.1, 0.2),
419 WeatherKind::ShootingStars => d.fall,
421 WeatherKind::Fireflies | WeatherKind::Sparkle => 0.0,
422 WeatherKind::Spray
423 | WeatherKind::Sandstorm
424 | WeatherKind::Tumbleweed
425 | WeatherKind::Cinders
426 | WeatherKind::SkyLanterns
427 | WeatherKind::Fireworks
428 | WeatherKind::Spores
429 | WeatherKind::Wisps
430 | WeatherKind::Bats
431 | WeatherKind::Spindrift
432 | WeatherKind::Dragonflies => d.fall,
433 };
434 }
435 }
436 if kind == WeatherKind::Birds {
437 flock(&mut drops);
438 }
439 drops
440}
441
442fn flock(drops: &mut [Drop]) {
445 for i in 0..drops.len() {
446 let place = i % 3;
447 if place == 0 {
448 continue;
449 }
450 let lead = drops[i - place];
451 let side = if place == 1 { -1.0 } else { 1.0 };
452 drops[i] = Drop {
453 x0: frac(lead.x0 - 0.012),
454 y0: lead.y0 + side * 0.014,
455 phase: lead.phase,
456 sway: lead.sway,
457 cycles: lead.cycles,
458 wraps: lead.wraps,
459 fall: lead.fall,
460 ..drops[i]
461 };
462 }
463}
464
465fn old_weather_set(kind: WeatherKind, seed: u64, aspect: f64) -> Vec<Drop> {
466 use crate::glyphs::id;
467 if kind == WeatherKind::ShootingStars {
468 return shooting_stars(seed, aspect);
469 }
470 let mut rng = Rng::stream(seed, "weather_particles");
471 let per = match kind {
472 WeatherKind::Snow => 70.0,
473 WeatherKind::Rain => 110.0,
474 WeatherKind::Fireflies => 14.0,
475 WeatherKind::Leaves => 22.0,
476 WeatherKind::Dust => 40.0,
477 WeatherKind::Petals => 34.0,
478 WeatherKind::Fog => 26.0,
479 WeatherKind::Blizzard => 150.0,
480 WeatherKind::Ash => 55.0,
481 WeatherKind::Sparkle => 30.0,
482 WeatherKind::Confetti => 45.0,
483 WeatherKind::Birds => 6.0,
484 WeatherKind::Butterflies => 8.0,
485 WeatherKind::Seeds => 24.0,
486 WeatherKind::ShootingStars => 0.0,
487 WeatherKind::Spray
488 | WeatherKind::Sandstorm
489 | WeatherKind::Tumbleweed
490 | WeatherKind::Cinders
491 | WeatherKind::SkyLanterns
492 | WeatherKind::Fireworks
493 | WeatherKind::Spores
494 | WeatherKind::Wisps
495 | WeatherKind::Bats
496 | WeatherKind::Spindrift
497 | WeatherKind::Dragonflies => {
498 unreachable!("made by local_weather")
499 }
500 };
501 let count = (per * aspect).round() as u32;
502 (0..count)
503 .map(|_| {
504 let x0 = rng.unit();
505 let y0 = rng.unit();
506 let phase = rng.unit();
507 let big = rng.chance(1, 4);
508 match kind {
509 WeatherKind::Snow => Drop {
510 x0,
511 y0,
512 wraps: rng.range_u32(1, 2),
513 sway: rng.range_f64(0.003, 0.010),
514 cycles: rng.range_u32(1, 3),
515 phase,
516 glyph: if big {
517 id('*')
518 } else {
519 *rng.choose(&[id('.'), id('\''), id('`')])
520 },
521 level: if big { 5 } else { rng.range_u32(2, 4) as u8 },
522 fall: 0.0,
523 },
524 WeatherKind::Rain => Drop {
525 x0,
526 y0,
527 wraps: rng.range_u32(6, 9),
528 sway: 0.0,
529 cycles: 1,
530 phase,
531 glyph: *rng.choose(&[id('/'), id('|'), id('\'')]),
532 level: rng.range_u32(2, 3) as u8,
533 fall: 0.0,
534 },
535 WeatherKind::Fireflies => Drop {
536 x0,
537 y0: 0.45 + 0.5 * y0,
539 wraps: rng.range_u32(1, 3),
540 sway: rng.range_f64(0.01, 0.03),
541 cycles: rng.range_u32(1, 2),
542 phase,
543 glyph: id('.'),
544 level: 0,
545 fall: 0.0,
546 },
547 WeatherKind::Leaves => Drop {
548 x0,
549 y0,
550 wraps: 1,
551 sway: rng.range_f64(0.01, 0.03),
552 cycles: rng.range_u32(2, 3),
553 phase,
554 glyph: *rng.choose(&[id(','), id('`'), id('\'')]),
555 level: rng.range_u32(2, 4) as u8,
556 fall: 0.0,
557 },
558 WeatherKind::Dust => Drop {
559 x0,
560 y0: 0.3 + 0.65 * y0,
561 wraps: 1,
562 sway: rng.range_f64(0.002, 0.008),
563 cycles: rng.range_u32(1, 2),
564 phase,
565 glyph: *rng.choose(&[id('.'), id('`')]),
566 level: rng.range_u32(1, 2) as u8,
567 fall: 0.0,
568 },
569 WeatherKind::Petals => Drop {
570 x0,
571 y0,
572 wraps: 1,
573 sway: rng.range_f64(0.01, 0.025),
574 cycles: rng.range_u32(2, 3),
575 phase,
576 glyph: *rng.choose(&[id('\''), id('`'), id(','), id('*')]),
577 level: rng.range_u32(3, 5) as u8,
578 fall: 0.0,
579 },
580 WeatherKind::Fog => Drop {
581 x0,
582 y0: 0.55 + 0.4 * y0,
584 wraps: 1,
585 sway: rng.range_f64(0.002, 0.006),
586 cycles: 1,
587 phase,
588 glyph: *rng.choose(&[id('~'), id('-'), id('='), id('~')]),
589 level: rng.range_u32(1, 2) as u8,
590 fall: 0.0,
591 },
592 WeatherKind::Blizzard => Drop {
593 x0,
594 y0,
595 wraps: rng.range_u32(2, 4),
596 sway: rng.range_f64(0.002, 0.006),
597 cycles: 1,
598 phase,
599 glyph: if big {
600 id('*')
601 } else {
602 *rng.choose(&[id('.'), id('\''), id('-'), id('`')])
603 },
604 level: if big { 5 } else { rng.range_u32(2, 4) as u8 },
605 fall: 0.0,
606 },
607 WeatherKind::Ash => Drop {
608 x0,
609 y0,
610 wraps: 1,
611 sway: rng.range_f64(0.004, 0.012),
612 cycles: rng.range_u32(1, 2),
613 phase,
614 glyph: *rng.choose(&[id('.'), id('`'), id(','), id('.')]),
615 level: rng.range_u32(1, 3) as u8,
616 fall: 0.0,
617 },
618 WeatherKind::Sparkle => Drop {
619 x0,
620 y0: 0.15 + 0.8 * y0,
622 wraps: rng.range_u32(1, 3),
623 sway: 0.0,
624 cycles: 1,
625 phase,
626 glyph: id('.'),
627 level: 0,
628 fall: 0.0,
629 },
630 WeatherKind::Confetti => Drop {
631 x0,
632 y0,
633 wraps: 1,
634 sway: rng.range_f64(0.008, 0.02),
635 cycles: rng.range_u32(2, 4),
636 phase,
637 glyph: *rng.choose(&[id('-'), id('|'), id('/'), id('\\')]),
638 level: rng.range_u32(3, 5) as u8,
639 fall: 0.0,
640 },
641 WeatherKind::Birds => Drop {
642 x0,
643 y0: 0.08 + 0.3 * y0,
645 wraps: 1,
646 sway: rng.range_f64(0.004, 0.012),
647 cycles: rng.range_u32(1, 2),
648 phase,
649 glyph: id('v'),
650 level: rng.range_u32(3, 4) as u8,
651 fall: 0.0,
652 },
653 WeatherKind::Butterflies => Drop {
654 x0,
655 y0: 0.5 + 0.4 * y0,
657 wraps: 1,
658 sway: rng.range_f64(0.006, 0.016),
659 cycles: 1,
660 phase,
661 glyph: id('x'),
662 level: rng.range_u32(4, 5) as u8,
663 fall: 0.0,
664 },
665 WeatherKind::Seeds => Drop {
666 x0,
667 y0,
668 wraps: 1,
669 sway: rng.range_f64(0.006, 0.018),
670 cycles: rng.range_u32(1, 3),
671 phase,
672 glyph: *rng.choose(&[id('*'), id('.'), id('\''), id('*')]),
673 level: rng.range_u32(2, 4) as u8,
674 fall: 0.0,
675 },
676 WeatherKind::ShootingStars => unreachable!("made by `shooting_stars`"),
677 WeatherKind::Spray
678 | WeatherKind::Sandstorm
679 | WeatherKind::Tumbleweed
680 | WeatherKind::Cinders
681 | WeatherKind::SkyLanterns
682 | WeatherKind::Fireworks
683 | WeatherKind::Spores
684 | WeatherKind::Wisps
685 | WeatherKind::Bats
686 | WeatherKind::Spindrift
687 | WeatherKind::Dragonflies => {
688 unreachable!("made by local_weather")
689 }
690 }
691 })
692 .collect()
693}
694
695fn shooting_stars(seed: u64, aspect: f64) -> Vec<Drop> {
699 use crate::glyphs::id;
700 let mut rng = Rng::stream(seed, "shooting_stars");
701 let count = (1.1 * aspect).round().max(1.0) as u32;
702 let mut drops = Vec::new();
703 for _ in 0..count {
704 let right = rng.chance(1, 2);
705 let across = rng.range_f64(0.14, 0.24) * if right { 1.0 } else { -1.0 };
706 let x0 = if right {
707 rng.range_f64(0.05, 0.7)
708 } else {
709 rng.range_f64(0.3, 0.95)
710 };
711 let y0 = rng.range_f64(0.04, 0.3);
712 let fall = rng.range_f64(0.08, 0.14);
713 let phase = rng.unit();
714 let tail = if right { id('\\') } else { id('/') };
715 for i in 0..4u32 {
716 drops.push(Drop {
717 x0,
718 y0,
719 wraps: 1,
720 sway: across,
721 cycles: i,
722 phase,
723 glyph: if i == 0 { id('*') } else { tail },
724 level: 5 - i.min(3) as u8,
725 fall,
726 });
727 }
728 }
729 drops
730}
731
732fn streak(d: &Drop, p: f64) -> Option<(f64, f64, u8, u8)> {
735 const SHOWS: f64 = 0.1;
736 if p >= SHOWS {
737 return None;
738 }
739 let s = p / SHOWS - 0.06 * f64::from(d.cycles);
741 if s < 0.0 {
742 return None;
743 }
744 let glow = (s * 4.0).min((1.0 - s) * 3.0).clamp(0.0, 1.0);
746 let level = (f64::from(d.level) * glow).round() as u8;
747 (level > 0).then(|| (frac(d.x0 + d.sway * s), d.y0 + d.fall * s, d.glyph, level))
748}
749
750fn frac(x: f64) -> f64 {
751 x - x.floor()
752}
753
754fn drop_state(kind: WeatherKind, d: &Drop, t_ms: u64) -> (f64, f64, u8, u8) {
756 use crate::glyphs::id;
757 let u = (t_ms % LOOP_MS) as f64 / LOOP_MS as f64;
758 let wave = |cycles: u32, phase: f64| sin(TAU * (f64::from(cycles) * u + phase));
759 match kind {
760 WeatherKind::Snow | WeatherKind::Leaves => (
761 frac(d.x0 + d.sway * wave(d.cycles, d.phase)),
762 frac(d.y0 + f64::from(d.wraps) * u),
763 d.glyph,
764 d.level,
765 ),
766 WeatherKind::Rain => (d.x0, frac(d.y0 + f64::from(d.wraps) * u), d.glyph, d.level),
767 WeatherKind::Fireflies => {
768 let glow = 0.5 + 0.5 * wave(d.wraps, d.phase * 2.0);
770 let level = (1.0 + 4.0 * glow).round() as u8;
771 (
772 frac(d.x0 + d.sway * wave(d.cycles, d.phase)),
773 d.y0 + 0.5 * d.sway * wave(d.cycles + 1, d.phase + 0.25),
774 if level >= 4 { id('*') } else { d.glyph },
775 level,
776 )
777 }
778 WeatherKind::Dust | WeatherKind::Fog => (
779 frac(d.x0 + f64::from(d.wraps) * u),
780 d.y0 + d.sway * wave(d.cycles, d.phase),
781 d.glyph,
782 d.level,
783 ),
784 WeatherKind::Petals | WeatherKind::Ash | WeatherKind::Confetti => (
785 frac(d.x0 + 0.3 * u + d.sway * wave(d.cycles, d.phase)),
786 frac(d.y0 + f64::from(d.wraps) * u),
787 d.glyph,
788 d.level,
789 ),
790 WeatherKind::Blizzard => (
791 frac(d.x0 + 0.8 * f64::from(d.wraps) * u),
792 frac(d.y0 + f64::from(d.wraps) * u),
793 d.glyph,
794 d.level,
795 ),
796 WeatherKind::Birds => {
797 let flap = sin(TAU * (24.0 * u + d.phase)) > 0.2;
799 (
800 frac(d.x0 + f64::from(d.wraps) * u),
801 d.y0 + d.sway * wave(d.cycles, d.phase),
802 if flap { id('v') } else { id('-') },
803 d.level,
804 )
805 }
806 WeatherKind::Butterflies => {
807 let open = sin(TAU * (60.0 * u + d.phase)) > 0.0;
809 (
810 frac(d.x0 + 0.3 * u + d.sway * wave(d.cycles, d.phase)),
811 d.y0 + 0.5 * d.sway * wave(d.cycles + 2, d.phase + 0.25),
812 if open { id('x') } else { id('+') },
813 d.level,
814 )
815 }
816 WeatherKind::Seeds => (
817 frac(d.x0 + 0.3 * u + d.sway * wave(d.cycles, d.phase)),
818 frac(d.y0 - f64::from(d.wraps) * u * 0.5 + 1.0),
819 d.glyph,
820 d.level,
821 ),
822 WeatherKind::ShootingStars => {
823 let p = frac(u * f64::from(d.wraps) + d.phase);
824 streak(d, p).unwrap_or((d.x0, d.y0, d.glyph, 0))
825 }
826 WeatherKind::Spray
827 | WeatherKind::Sandstorm
828 | WeatherKind::Tumbleweed
829 | WeatherKind::Cinders
830 | WeatherKind::SkyLanterns
831 | WeatherKind::Fireworks
832 | WeatherKind::Spores
833 | WeatherKind::Wisps
834 | WeatherKind::Bats
835 | WeatherKind::Spindrift
836 | WeatherKind::Dragonflies => crate::local_weather::state(kind, d, t_ms)
837 .flatten()
838 .unwrap_or((d.x0, d.y0, d.glyph, 0)),
839 WeatherKind::Sparkle => {
840 let glint = sin(TAU * (f64::from(d.wraps) * u + d.phase)).max(0.0);
842 let glint = glint * glint * glint * glint;
843 let level = (5.0 * glint).round() as u8;
844 let glyph = match level {
845 5 => id('*'),
846 3 | 4 => id('+'),
847 _ => d.glyph,
848 };
849 (d.x0, d.y0, glyph, level)
850 }
851 }
852}
853
854fn calm_drop_state(kind: WeatherKind, d: &Drop, t_ms: u64) -> Option<(f64, f64, u8, u8)> {
858 if let Some(s) = crate::local_weather::state(kind, d, t_ms) {
859 return s;
860 }
861 if matches!(kind, WeatherKind::Fireflies | WeatherKind::Sparkle) {
862 let s = drop_state(kind, d, t_ms);
863 return (s.3 > 0).then_some(s);
864 }
865 let life = calm_life_ms(kind);
866 let p = frac((t_ms % life) as f64 / life as f64 + d.phase);
867 if kind == WeatherKind::ShootingStars {
868 return streak(d, p);
869 }
870 let fade = (p / 0.2).min((1.0 - p) / 0.2).min(1.0);
872 let level = (f64::from(d.level) * fade).round() as u8;
873 if level == 0 {
874 return None;
875 }
876 let sway = d.sway * sin(TAU * (p + d.phase));
878 Some(match kind {
879 WeatherKind::Dust | WeatherKind::Fog => {
880 (frac(d.x0 + d.fall * p), d.y0 + sway, d.glyph, level)
881 }
882 WeatherKind::Rain => (d.x0, frac(d.y0 + d.fall * p), d.glyph, level),
883 WeatherKind::Petals | WeatherKind::Ash => (
886 frac(d.x0 + 0.5 * d.fall * p + sway),
887 frac(d.y0 + d.fall * p),
888 d.glyph,
889 level,
890 ),
891 WeatherKind::Blizzard => (
892 frac(d.x0 + 0.9 * d.fall * p + sway),
893 frac(d.y0 + d.fall * p),
894 d.glyph,
895 level,
896 ),
897 WeatherKind::Confetti => {
898 use crate::glyphs::id;
900 const TURN: [u8; 4] = [id('-'), id('\\'), id('|'), id('/')];
901 let turn = TURN[((p * 8.0 + d.phase * 4.0) as usize) % 4];
902 (frac(d.x0 + sway), frac(d.y0 + d.fall * p), turn, level)
903 }
904 WeatherKind::Birds => {
906 use crate::glyphs::id;
907 let beat = ((p * 40.0 + d.phase * 7.0) as usize) % 6 < 3;
908 let glyph = if beat && ((p * 160.0) as usize).is_multiple_of(2) {
909 id('v')
910 } else {
911 id('-')
912 };
913 (frac(d.x0 + d.fall * p), d.y0 + sway * 0.5, glyph, level)
914 }
915 WeatherKind::Butterflies => {
917 use crate::glyphs::id;
918 let bob = 0.006 * sin(TAU * (3.0 * p + d.phase));
919 let open = ((p * 90.0) as usize).is_multiple_of(2);
920 (
921 frac(d.x0 + d.fall * p + sway),
922 d.y0 + bob,
923 if open { id('x') } else { id('+') },
924 level,
925 )
926 }
927 WeatherKind::Seeds => (
929 frac(d.x0 + 0.8 * d.fall * p + sway),
930 frac(d.y0 - 0.25 * d.fall * p + 1.0),
931 d.glyph,
932 level,
933 ),
934 _ => (frac(d.x0 + sway), frac(d.y0 + d.fall * p), d.glyph, level),
935 })
936}
937
938#[derive(Clone, Copy, Debug, PartialEq, Eq)]
940pub enum Preset {
941 Sparkles,
943 Steam,
945 Notes,
947 SnowSpray,
949 Bubbles,
951 Drops,
953}
954
955impl Preset {
956 pub fn from_id(id: &str) -> Option<Self> {
957 match id {
958 "sparkles" => Some(Preset::Sparkles),
959 "steam" => Some(Preset::Steam),
960 "notes" => Some(Preset::Notes),
961 "snow_spray" => Some(Preset::SnowSpray),
962 "bubbles" => Some(Preset::Bubbles),
963 "drops" => Some(Preset::Drops),
964 _ => None,
965 }
966 }
967}
968
969#[derive(Clone, Copy, Debug, PartialEq)]
971pub struct PresetParticle {
972 pub dx: f64,
973 pub dy: f64,
974 pub glyph: u8,
975 pub level: u8,
976}
977
978pub fn preset_particles(preset: Preset, seed: u64, t_ms: u64, pace: u8) -> Vec<PresetParticle> {
981 use crate::glyphs::id;
982 let calm = pace >= CALM_PACE;
983 let (label, count, lives): (&str, u32, &[u32]) = match (preset, calm) {
984 (Preset::Sparkles, false) => ("fx_sparkles", 9, &[1000, 1500, 2000]),
985 (Preset::Steam, false) => ("fx_steam", 5, &[2000, 3000]),
986 (Preset::Notes, false) => ("fx_notes", 4, &[1500, 2000, 3000]),
987 (Preset::Sparkles, true) => ("fx_sparkles", 9, &[2000, 3000]),
989 (Preset::Steam, true) => ("fx_steam", 5, &[3000, 6000]),
990 (Preset::Notes, true) => ("fx_notes", 4, &[3000, 6000]),
991 (Preset::SnowSpray, false) => ("fx_snow_spray", 8, &[600, 1000]),
993 (Preset::SnowSpray, true) => ("fx_snow_spray", 8, &[1000, 1500]),
994 (Preset::Bubbles, false) => ("fx_bubbles", 7, &[2000, 3000]),
995 (Preset::Bubbles, true) => ("fx_bubbles", 7, &[3000, 6000]),
996 (Preset::Drops, false) => ("fx_drops", 8, &[600, 1000]),
998 (Preset::Drops, true) => ("fx_drops", 8, &[1000, 1500]),
999 };
1000 let mut rng = Rng::stream(seed, label);
1001 let mut out = Vec::new();
1002 for _ in 0..count {
1003 let life = *rng.choose(lives);
1004 let phase = rng.below(life);
1005 let a = rng.unit();
1006 let b = rng.unit();
1007 let c = rng.unit();
1008 let p = ((t_ms + u64::from(phase)) % u64::from(life)) as f64 / f64::from(life);
1009 match preset {
1010 Preset::Sparkles => {
1011 let ang = TAU * a;
1013 let dist = (1.0 + 5.0 * b) * p;
1014 let level = (6.0 * (1.0 - p)).round() as u8;
1015 if level == 0 {
1016 continue;
1017 }
1018 let glyph = [id('*'), id('+'), id('\''), id('.')][((p * 4.0) as usize).min(3)];
1019 out.push(PresetParticle {
1020 dx: dist * sin(ang + TAU / 4.0),
1021 dy: -dist * sin(ang) - 1.5 * p,
1022 glyph,
1023 level,
1024 });
1025 }
1026 Preset::Steam => {
1027 let rise = (8.0 + 6.0 * b) * p;
1029 let sway = 1.2 * sin(TAU * (p + c)) * p;
1030 let level = (4.0 * (1.0 - p) + 0.5).round() as u8;
1031 if level == 0 || p < 0.08 {
1032 continue;
1033 }
1034 let glyph = [id('\''), id('~'), id('`'), id('.')][((p * 4.0) as usize).min(3)];
1035 out.push(PresetParticle {
1036 dx: sway + 0.5 * (a - 0.5),
1037 dy: -rise - 1.0,
1038 glyph,
1039 level,
1040 });
1041 }
1042 Preset::SnowSpray => {
1043 let back = (1.5 + 6.0 * b) * p;
1045 let up = (2.0 + 3.0 * a) * p - 5.0 * p * p;
1046 let level = (5.0 * (1.0 - p) + 0.5).round() as u8;
1047 if level == 0 {
1048 continue;
1049 }
1050 let glyph = [id('*'), id('\''), id('.'), id(',')][((p * 4.0) as usize).min(3)];
1051 out.push(PresetParticle {
1052 dx: -back - 1.0 - c,
1053 dy: -up,
1054 glyph,
1055 level,
1056 });
1057 }
1058 Preset::Bubbles => {
1059 let drift = (3.0 + 7.0 * b) * p;
1062 let rise = (5.0 + 6.0 * a) * p;
1063 let bob = 0.8 * sin(TAU * (1.5 * p + c));
1064 let glyph = if p > 0.92 {
1065 id('*')
1066 } else if p > 0.45 {
1067 id('O')
1068 } else if p > 0.12 {
1069 id('o')
1070 } else {
1071 id('.')
1072 };
1073 out.push(PresetParticle {
1074 dx: 1.0 + drift + bob * 0.5,
1075 dy: -rise - 1.0 + bob,
1076 glyph,
1077 level: if p > 0.92 { 3 } else { 5 },
1078 });
1079 }
1080 Preset::Drops => {
1081 let ahead = (0.5 + 1.5 * b) * p;
1084 let down = (2.0 + 2.0 * a) * p + 8.0 * p * p;
1085 let level = (4.0 * (1.0 - 0.6 * p) + 0.5).round() as u8;
1086 let glyph = [id('\''), id('.'), id(','), id('.')][((p * 4.0) as usize).min(3)];
1087 out.push(PresetParticle {
1088 dx: ahead + 0.6 * (c - 0.5),
1089 dy: down,
1090 glyph,
1091 level,
1092 });
1093 }
1094 Preset::Notes => {
1095 let side = if a < 0.5 { -1.0 } else { 1.0 };
1097 let rise = (6.0 + 5.0 * b) * p;
1098 let level = (5.0 * (1.0 - p) + 0.5).round() as u8;
1099 if level == 0 {
1100 continue;
1101 }
1102 out.push(PresetParticle {
1103 dx: side * (1.0 + 3.0 * p) + 0.8 * sin(TAU * (2.0 * p + c)),
1104 dy: -rise - 1.0,
1105 glyph: crate::glyphs::NOTES[(b * 2.0) as usize % 2],
1106 level,
1107 });
1108 }
1109 }
1110 }
1111 out
1112}
1113
1114#[cfg(test)]
1115mod weather_tests {
1116 use super::*;
1117
1118 const KINDS: [WeatherKind; 15] = [
1119 WeatherKind::Snow,
1120 WeatherKind::Rain,
1121 WeatherKind::Fireflies,
1122 WeatherKind::Leaves,
1123 WeatherKind::Dust,
1124 WeatherKind::Petals,
1125 WeatherKind::Fog,
1126 WeatherKind::Blizzard,
1127 WeatherKind::Ash,
1128 WeatherKind::Sparkle,
1129 WeatherKind::Confetti,
1130 WeatherKind::Birds,
1131 WeatherKind::Butterflies,
1132 WeatherKind::Seeds,
1133 WeatherKind::ShootingStars,
1134 ];
1135
1136 fn emitter(kind: WeatherKind, pace: u8) -> Emitter {
1137 Emitter {
1138 kind: EmitterKind::Weather(kind),
1139 origin_x: 0.0,
1140 origin_y: 0.0,
1141 unit: 1.0,
1142 intensity: 1.0,
1143 embers: Vec::new(),
1144 drops: weather_set(kind, 9, 16.0 / 9.0, pace),
1145 size: (1920.0, 1080.0),
1146 pace,
1147 }
1148 }
1149
1150 #[test]
1151 fn weather_loops_and_moves() {
1152 for pace in [0, CALM_PACE] {
1153 for kind in KINDS {
1154 let e = emitter(kind, pace);
1155 assert!(!e.drops.is_empty());
1156 assert_eq!(
1157 e.sample(1234),
1158 e.sample(1234 + LOOP_MS),
1159 "{kind:?} pace {pace}"
1160 );
1161 if kind == WeatherKind::ShootingStars {
1162 let shown: Vec<_> = (0..60u64)
1165 .map(|k| e.sample(k * 100))
1166 .filter(|s| s.iter().any(|p| p.level > 0))
1167 .collect();
1168 assert!(
1169 shown.len() >= 2 && shown.windows(2).any(|w| w[0] != w[1]),
1170 "{kind:?} pace {pace} should streak"
1171 );
1172 continue;
1173 }
1174 assert_ne!(
1175 e.sample(0),
1176 e.sample(700),
1177 "{kind:?} pace {pace} should move"
1178 );
1179 }
1180 }
1181 }
1182
1183 fn mean_speed(kind: WeatherKind, pace: u8) -> f64 {
1186 let e = emitter(kind, pace);
1187 let (mut sum, mut n) = (0.0, 0usize);
1188 for k in 0..60u64 {
1189 let t = k * 100;
1190 for d in &e.drops {
1191 let at = |t| match pace {
1192 0 => Some(drop_state(kind, d, t)),
1193 _ => calm_drop_state(kind, d, t),
1194 };
1195 if let (Some(a), Some(b)) = (at(t), at(t + 100)) {
1196 let (dx, dy) = ((b.0 - a.0) * 16.0 / 9.0, b.1 - a.1);
1197 let dist = (dx * dx + dy * dy).sqrt();
1198 if dist < 0.3 {
1199 sum += dist * 10.0;
1200 n += 1;
1201 }
1202 }
1203 }
1204 }
1205 sum / n.max(1) as f64
1206 }
1207
1208 #[test]
1209 fn the_calm_pace_is_calm() {
1210 for kind in KINDS {
1211 if kind == WeatherKind::ShootingStars {
1214 continue;
1215 }
1216 let (old, calm) = (mean_speed(kind, 0), mean_speed(kind, CALM_PACE));
1217 let cap = if matches!(kind, WeatherKind::Rain | WeatherKind::Blizzard) {
1219 0.2
1220 } else {
1221 0.06
1222 };
1223 assert!(calm <= cap, "{kind:?}: {calm:.3} screen heights a second");
1224 if !matches!(kind, WeatherKind::Fireflies | WeatherKind::Sparkle) {
1225 assert!(calm < old * 0.6, "{kind:?}: calm {calm:.3} vs {old:.3}");
1226 }
1227 }
1228 }
1229
1230 #[test]
1231 fn the_original_pace_is_unchanged() {
1232 let e = emitter(WeatherKind::Snow, 0);
1234 assert!(e.drops.iter().all(|d| d.fall == 0.0));
1235 let calm = emitter(WeatherKind::Snow, CALM_PACE);
1236 assert_eq!(
1237 e.drops.iter().map(|d| (d.x0, d.y0)).collect::<Vec<_>>(),
1238 calm.drops.iter().map(|d| (d.x0, d.y0)).collect::<Vec<_>>()
1239 );
1240 }
1241}
1242
1243#[cfg(test)]
1244mod preset_tests {
1245 use super::*;
1246
1247 #[test]
1248 fn presets_loop_and_vary() {
1249 for pace in [0, CALM_PACE] {
1250 for preset in [Preset::Sparkles, Preset::Steam, Preset::Notes] {
1251 assert_eq!(
1252 preset_particles(preset, 3, 700, pace),
1253 preset_particles(preset, 3, 700 + LOOP_MS, pace)
1254 );
1255 assert_ne!(
1256 preset_particles(preset, 3, 700, pace),
1257 preset_particles(preset, 3, 1900, pace)
1258 );
1259 assert!(
1260 !preset_particles(preset, 3, 0, pace).is_empty()
1261 || !preset_particles(preset, 3, 500, pace).is_empty()
1262 );
1263 }
1264 }
1265 }
1266}
1267
1268#[cfg(test)]
1269mod tests {
1270 use super::*;
1271
1272 fn embers(pace: u8) -> Emitter {
1273 Emitter {
1274 kind: EmitterKind::Embers,
1275 origin_x: 100.0,
1276 origin_y: 200.0,
1277 unit: 1000.0,
1278 intensity: 1.0,
1279 embers: ember_set(5, pace),
1280 drops: Vec::new(),
1281 size: (0.0, 0.0),
1282 pace,
1283 }
1284 }
1285
1286 #[test]
1287 fn particles_loop_seamlessly() {
1288 for pace in [0, CALM_PACE] {
1289 let e = embers(pace);
1290 assert_eq!(e.sample(1234), e.sample(1234 + LOOP_MS));
1291 assert_eq!(e.sample(0), e.sample(LOOP_MS * 3));
1292 }
1293 }
1294
1295 #[test]
1296 fn calm_embers_float_up_slowly() {
1297 let fastest = |set: &[Ember]| {
1299 set.iter()
1300 .map(|e| e.rise / (f64::from(e.life_ms) / 1000.0))
1301 .fold(0.0, f64::max)
1302 };
1303 let (old, calm) = (fastest(&ember_set(5, 0)), fastest(&ember_set(5, CALM_PACE)));
1304 assert!(calm <= 0.08, "calm embers rise {calm:.3} heights a second");
1305 assert!(
1306 old > 0.2,
1307 "the original pace is kept for older scenes ({old:.3})"
1308 );
1309 }
1310
1311 #[test]
1312 fn hero_time_is_stable_and_in_range() {
1313 for pace in [0, CALM_PACE] {
1314 let set = ember_set(5, pace);
1315 let t = hero_time(&set);
1316 assert_eq!(t, hero_time(&ember_set(5, pace)));
1317 assert!(t < HERO_STEP_MS * HERO_CANDIDATES);
1318 }
1319 }
1320}