1use crate::aseprite::{Export, Slice};
4use clairlune_scene::Rgb;
5use std::collections::BTreeMap;
6use std::fmt;
7
8pub const MAX_CHARACTER_COLORS: usize = 16;
10pub const ORIGIN: &str = "origin";
12
13#[derive(Clone, Debug, PartialEq, Eq)]
15pub struct Frame {
16 pub width: u32,
17 pub height: u32,
18 pub pixels: Vec<Option<Rgb>>,
19 pub duration_ms: u32,
20 pub anchors: BTreeMap<String, (i32, i32)>,
22}
23
24impl Frame {
25 pub fn pixel(&self, x: u32, y: u32) -> Option<Rgb> {
26 self.pixels[(y * self.width + x) as usize]
27 }
28
29 pub fn origin(&self) -> (i32, i32) {
31 self.anchors[ORIGIN]
32 }
33}
34
35#[derive(Clone, Debug, PartialEq, Eq)]
37pub struct Animation {
38 pub name: String,
39 pub frames: Vec<Frame>,
40}
41
42impl Animation {
43 pub fn duration_ms(&self) -> u64 {
44 self.frames.iter().map(|f| u64::from(f.duration_ms)).sum()
45 }
46
47 pub fn frame_at(&self, elapsed_ms: u64, looping: bool) -> &Frame {
50 let total = self.duration_ms().max(1);
51 let mut t = if looping {
52 elapsed_ms % total
53 } else {
54 elapsed_ms.min(total - 1)
55 };
56 for f in &self.frames {
57 let d = u64::from(f.duration_ms);
58 if t < d {
59 return f;
60 }
61 t -= d;
62 }
63 self.frames.last().expect("animations have frames")
64 }
65}
66
67#[derive(Clone, Debug, PartialEq, Eq)]
69pub struct SpriteSheet {
70 pub animations: BTreeMap<String, Animation>,
71 pub colors: Vec<Rgb>,
73 pub source_sha256: Option<String>,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum SheetError {
78 Json(String),
79 Png(String),
80 Rotated(String),
81 OutOfBounds(String),
82 PartialAlpha {
83 frame: usize,
84 x: u32,
85 y: u32,
86 alpha: u8,
87 },
88 TooManyColors(usize),
89 BadTag(String),
90 MissingOrigin {
91 tag: String,
92 frame: usize,
93 },
94 NoTags,
95}
96
97impl fmt::Display for SheetError {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 match self {
100 SheetError::Json(e) => write!(f, "sheet JSON: {e}"),
101 SheetError::Png(e) => write!(f, "sheet PNG: {e}"),
102 SheetError::Rotated(n) => write!(f, "frame `{n}` is rotated; export without rotation"),
103 SheetError::OutOfBounds(n) => write!(f, "frame `{n}` lies outside the sheet image"),
104 SheetError::PartialAlpha { frame, x, y, alpha } => write!(
105 f,
106 "frame {frame} pixel ({x}, {y}) has alpha {alpha}; pixels must be fully opaque or transparent"
107 ),
108 SheetError::TooManyColors(n) => {
109 write!(
110 f,
111 "{n} colours; the character may use at most {MAX_CHARACTER_COLORS}"
112 )
113 }
114 SheetError::BadTag(t) => write!(f, "tag `{t}` has an invalid frame range or direction"),
115 SheetError::MissingOrigin { tag, frame } => {
116 write!(f, "tag `{tag}` frame {frame} has no `{ORIGIN}` slice key")
117 }
118 SheetError::NoTags => write!(f, "the sheet has no tags; every state needs one"),
119 }
120 }
121}
122
123impl std::error::Error for SheetError {}
124
125fn decode_rgba(bytes: &[u8]) -> Result<(u32, u32, Vec<u8>), SheetError> {
127 let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
128 decoder.set_transformations(png::Transformations::normalize_to_color8());
129 let mut reader = decoder
130 .read_info()
131 .map_err(|e| SheetError::Png(e.to_string()))?;
132 let mut buf = vec![
133 0;
134 reader
135 .output_buffer_size()
136 .ok_or_else(|| SheetError::Png("image too large".into()))?
137 ];
138 let info = reader
139 .next_frame(&mut buf)
140 .map_err(|e| SheetError::Png(e.to_string()))?;
141 let (w, h) = (info.width, info.height);
142 let n = (w * h) as usize;
143 let rgba = match info.color_type {
144 png::ColorType::Rgba => buf[..n * 4].to_vec(),
145 png::ColorType::Rgb => buf[..n * 3]
146 .as_chunks::<3>()
147 .0
148 .iter()
149 .flat_map(|&[r, g, b]| [r, g, b, 255])
150 .collect(),
151 png::ColorType::GrayscaleAlpha => buf[..n * 2]
152 .as_chunks::<2>()
153 .0
154 .iter()
155 .flat_map(|&[g, a]| [g, g, g, a])
156 .collect(),
157 png::ColorType::Grayscale => buf[..n].iter().flat_map(|&g| [g, g, g, 255]).collect(),
158 png::ColorType::Indexed => {
159 return Err(SheetError::Png("indexed PNG was not expanded".into()));
160 }
161 };
162 Ok((w, h, rgba))
163}
164
165fn anchor_at(slice: &Slice, frame: usize) -> Option<(i32, i32)> {
170 let key = slice
171 .keys
172 .iter()
173 .filter(|k| k.frame <= frame)
174 .max_by_key(|k| k.frame)?;
175 let b = key.bounds;
176 Some(((b.x + b.w / 2) as i32, (b.y + b.h / 2) as i32))
177}
178
179impl SpriteSheet {
180 pub fn parse(json: &str, png_bytes: &[u8]) -> Result<Self, SheetError> {
182 let export: Export =
183 serde_json::from_str(json).map_err(|e| SheetError::Json(e.to_string()))?;
184 let (iw, ih, rgba) = decode_rgba(png_bytes)?;
185
186 let mut colors: Vec<Rgb> = Vec::new();
187 let mut frames = Vec::with_capacity(export.frames.len());
188 for (i, fe) in export.frames.iter().enumerate() {
189 if fe.rotated {
190 return Err(SheetError::Rotated(fe.filename.clone()));
191 }
192 let r = fe.frame;
193 if r.x + r.w > iw || r.y + r.h > ih {
194 return Err(SheetError::OutOfBounds(fe.filename.clone()));
195 }
196 let mut pixels = Vec::with_capacity((r.w * r.h) as usize);
197 for y in 0..r.h {
198 for x in 0..r.w {
199 let o = (((r.y + y) * iw + r.x + x) * 4) as usize;
200 let a = rgba[o + 3];
201 match a {
202 0 => pixels.push(None),
203 255 => {
204 let c = Rgb {
205 r: rgba[o],
206 g: rgba[o + 1],
207 b: rgba[o + 2],
208 };
209 if !colors.contains(&c) {
210 colors.push(c);
211 }
212 pixels.push(Some(c));
213 }
214 alpha => {
215 return Err(SheetError::PartialAlpha {
216 frame: i,
217 x,
218 y,
219 alpha,
220 });
221 }
222 }
223 }
224 }
225 let anchors = export
226 .meta
227 .slices
228 .iter()
229 .filter_map(|s| anchor_at(s, i).map(|p| (s.name.clone(), p)))
230 .collect();
231 frames.push(Frame {
232 width: r.w,
233 height: r.h,
234 pixels,
235 duration_ms: fe.duration,
236 anchors,
237 });
238 }
239 if colors.len() > MAX_CHARACTER_COLORS {
240 return Err(SheetError::TooManyColors(colors.len()));
241 }
242 if export.meta.frame_tags.is_empty() {
243 return Err(SheetError::NoTags);
244 }
245
246 let mut animations = BTreeMap::new();
247 for tag in &export.meta.frame_tags {
248 if tag.from > tag.to || tag.to >= frames.len() {
249 return Err(SheetError::BadTag(tag.name.clone()));
250 }
251 let forward: Vec<usize> = (tag.from..=tag.to).collect();
252 let order: Vec<usize> = match tag.direction.as_str() {
253 "forward" => forward,
254 "reverse" => forward.into_iter().rev().collect(),
255 "pingpong" => {
256 let back: Vec<usize> = forward
257 .iter()
258 .rev()
259 .skip(1)
260 .take(forward.len().saturating_sub(2))
261 .copied()
262 .collect();
263 forward.into_iter().chain(back).collect()
264 }
265 _ => return Err(SheetError::BadTag(tag.name.clone())),
266 };
267 for &i in &order {
268 if !frames[i].anchors.contains_key(ORIGIN) {
269 return Err(SheetError::MissingOrigin {
270 tag: tag.name.clone(),
271 frame: i,
272 });
273 }
274 }
275 let anim = Animation {
276 name: tag.name.clone(),
277 frames: order.iter().map(|&i| frames[i].clone()).collect(),
278 };
279 animations.insert(tag.name.clone(), anim);
280 }
281 Ok(Self {
282 animations,
283 colors,
284 source_sha256: export.meta.source_sha256,
285 })
286 }
287}
288
289#[cfg(test)]
290pub(crate) mod tests {
291 use super::*;
292
293 pub(crate) fn fixture(frames: u32, alpha_of_first: u8, extra_colors: u32) -> (String, Vec<u8>) {
295 let (fw, fh) = (4u32, 4u32);
296 let w = fw * frames;
297 let mut rgba = vec![0u8; (w * fh * 4) as usize];
298 for f in 0..frames {
299 for y in 1..fh {
300 for x in 1..3 {
301 let o = ((y * w + f * fw + x) * 4) as usize;
302 rgba[o..o + 4].copy_from_slice(&[0xD9, 0x78, 0x5C, 255]);
303 }
304 }
305 }
306 rgba[3] = alpha_of_first; for i in 0..extra_colors {
308 let o = ((i % w) * 4) as usize;
309 rgba[o..o + 4].copy_from_slice(&[i as u8, 7, 9, 255]);
310 }
311 let mut png_bytes = Vec::new();
312 {
313 let mut enc = png::Encoder::new(&mut png_bytes, w, fh);
314 enc.set_color(png::ColorType::Rgba);
315 enc.set_depth(png::BitDepth::Eight);
316 let mut wr = enc.write_header().unwrap();
317 wr.write_image_data(&rgba).unwrap();
318 }
319 let frame_json: Vec<String> = (0..frames)
320 .map(|f| {
321 format!(
322 r#"{{"filename":"t#{f}","frame":{{"x":{},"y":0,"w":4,"h":4}},"rotated":false,"trimmed":false,"duration":{}}}"#,
323 f * fw,
324 100 + f * 10
325 )
326 })
327 .collect();
328 let json = format!(
329 r##"{{"frames":[{}],"meta":{{"app":"test","image":"t.png","frameTags":[{{"name":"idle","from":0,"to":{},"direction":"forward"}},{{"name":"bob","from":0,"to":{},"direction":"pingpong"}}],"slices":[{{"name":"origin","color":"#0000ffff","keys":[{{"frame":0,"bounds":{{"x":2,"y":3,"w":1,"h":1}}}}]}},{{"name":"hand_r","keys":[{{"frame":0,"bounds":{{"x":3,"y":2,"w":1,"h":1}}}},{{"frame":1,"bounds":{{"x":3,"y":1,"w":1,"h":1}}}}]}}],"source_sha256":"abc"}}}}"##,
330 frame_json.join(","),
331 frames - 1,
332 frames - 1
333 );
334 (json, png_bytes)
335 }
336
337 #[test]
338 fn parses_tags_durations_and_anchors() {
339 let (json, png) = fixture(3, 0, 0);
340 let sheet = SpriteSheet::parse(&json, &png).unwrap();
341 assert_eq!(sheet.colors, vec![Rgb::hex(0xD9785C)]);
342 assert_eq!(sheet.source_sha256.as_deref(), Some("abc"));
343 let idle = &sheet.animations["idle"];
344 assert_eq!(idle.frames.len(), 3);
345 assert_eq!(idle.duration_ms(), 100 + 110 + 120);
346 assert_eq!(idle.frames[0].origin(), (2, 3));
347 assert_eq!(idle.frames[0].anchors["hand_r"], (3, 2));
349 assert_eq!(idle.frames[2].anchors["hand_r"], (3, 1));
350 let bob = &sheet.animations["bob"];
352 assert_eq!(bob.frames.len(), 4);
353 assert_eq!(bob.frames[3], idle.frames[1]);
354 assert_eq!(idle.frame_at(105, true), &idle.frames[1]);
356 assert_eq!(idle.frame_at(330 + 5, true), &idle.frames[0]);
357 assert_eq!(idle.frame_at(10_000, false), &idle.frames[2]);
358 }
359
360 #[test]
361 fn rejects_partial_alpha_and_too_many_colours() {
362 let (json, png) = fixture(2, 128, 0);
363 assert!(matches!(
364 SpriteSheet::parse(&json, &png),
365 Err(SheetError::PartialAlpha { alpha: 128, .. })
366 ));
367 let (json, png) = fixture(8, 0, 20);
368 assert!(matches!(
369 SpriteSheet::parse(&json, &png),
370 Err(SheetError::TooManyColors(_))
371 ));
372 }
373
374 #[test]
375 fn rejects_missing_origin() {
376 let (json, png) = fixture(2, 0, 0);
377 let json = json.replace("\"name\":\"origin\"", "\"name\":\"feet\"");
378 assert!(matches!(
379 SpriteSheet::parse(&json, &png),
380 Err(SheetError::MissingOrigin { .. })
381 ));
382 }
383}