aseprite-loader 0.4.2

Aseprite file loader
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
//! This module contains the actual loader API. This API is based on the
//! `binary`-module of this crate and does provide a convenience API for
//! accessing layers, frames, tags and fully blended images.

use flate2::Decompress;
use std::{
    collections::hash_map::DefaultHasher,
    collections::HashMap,
    hash::{Hash, Hasher},
    ops::RangeInclusive,
};

mod blend;

use crate::{
    binary::{
        blend_mode::BlendMode,
        chunks::{
            cel::CelContent,
            layer::{LayerFlags, LayerType},
            slice::SliceChunk,
            tags::AnimationDirection,
        },
        color_depth::ColorDepth,
        file::{parse_file, File},
        image::Image,
        palette::Palette,
    },
    loader::blend::{blend_mode_to_blend_fn, Color},
};

/// This can be used to load an Aseprite file.
#[derive(Debug)]
pub struct AsepriteFile<'a> {
    /// Parsed low-level file representation.
    pub file: File<'a>,
    /// All layers in the file in order
    pub layers: Vec<Layer>,
    /// All frames in the file in order
    pub frames: Vec<Frame>,
    /// All tags in the file
    pub tags: Vec<Tag>,
    /// All images in the file
    pub images: Vec<Image<'a>>,
}

/// A cel in a frame
///
/// This is a reference to an image cel
#[derive(Debug, Copy, Clone)]
pub struct FrameCel {
    /// Cel origin in sprite coordinates.
    pub origin: (i16, i16),
    /// Cel size in pixels `(width, height)`.
    pub size: (u16, u16),
    /// Index into [`AsepriteFile::layers`].
    pub layer_index: usize,
    /// Index into [`AsepriteFile::images`].
    pub image_index: usize,
}

/// A frame in the file
///
/// This is a collection of cels for each layer
#[derive(Debug, Clone)]
pub struct Frame {
    /// Frame duration in milliseconds.
    pub duration: u16,
    /// Frame origin in sprite coordinates.
    pub origin: (i16, i16),
    /// Cels in this frame.
    pub cels: Vec<FrameCel>,
}

/// A tag in the file
///
/// This is a range of frames over the frames in the file, ordered by frame index
#[derive(Debug, Clone)]
pub struct Tag {
    /// Tag name as defined in the Aseprite file.
    pub name: String,
    /// Inclusive frame range covered by this tag.
    pub range: RangeInclusive<u16>,
    /// Playback direction for this tag.
    pub direction: AnimationDirection,
    /// Optional repeat count (`None` means infinite/unspecified).
    pub repeat: Option<u16>,
}

/// A layer in the file
#[derive(Debug, Clone)]
pub struct Layer {
    /// Layer name.
    pub name: String,
    /// Layer opacity in the range `0..=255`.
    pub opacity: u8,
    /// Layer blend mode.
    pub blend_mode: BlendMode,
    /// Whether the layer is visible in the source file.
    pub visible: bool,
    /// Layer kind (normal/group/etc).
    pub layer_type: LayerType,
}

/// Pre-computed layer visibility selection for efficient per-frame filtering.
///
/// Created via [`AsepriteFile::select_layers`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LayerSelection {
    /// Render visible layers as defined in the aseprite file.
    Visible,
    /// Render all layers regardless of their visibility in the aseprite file.
    All,
    /// Render layers using a mask.
    Mask(Vec<bool>),
}

impl LayerSelection {
    fn is_selected(&self, layer_index: usize, layer: &Layer) -> bool {
        match self {
            Self::Visible => layer.visible,
            Self::All => true,
            Self::Mask(mask) => mask.get(layer_index).copied().unwrap_or(false),
        }
    }
}

