Skip to main content

clairlune_scene/
recipe.rs

1//! The scene recipe: a small, theme-independent JSON document that reproduces a
2//! scene at any resolution, in either theme it supports, with or without Clawd.
3//! The recipe, not the pixels, is what gets archived.
4
5use crate::hash::hash_bytes;
6use crate::palette::Theme;
7use serde::{Deserialize, Serialize};
8
9/// Bump whenever generator logic changes output for an existing recipe.
10///
11/// History: 1 = M1 canyon + placeholder focal group; 2 = activity-first composition (M2);
12/// 3 = drawn character art, sized by the art's box.
13pub const GENERATOR_VERSION: u32 = 3;
14
15/// The nine v1 archetype ids (PLAN.md section 4.2).
16pub const ARCHETYPES: [&str; 9] = {
17    let mut ids = [""; 9];
18    let mut i = 0;
19    while i < 9 {
20        ids[i] = crate::archetype::ARCHETYPE_INFO[i].id;
21        i += 1;
22    }
23    ids
24};
25
26/// Reduced aspect ratio, e.g. 16:9.
27#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]
28pub struct Aspect {
29    pub w: u32,
30    pub h: u32,
31}
32
33impl Aspect {
34    /// Aspect of a pixel size, reduced by the greatest common divisor.
35    pub fn from_size(width: u32, height: u32) -> Self {
36        assert!(width > 0 && height > 0);
37        let g = gcd(width, height);
38        Self {
39            w: width / g,
40            h: height / g,
41        }
42    }
43
44    pub fn ratio(self) -> f64 {
45        f64::from(self.w) / f64::from(self.h)
46    }
47}
48
49fn gcd(mut a: u32, mut b: u32) -> u32 {
50    while b != 0 {
51        (a, b) = (b, a % b);
52    }
53    a
54}
55
56/// Time of day. Light themes use the first three, dark themes the last three.
57#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]
58#[serde(rename_all = "snake_case")]
59pub enum TimeOfDay {
60    Morning,
61    Noon,
62    GoldenHour,
63    Dusk,
64    DeepDusk,
65    Night,
66}
67
68impl TimeOfDay {
69    pub const LIGHT: [TimeOfDay; 3] = [TimeOfDay::Morning, TimeOfDay::Noon, TimeOfDay::GoldenHour];
70    pub const DARK: [TimeOfDay; 3] = [TimeOfDay::Dusk, TimeOfDay::DeepDusk, TimeOfDay::Night];
71
72    pub fn theme(self) -> Theme {
73        match self {
74            TimeOfDay::Morning | TimeOfDay::Noon | TimeOfDay::GoldenHour => Theme::Light,
75            TimeOfDay::Dusk | TimeOfDay::DeepDusk | TimeOfDay::Night => Theme::Dark,
76        }
77    }
78}
79
80/// Composition variables. Fractions are stored as integer per-mille so the
81/// recipe JSON is exact and stable.
82#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
83pub struct Composition {
84    /// Platform top (the horizon line), per-mille of height from the top.
85    pub horizon_pm: u32,
86    /// Horizontal centre of the focal character, per-mille of width.
87    pub focus_x_pm: u32,
88    /// Width of the open centre between the canyon walls, per-mille.
89    pub gap_pm: u32,
90    /// Exponent of the canyon wall profile, times 1000.
91    pub shape_pow_pm: u32,
92    /// Extra platform width on each side of the focal group, per-mille of height.
93    pub platform_margin_pm: u32,
94    /// Number of cliff layers behind the platform.
95    pub cliff_layers: u32,
96    /// Main prop on the left of the character (`true`) or the right.
97    pub prop_left: bool,
98    /// Movement speed in hundredths of a cell per second (0 when stationary).
99    pub motion_speed_cc: u32,
100    /// Half the pacing range, per-mille of the short side (0 when not pacing).
101    pub pace_half_pm: u32,
102}
103
104/// One palette family id per theme.
105#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
106pub struct PalettePick {
107    pub light: String,
108    pub dark: String,
109}
110
111/// Everything the seed decided. Theme-independent.
112#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
113pub struct SceneRecipe {
114    pub generator_version: u32,
115    pub seed: u64,
116    pub aspect: Aspect,
117    /// Hex of [`ContentContext::hash`] at compose time.
118    pub content_ctx_hash: String,
119    /// The activity id (M2). `None` until the activity engine exists.
120    pub activity: Option<String>,
121    pub archetype: String,
122    /// Time of day used in the light theme. `None` makes the scene dark-only.
123    pub light_tod: Option<TimeOfDay>,
124    /// Time of day used in the dark theme. `None` makes the scene light-only.
125    pub dark_tod: Option<TimeOfDay>,
126    pub platform: String,
127    pub props: Vec<String>,
128    pub weather: String,
129    pub composition: Composition,
130    pub palette: PalettePick,
131}
132
133impl SceneRecipe {
134    /// Time of day for a theme, or `None` if the scene is locked to the other theme.
135    pub fn tod_for(&self, theme: Theme) -> Option<TimeOfDay> {
136        match theme {
137            Theme::Light => self.light_tod,
138            Theme::Dark => self.dark_tod,
139        }
140    }
141
142    /// True when the scene can only render in one theme (PLAN.md section 1.2).
143    pub fn is_theme_locked(&self) -> bool {
144        self.light_tod.is_none() || self.dark_tod.is_none()
145    }
146
147    /// Stable short id of the recipe (hash of its JSON), for logs and bug reports.
148    pub fn hash_hex(&self) -> String {
149        format!("{:016x}", hash_bytes(self.to_json().as_bytes()))
150    }
151
152    /// Pretty JSON. Field order is fixed by the struct, so output is stable.
153    pub fn to_json(&self) -> String {
154        serde_json::to_string_pretty(self).expect("recipe serialises")
155    }
156
157    pub fn from_json(s: &str) -> Result<Self, serde_json::Error> {
158        serde_json::from_str(s)
159    }
160}
161
162/// One entry of the recent-history list used to avoid near-duplicates.
163#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
164pub struct HistoryEntry {
165    pub activity: Option<String>,
166    pub archetype: String,
167    pub platform: String,
168    pub prop: Option<String>,
169}
170
171/// Everything besides the seed that affects composition picks.
172#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
173pub struct ContentContext {
174    pub enabled_archetypes: Vec<String>,
175    pub enabled_weather: Vec<String>,
176    pub enabled_activities: Vec<String>,
177    /// Most recent last. The CLI and tests pass an empty history.
178    pub recent: Vec<HistoryEntry>,
179    /// Hash of the activity data files.
180    pub data_hash: u64,
181}
182
183impl Default for ContentContext {
184    fn default() -> Self {
185        Self {
186            enabled_archetypes: ARCHETYPES.iter().map(|s| s.to_string()).collect(),
187            enabled_weather: crate::archetype::WEATHERS
188                .iter()
189                .map(|s| s.to_string())
190                .collect(),
191            enabled_activities: crate::activity::Catalog::builtin()
192                .activities
193                .iter()
194                .map(|a| a.id.clone())
195                .collect(),
196            recent: Vec::new(),
197            data_hash: crate::activity::builtin_data_hash(),
198        }
199    }
200}
201
202impl ContentContext {
203    /// Stable hash of the whole context, recorded in the recipe.
204    pub fn hash(&self) -> u64 {
205        hash_bytes(&serde_json::to_vec(self).expect("context serialises"))
206    }
207}