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