impl AsepriteFile<'_> {
    /// Load a aseprite file from a byte slice
    pub fn load(data: &[u8]) -> Result<AsepriteFile<'_>, LoadSpriteError> {
        let file = parse_file(data).map_err(|e| LoadSpriteError::Parse {
            message: e.to_string(),
        })?;
        let layers: Vec<_> = file
            .layers
            .iter()
            .filter_map(|layer| {
                if layer.layer_type == LayerType::Normal || layer.layer_type == LayerType::Group {
                    Some(Layer {
                        name: layer.name.to_string(),
                        opacity: layer.opacity,
                        blend_mode: layer.blend_mode,
                        visible: layer.flags.contains(LayerFlags::VISIBLE),
                        layer_type: layer.layer_type,
                    })
                } else {
                    None
                }
            })
            .collect();

        let mut image_vec: Vec<Image<'_>> = Vec::new();
        let mut image_map: HashMap<(usize, usize), usize> = HashMap::new();

        for (frame_index, frame) in file.frames.iter().enumerate() {
            for cel in frame.cels.iter().filter_map(|x| x.as_ref()) {
                if let CelContent::Image(image) = &cel.content {
                    let image_index = image_vec.len();
                    image_vec.push(image.clone());
                    let _ = image_map.insert((frame_index, cel.layer_index.into()), image_index);
                }
            }
        }

        let mut frames: Vec<Frame> = Vec::new();
        let mut tags: Vec<Tag> = Vec::new();

        for tag in file.tags.iter() {
            tags.push(Tag {
                name: tag.name.to_string(),
                range: tag.frames.clone(),
                direction: tag.animation_direction,
                repeat: if tag.animation_repeat > 0 {
                    Some(tag.animation_repeat)
                } else {
                    None
                },
            });
        }

        for (index, frame) in file.frames.iter().enumerate() {
            let mut cels: Vec<FrameCel> = Vec::new();
            for cel in frame.cels.iter().filter_map(|x| x.as_ref()) {
                let image_index = match cel.content {
                    CelContent::Image(_) => image_map[&(index, cel.layer_index.into())],
                    CelContent::LinkedCel { frame_position } => *image_map
                        .get(&(frame_position.into(), cel.layer_index.into()))
                        .ok_or_else(|| LoadSpriteError::Parse {
                            message: format!(
                                "invalid linked cel at frame {} layer {}",
                                index, cel.layer_index
                            ),
                        })?,
                    _ => {
                        return Err(LoadSpriteError::Parse {
                            message: "invalid cel".to_owned(),
                        })
                    }
                };
                let width = image_vec[image_index].width;
                let height = image_vec[image_index].height;
                cels.push(FrameCel {
                    origin: (cel.x, cel.y),
                    size: (width, height),
                    layer_index: cel.layer_index.into(),
                    image_index,
                });
            }

            frames.push(Frame {
                duration: frame.duration,
                origin: (0, 0),
                cels,
            });
        }

        Ok(AsepriteFile {
            file,
            tags,
            layers,
            frames,
            images: image_vec,
        })
    }
    /// Get size of the sprite (width, height)
    pub fn size(&self) -> (u16, u16) {
        (self.file.header.width, self.file.header.height)
    }
    /// Get tag names
    pub fn tags(&self) -> &[Tag] {
        &self.tags
    }
    /// Get layer names
    pub fn layers(&self) -> &[Layer] {
        &self.layers
    }
    /// Get the image indices for a given tag and layer
    pub fn frames(&self) -> &[Frame] {
        &self.frames
    }
    /// Get image count
    pub fn image_count(&self) -> usize {
        self.images.len()
    }

    /// Convert layer names into a [`LayerSelection`] for use with
    /// [`render_frame`](Self::render_frame).
    ///
    /// The premise is used to select the layers which should be included.
    pub fn select_layers(&self, predicate: impl Fn(&Layer) -> bool) -> LayerSelection {
        LayerSelection::Mask(self.layers.iter().map(predicate).collect())
    }

    /// Convert layer names into a [`LayerSelection`] for use with
    /// [`render_frame`](Self::render_frame).
    ///
    /// The returned selection marks a layer as visible if its name appears
    /// in `names`. Call this once and reuse the result across frames.
    pub fn select_layers_by_name(&self, names: &[&str]) -> LayerSelection {
        self.select_layers(|l| names.contains(&l.name.as_str()))
    }

    /// Render a frame for a given frame index. This combines all visible
    /// layers into a buffer.
    ///
    /// Returns a hash describing the image, since cels can be reused in multiple frames.
    #[deprecated(note = "Use `render_frame` instead.")]
    pub fn combined_frame_image(
        &self,
        frame_index: usize,
        target: &mut [u8],
    ) -> Result<u64, LoadImageError> {
        self.render_frame(frame_index, target, &LayerSelection::Visible)?;
        let mut hasher = DefaultHasher::new();
        let frame = &self.frames[frame_index];
        for cel in frame.cels.iter() {
            (cel.image_index, cel.layer_index, cel.origin, cel.size).hash(&mut hasher);
        }
        Ok(hasher.finish())
    }

    /// Render a frame for a given frame index. This combines layers depending
    /// on the layer selection into a buffer.
    ///
    /// The `target` buffer must be at least `width * height * 4` bytes.
    /// Pixels are written as RGBA8.
    pub fn render_frame(
        &self,
        frame_index: usize,
        target: &mut [u8],
        layers: &LayerSelection,
    ) -> Result<(), LoadImageError> {
        let target_size =
            usize::from(self.file.header.width) * usize::from(self.file.header.height) * 4;

        if target.len() < target_size {
            return Err(LoadImageError::TargetBufferTooSmall);
        }

        let frame = &self.frames[frame_index];

        for cel in frame.cels.iter() {
            let Some(layer) = self.layers.get(cel.layer_index) else {
                continue;
            };
            if layer.layer_type == LayerType::Group || !layers.is_selected(cel.layer_index, layer) {
                continue;
            }

            let mut cel_target = vec![0; usize::from(cel.size.0) * usize::from(cel.size.1) * 4];
            self.load_image(cel.image_index, &mut cel_target).unwrap();
            let layer = &self.layers[cel.layer_index];

            let blend_fn = blend_mode_to_blend_fn(layer.blend_mode);

            for y in 0..cel.size.1 {
                for x in 0..cel.size.0 {
                    let Some(target_x) = x.checked_add_signed(cel.origin.0) else {
                        continue;
                    };
                    if target_x >= self.file.header.width {
                        continue;
                    }
                    let Some(target_y) = y.checked_add_signed(cel.origin.1) else {
                        continue;
                    };
                    if target_y >= self.file.header.height {
                        continue;
                    }

                    let target_index = usize::from(target_y) * usize::from(self.file.header.width)
                        + usize::from(target_x);
                    let cel_index = usize::from(y) * usize::from(cel.size.0) + usize::from(x);

                    let cel_pixel: &[u8] = &cel_target[cel_index * 4..cel_index * 4 + 4];
                    let target_pixel: &mut [u8] =
                        &mut target[target_index * 4..target_index * 4 + 4];

                    let back = Color::from(&*target_pixel);
                    let front = Color::from(cel_pixel);
                    let out = blend_fn(back, front, layer.opacity);

                    target_pixel[0] = out.r;
                    target_pixel[1] = out.g;
                    target_pixel[2] = out.b;
                    target_pixel[3] = out.a;
                }
            }
        }
        Ok(())
    }

    /// Get image loader for a given image index
    pub fn load_image(&self, index: usize, target: &mut [u8]) -> Result<(), LoadImageError> {
        let image = &self.images[index];
        let target_size = usize::from(image.width) * usize::from(image.height) * 4;
        if target.len() < target_size {
            return Err(LoadImageError::TargetBufferTooSmall);
        }
        let target = &mut target[..target_size];
        match (self.file.header.color_depth, image.compressed) {
            (ColorDepth::Rgba, false) => target.copy_from_slice(image.data),
            (ColorDepth::Rgba, true) => decompress(image.data, target)?,
            (ColorDepth::Grayscale, false) => {
                grayscale_to_rgba(image.data, target)?;
            }
            (ColorDepth::Grayscale, true) => {
                let mut buf = vec![0u8; usize::from(image.width) * usize::from(image.height) * 2];
                decompress(image.data, &mut buf)?;
                grayscale_to_rgba(&buf, target)?;
            }
            (ColorDepth::Indexed, false) => {
                indexed_to_rgba(
                    image.data,
                    self.file
                        .palette
                        .as_ref()
                        .ok_or(LoadImageError::MissingPalette)?,
                    target,
                )?;
            }
            (ColorDepth::Indexed, true) => {
                let mut buf = vec![0u8; usize::from(image.width) * usize::from(image.height)];
                decompress(image.data, &mut buf)?;
                indexed_to_rgba(
                    &buf,
                    self.file
                        .palette
                        .as_ref()
                        .ok_or(LoadImageError::MissingPalette)?,
                    target,
                )?;
            }
            (ColorDepth::Unknown(_), _) => return Err(LoadImageError::UnsupportedColorDepth),
        }
        Ok(())
    }
    /// Return all slice chunks from the source file.
    pub fn slices(&self) -> &[SliceChunk<'_>] {
        &self.file.slices
    }
}

