1use crate::archetype::{ArchetypeInfo, SURFACES, TERRAINS, WEATHERS};
9use crate::hash::StableHasher;
10use crate::recipe::TimeOfDay;
11use serde::{Deserialize, Serialize};
12use std::collections::BTreeMap;
13use std::sync::OnceLock;
14
15pub const PROPS: [&str; 25] = [
17 "campfire",
18 "log_seat",
19 "telescope",
20 "lantern",
21 "spellbook",
22 "camp_stove",
23 "coffee_mug",
24 "fallen_hat",
25 "book_closed",
26 "guitar_rest",
27 "bucket",
28 "kite_rest",
29 "stone_pile",
30 "easel",
31 "snowman",
32 "basket",
33 "picnic_basket",
34 "chess_table",
35 "practice_wall",
36 "skis_rest",
37 "flower_pots",
38 "music_stand",
39 "camera_tripod",
40 "sandcastle",
41 "yoga_mat",
42];
43pub const EFFECTS: [&str; 1] = ["embers"];
45pub const PARTICLE_PRESETS: [&str; 6] = [
47 "sparkles",
48 "steam",
49 "notes",
50 "snow_spray",
51 "bubbles",
52 "drops",
53];
54pub const TETHER_PRESETS: [&str; 2] = ["fishing_line", "kite_string"];
57pub const PROJECTILE_PRESETS: [&str; 3] = ["skipping_stone", "snowball", "tennis_ball"];
60pub const FACINGS: [&str; 2] = ["water", "open"];
64pub const ANCHORS: [&str; 6] = ["origin", "feet", "head", "hand_l", "hand_r", "item_tip"];
66pub const ATTACH: [&str; 4] = ["path", "left_of_clawd", "right_of_clawd", "either_side"];
68
69const SOURCES: [(&str, &str); 40] = [
71 (
72 "balloon_journey.toml",
73 include_str!("../activities/balloon_journey.toml"),
74 ),
75 (
76 "balloon_ride.toml",
77 include_str!("../activities/balloon_ride.toml"),
78 ),
79 (
80 "birdwatching.toml",
81 include_str!("../activities/birdwatching.toml"),
82 ),
83 (
84 "broom_flight.toml",
85 include_str!("../activities/broom_flight.toml"),
86 ),
87 (
88 "broom_journey.toml",
89 include_str!("../activities/broom_journey.toml"),
90 ),
91 ("bubbles.toml", include_str!("../activities/bubbles.toml")),
92 (
93 "catch_snowflakes.toml",
94 include_str!("../activities/catch_snowflakes.toml"),
95 ),
96 ("chess.toml", include_str!("../activities/chess.toml")),
97 ("dance.toml", include_str!("../activities/dance.toml")),
98 (
99 "desert_trek.toml",
100 include_str!("../activities/desert_trek.toml"),
101 ),
102 ("fishing.toml", include_str!("../activities/fishing.toml")),
103 ("fly_kite.toml", include_str!("../activities/fly_kite.toml")),
104 (
105 "forest_walk.toml",
106 include_str!("../activities/forest_walk.toml"),
107 ),
108 (
109 "gardening.toml",
110 include_str!("../activities/gardening.toml"),
111 ),
112 (
113 "hike_ridge.toml",
114 include_str!("../activities/hike_ridge.toml"),
115 ),
116 (
117 "hot_cocoa.toml",
118 include_str!("../activities/hot_cocoa.toml"),
119 ),
120 ("journal.toml", include_str!("../activities/journal.toml")),
121 (
122 "make_coffee.toml",
123 include_str!("../activities/make_coffee.toml"),
124 ),
125 ("meditate.toml", include_str!("../activities/meditate.toml")),
126 ("nap.toml", include_str!("../activities/nap.toml")),
127 (
128 "paint_easel.toml",
129 include_str!("../activities/paint_easel.toml"),
130 ),
131 (
132 "photography.toml",
133 include_str!("../activities/photography.toml"),
134 ),
135 ("picnic.toml", include_str!("../activities/picnic.toml")),
136 (
137 "play_flute.toml",
138 include_str!("../activities/play_flute.toml"),
139 ),
140 (
141 "play_guitar.toml",
142 include_str!("../activities/play_guitar.toml"),
143 ),
144 (
145 "read_lantern.toml",
146 include_str!("../activities/read_lantern.toml"),
147 ),
148 ("rowing.toml", include_str!("../activities/rowing.toml")),
149 (
150 "sandcastle.toml",
151 include_str!("../activities/sandcastle.toml"),
152 ),
153 ("ski_tour.toml", include_str!("../activities/ski_tour.toml")),
154 ("skiing.toml", include_str!("../activities/skiing.toml")),
155 (
156 "skip_stones.toml",
157 include_str!("../activities/skip_stones.toml"),
158 ),
159 ("sledding.toml", include_str!("../activities/sledding.toml")),
160 (
161 "snowballs.toml",
162 include_str!("../activities/snowballs.toml"),
163 ),
164 ("stargaze.toml", include_str!("../activities/stargaze.toml")),
165 ("stroll.toml", include_str!("../activities/stroll.toml")),
166 ("sweep.toml", include_str!("../activities/sweep.toml")),
167 ("tennis.toml", include_str!("../activities/tennis.toml")),
168 (
169 "warm_hands.toml",
170 include_str!("../activities/warm_hands.toml"),
171 ),
172 (
173 "wizard_magic.toml",
174 include_str!("../activities/wizard_magic.toml"),
175 ),
176 ("yoga.toml", include_str!("../activities/yoga.toml")),
177];
178
179#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
180#[serde(deny_unknown_fields)]
181pub struct Activity {
182 pub id: String,
183 #[serde(default = "one")]
184 pub weight: f64,
185 pub requires: Requires,
186 pub motion: Motion,
187 #[serde(default)]
189 pub trail: Option<String>,
190 #[serde(default)]
191 pub props: BTreeMap<String, PropDef>,
192 pub animation: AnimationDef,
193 #[serde(default)]
194 pub effects_by_state: BTreeMap<String, Vec<String>>,
195 pub gif: Option<GifDef>,
196 pub unattended: Unattended,
197 #[serde(default)]
198 pub character: CharacterDef,
199 #[serde(default)]
201 pub effects: Vec<EffectDef>,
202}
203
204#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
206#[serde(deny_unknown_fields)]
207pub struct CharacterDef {
208 #[serde(default)]
211 pub headroom: u32,
212}
213
214#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
216#[serde(deny_unknown_fields)]
217pub struct EffectDef {
218 #[serde(rename = "type")]
220 pub kind: String,
221 pub preset: String,
224 pub at: String,
226 #[serde(default)]
228 pub states: Vec<String>,
229}
230
231impl EffectDef {
232 pub fn active_in(&self, state: &str) -> bool {
233 self.states.is_empty() || self.states.iter().any(|s| s == state)
234 }
235}
236
237fn one() -> f64 {
238 1.0
239}
240
241#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
243#[serde(deny_unknown_fields)]
244pub struct Requires {
245 #[serde(default)]
246 pub terrain: Vec<String>,
247 #[serde(default)]
248 pub surface: Vec<String>,
249 pub time_of_day: Vec<TimeOfDay>,
250 #[serde(default)]
251 pub weather: Vec<String>,
252 #[serde(default)]
254 pub sky: bool,
255}
256
257#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
258#[serde(rename_all = "snake_case")]
259pub enum MotionKind {
260 Stationary,
261 Pace,
262 Path,
263 Bob,
264 Fly,
265 Journey,
268}
269
270#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
271#[serde(deny_unknown_fields)]
272pub struct Motion {
273 #[serde(rename = "type")]
274 pub kind: MotionKind,
275 pub path: Option<String>,
276 pub speed_cells_per_s: Option<[f64; 2]>,
277 pub at_path_end: Option<String>,
278 #[serde(default)]
280 pub face: Option<String>,
281 #[serde(default)]
284 pub loop_s: Option<[f64; 2]>,
285 #[serde(default)]
287 pub screen_x: Option<f64>,
288 #[serde(default)]
291 pub altitude: Option<f64>,
292}
293
294#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
295#[serde(deny_unknown_fields)]
296pub struct PropDef {
297 pub attach: String,
298 #[serde(default)]
299 pub effects: Vec<String>,
300 #[serde(default)]
303 pub gap: u32,
304}
305
306#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
307#[serde(deny_unknown_fields)]
308pub struct AnimationDef {
309 pub start: String,
310 pub states: BTreeMap<String, StateDef>,
311}
312
313#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
314#[serde(deny_unknown_fields)]
315pub struct StateDef {
316 #[serde(default, rename = "loop")]
317 pub looping: bool,
318 pub dwell_s: Option<[f64; 2]>,
319 #[serde(default)]
320 pub next: BTreeMap<String, f64>,
321}
322
323#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
324#[serde(deny_unknown_fields)]
325pub struct GifDef {
326 pub loop_script: Vec<String>,
327}
328
329#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
330#[serde(deny_unknown_fields)]
331pub struct Unattended {
332 pub props: Vec<String>,
333}
334
335pub fn int_weight(w: f64) -> u32 {
337 (w * 1000.0).round().max(0.0) as u32
338}
339
340pub const MAX_WEIGHT: f64 = 1000.0;
342
343fn usable_weight(w: f64) -> bool {
346 w <= MAX_WEIGHT && int_weight(w) > 0
347}
348
349fn overlaps(need: &[String], offer: &[&str]) -> bool {
350 need.is_empty() || need.iter().any(|n| offer.contains(&n.as_str()))
351}
352
353impl Activity {
354 pub fn fits(&self, a: &ArchetypeInfo, enabled_weather: &[String]) -> bool {
356 overlaps(&self.requires.terrain, a.terrain)
357 && overlaps(&self.requires.surface, a.surface)
358 && (!self.requires.sky || a.sky)
359 && !self.weathers_in(a, enabled_weather).is_empty()
360 }
361
362 pub fn weathers_in(&self, a: &ArchetypeInfo, enabled: &[String]) -> Vec<&'static str> {
364 a.weather
365 .iter()
366 .copied()
367 .filter(|w| {
368 let fine = |x: &str| self.requires.weather.iter().any(|r| r == x);
369 self.requires.weather.is_empty()
372 || fine(w)
373 || (crate::archetype::LOCAL_WEATHERS.contains(w) && fine("none"))
374 })
375 .filter(|w| enabled.iter().any(|e| e == w))
376 .collect()
377 }
378
379 pub fn times_in(&self, family: &[TimeOfDay]) -> Vec<TimeOfDay> {
381 family
382 .iter()
383 .copied()
384 .filter(|t| self.requires.time_of_day.contains(t))
385 .collect()
386 }
387
388 pub fn successors(&self, state: &str) -> Vec<(&str, u32)> {
390 match self.animation.states.get(state) {
391 Some(s) if !s.next.is_empty() => s
392 .next
393 .iter()
394 .map(|(k, w)| (k.as_str(), int_weight(*w)))
395 .collect(),
396 _ => vec![(self.animation.start.as_str(), 1)],
397 }
398 }
399
400 pub fn playable(&self) -> bool {
404 self.animation.states.values().all(|s| {
405 s.next.is_empty()
406 || s.next
407 .values()
408 .map(|w| u64::from(int_weight(*w)))
409 .sum::<u64>()
410 > 0
411 })
412 }
413
414 pub fn validate(&self) -> Vec<String> {
416 let mut errs = Vec::new();
417 let id = &self.id;
418 let mut err = |m: String| errs.push(format!("{id}: {m}"));
419 if !usable_weight(self.weight) {
420 err(format!("weight must be between 0.001 and {MAX_WEIGHT}"));
421 }
422 for t in &self.requires.terrain {
423 if !TERRAINS.contains(&t.as_str()) {
424 err(format!("unknown terrain `{t}`"));
425 }
426 }
427 for s in &self.requires.surface {
428 if !SURFACES.contains(&s.as_str()) {
429 err(format!("unknown surface `{s}`"));
430 }
431 }
432 for w in &self.requires.weather {
433 if !WEATHERS.contains(&w.as_str()) {
434 err(format!("unknown weather `{w}`"));
435 }
436 }
437 if self.requires.time_of_day.is_empty() {
438 err("requires.time_of_day is empty".into());
439 }
440 let states = &self.animation.states;
441 if !states.contains_key(&self.animation.start) {
442 err(format!(
443 "start state `{}` is not defined",
444 self.animation.start
445 ));
446 }
447 for (name, s) in states {
448 for (to, w) in &s.next {
449 if !states.contains_key(to) {
450 err(format!("state `{name}` goes to undefined state `{to}`"));
451 }
452 if !usable_weight(*w) {
453 err(format!(
454 "state `{name}`: weight for `{to}` must be between 0.001 and {MAX_WEIGHT}"
455 ));
456 }
457 }
458 match (s.looping, s.dwell_s) {
459 (true, None) => err(format!("looping state `{name}` needs dwell_s")),
460 (true, Some([lo, hi])) if !(lo >= 0.2 && hi >= lo) => err(format!(
461 "state `{name}`: dwell_s must be [lo, hi] with 0.2 <= lo <= hi"
462 )),
463 (false, Some(_)) => err(format!(
464 "state `{name}`: dwell_s only applies to looping states"
465 )),
466 _ => {}
467 }
468 }
469 for (state, effects) in &self.effects_by_state {
470 if !states.contains_key(state) {
471 err(format!("effects_by_state names undefined state `{state}`"));
472 }
473 for e in effects {
474 if !EFFECTS.contains(&e.as_str()) {
475 err(format!("unknown effect `{e}`"));
476 }
477 }
478 }
479 for (prop, def) in &self.props {
480 if !PROPS.contains(&prop.as_str()) {
481 err(format!("unknown prop `{prop}`"));
482 }
483 if !ATTACH.contains(&def.attach.as_str()) {
484 err(format!("prop `{prop}`: unknown attach `{}`", def.attach));
485 }
486 for e in &def.effects {
487 if !EFFECTS.contains(&e.as_str()) {
488 err(format!("prop `{prop}`: unknown effect `{e}`"));
489 }
490 }
491 }
492 if let Some(t) = &self.trail
493 && t != "ski_tracks"
494 {
495 err(format!("unknown trail `{t}`"));
496 }
497 if self.motion.kind == MotionKind::Bob && self.requires.terrain != ["shore"] {
498 err("bob motion floats on the shore's water: requires.terrain = [\"shore\"]".into());
499 }
500 if let Some(face) = &self.motion.face {
501 if !FACINGS.contains(&face.as_str()) {
502 err(format!("unknown facing `{face}`"));
503 }
504 if face == "water" && self.requires.terrain != ["shore"] {
505 err("facing the water needs requires.terrain = [\"shore\"]".into());
506 }
507 }
508 for e in &self.effects {
509 match e.kind.as_str() {
510 "particles" if !PARTICLE_PRESETS.contains(&e.preset.as_str()) => {
511 err(format!("unknown particle preset `{}`", e.preset));
512 }
513 "tether" if !TETHER_PRESETS.contains(&e.preset.as_str()) => {
514 err(format!("unknown tether preset `{}`", e.preset));
515 }
516 "projectile" if !PROJECTILE_PRESETS.contains(&e.preset.as_str()) => {
517 err(format!("unknown projectile preset `{}`", e.preset));
518 }
519 "particles" | "tether" | "projectile" => {}
520 other => err(format!(
521 "effect type `{other}` is not implemented (`particles`, `tether`, `projectile`)"
522 )),
523 }
524 if e.preset == "tennis_ball" && !self.props.contains_key("practice_wall") {
525 err("a tennis ball needs a practice wall (props.practice_wall)".into());
526 }
527 if e.preset == "snowball" && !self.props.contains_key("snowman") {
528 err("a snowball needs a snowman to throw at (props.snowman)".into());
529 }
530 if ["fishing_line", "skipping_stone"].contains(&e.preset.as_str())
531 && self.requires.terrain != ["shore"]
532 {
533 err(format!(
534 "`{}` needs requires.terrain = [\"shore\"]",
535 e.preset
536 ));
537 }
538 if !ANCHORS.contains(&e.at.as_str()) {
539 err(format!("effect anchor `{}` is not a known anchor", e.at));
540 }
541 for s in &e.states {
542 if !states.contains_key(s) {
543 err(format!("effect names undefined state `{s}`"));
544 }
545 }
546 }
547 let journey = self.motion.kind == MotionKind::Journey;
548 if journey && !self.props.is_empty() {
549 err("a journey has no props: the ground moves under them".into());
550 }
551 if self.unattended.props.is_empty() && !journey {
553 err("unattended.props is empty: Buddy-off scenes need a focal object".into());
554 }
555 for p in &self.unattended.props {
556 if !PROPS.contains(&p.as_str()) && !EFFECTS.contains(&p.as_str()) {
557 err(format!("unattended: unknown prop or effect `{p}`"));
558 }
559 }
560 if self.motion.altitude.is_some() && self.motion.kind != MotionKind::Journey {
561 err("altitude is for journeys".into());
562 }
563 match self.motion.kind {
564 MotionKind::Stationary => {}
565 MotionKind::Pace | MotionKind::Fly | MotionKind::Bob => {
566 match self.motion.speed_cells_per_s {
567 Some([lo, hi]) if lo > 0.0 && hi >= lo => {}
568 _ => err(format!(
569 "{} motion needs speed_cells_per_s = [lo, hi] with 0 < lo <= hi",
570 format!("{:?}", self.motion.kind).to_lowercase()
571 )),
572 }
573 }
574 MotionKind::Journey => {
575 match self.motion.speed_cells_per_s {
576 Some([lo, hi]) if lo >= 1.0 && hi >= lo && hi <= 20.0 => {}
577 _ => err(
578 "journey motion needs speed_cells_per_s = [lo, hi] within 1..=20 (the ground's pace)"
579 .into(),
580 ),
581 }
582 if let Some(x) = self.motion.screen_x
583 && !(0.15..=0.85).contains(&x)
584 {
585 err("journey screen_x must be within 0.15..=0.85".into());
586 }
587 if let Some(y) = self.motion.altitude
588 && !(0.2..=0.6).contains(&y)
589 {
590 err("journey altitude must be within 0.2..=0.6".into());
591 }
592 }
593 MotionKind::Path => err(format!(
594 "motion `{:?}` is not implemented yet (milestone M4)",
595 self.motion.kind
596 )),
597 }
598 if let Some(gif) = &self.gif {
599 let script = &gif.loop_script;
600 if script.first() != Some(&self.animation.start) {
601 err("gif.loop_script must start with the start state".into());
602 }
603 for pair in script.windows(2).chain(std::iter::once(
604 [
605 script.last().cloned().unwrap_or_default(),
606 script.first().cloned().unwrap_or_default(),
607 ]
608 .as_slice(),
609 )) {
610 let (from, to) = (&pair[0], &pair[1]);
611 if !states.contains_key(from) {
612 err(format!("gif.loop_script names undefined state `{from}`"));
613 } else if !self.successors(from).iter().any(|(s, _)| s == to) {
614 err(format!("gif.loop_script: `{from}` can't go to `{to}`"));
615 }
616 }
617 }
618 errs
619 }
620}
621
622#[derive(Clone, Debug, PartialEq)]
624pub struct Catalog {
625 pub activities: Vec<Activity>,
626 pub data_hash: u64,
628}
629
630impl Catalog {
631 pub fn builtin() -> Self {
634 Self::from_sources(&SOURCES)
635 .unwrap_or_else(|e| panic!("invalid built-in activities:\n{}", e.join("\n")))
636 }
637
638 pub fn from_sources(sources: &[(&str, &str)]) -> Result<Self, Vec<String>> {
640 let mut errors = Vec::new();
641 let mut activities = Vec::new();
642 let mut h = StableHasher::new();
643 for (name, text) in sources {
644 h.write_str(name);
645 write_text(&mut h, text);
646 match toml::from_str::<Activity>(text) {
647 Ok(a) => {
648 if format!("{}.toml", a.id) != *name {
649 errors.push(format!("{name}: id `{}` must match the file name", a.id));
650 }
651 errors.extend(a.validate());
652 activities.push(a);
653 }
654 Err(e) => errors.push(format!("{name}: {e}")),
655 }
656 }
657 activities.sort_by(|a, b| a.id.cmp(&b.id));
658 if errors.is_empty() {
659 Ok(Self {
660 activities,
661 data_hash: h.finish(),
662 })
663 } else {
664 Err(errors)
665 }
666 }
667
668 pub fn get(&self, id: &str) -> Option<&Activity> {
669 self.activities.iter().find(|a| a.id == id)
670 }
671}
672
673fn write_text(h: &mut StableHasher, text: &str) {
676 h.write_str(&text.replace("\r\n", "\n"));
677}
678
679pub fn builtin_catalog() -> &'static Catalog {
681 static CATALOG: OnceLock<Catalog> = OnceLock::new();
682 CATALOG.get_or_init(Catalog::builtin)
683}
684
685pub fn builtin_data_hash() -> u64 {
687 let mut h = StableHasher::new();
688 for (name, text) in SOURCES {
689 h.write_str(name);
690 write_text(&mut h, text);
691 }
692 h.finish()
693}
694
695#[cfg(test)]
696mod tests {
697 use super::*;
698
699 #[test]
700 fn builtin_catalog_is_valid() {
701 let c = Catalog::builtin();
702 assert_eq!(c.activities.len(), SOURCES.len());
703 assert_eq!(c.data_hash, builtin_data_hash());
704 }
705
706 #[test]
707 fn validation_reports_bad_files() {
708 let bad = r#"
709 id = "bad"
710 [requires]
711 terrain = ["lava"]
712 time_of_day = []
713 [motion]
714 type = "pace"
715 [props.anvil]
716 attach = "on_head"
717 [animation]
718 start = "idle"
719 [animation.states.idle]
720 loop = true
721 next = { nowhere = 1.0, idle = 0.0001 }
722 [gif]
723 loop_script = ["sit"]
724 [unattended]
725 props = []
726 "#;
727 let errs = Catalog::from_sources(&[("bad.toml", bad)]).unwrap_err();
728 let all = errs.join("\n");
729 for needle in [
730 "unknown terrain `lava`",
731 "time_of_day is empty",
732 "undefined state `nowhere`",
733 "needs dwell_s",
734 "unknown prop `anvil`",
735 "unknown attach `on_head`",
736 "unattended.props is empty",
737 "pace motion needs speed",
738 "must start with the start state",
739 "weight for `idle` must be between 0.001",
740 ] {
741 assert!(all.contains(needle), "missing `{needle}` in:\n{all}");
742 }
743 }
744
745 #[test]
746 fn sources_are_sorted_by_file_name_like_a_folder_listing() {
747 let names: Vec<&str> = SOURCES.iter().map(|(n, _)| *n).collect();
750 let mut sorted = names.clone();
751 sorted.sort_unstable();
752 assert_eq!(names, sorted);
753 }
754
755 #[test]
756 fn data_hash_ignores_line_endings() {
757 let lf = Catalog::builtin();
758 let crlf: Vec<(String, String)> = SOURCES
759 .iter()
760 .map(|(n, t)| (n.to_string(), t.replace('\n', "\r\n")))
761 .collect();
762 let refs: Vec<(&str, &str)> = crlf.iter().map(|(n, t)| (n.as_str(), t.as_str())).collect();
763 assert_eq!(
764 Catalog::from_sources(&refs).unwrap().data_hash,
765 lf.data_hash
766 );
767 }
768
769 #[test]
770 fn unknown_fields_are_rejected() {
771 let text = "id = \"x\"\ncolour = \"red\"\n";
772 assert!(Catalog::from_sources(&[("x.toml", text)]).is_err());
773 }
774}