1use serde::{Deserialize, Serialize};
4use std::collections::BTreeMap;
5
6pub const ACTS: [&str; 17] = [
7 "rest", "listen", "think", "busy", "read", "search", "write", "run", "browse", "talk", "pod",
8 "needs", "done", "hmm", "computer", "connect", "sleep",
9];
10pub const MAX_PNG_BYTES: usize = 4 * 1024 * 1024;
11pub const MAX_PACK_BYTES: usize = 128 * 1024;
12
13#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
14#[serde(deny_unknown_fields, rename_all = "camelCase")]
15pub struct Pack {
16 pub version: u8,
17 pub id: String,
18 pub name: String,
19 pub atlases: Vec<String>,
20 pub columns: u16,
21 pub rows: u16,
22 pub tile_width: u16,
23 pub tile_height: u16,
24 pub actions: BTreeMap<String, Action>,
25 pub states: BTreeMap<String, String>,
26 #[serde(default)]
27 pub views: BTreeMap<String, String>,
28}
29
30#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
31#[serde(deny_unknown_fields, rename_all = "camelCase")]
32pub struct Action {
33 pub frames: Vec<u16>,
34 pub durations_ms: Vec<u16>,
35 pub poster: u16,
36 #[serde(default)]
37 pub repeat: bool,
38}
39
40#[derive(Clone, Copy, Debug, PartialEq)]
41pub struct Frame {
42 pub index: usize,
43}
44
45pub fn slug(value: &str) -> bool {
46 !value.is_empty()
47 && value.len() <= 64
48 && value
49 .bytes()
50 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
51}
52
53pub fn relative_asset(value: &str) -> bool {
54 !value.is_empty()
55 && value.len() <= 256
56 && !value
57 .chars()
58 .any(|c| c.is_control() || matches!(c, '\\' | ':'))
59 && value
60 .split('/')
61 .all(|s| !s.is_empty() && s != "." && s != "..")
62}
63
64impl Pack {
65 pub fn page(&self, frame: usize) -> usize {
66 frame / (usize::from(self.columns).max(1) * usize::from(self.rows).max(1))
67 }
68 pub fn local_frame(&self, frame: usize) -> usize {
69 frame % (usize::from(self.columns).max(1) * usize::from(self.rows).max(1))
70 }
71
72 pub fn parse(bytes: &[u8]) -> Result<Self, String> {
73 if bytes.len() > MAX_PACK_BYTES {
74 return Err("Avatar manifest exceeds 128 KiB".into());
75 }
76 let pack: Self =
77 serde_json::from_slice(bytes).map_err(|e| format!("Invalid avatar manifest: {e}"))?;
78 pack.validate()?;
79 Ok(pack)
80 }
81
82 pub fn validate(&self) -> Result<(), String> {
83 let count = u32::from(self.columns)
84 .saturating_mul(u32::from(self.rows))
85 .saturating_mul(self.atlases.len().try_into().unwrap_or(u32::MAX));
86 if self.version != 1
87 || !slug(&self.id)
88 || self.name.trim().is_empty()
89 || self.name.len() > 96
90 || self.name.chars().any(char::is_control)
91 || self.atlases.is_empty()
92 || self.atlases.len() > 16
93 || self
94 .atlases
95 .iter()
96 .any(|a| !relative_asset(a) || !a.ends_with(".png"))
97 || count == 0
98 || count > 128
99 || self.tile_width == 0
100 || self.tile_height == 0
101 || u32::from(self.tile_width) * u32::from(self.columns) > 2048
102 || u32::from(self.tile_height) * u32::from(self.rows) > 2048
103 || self.actions.is_empty()
104 || self.actions.len() > 64
105 || self.views.len() > 8
106 || !self.states.contains_key("rest")
107 {
108 return Err("Invalid avatar identity, atlas dimensions, or action limits".into());
109 }
110 for (id, action) in &self.actions {
111 if !slug(id)
112 || action.frames.is_empty()
113 || action.frames.len() > 64
114 || action.frames.len() != action.durations_ms.len()
115 || u32::from(action.poster) >= count
116 || action.frames.iter().any(|&f| u32::from(f) >= count)
117 || action
118 .durations_ms
119 .iter()
120 .any(|&d| !(80..=10_000).contains(&d))
121 || action
122 .durations_ms
123 .iter()
124 .map(|&d| u32::from(d))
125 .sum::<u32>()
126 > 30_000
127 {
128 return Err(format!("Invalid avatar action {id}"));
129 }
130 }
131 for (state, action) in &self.states {
132 if !ACTS.contains(&state.as_str()) || !self.actions.contains_key(action) {
133 return Err(format!("Invalid avatar state binding {state}"));
134 }
135 }
136 for (view, action) in &self.views {
137 if !slug(view) || !self.actions.contains_key(action) {
138 return Err(format!("Invalid avatar view binding {view}"));
139 }
140 }
141 Ok(())
142 }
143
144 pub fn validate_png(&self, png: &[u8]) -> Result<(), String> {
146 self.validate()?;
147 if png.len() < 33
148 || png.len() > MAX_PNG_BYTES
149 || &png[..8] != b"\x89PNG\r\n\x1a\n"
150 || png[8..12] != 13u32.to_be_bytes()
151 || &png[12..16] != b"IHDR"
152 {
153 return Err("Avatar atlas must be a bounded PNG".into());
154 }
155 let width = u32::from_be_bytes(png[16..20].try_into().unwrap());
156 let height = u32::from_be_bytes(png[20..24].try_into().unwrap());
157 if width != u32::from(self.columns) * u32::from(self.tile_width)
158 || height != u32::from(self.rows) * u32::from(self.tile_height)
159 {
160 return Err("Avatar atlas dimensions do not match the manifest".into());
161 }
162 Ok(())
163 }
164
165 pub fn sample(
168 &self,
169 state: &str,
170 frame: f64,
171 reduced: bool,
172 view: Option<&str>,
173 action: Option<&str>,
174 ) -> Frame {
175 let named = action
176 .filter(|a| self.actions.contains_key(*a))
177 .or_else(|| view.and_then(|v| self.views.get(v).map(String::as_str)))
178 .or_else(|| self.states.get(state).map(String::as_str))
179 .or_else(|| self.states.get("rest").map(String::as_str));
180 let Some(clip) = named.and_then(|name| self.actions.get(name)) else {
181 return Frame { index: 0 };
182 };
183 if reduced || !frame.is_finite() {
184 return Frame {
185 index: clip.poster as usize,
186 };
187 }
188 let total: u64 = clip.durations_ms.iter().map(|&d| u64::from(d)).sum();
189 if total == 0 {
190 return Frame {
191 index: clip.poster as usize,
192 };
193 }
194 let elapsed = (frame.max(0.) / 30. * 1000.).min(u64::MAX as f64) as u64;
195 let mut elapsed = if clip.repeat {
196 elapsed % total
197 } else {
198 elapsed.min(total - 1)
199 };
200 for (&index, &duration) in clip.frames.iter().zip(&clip.durations_ms) {
201 if elapsed < u64::from(duration) {
202 return Frame {
203 index: index as usize,
204 };
205 }
206 elapsed -= u64::from(duration);
207 }
208 Frame {
209 index: clip.poster as usize,
210 }
211 }
212}
213
214#[derive(Clone, Debug, Serialize, Deserialize)]
217#[serde(deny_unknown_fields, rename_all = "camelCase")]
218pub struct RegisteredPack {
219 pub key: String,
220 pub handle: u64,
221 pub content_hash: String,
222 pub pack: Pack,
223}
224
225impl RegisteredPack {
226 pub fn image_key(&self, page: usize) -> String {
227 format!("{}:{}:{}:{page}", self.key, self.content_hash, self.handle)
228 }
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234 fn example() -> Pack {
235 Pack::parse(br#"{"version":1,"id":"studio","name":"Studio avatar","atlases":["art/atlas.png"],"columns":2,"rows":1,"tileWidth":8,"tileHeight":8,"actions":{"wave":{"frames":[0,1],"durationsMs":[100,200],"poster":1,"repeat":true}},"states":{"rest":"wave","done":"wave"},"views":{"side":"wave"}}"#).unwrap()
236 }
237 #[test]
238 fn avatar_named_actions_share_clock_and_reduced_posters() {
239 let p = example();
240 assert_eq!(p.sample("rest", 0., false, None, None).index, 0);
241 assert_eq!(p.sample("done", 3., false, None, None).index, 1);
242 assert_eq!(p.sample("unknown", 9., false, None, None).index, 0);
243 for time in [0., f64::INFINITY, f64::NAN, 5000.] {
244 assert_eq!(p.sample("rest", time, true, None, None).index, 1);
245 }
246 assert_eq!(
247 p.sample("rest", 0., false, Some("side"), Some("missing"))
248 .index,
249 0
250 );
251 let mut p = p;
252 p.actions.get_mut("wave").unwrap().repeat = false;
253 assert_eq!(p.sample("rest", 10000., false, None, Some("wave")).index, 1);
254 }
255 #[test]
256 fn avatar_limits_and_references_are_validated_before_rendering() {
257 for path in [
258 "/absolute.png",
259 "../outside.png",
260 "a/../b.png",
261 "https://a.png",
262 "a\\b.png",
263 "a//b.png",
264 "a/./b.png",
265 ] {
266 let mut p = example();
267 p.atlases = vec![path.into()];
268 assert!(p.validate().is_err(), "{path}");
269 }
270 let mut p = example();
271 p.actions.get_mut("wave").unwrap().frames[0] = 2;
272 assert!(p.validate().is_err());
273 let mut p = example();
274 p.actions.get_mut("wave").unwrap().durations_ms[0] = 0;
275 assert!(p.validate().is_err());
276 let mut p = example();
277 p.states.insert("made-up-owner-state".into(), "wave".into());
278 assert!(p.validate().is_err());
279 let mut p = example();
280 p.tile_width = 2049;
281 assert!(p.validate().is_err());
282 let mut p = example();
283 p.columns = u16::MAX;
284 p.rows = u16::MAX;
285 p.atlases.push("another.png".into());
286 assert!(p.validate().is_err());
287 let mut p = example();
288 p.actions.clear();
289 assert_eq!(p.sample("rest", 3., false, None, None).index, 0);
290 }
291 #[test]
292 fn avatar_image_dimensions_are_checked_without_invoking_a_codec() {
293 let p = example();
294 let mut header = vec![0u8; 33];
295 header[..8].copy_from_slice(b"\x89PNG\r\n\x1a\n");
296 header[8..12].copy_from_slice(&13u32.to_be_bytes());
297 header[12..16].copy_from_slice(b"IHDR");
298 header[16..20].copy_from_slice(&16u32.to_be_bytes());
299 header[20..24].copy_from_slice(&8u32.to_be_bytes());
300 assert!(p.validate_png(&header).is_ok());
301 header[20..24].copy_from_slice(&4096u32.to_be_bytes());
302 assert!(p.validate_png(&header).is_err());
303 assert!(p.validate_png(&[]).is_err());
304 }
305}