Skip to main content

clairlune_scene/
activity.rs

1//! Activities: what the character is doing.
2//!
3//! One TOML file per activity in `crates/scene/activities/`, embedded at compile
4//! time. The engine never hardcodes a specific activity: adding a file (and its
5//! sprites) is how content grows. Maps are `BTreeMap` so iteration order, and
6//! therefore every seeded pick, is deterministic.
7
8use 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
15/// Prop ids the engine can draw.
16pub 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];
43/// Effect ids the engine can draw.
44pub const EFFECTS: [&str; 1] = ["embers"];
45/// Particle presets an `[[effects]]` entry can attach to an anchor.
46pub const PARTICLE_PRESETS: [&str; 6] = [
47    "sparkles",
48    "steam",
49    "notes",
50    "snow_spray",
51    "bubbles",
52    "drops",
53];
54/// Tether presets: a line from an anchor to a moving end (a float on the
55/// water, a kite in the sky).
56pub const TETHER_PRESETS: [&str; 2] = ["fishing_line", "kite_string"];
57/// Projectile presets: something thrown on its own arc, timed from the start
58/// of the effect's state.
59pub const PROJECTILE_PRESETS: [&str; 3] = ["skipping_stone", "snowball", "tennis_ball"];
60/// Which way the character faces, when it matters: `water` (the open water,
61/// on the shore) or `open` (the middle of the screen, where the sky is
62/// widest).
63pub const FACINGS: [&str; 2] = ["water", "open"];
64/// Anchor names the art exports (docs/dev/clawd-style.md).
65pub const ANCHORS: [&str; 6] = ["origin", "feet", "head", "hand_l", "hand_r", "item_tip"];
66/// Generic prop attachment points.
67pub const ATTACH: [&str; 4] = ["path", "left_of_clawd", "right_of_clawd", "either_side"];
68
69/// Embedded activity files, sorted by file name.
70const SOURCES: [(&str, &str); 38] = [
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    (
121        "make_coffee.toml",
122        include_str!("../activities/make_coffee.toml"),
123    ),
124    ("meditate.toml", include_str!("../activities/meditate.toml")),
125    (
126        "paint_easel.toml",
127        include_str!("../activities/paint_easel.toml"),
128    ),
129    (
130        "photography.toml",
131        include_str!("../activities/photography.toml"),
132    ),
133    ("picnic.toml", include_str!("../activities/picnic.toml")),
134    (
135        "play_flute.toml",
136        include_str!("../activities/play_flute.toml"),
137    ),
138    (
139        "play_guitar.toml",
140        include_str!("../activities/play_guitar.toml"),
141    ),
142    (
143        "read_lantern.toml",
144        include_str!("../activities/read_lantern.toml"),
145    ),
146    ("rowing.toml", include_str!("../activities/rowing.toml")),
147    (
148        "sandcastle.toml",
149        include_str!("../activities/sandcastle.toml"),
150    ),
151    ("ski_tour.toml", include_str!("../activities/ski_tour.toml")),
152    ("skiing.toml", include_str!("../activities/skiing.toml")),
153    (
154        "skip_stones.toml",
155        include_str!("../activities/skip_stones.toml"),
156    ),
157    ("sledding.toml", include_str!("../activities/sledding.toml")),
158    (
159        "snowballs.toml",
160        include_str!("../activities/snowballs.toml"),
161    ),
162    ("stargaze.toml", include_str!("../activities/stargaze.toml")),
163    ("stroll.toml", include_str!("../activities/stroll.toml")),
164    ("sweep.toml", include_str!("../activities/sweep.toml")),
165    ("tennis.toml", include_str!("../activities/tennis.toml")),
166    (
167        "warm_hands.toml",
168        include_str!("../activities/warm_hands.toml"),
169    ),
170    (
171        "wizard_magic.toml",
172        include_str!("../activities/wizard_magic.toml"),
173    ),
174    ("yoga.toml", include_str!("../activities/yoga.toml")),
175];
176
177#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
178#[serde(deny_unknown_fields)]
179pub struct Activity {
180    pub id: String,
181    #[serde(default = "one")]
182    pub weight: f64,
183    pub requires: Requires,
184    pub motion: Motion,
185    /// Marks left in the ground along the character's way: `ski_tracks`.
186    #[serde(default)]
187    pub trail: Option<String>,
188    #[serde(default)]
189    pub props: BTreeMap<String, PropDef>,
190    pub animation: AnimationDef,
191    #[serde(default)]
192    pub effects_by_state: BTreeMap<String, Vec<String>>,
193    pub gif: Option<GifDef>,
194    pub unattended: Unattended,
195    #[serde(default)]
196    pub character: CharacterDef,
197    /// Effects attached to the character (docs/dev/activity-system.md section 3).
198    #[serde(default)]
199    pub effects: Vec<EffectDef>,
200}
201
202/// Per-activity character settings.
203#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
204#[serde(deny_unknown_fields)]
205pub struct CharacterDef {
206    /// Extra cleared space above the character's box, in sprite pixels
207    /// (a wizard hat, a raised wand).
208    #[serde(default)]
209    pub headroom: u32,
210}
211
212/// An effect attached to an anchor of the character's current frame.
213#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
214#[serde(deny_unknown_fields)]
215pub struct EffectDef {
216    /// `particles`, `tether` or `projectile`.
217    #[serde(rename = "type")]
218    pub kind: String,
219    /// One of [`PARTICLE_PRESETS`], [`TETHER_PRESETS`] or
220    /// [`PROJECTILE_PRESETS`], by type.
221    pub preset: String,
222    /// Anchor name, e.g. `item_tip`.
223    pub at: String,
224    /// States in which the effect runs; empty means all.
225    #[serde(default)]
226    pub states: Vec<String>,
227}
228
229impl EffectDef {
230    pub fn active_in(&self, state: &str) -> bool {
231        self.states.is_empty() || self.states.iter().any(|s| s == state)
232    }
233}
234
235fn one() -> f64 {
236    1.0
237}
238
239/// Capability requirements. An empty list means "no constraint".
240#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
241#[serde(deny_unknown_fields)]
242pub struct Requires {
243    #[serde(default)]
244    pub terrain: Vec<String>,
245    #[serde(default)]
246    pub surface: Vec<String>,
247    pub time_of_day: Vec<TimeOfDay>,
248    #[serde(default)]
249    pub weather: Vec<String>,
250    /// Needs open sky overhead (stargazing): rules out caves and interiors.
251    #[serde(default)]
252    pub sky: bool,
253}
254
255#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
256#[serde(rename_all = "snake_case")]
257pub enum MotionKind {
258    Stationary,
259    Pace,
260    Path,
261    Bob,
262    Fly,
263    /// The camera travels: the landscape scrolls past in layers while the
264    /// character walks on the nearest (docs/dev/scrolling-scenes.md).
265    Journey,
266}
267
268#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
269#[serde(deny_unknown_fields)]
270pub struct Motion {
271    #[serde(rename = "type")]
272    pub kind: MotionKind,
273    pub path: Option<String>,
274    pub speed_cells_per_s: Option<[f64; 2]>,
275    pub at_path_end: Option<String>,
276    /// One of [`FACINGS`].
277    #[serde(default)]
278    pub face: Option<String>,
279    /// Journeys before 0.12: the loop length range in seconds. Unused now
280    /// (the pace, `speed_cells_per_s`, sets the loop); still read.
281    #[serde(default)]
282    pub loop_s: Option<[f64; 2]>,
283    /// Journeys: where the character walks, as a fraction of the width.
284    #[serde(default)]
285    pub screen_x: Option<f64>,
286    /// Journeys: fly instead of walking, the feet this far down the screen
287    /// (a fraction of the height), the land going by below.
288    #[serde(default)]
289    pub altitude: Option<f64>,
290}
291
292#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
293#[serde(deny_unknown_fields)]
294pub struct PropDef {
295    pub attach: String,
296    #[serde(default)]
297    pub effects: Vec<String>,
298    /// Extra space before the prop, in sprite pixels (a practice wall
299    /// stands back from the player).
300    #[serde(default)]
301    pub gap: u32,
302}
303
304#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
305#[serde(deny_unknown_fields)]
306pub struct AnimationDef {
307    pub start: String,
308    pub states: BTreeMap<String, StateDef>,
309}
310
311#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
312#[serde(deny_unknown_fields)]
313pub struct StateDef {
314    #[serde(default, rename = "loop")]
315    pub looping: bool,
316    pub dwell_s: Option<[f64; 2]>,
317    #[serde(default)]
318    pub next: BTreeMap<String, f64>,
319}
320
321#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
322#[serde(deny_unknown_fields)]
323pub struct GifDef {
324    pub loop_script: Vec<String>,
325}
326
327#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
328#[serde(deny_unknown_fields)]
329pub struct Unattended {
330    pub props: Vec<String>,
331}
332
333/// Integer weight for seeded picks (weights in files are decimals).
334pub fn int_weight(w: f64) -> u32 {
335    (w * 1000.0).round().max(0.0) as u32
336}
337
338/// The largest weight a file may give (picks multiply weights).
339pub const MAX_WEIGHT: f64 = 1000.0;
340
341/// A weight from a file that picks can use: at least 0.001 (it rounds to a
342/// whole thousandth) and at most `MAX_WEIGHT`.
343fn usable_weight(w: f64) -> bool {
344    w <= MAX_WEIGHT && int_weight(w) > 0
345}
346
347fn overlaps(need: &[String], offer: &[&str]) -> bool {
348    need.is_empty() || need.iter().any(|n| offer.contains(&n.as_str()))
349}
350
351impl Activity {
352    /// Whether this activity can take place in an archetype, given enabled weather.
353    pub fn fits(&self, a: &ArchetypeInfo, enabled_weather: &[String]) -> bool {
354        overlaps(&self.requires.terrain, a.terrain)
355            && overlaps(&self.requires.surface, a.surface)
356            && (!self.requires.sky || a.sky)
357            && !self.weathers_in(a, enabled_weather).is_empty()
358    }
359
360    /// Weather that the activity, the archetype and the user all allow.
361    pub fn weathers_in(&self, a: &ArchetypeInfo, enabled: &[String]) -> Vec<&'static str> {
362        a.weather
363            .iter()
364            .copied()
365            .filter(|w| {
366                let fine = |x: &str| self.requires.weather.iter().any(|r| r == x);
367                // A landscape's own weather comes with any activity that is
368                // fine with none.
369                self.requires.weather.is_empty()
370                    || fine(w)
371                    || (crate::archetype::LOCAL_WEATHERS.contains(w) && fine("none"))
372            })
373            .filter(|w| enabled.iter().any(|e| e == w))
374            .collect()
375    }
376
377    /// Allowed times of day for one theme family, in canonical order.
378    pub fn times_in(&self, family: &[TimeOfDay]) -> Vec<TimeOfDay> {
379        family
380            .iter()
381            .copied()
382            .filter(|t| self.requires.time_of_day.contains(t))
383            .collect()
384    }
385
386    /// The state that follows `state` (when no `next`, back to `start`).
387    pub fn successors(&self, state: &str) -> Vec<(&str, u32)> {
388        match self.animation.states.get(state) {
389            Some(s) if !s.next.is_empty() => s
390                .next
391                .iter()
392                .map(|(k, w)| (k.as_str(), int_weight(*w)))
393                .collect(),
394            _ => vec![(self.animation.start.as_str(), 1)],
395        }
396    }
397
398    /// Whether the state machine can run: every state that goes on has a
399    /// way to go. Looser than [`validate`](Self::validate), which also holds
400    /// art and names to today's rules, for activities saved in older scenes.
401    pub fn playable(&self) -> bool {
402        self.animation.states.values().all(|s| {
403            s.next.is_empty()
404                || s.next
405                    .values()
406                    .map(|w| u64::from(int_weight(*w)))
407                    .sum::<u64>()
408                    > 0
409        })
410    }
411
412    /// Every activity rule that can be checked without sprites.
413    pub fn validate(&self) -> Vec<String> {
414        let mut errs = Vec::new();
415        let id = &self.id;
416        let mut err = |m: String| errs.push(format!("{id}: {m}"));
417        if !usable_weight(self.weight) {
418            err(format!("weight must be between 0.001 and {MAX_WEIGHT}"));
419        }
420        for t in &self.requires.terrain {
421            if !TERRAINS.contains(&t.as_str()) {
422                err(format!("unknown terrain `{t}`"));
423            }
424        }
425        for s in &self.requires.surface {
426            if !SURFACES.contains(&s.as_str()) {
427                err(format!("unknown surface `{s}`"));
428            }
429        }
430        for w in &self.requires.weather {
431            if !WEATHERS.contains(&w.as_str()) {
432                err(format!("unknown weather `{w}`"));
433            }
434        }
435        if self.requires.time_of_day.is_empty() {
436            err("requires.time_of_day is empty".into());
437        }
438        let states = &self.animation.states;
439        if !states.contains_key(&self.animation.start) {
440            err(format!(
441                "start state `{}` is not defined",
442                self.animation.start
443            ));
444        }
445        for (name, s) in states {
446            for (to, w) in &s.next {
447                if !states.contains_key(to) {
448                    err(format!("state `{name}` goes to undefined state `{to}`"));
449                }
450                if !usable_weight(*w) {
451                    err(format!(
452                        "state `{name}`: weight for `{to}` must be between 0.001 and {MAX_WEIGHT}"
453                    ));
454                }
455            }
456            match (s.looping, s.dwell_s) {
457                (true, None) => err(format!("looping state `{name}` needs dwell_s")),
458                (true, Some([lo, hi])) if !(lo >= 0.2 && hi >= lo) => err(format!(
459                    "state `{name}`: dwell_s must be [lo, hi] with 0.2 <= lo <= hi"
460                )),
461                (false, Some(_)) => err(format!(
462                    "state `{name}`: dwell_s only applies to looping states"
463                )),
464                _ => {}
465            }
466        }
467        for (state, effects) in &self.effects_by_state {
468            if !states.contains_key(state) {
469                err(format!("effects_by_state names undefined state `{state}`"));
470            }
471            for e in effects {
472                if !EFFECTS.contains(&e.as_str()) {
473                    err(format!("unknown effect `{e}`"));
474                }
475            }
476        }
477        for (prop, def) in &self.props {
478            if !PROPS.contains(&prop.as_str()) {
479                err(format!("unknown prop `{prop}`"));
480            }
481            if !ATTACH.contains(&def.attach.as_str()) {
482                err(format!("prop `{prop}`: unknown attach `{}`", def.attach));
483            }
484            for e in &def.effects {
485                if !EFFECTS.contains(&e.as_str()) {
486                    err(format!("prop `{prop}`: unknown effect `{e}`"));
487                }
488            }
489        }
490        if let Some(t) = &self.trail
491            && t != "ski_tracks"
492        {
493            err(format!("unknown trail `{t}`"));
494        }
495        if self.motion.kind == MotionKind::Bob && self.requires.terrain != ["shore"] {
496            err("bob motion floats on the shore's water: requires.terrain = [\"shore\"]".into());
497        }
498        if let Some(face) = &self.motion.face {
499            if !FACINGS.contains(&face.as_str()) {
500                err(format!("unknown facing `{face}`"));
501            }
502            if face == "water" && self.requires.terrain != ["shore"] {
503                err("facing the water needs requires.terrain = [\"shore\"]".into());
504            }
505        }
506        for e in &self.effects {
507            match e.kind.as_str() {
508                "particles" if !PARTICLE_PRESETS.contains(&e.preset.as_str()) => {
509                    err(format!("unknown particle preset `{}`", e.preset));
510                }
511                "tether" if !TETHER_PRESETS.contains(&e.preset.as_str()) => {
512                    err(format!("unknown tether preset `{}`", e.preset));
513                }
514                "projectile" if !PROJECTILE_PRESETS.contains(&e.preset.as_str()) => {
515                    err(format!("unknown projectile preset `{}`", e.preset));
516                }
517                "particles" | "tether" | "projectile" => {}
518                other => err(format!(
519                    "effect type `{other}` is not implemented (`particles`, `tether`, `projectile`)"
520                )),
521            }
522            if e.preset == "tennis_ball" && !self.props.contains_key("practice_wall") {
523                err("a tennis ball needs a practice wall (props.practice_wall)".into());
524            }
525            if e.preset == "snowball" && !self.props.contains_key("snowman") {
526                err("a snowball needs a snowman to throw at (props.snowman)".into());
527            }
528            if ["fishing_line", "skipping_stone"].contains(&e.preset.as_str())
529                && self.requires.terrain != ["shore"]
530            {
531                err(format!(
532                    "`{}` needs requires.terrain = [\"shore\"]",
533                    e.preset
534                ));
535            }
536            if !ANCHORS.contains(&e.at.as_str()) {
537                err(format!("effect anchor `{}` is not a known anchor", e.at));
538            }
539            for s in &e.states {
540                if !states.contains_key(s) {
541                    err(format!("effect names undefined state `{s}`"));
542                }
543            }
544        }
545        let journey = self.motion.kind == MotionKind::Journey;
546        if journey && !self.props.is_empty() {
547            err("a journey has no props: the ground moves under them".into());
548        }
549        // A journey without the character is the landscape going by.
550        if self.unattended.props.is_empty() && !journey {
551            err("unattended.props is empty: Buddy-off scenes need a focal object".into());
552        }
553        for p in &self.unattended.props {
554            if !PROPS.contains(&p.as_str()) && !EFFECTS.contains(&p.as_str()) {
555                err(format!("unattended: unknown prop or effect `{p}`"));
556            }
557        }
558        if self.motion.altitude.is_some() && self.motion.kind != MotionKind::Journey {
559            err("altitude is for journeys".into());
560        }
561        match self.motion.kind {
562            MotionKind::Stationary => {}
563            MotionKind::Pace | MotionKind::Fly | MotionKind::Bob => {
564                match self.motion.speed_cells_per_s {
565                    Some([lo, hi]) if lo > 0.0 && hi >= lo => {}
566                    _ => err(format!(
567                        "{} motion needs speed_cells_per_s = [lo, hi] with 0 < lo <= hi",
568                        format!("{:?}", self.motion.kind).to_lowercase()
569                    )),
570                }
571            }
572            MotionKind::Journey => {
573                match self.motion.speed_cells_per_s {
574                    Some([lo, hi]) if lo >= 1.0 && hi >= lo && hi <= 20.0 => {}
575                    _ => err(
576                        "journey motion needs speed_cells_per_s = [lo, hi] within 1..=20 (the ground's pace)"
577                            .into(),
578                    ),
579                }
580                if let Some(x) = self.motion.screen_x
581                    && !(0.15..=0.85).contains(&x)
582                {
583                    err("journey screen_x must be within 0.15..=0.85".into());
584                }
585                if let Some(y) = self.motion.altitude
586                    && !(0.2..=0.6).contains(&y)
587                {
588                    err("journey altitude must be within 0.2..=0.6".into());
589                }
590            }
591            MotionKind::Path => err(format!(
592                "motion `{:?}` is not implemented yet (milestone M4)",
593                self.motion.kind
594            )),
595        }
596        if let Some(gif) = &self.gif {
597            let script = &gif.loop_script;
598            if script.first() != Some(&self.animation.start) {
599                err("gif.loop_script must start with the start state".into());
600            }
601            for pair in script.windows(2).chain(std::iter::once(
602                [
603                    script.last().cloned().unwrap_or_default(),
604                    script.first().cloned().unwrap_or_default(),
605                ]
606                .as_slice(),
607            )) {
608                let (from, to) = (&pair[0], &pair[1]);
609                if !states.contains_key(from) {
610                    err(format!("gif.loop_script names undefined state `{from}`"));
611                } else if !self.successors(from).iter().any(|(s, _)| s == to) {
612                    err(format!("gif.loop_script: `{from}` can't go to `{to}`"));
613                }
614            }
615        }
616        errs
617    }
618}
619
620/// The activity catalog.
621#[derive(Clone, Debug, PartialEq)]
622pub struct Catalog {
623    pub activities: Vec<Activity>,
624    /// Hash of the source files; part of the content context.
625    pub data_hash: u64,
626}
627
628impl Catalog {
629    /// Parses and validates the embedded activity files. Panics on invalid data,
630    /// which CI catches through the tests.
631    pub fn builtin() -> Self {
632        Self::from_sources(&SOURCES)
633            .unwrap_or_else(|e| panic!("invalid built-in activities:\n{}", e.join("\n")))
634    }
635
636    /// Parses `(file name, toml)` pairs. Returns every error at once.
637    pub fn from_sources(sources: &[(&str, &str)]) -> Result<Self, Vec<String>> {
638        let mut errors = Vec::new();
639        let mut activities = Vec::new();
640        let mut h = StableHasher::new();
641        for (name, text) in sources {
642            h.write_str(name);
643            write_text(&mut h, text);
644            match toml::from_str::<Activity>(text) {
645                Ok(a) => {
646                    if format!("{}.toml", a.id) != *name {
647                        errors.push(format!("{name}: id `{}` must match the file name", a.id));
648                    }
649                    errors.extend(a.validate());
650                    activities.push(a);
651                }
652                Err(e) => errors.push(format!("{name}: {e}")),
653            }
654        }
655        activities.sort_by(|a, b| a.id.cmp(&b.id));
656        if errors.is_empty() {
657            Ok(Self {
658                activities,
659                data_hash: h.finish(),
660            })
661        } else {
662            Err(errors)
663        }
664    }
665
666    pub fn get(&self, id: &str) -> Option<&Activity> {
667        self.activities.iter().find(|a| a.id == id)
668    }
669}
670
671/// Hashes text with CRLF normalised to LF, so a Windows checkout with
672/// `core.autocrlf` gives the same hash (and recipes) as everywhere else.
673fn write_text(h: &mut StableHasher, text: &str) {
674    h.write_str(&text.replace("\r\n", "\n"));
675}
676
677/// The built-in catalog, parsed once.
678pub fn builtin_catalog() -> &'static Catalog {
679    static CATALOG: OnceLock<Catalog> = OnceLock::new();
680    CATALOG.get_or_init(Catalog::builtin)
681}
682
683/// Hash of the built-in activity files without parsing them.
684pub fn builtin_data_hash() -> u64 {
685    let mut h = StableHasher::new();
686    for (name, text) in SOURCES {
687        h.write_str(name);
688        write_text(&mut h, text);
689    }
690    h.finish()
691}
692
693#[cfg(test)]
694mod tests {
695    use super::*;
696
697    #[test]
698    fn builtin_catalog_is_valid() {
699        let c = Catalog::builtin();
700        assert_eq!(c.activities.len(), SOURCES.len());
701        assert_eq!(c.data_hash, builtin_data_hash());
702    }
703
704    #[test]
705    fn validation_reports_bad_files() {
706        let bad = r#"
707            id = "bad"
708            [requires]
709            terrain = ["lava"]
710            time_of_day = []
711            [motion]
712            type = "pace"
713            [props.anvil]
714            attach = "on_head"
715            [animation]
716            start = "idle"
717            [animation.states.idle]
718            loop = true
719            next = { nowhere = 1.0, idle = 0.0001 }
720            [gif]
721            loop_script = ["sit"]
722            [unattended]
723            props = []
724        "#;
725        let errs = Catalog::from_sources(&[("bad.toml", bad)]).unwrap_err();
726        let all = errs.join("\n");
727        for needle in [
728            "unknown terrain `lava`",
729            "time_of_day is empty",
730            "undefined state `nowhere`",
731            "needs dwell_s",
732            "unknown prop `anvil`",
733            "unknown attach `on_head`",
734            "unattended.props is empty",
735            "pace motion needs speed",
736            "must start with the start state",
737            "weight for `idle` must be between 0.001",
738        ] {
739            assert!(all.contains(needle), "missing `{needle}` in:\n{all}");
740        }
741    }
742
743    #[test]
744    fn sources_are_sorted_by_file_name_like_a_folder_listing() {
745        // The data hash follows this order, and tools that read the folder
746        // (the preview window) sort by name, so both must agree.
747        let names: Vec<&str> = SOURCES.iter().map(|(n, _)| *n).collect();
748        let mut sorted = names.clone();
749        sorted.sort_unstable();
750        assert_eq!(names, sorted);
751    }
752
753    #[test]
754    fn data_hash_ignores_line_endings() {
755        let lf = Catalog::builtin();
756        let crlf: Vec<(String, String)> = SOURCES
757            .iter()
758            .map(|(n, t)| (n.to_string(), t.replace('\n', "\r\n")))
759            .collect();
760        let refs: Vec<(&str, &str)> = crlf.iter().map(|(n, t)| (n.as_str(), t.as_str())).collect();
761        assert_eq!(
762            Catalog::from_sources(&refs).unwrap().data_hash,
763            lf.data_hash
764        );
765    }
766
767    #[test]
768    fn unknown_fields_are_rejected() {
769        let text = "id = \"x\"\ncolour = \"red\"\n";
770        assert!(Catalog::from_sources(&[("x.toml", text)]).is_err());
771    }
772}