use thiserror::Error;

/// Errors that can occur while building the high-level [`AsepriteFile`].
#[derive(Error, Debug)]
pub enum LoadSpriteError {
    /// Parsing the binary `.aseprite` content failed.
    #[error("parsing failed {message}")]
    Parse {
        /// Detailed parse failure description.
        message: String,
    },
    /// A named tag lookup failed.
    #[error("missing tag: {0}")]
    MissingTag(String),
    /// A named layer lookup failed.
    #[error("missing layer: {0}")]
    MissingLayer(String),
    /// A frame index was outside available frame bounds.
    #[error("frame index out of range: {0}")]
    FrameIndexOutOfRange(usize),
}

/// Errors that can occur while decoding image pixel data.
#[allow(missing_copy_implementations)]
#[derive(Error, Debug)]
pub enum LoadImageError {
    /// The destination buffer is not large enough.
    #[error("target buffer too small")]
    TargetBufferTooSmall,
    /// Indexed image decoding requires a palette, but none was present.
    #[error("missing palette")]
    MissingPalette,
    /// The file uses an unsupported color depth.
    #[error("unsupported color depth")]
    UnsupportedColorDepth,
    /// Zlib decompression failed.
    #[error("decompression failed")]
    DecompressError,
    /// Pixel data length did not match the expected format.
    #[error("invalid image data")]
    InvalidImageData,
}

