1use std::time::Duration;
20
21use nadir_assets::{
22 Asset, AssetError, AssetPath, AssetServer, DecodeCtx, FinalizeCtx, Handle, Scope,
23};
24use nadir_codec::atlas::{self, SpriteKind};
25use nadir_core::{Rect, UVec2, Vec2};
26
27use crate::{Texture, TileSet};
28
29#[derive(Clone, Debug, PartialEq)]
39pub struct Atlas {
40 pages: Vec<AtlasPage>,
41 sprites: Vec<AtlasSprite>,
42}
43
44#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct AtlasPage {
47 path: String,
48 size: UVec2,
49}
50
51#[derive(Clone, Debug, PartialEq)]
54pub struct AtlasSprite {
55 name: String,
56 frames: Vec<AtlasFrame>,
57 pivot: Option<Vec2>,
58 tile_size: Option<UVec2>,
59 clips: Vec<AtlasClip>,
60}
61
62#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct AtlasClip {
67 name: String,
68 looping: bool,
69 frames: Vec<AtlasClipFrame>,
70}
71
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub struct AtlasClipFrame {
75 frame: usize,
76 duration: Duration,
77}
78
79#[derive(Clone, Copy, Debug, PartialEq)]
82pub struct AtlasFrame {
83 page: usize,
84 uv: Rect,
85 size: UVec2,
86 offset: UVec2,
87 source_size: UVec2,
88}
89
90impl Atlas {
91 pub fn pages(&self) -> &[AtlasPage] {
93 &self.pages
94 }
95
96 pub fn page(&self, frame: &AtlasFrame) -> Option<&AtlasPage> {
98 self.pages.get(frame.page)
99 }
100
101 pub fn load_pages(&self, server: &mut AssetServer, scope: Scope) -> Vec<Handle<Texture>> {
106 self.pages
107 .iter()
108 .map(|page| server.load_in(&page.path, scope))
109 .collect()
110 }
111
112 pub fn sprites(&self) -> &[AtlasSprite] {
114 &self.sprites
115 }
116
117 pub fn sprite(&self, name: &str) -> Option<&AtlasSprite> {
120 let index = self
121 .sprites
122 .binary_search_by(|sprite| sprite.name.as_bytes().cmp(name.as_bytes()))
123 .ok()?;
124 self.sprites.get(index)
125 }
126}
127
128impl AtlasPage {
129 pub fn path(&self) -> &str {
132 &self.path
133 }
134
135 pub fn size(&self) -> UVec2 {
137 self.size
138 }
139}
140
141impl AtlasSprite {
142 pub fn name(&self) -> &str {
144 &self.name
145 }
146
147 pub fn frames(&self) -> &[AtlasFrame] {
149 &self.frames
150 }
151
152 pub fn frame(&self, index: usize) -> Option<&AtlasFrame> {
154 self.frames.get(index)
155 }
156
157 pub fn pivot(&self) -> Option<Vec2> {
160 self.pivot
161 }
162
163 pub fn tile_size(&self) -> Option<UVec2> {
165 self.tile_size
166 }
167
168 pub fn clips(&self) -> &[AtlasClip] {
171 &self.clips
172 }
173
174 pub fn clip(&self, name: &str) -> Option<&AtlasClip> {
176 let index = self
177 .clips
178 .binary_search_by(|clip| clip.name.as_bytes().cmp(name.as_bytes()))
179 .ok()?;
180 self.clips.get(index)
181 }
182
183 pub fn tile_set(&self, texture: Handle<Texture>) -> Option<TileSet> {
185 let tile = self.tile_size?;
186 let size = self.frames.first()?.source_size;
187 Some(TileSet {
188 texture,
189 columns: u16::try_from(size.x / tile.x).ok()?,
190 rows: u16::try_from(size.y / tile.y).ok()?,
191 })
192 }
193}
194
195impl AtlasClip {
196 pub fn name(&self) -> &str {
198 &self.name
199 }
200
201 pub fn is_looping(&self) -> bool {
204 self.looping
205 }
206
207 pub fn frames(&self) -> &[AtlasClipFrame] {
209 &self.frames
210 }
211}
212
213impl AtlasClipFrame {
214 pub fn frame(&self) -> usize {
216 self.frame
217 }
218
219 pub fn duration(&self) -> Duration {
221 self.duration
222 }
223}
224
225impl AtlasFrame {
226 pub fn page(&self) -> usize {
228 self.page
229 }
230
231 pub fn uv(&self) -> Rect {
234 self.uv
235 }
236
237 pub fn size(&self) -> UVec2 {
239 self.size
240 }
241
242 pub fn offset(&self) -> UVec2 {
244 self.offset
245 }
246
247 pub fn source_size(&self) -> UVec2 {
249 self.source_size
250 }
251
252 pub fn is_empty(&self) -> bool {
254 self.size == UVec2::ZERO
255 }
256
257 pub fn pivot_in(&self, pivot: Vec2) -> Vec2 {
263 if self.is_empty() {
264 return pivot / self.source_size.as_vec2();
265 }
266 (pivot - self.offset.as_vec2()) / self.size.as_vec2()
267 }
268}
269
270impl Asset for Atlas {
271 type Decoded = Atlas;
272 const EXTENSIONS: &'static [&'static str] = &["kbj"];
273
274 fn decode(bytes: &[u8], ctx: &DecodeCtx<'_>) -> Result<Atlas, AssetError> {
275 let file = atlas::parse(bytes, ctx.limits()).map_err(AssetError::Decode)?;
276 let mut pages = Vec::with_capacity(file.pages.len());
277 for (index, page) in file.pages.into_iter().enumerate() {
278 let path = AssetPath::new(&page.path)
279 .ok()
280 .filter(|path| path.as_str() == page.path && path.extension() == Some("qoi"))
281 .ok_or_else(|| {
282 AssetError::Invalid(format!(
283 "page {index}, `{}`, is not the path of a QOI texture",
284 page.path
285 ))
286 })?;
287 pages.push(AtlasPage {
288 path: path.as_str().to_string(),
289 size: UVec2::new(page.width, page.height),
290 });
291 }
292 let sprites = file
293 .sprites
294 .into_iter()
295 .map(|sprite| AtlasSprite {
296 name: sprite.name,
297 frames: sprite
298 .frames
299 .iter()
300 .map(|frame| AtlasFrame::new(frame, &pages))
301 .collect(),
302 pivot: match sprite.kind {
303 SpriteKind::Pivot([x, y]) => Some(Vec2::new(x, y)),
304 _ => None,
305 },
306 tile_size: match sprite.kind {
307 SpriteKind::Tiles([w, h]) => Some(UVec2::new(w, h)),
308 _ => None,
309 },
310 clips: sprite
311 .clips
312 .into_iter()
313 .map(|clip| AtlasClip {
314 name: clip.name,
315 looping: clip.looping,
316 frames: clip
317 .frames
318 .iter()
319 .map(|step| AtlasClipFrame {
320 frame: step.frame as usize,
321 duration: Duration::from_millis(u64::from(step.millis)),
322 })
323 .collect(),
324 })
325 .collect(),
326 })
327 .collect();
328 Ok(Atlas { pages, sprites })
329 }
330
331 fn finalize(decoded: Atlas, _: &mut FinalizeCtx<'_>) -> Result<Self, AssetError> {
332 Ok(decoded)
333 }
334}
335
336impl AtlasFrame {
337 fn new(frame: &atlas::Frame, pages: &[AtlasPage]) -> Self {
340 let page = frame.page as usize;
341 let page_size = pages
342 .get(page)
343 .map_or(Vec2::ONE, |page| page.size.as_vec2());
344 let corner = Vec2::new(frame.x as f32, frame.y as f32);
345 let size = UVec2::new(frame.width, frame.height);
346 Self {
347 page,
348 uv: Rect::new(corner / page_size, (corner + size.as_vec2()) / page_size),
349 size,
350 offset: UVec2::new(frame.offset_x, frame.offset_y),
351 source_size: UVec2::new(frame.source_width, frame.source_height),
352 }
353 }
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359 use nadir_codec::{Limits, json, kbj};
360
361 fn decoded(text: &str) -> Result<Atlas, AssetError> {
363 let value = json::parse(text, Limits::default()).expect("the test's JSON");
364 let bytes = kbj::encode(&value, Limits::default()).expect("encodable");
365 Atlas::decode(
366 &bytes,
367 &DecodeCtx::new("atlas/sprites.kbj", Limits::default()),
368 )
369 }
370
371 const ATLAS: &str = r#"{ "version": 2,
372 "pages": [ { "path": "atlas/sprites_0.qoi", "w": 128, "h": 128 },
373 { "path": "atlas/sprites/tiles.tiles.qoi", "w": 128, "h": 64 } ],
374 "sprites": [
375 { "name": "sprites/person",
376 "frames": [ { "page": 0, "x": 33, "y": 85, "w": 10, "h": 20, "ox": 1, "oy": 0, "sw": 12, "sh": 20 },
377 { "page": 0, "x": 0, "y": 0, "w": 0, "h": 0, "ox": 0, "oy": 0, "sw": 12, "sh": 20 } ],
378 "pivot": [6.0, 20.0],
379 "clips": [ { "name": "blink", "loop": false, "frames": [[0, 250], [1, 40], [0, 1000]] },
380 { "name": "stand", "loop": true, "frames": [[0, 100]] } ] },
381 { "name": "sprites/tiles",
382 "frames": [ { "page": 1, "x": 0, "y": 0, "w": 128, "h": 64, "ox": 0, "oy": 0, "sw": 128, "sh": 64 } ],
383 "tiles": [16, 16] },
384 { "name": "sprites/tree",
385 "frames": [ { "page": 0, "x": 1, "y": 1, "w": 24, "h": 44, "ox": 0, "oy": 4, "sw": 24, "sh": 48 } ],
386 "pivot": [12.0, 48.0] } ] }"#;
387
388 #[test]
389 fn sprites_are_found_by_name_with_their_regions() {
390 let atlas = decoded(ATLAS).expect("an atlas");
391 assert_eq!(atlas.pages().len(), 2);
392 assert_eq!(atlas.pages()[1].path(), "atlas/sprites/tiles.tiles.qoi");
393 assert_eq!(atlas.pages()[1].size(), UVec2::new(128, 64));
394 assert!(atlas.sprite("sprites/rock").is_none());
395 assert!(atlas.sprite("sprites").is_none());
396
397 let person = atlas.sprite("sprites/person").expect("the person");
398 assert_eq!(person.name(), "sprites/person");
399 assert_eq!(person.pivot(), Some(Vec2::new(6.0, 20.0)));
400 assert_eq!(person.tile_size(), None);
401 let frame = person.frame(0).expect("a frame");
402 assert_eq!(frame.page(), 0);
403 assert_eq!(
404 frame.uv(),
405 Rect::new(
406 Vec2::new(33.0 / 128.0, 85.0 / 128.0),
407 Vec2::new(43.0 / 128.0, 105.0 / 128.0)
408 )
409 );
410 assert_eq!(
411 (frame.size(), frame.offset(), frame.source_size()),
412 (UVec2::new(10, 20), UVec2::new(1, 0), UVec2::new(12, 20))
413 );
414 assert_eq!(
415 atlas.page(frame).map(AtlasPage::path),
416 Some("atlas/sprites_0.qoi")
417 );
418 assert!(!frame.is_empty());
419 assert!(person.frame(1).expect("a frame").is_empty());
420 assert!(person.frame(2).is_none());
421 }
422
423 #[test]
424 fn a_trimmed_frame_s_pivot_keeps_its_pixels_where_the_cell_had_them() {
425 let atlas = decoded(ATLAS).expect("an atlas");
426 let tree = atlas.sprite("sprites/tree").expect("the tree");
427 let frame = tree.frames()[0];
428 let pivot = frame.pivot_in(tree.pivot().expect("a pivot"));
430 assert_eq!(pivot, Vec2::new(0.5, 1.0));
431 let feet = Vec2::new(100.0, 200.0);
434 let corner = feet - pivot * frame.size().as_vec2();
435 let cell = feet - Vec2::new(12.0, 48.0);
436 assert_eq!(corner, cell + frame.offset().as_vec2());
437
438 let person = atlas.sprite("sprites/person").expect("the person");
439 let pivot = person.pivot().expect("a pivot");
440 assert_eq!(person.frames()[0].pivot_in(pivot), Vec2::new(0.5, 1.0));
441 assert_eq!(person.frames()[1].pivot_in(pivot), Vec2::new(0.5, 1.0));
443 }
444
445 #[test]
446 fn a_tile_set_gives_its_grid() {
447 let atlas = decoded(ATLAS).expect("an atlas");
448 let tiles = atlas.sprite("sprites/tiles").expect("the tiles");
449 assert_eq!(tiles.tile_size(), Some(UVec2::new(16, 16)));
450 assert_eq!(tiles.pivot(), None);
451 let texture = Handle::new(nadir_core::GenIndex::new(0, std::num::NonZeroU32::MIN));
452 let set = tiles.tile_set(texture).expect("a tile set");
453 assert_eq!((set.texture, set.columns, set.rows), (texture, 8, 4));
454 let tree = atlas.sprite("sprites/tree").expect("the tree");
455 assert_eq!(tree.tile_set(texture), None);
456 }
457
458 #[test]
459 fn a_page_whose_path_is_not_a_qoi_asset_path_is_refused() {
460 for path in [
461 "atlas/../page.qoi",
462 "atlas/page.png",
463 "Atlas/page.qoi",
464 "/atlas/page.qoi",
465 ] {
466 let text = ATLAS.replacen("atlas/sprites_0.qoi", path, 1);
467 assert_eq!(
468 decoded(&text),
469 Err(AssetError::Invalid(format!(
470 "page 0, `{path}`, is not the path of a QOI texture"
471 ))),
472 "{path}"
473 );
474 }
475 for version in [1, 9] {
478 let text = ATLAS.replacen(r#""version": 2"#, &format!(r#""version": {version}"#), 1);
479 assert!(text.contains(&format!(r#""version": {version}"#)));
480 assert!(
481 matches!(
482 decoded(&text),
483 Err(AssetError::Decode(nadir_codec::CodecError::Atlas { ref at, .. })) if at == "version"
484 ),
485 "version {version}"
486 );
487 }
488 }
489
490 #[test]
491 fn a_sprite_s_clips_are_found_by_name_with_their_frames_and_times() {
492 let atlas = decoded(ATLAS).expect("an atlas");
493 let person = atlas.sprite("sprites/person").expect("the person");
494 let names: Vec<&str> = person.clips().iter().map(AtlasClip::name).collect();
495 assert_eq!(names, ["blink", "stand"]);
496 let blink = person.clip("blink").expect("a clip");
497 assert!(!blink.is_looping());
498 let steps: Vec<(usize, Duration)> = blink
499 .frames()
500 .iter()
501 .map(|step| (step.frame(), step.duration()))
502 .collect();
503 assert_eq!(
504 steps,
505 [
506 (0, Duration::from_millis(250)),
507 (1, Duration::from_millis(40)),
508 (0, Duration::from_secs(1)),
509 ]
510 );
511 assert!(person.clip("stand").expect("a clip").is_looping());
512 assert!(person.clip("walk").is_none());
513 assert!(person.clip("").is_none());
514 assert!(
516 atlas
517 .sprite("sprites/tree")
518 .expect("the tree")
519 .clips()
520 .is_empty()
521 );
522 assert!(
523 atlas
524 .sprite("sprites/tiles")
525 .expect("the tiles")
526 .clips()
527 .is_empty()
528 );
529 }
530
531 #[test]
532 fn its_pages_load_as_textures_in_the_scope_given() {
533 let atlas = decoded(ATLAS).expect("an atlas");
534 let mut server = AssetServer::new("no-such-folder", nadir_assets::OnFailure::Nothing);
535 let pages = atlas.load_pages(&mut server, Scope::Level);
536 assert_eq!(pages.len(), 2);
537 assert_eq!(server.path(pages[0]), Some("atlas/sprites_0.qoi"));
538 assert_eq!(server.path(pages[1]), Some("atlas/sprites/tiles.tiles.qoi"));
539 assert_eq!(server.unload_scope(Scope::Level), 2);
541 assert_eq!(server.state(pages[0]), None);
542 }
543
544 #[test]
545 fn it_is_made_with_nothing_in_its_context() {
546 let atlas = decoded(ATLAS).expect("an atlas");
547 let made = Atlas::finalize(atlas.clone(), &mut FinalizeCtx::new());
548 assert_eq!(made, Ok(atlas));
549 }
550}