clairlune_sprites/
character.rs1use crate::embedded::SHEETS;
5use crate::sheet::{Animation, Frame, MAX_CHARACTER_COLORS, ORIGIN, SpriteSheet};
6use clairlune_scene::activity::Catalog;
7use clairlune_scene::anim::DEFAULT_ONE_SHOT_MS;
8use clairlune_scene::placeholder::CLAWD_PLACEHOLDER;
9use std::collections::BTreeMap;
10
11pub const BASE_SHEET: &str = "_base";
13
14pub trait Character {
16 fn animation(&self, activity: &str, state: &str) -> Option<&Animation>;
18
19 fn one_shot_ms(&self, activity: &str, state: &str) -> u64 {
21 self.animation(activity, state)
22 .map(Animation::duration_ms)
23 .filter(|&d| d > 0)
24 .unwrap_or(DEFAULT_ONE_SHOT_MS)
25 }
26}
27
28#[derive(Clone, Debug)]
30pub struct Placeholder {
31 anim: Animation,
32}
33
34impl Default for Placeholder {
35 fn default() -> Self {
36 Self::new()
37 }
38}
39
40impl Placeholder {
41 pub fn new() -> Self {
42 let m = &CLAWD_PLACEHOLDER;
43 let pixels = (0..m.height)
44 .flat_map(|y| (0..m.width).map(move |x| m.pixel(x, y)))
45 .collect();
46 let mut anchors = BTreeMap::new();
47 anchors.insert(ORIGIN.to_string(), ((m.width / 2) as i32, m.height as i32));
48 let frame = Frame {
49 width: m.width,
50 height: m.height,
51 pixels,
52 duration_ms: DEFAULT_ONE_SHOT_MS as u32,
53 anchors,
54 };
55 Self {
56 anim: Animation {
57 name: "placeholder".into(),
58 frames: vec![frame],
59 },
60 }
61 }
62}
63
64impl Character for Placeholder {
65 fn animation(&self, _activity: &str, _state: &str) -> Option<&Animation> {
66 Some(&self.anim)
67 }
68}
69
70#[derive(Clone, Debug)]
74pub struct SheetCharacter {
75 sheets: BTreeMap<String, SpriteSheet>,
76 placeholder: Placeholder,
77}
78
79impl SheetCharacter {
80 pub fn builtin() -> Result<Self, Vec<String>> {
82 Self::from_sources(SHEETS)
83 }
84
85 pub fn from_sources(sources: &[(&str, &str, &[u8])]) -> Result<Self, Vec<String>> {
87 let mut errors = Vec::new();
88 let mut sheets = BTreeMap::new();
89 let mut colors = Vec::new();
90 for (name, json, png) in sources {
91 match SpriteSheet::parse(json, png) {
92 Ok(sheet) => {
93 for c in &sheet.colors {
94 if !colors.contains(c) {
95 colors.push(*c);
96 }
97 }
98 sheets.insert(name.to_string(), sheet);
99 }
100 Err(e) => errors.push(format!("{name}: {e}")),
101 }
102 }
103 if colors.len() > MAX_CHARACTER_COLORS {
104 errors.push(format!(
105 "all sheets together use {} colours; the character may use at most {MAX_CHARACTER_COLORS}",
106 colors.len()
107 ));
108 }
109 if errors.is_empty() {
110 Ok(Self {
111 sheets,
112 placeholder: Placeholder::new(),
113 })
114 } else {
115 Err(errors)
116 }
117 }
118
119 pub fn has_sheet(&self, activity: &str) -> bool {
120 self.sheets.contains_key(activity)
121 }
122
123 pub fn missing_art<'c>(&self, catalog: &'c Catalog) -> Vec<&'c str> {
125 catalog
126 .activities
127 .iter()
128 .map(|a| a.id.as_str())
129 .filter(|id| !self.has_sheet(id))
130 .collect()
131 }
132
133 pub fn validate(&self, catalog: &Catalog) -> Vec<String> {
136 let mut errors = Vec::new();
137 for a in &catalog.activities {
138 let Some(sheet) = self.sheets.get(&a.id) else {
139 continue;
140 };
141 for state in a.animation.states.keys() {
142 let in_base = self
143 .sheets
144 .get(BASE_SHEET)
145 .is_some_and(|b| b.animations.contains_key(state));
146 if !sheet.animations.contains_key(state) && !in_base {
147 errors.push(format!(
148 "{}: state `{state}` has no tag in {}.aseprite or {BASE_SHEET}.aseprite",
149 a.id, a.id
150 ));
151 }
152 }
153 }
154 errors
155 }
156}
157
158impl Character for SheetCharacter {
159 fn animation(&self, activity: &str, state: &str) -> Option<&Animation> {
160 self.sheets
161 .get(activity)
162 .and_then(|s| s.animations.get(state))
163 .or_else(|| {
164 self.sheets
165 .get(BASE_SHEET)
166 .and_then(|s| s.animations.get(state))
167 })
168 .or_else(|| self.placeholder.animation(activity, state))
169 }
170}
171
172#[cfg(test)]
173mod tests {
174 use super::*;
175 use crate::sheet::tests::fixture;
176 use clairlune_scene::activity::builtin_catalog;
177
178 #[test]
179 fn placeholder_matches_the_pixel_map() {
180 let p = Placeholder::new();
181 let a = p.animation("anything", "any").unwrap();
182 let f = &a.frames[0];
183 assert_eq!((f.width, f.height), (15, 9));
184 assert_eq!(f.origin(), (7, 9));
185 assert_eq!(p.one_shot_ms("x", "y"), DEFAULT_ONE_SHOT_MS);
186 }
187
188 #[test]
189 fn builtin_sheets_are_valid_and_complete() {
190 let c = SheetCharacter::builtin().expect("embedded sheets parse");
191 let errors = c.validate(builtin_catalog());
192 assert!(errors.is_empty(), "{}", errors.join("\n"));
193 for a in &builtin_catalog().activities {
195 for s in a.animation.states.keys() {
196 assert!(c.animation(&a.id, s).is_some());
197 }
198 }
199 }
200
201 #[test]
202 fn validation_reports_states_without_tags() {
203 let (json, png) = fixture(2, 0, 0);
204 let c = SheetCharacter::from_sources(&[("warm_hands", &json, &png)]).unwrap();
205 let errors = c.validate(builtin_catalog()).join("\n");
206 assert!(errors.contains("state `warm` has no tag"), "{errors}");
207 assert!(
208 errors.contains("state `look_around` has no tag"),
209 "{errors}"
210 );
211 assert!(!errors.contains("`idle`"));
213 assert_eq!(c.animation("warm_hands", "idle").unwrap().name, "idle");
214 assert_eq!(
216 c.animation("warm_hands", "warm").unwrap().name,
217 "placeholder"
218 );
219 assert!(c.missing_art(builtin_catalog()).contains(&"stroll"));
220 }
221}