/// Decompress zlib-compressed image bytes into `target`.
///
/// The expected output size depends on color depth and dimensions.
pub fn decompress(data: &[u8], target: &mut [u8]) -> Result<(), LoadImageError> {
    let mut decompressor = Decompress::new(true);
    match decompressor.decompress(data, target, flate2::FlushDecompress::Finish) {
        Ok(flate2::Status::Ok | flate2::Status::BufError) => Err(LoadImageError::DecompressError),
        Ok(flate2::Status::StreamEnd) => Ok(()),
        Err(_) => Err(LoadImageError::DecompressError),
    }
}

fn grayscale_to_rgba(source: &[u8], target: &mut [u8]) -> Result<(), LoadImageError> {
    if target.len() != source.len() * 2 {
        return Err(LoadImageError::InvalidImageData);
    }
    for (i, chunk) in source.chunks(2).enumerate() {
        target[i * 4] = chunk[0];
        target[i * 4 + 1] = chunk[0];
        target[i * 4 + 2] = chunk[0];
        target[i * 4 + 3] = chunk[1];
    }
    Ok(())
}

fn indexed_to_rgba(
    source: &[u8],
    palette: &Palette,
    target: &mut [u8],
) -> Result<(), LoadImageError> {
    if target.len() != source.len() * 4 {
        return Err(LoadImageError::InvalidImageData);
    }
    for (i, px) in source.iter().enumerate() {
        let color = palette.colors[usize::from(*px)];
        target[i * 4] = color.red;
        target[i * 4 + 1] = color.green;
        target[i * 4 + 2] = color.blue;
        target[i * 4 + 3] = color.alpha;
    }
    Ok(())
}

