Skip to main content

clairlune_scene/
activity.rs

1//! Activities: what the character is doing (PLAN.md section 4.7).
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;
12use std::collections::BTreeMap;
13use std::sync::OnceLock;
14
15/// Prop ids the engine can draw.
16pub const PROPS: [&str; 4] = ["campfire", "log_seat", "telescope", "lantern"];
17/// Effect ids the engine can draw.
18pub const EFFECTS: [&str; 1] = ["embers"];
19/// Generic prop attachment points.
20pub const ATTACH: [&str; 4] = ["path", "left_of_clawd", "right_of_clawd", "either_side"];
21
22/// Embedded activity files, sorted by file name.
23const SOURCES: [(&str, &str); 3] = [
24    ("stargaze.toml", include_str!("../activities/stargaze.toml")),
25    ("stroll.toml", include_str!("../activities/stroll.toml")),
26    (
27        "warm_hands.toml",
28        include_str!("../activities/warm_hands.toml"),
29    ),
30];
31
32#[derive(Deserialize, Clone, Debug, PartialEq)]
33#[serde(deny_unknown_fields)]
34pub struct Activity {
35    pub id: String,
36    #[serde(default = "one")]
37    pub weight: f64,
38    pub requires: Requires,
39    pub motion: Motion,
40    #[serde(default)]
41    pub props: BTreeMap<String, PropDef>,
42    pub animation: AnimationDef,
43    #[serde(default)]
44    pub effects_by_state: BTreeMap<String, Vec<String>>,
45    pub gif: Option<GifDef>,
46    pub unattended: Unattended,
47}
48
49fn one() -> f64 {
50    1.0
51}
52
53/// Capability requirements. An empty list means "no constraint".
54#[derive(Deserialize, Clone, Debug, PartialEq)]
55#[serde(deny_unknown_fields)]
56pub struct Requires {
57    #[serde(default)]
58    pub terrain: Vec<String>,
59    #[serde(default)]
60    pub surface: Vec<String>,
61    pub time_of_day: Vec<TimeOfDay>,
62    #[serde(default)]
63    pub weather: Vec<String>,
64}
65
66#[derive(Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
67#[serde(rename_all = "snake_case")]
68pub enum MotionKind {
69    Stationary,
70    Pace,
71    Path,
72    Bob,
73    Fly,
74}
75
76#[derive(Deserialize, Clone, Debug, PartialEq)]
77#[serde(deny_unknown_fields)]
78pub struct Motion {
79    #[serde(rename = "type")]
80    pub kind: MotionKind,
81    pub path: Option<String>,
82    pub speed_cells_per_s: Option<[f64; 2]>,
83    pub at_path_end: Option<String>,
84}
85
86#[derive(Deserialize, Clone, Debug, PartialEq)]
87#[serde(deny_unknown_fields)]
88pub struct PropDef {
89    pub attach: String,
90    #[serde(default)]
91    pub effects: Vec<String>,
92}
93
94#[derive(Deserialize, Clone, Debug, PartialEq)]
95#[serde(deny_unknown_fields)]
96pub struct AnimationDef {
97    pub start: String,
98    pub states: BTreeMap<String, StateDef>,
99}
100
101#[derive(Deserialize, Clone, Debug, PartialEq)]
102#[serde(deny_unknown_fields)]
103pub struct StateDef {
104    #[serde(default, rename = "loop")]
105    pub looping: bool,
106    pub dwell_s: Option<[f64; 2]>,
107    #[serde(default)]
108    pub next: BTreeMap<String, f64>,
109}
110
111#[derive(Deserialize, Clone, Debug, PartialEq)]
112#[serde(deny_unknown_fields)]
113pub struct GifDef {
114    pub loop_script: Vec<String>,
115}
116
117#[derive(Deserialize, Clone, Debug, PartialEq)]
118#[serde(deny_unknown_fields)]
119pub struct Unattended {
120    pub props: Vec<String>,
121}
122
123/// Integer weight for seeded picks (weights in files are decimals).
124pub fn int_weight(w: f64) -> u32 {
125    (w * 1000.0).round().max(0.0) as u32
126}
127
128fn overlaps(need: &[String], offer: &[&str]) -> bool {
129    need.is_empty() || need.iter().any(|n| offer.contains(&n.as_str()))
130}
131
132impl Activity {
133    /// Whether this activity can take place in an archetype, given enabled weather.
134    pub fn fits(&self, a: &ArchetypeInfo, enabled_weather: &[String]) -> bool {
135        overlaps(&self.requires.terrain, a.terrain)
136            && overlaps(&self.requires.surface, a.surface)
137            && !self.weathers_in(a, enabled_weather).is_empty()
138    }
139
140    /// Weather that the activity, the archetype and the user all allow.
141    pub fn weathers_in(&self, a: &ArchetypeInfo, enabled: &[String]) -> Vec<&'static str> {
142        a.weather
143            .iter()
144            .copied()
145            .filter(|w| {
146                self.requires.weather.is_empty() || self.requires.weather.iter().any(|r| r == w)
147            })
148            .filter(|w| enabled.iter().any(|e| e == w))
149            .collect()
150    }
151
152    /// Allowed times of day for one theme family, in canonical order.
153    pub fn times_in(&self, family: &[TimeOfDay]) -> Vec<TimeOfDay> {
154        family
155            .iter()
156            .copied()
157            .filter(|t| self.requires.time_of_day.contains(t))
158            .collect()
159    }
160
161    /// The state that follows `state` (when no `next`, back to `start`).
162    pub fn successors(&self, state: &str) -> Vec<(&str, u32)> {
163        match self.animation.states.get(state) {
164            Some(s) if !s.next.is_empty() => s
165                .next
166                .iter()
167                .map(|(k, w)| (k.as_str(), int_weight(*w)))
168                .collect(),
169            _ => vec![(self.animation.start.as_str(), 1)],
170        }
171    }
172
173    /// Every rule from PLAN.md section 4.7 that can be checked without sprites.
174    pub fn validate(&self) -> Vec<String> {
175        let mut errs = Vec::new();
176        let id = &self.id;
177        let mut err = |m: String| errs.push(format!("{id}: {m}"));
178        if self.weight.is_nan() || self.weight <= 0.0 {
179            err("weight must be positive".into());
180        }
181        for t in &self.requires.terrain {
182            if !TERRAINS.contains(&t.as_str()) {
183                err(format!("unknown terrain `{t}`"));
184            }
185        }
186        for s in &self.requires.surface {
187            if !SURFACES.contains(&s.as_str()) {
188                err(format!("unknown surface `{s}`"));
189            }
190        }
191        for w in &self.requires.weather {
192            if !WEATHERS.contains(&w.as_str()) {
193                err(format!("unknown weather `{w}`"));
194            }
195        }
196        if self.requires.time_of_day.is_empty() {
197            err("requires.time_of_day is empty".into());
198        }
199        let states = &self.animation.states;
200        if !states.contains_key(&self.animation.start) {
201            err(format!(
202                "start state `{}` is not defined",
203                self.animation.start
204            ));
205        }
206        for (name, s) in states {
207            for (to, w) in &s.next {
208                if !states.contains_key(to) {
209                    err(format!("state `{name}` goes to undefined state `{to}`"));
210                }
211                if w.is_nan() || *w <= 0.0 {
212                    err(format!(
213                        "state `{name}`: weight for `{to}` must be positive"
214                    ));
215                }
216            }
217            match (s.looping, s.dwell_s) {
218                (true, None) => err(format!("looping state `{name}` needs dwell_s")),
219                (true, Some([lo, hi])) if !(lo >= 0.2 && hi >= lo) => err(format!(
220                    "state `{name}`: dwell_s must be [lo, hi] with 0.2 <= lo <= hi"
221                )),
222                (false, Some(_)) => err(format!(
223                    "state `{name}`: dwell_s only applies to looping states"
224                )),
225                _ => {}
226            }
227        }
228        for (state, effects) in &self.effects_by_state {
229            if !states.contains_key(state) {
230                err(format!("effects_by_state names undefined state `{state}`"));
231            }
232            for e in effects {
233                if !EFFECTS.contains(&e.as_str()) {
234                    err(format!("unknown effect `{e}`"));
235                }
236            }
237        }
238        for (prop, def) in &self.props {
239            if !PROPS.contains(&prop.as_str()) {
240                err(format!("unknown prop `{prop}`"));
241            }
242            if !ATTACH.contains(&def.attach.as_str()) {
243                err(format!("prop `{prop}`: unknown attach `{}`", def.attach));
244            }
245            for e in &def.effects {
246                if !EFFECTS.contains(&e.as_str()) {
247                    err(format!("prop `{prop}`: unknown effect `{e}`"));
248                }
249            }
250        }
251        if self.unattended.props.is_empty() {
252            err("unattended.props is empty: Buddy-off scenes need a focal object".into());
253        }
254        for p in &self.unattended.props {
255            if !PROPS.contains(&p.as_str()) && !EFFECTS.contains(&p.as_str()) {
256                err(format!("unattended: unknown prop or effect `{p}`"));
257            }
258        }
259        match self.motion.kind {
260            MotionKind::Stationary => {}
261            MotionKind::Pace => match self.motion.speed_cells_per_s {
262                Some([lo, hi]) if lo > 0.0 && hi >= lo => {}
263                _ => err("pace motion needs speed_cells_per_s = [lo, hi] with 0 < lo <= hi".into()),
264            },
265            MotionKind::Path | MotionKind::Bob | MotionKind::Fly => err(format!(
266                "motion `{:?}` is not implemented yet (milestone M4)",
267                self.motion.kind
268            )),
269        }
270        if let Some(gif) = &self.gif {
271            let script = &gif.loop_script;
272            if script.first() != Some(&self.animation.start) {
273                err("gif.loop_script must start with the start state".into());
274            }
275            for pair in script.windows(2).chain(std::iter::once(
276                [
277                    script.last().cloned().unwrap_or_default(),
278                    script.first().cloned().unwrap_or_default(),
279                ]
280                .as_slice(),
281            )) {
282                let (from, to) = (&pair[0], &pair[1]);
283                if !states.contains_key(from) {
284                    err(format!("gif.loop_script names undefined state `{from}`"));
285                } else if !self.successors(from).iter().any(|(s, _)| s == to) {
286                    err(format!("gif.loop_script: `{from}` can't go to `{to}`"));
287                }
288            }
289        }
290        errs
291    }
292}
293
294/// The activity catalog.
295#[derive(Clone, Debug, PartialEq)]
296pub struct Catalog {
297    pub activities: Vec<Activity>,
298    /// Hash of the source files; part of the content context.
299    pub data_hash: u64,
300}
301
302impl Catalog {
303    /// Parses and validates the embedded activity files. Panics on invalid data,
304    /// which CI catches through the tests.
305    pub fn builtin() -> Self {
306        Self::from_sources(&SOURCES)
307            .unwrap_or_else(|e| panic!("invalid built-in activities:\n{}", e.join("\n")))
308    }
309
310    /// Parses `(file name, toml)` pairs. Returns every error at once.
311    pub fn from_sources(sources: &[(&str, &str)]) -> Result<Self, Vec<String>> {
312        let mut errors = Vec::new();
313        let mut activities = Vec::new();
314        let mut h = StableHasher::new();
315        for (name, text) in sources {
316            h.write_str(name);
317            write_text(&mut h, text);
318            match toml::from_str::<Activity>(text) {
319                Ok(a) => {
320                    if format!("{}.toml", a.id) != *name {
321                        errors.push(format!("{name}: id `{}` must match the file name", a.id));
322                    }
323                    errors.extend(a.validate());
324                    activities.push(a);
325                }
326                Err(e) => errors.push(format!("{name}: {e}")),
327            }
328        }
329        activities.sort_by(|a, b| a.id.cmp(&b.id));
330        if errors.is_empty() {
331            Ok(Self {
332                activities,
333                data_hash: h.finish(),
334            })
335        } else {
336            Err(errors)
337        }
338    }
339
340    pub fn get(&self, id: &str) -> Option<&Activity> {
341        self.activities.iter().find(|a| a.id == id)
342    }
343}
344
345/// Hashes text with CRLF normalised to LF, so a Windows checkout with
346/// `core.autocrlf` gives the same hash (and recipes) as everywhere else.
347fn write_text(h: &mut StableHasher, text: &str) {
348    h.write_str(&text.replace("\r\n", "\n"));
349}
350
351/// The built-in catalog, parsed once.
352pub fn builtin_catalog() -> &'static Catalog {
353    static CATALOG: OnceLock<Catalog> = OnceLock::new();
354    CATALOG.get_or_init(Catalog::builtin)
355}
356
357/// Hash of the built-in activity files without parsing them.
358pub fn builtin_data_hash() -> u64 {
359    let mut h = StableHasher::new();
360    for (name, text) in SOURCES {
361        h.write_str(name);
362        write_text(&mut h, text);
363    }
364    h.finish()
365}
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370
371    #[test]
372    fn builtin_catalog_is_valid() {
373        let c = Catalog::builtin();
374        assert_eq!(c.activities.len(), SOURCES.len());
375        assert_eq!(c.data_hash, builtin_data_hash());
376    }
377
378    #[test]
379    fn validation_reports_bad_files() {
380        let bad = r#"
381            id = "bad"
382            [requires]
383            terrain = ["lava"]
384            time_of_day = []
385            [motion]
386            type = "pace"
387            [props.anvil]
388            attach = "on_head"
389            [animation]
390            start = "idle"
391            [animation.states.idle]
392            loop = true
393            next = { nowhere = 1.0 }
394            [gif]
395            loop_script = ["sit"]
396            [unattended]
397            props = []
398        "#;
399        let errs = Catalog::from_sources(&[("bad.toml", bad)]).unwrap_err();
400        let all = errs.join("\n");
401        for needle in [
402            "unknown terrain `lava`",
403            "time_of_day is empty",
404            "undefined state `nowhere`",
405            "needs dwell_s",
406            "unknown prop `anvil`",
407            "unknown attach `on_head`",
408            "unattended.props is empty",
409            "pace motion needs speed",
410            "must start with the start state",
411        ] {
412            assert!(all.contains(needle), "missing `{needle}` in:\n{all}");
413        }
414    }
415
416    #[test]
417    fn data_hash_ignores_line_endings() {
418        let lf = Catalog::builtin();
419        let crlf: Vec<(String, String)> = SOURCES
420            .iter()
421            .map(|(n, t)| (n.to_string(), t.replace('\n', "\r\n")))
422            .collect();
423        let refs: Vec<(&str, &str)> = crlf.iter().map(|(n, t)| (n.as_str(), t.as_str())).collect();
424        assert_eq!(
425            Catalog::from_sources(&refs).unwrap().data_hash,
426            lf.data_hash
427        );
428    }
429
430    #[test]
431    fn unknown_fields_are_rejected() {
432        let text = "id = \"x\"\ncolour = \"red\"\n";
433        assert!(Catalog::from_sources(&[("x.toml", text)]).is_err());
434    }
435}