#[test]
fn test_cel() {
    use image::RgbaImage;
    use tempfile::TempDir;

    let path = "./tests/combine.aseprite";
    let file = std::fs::read(path).unwrap();
    let file = AsepriteFile::load(&file).unwrap();

    for frame in file.frames().iter() {
        for (i, cel) in frame.cels.iter().enumerate() {
            let (width, height) = cel.size;

            let mut target = vec![0; usize::from(width * height) * 4];
            file.load_image(cel.image_index, &mut target).unwrap();

            let image = RgbaImage::from_raw(u32::from(width), u32::from(height), target).unwrap();

            let tmp = TempDir::with_prefix("aseprite-loader").unwrap();
            let path = tmp.path().join(format!("cel_{}.png", i));
            image.save(path).unwrap();
        }
    }
}

#[test]
fn test_combine() {
    use image::RgbaImage;
    use tempfile::TempDir;

    let path = "./tests/combine.aseprite";
    let file = std::fs::read(path).unwrap();
    let file = AsepriteFile::load(&file).unwrap();

    let (width, height) = file.size();
    for (index, _) in file.frames().iter().enumerate() {
        let mut target = vec![0; usize::from(width * height) * 4];
        file.render_frame(index, &mut target, &LayerSelection::Visible)
            .unwrap();
        let image = RgbaImage::from_raw(u32::from(width), u32::from(height), target).unwrap();

        let tmp = TempDir::with_prefix("aseprite-loader").unwrap();
        println!("{:?}", tmp);
        let path = tmp.path().join(format!("combined_{}.png", index));
        image.save(path).unwrap();
    }
}

#[test]
fn test_visible_layers_empty_produces_blank() {
    let data = std::fs::read("./tests/layers.aseprite").unwrap();
    let file = AsepriteFile::load(&data).unwrap();
    let (width, height) = file.size();
    let mut buf = vec![0u8; usize::from(width) * usize::from(height) * 4];
    let sel = file.select_layers_by_name(&[]);
    file.render_frame(0, &mut buf, &sel).unwrap();
    assert!(
        buf.iter().all(|&b| b == 0),
        "empty layer list should produce a blank image"
    );
}

#[test]
fn test_visible_layers_single_differs_from_all() {
    let data = std::fs::read("./tests/layers.aseprite").unwrap();
    let file = AsepriteFile::load(&data).unwrap();

    let visible_normal: Vec<&str> = file
        .layers()
        .iter()
        .filter(|l| l.visible && l.layer_type != LayerType::Group)
        .map(|l| l.name.as_str())
        .collect();

    assert!(
        visible_normal.len() >= 2,
        "layers.aseprite needs at least 2 visible layers for this test"
    );

    let (width, height) = file.size();
    let buf_size = usize::from(width) * usize::from(height) * 4;

    let mut buf_all = vec![0u8; buf_size];
    file.render_frame(0, &mut buf_all, &LayerSelection::Visible)
        .unwrap();

    let sel = file.select_layers_by_name(&visible_normal[..1]);
    let mut buf_one = vec![0u8; buf_size];
    file.render_frame(0, &mut buf_one, &sel).unwrap();

    assert_ne!(
        buf_all, buf_one,
        "single layer composite should differ from all-layers composite"
    );
}

/// https://github.com/bikeshedder/aseprite-loader/issues/4
#[test]
fn test_issue_4_1() {
    let path = "./tests/issue_4_1.aseprite";
    let file = std::fs::read(path).unwrap();
    let file = AsepriteFile::load(&file).unwrap();
    let (width, height) = file.size();
    let mut buf = vec![0; usize::from(width * height) * 4];
    for idx in 0..file.frames().len() {
        file.render_frame(idx, &mut buf, &LayerSelection::Visible)
            .unwrap();
    }
}

#[test]
fn test_issue_4_2() {
    let path = "./tests/issue_4_2.aseprite";
    let file = std::fs::read(path).unwrap();
    let file = AsepriteFile::load(&file).unwrap();
    let (width, height) = file.size();
    let mut buf = vec![0; usize::from(width * height) * 4];
    for idx in 0..file.frames().len() {
        file.render_frame(idx, &mut buf, &LayerSelection::Visible)
            .unwrap();
    }
}