-
Notifications
You must be signed in to change notification settings - Fork 1
/
tatl.zig
772 lines (675 loc) · 23.3 KB
/
tatl.zig
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
const std = @import("std");
const zlib = std.compress.zlib;
const Allocator = std.mem.Allocator;
const ArrayListUnmanaged = std.ArrayListUnmanaged;
const File = std.fs.File;
const Reader = File.Reader;
pub const AsepriteImportError = error{
InvalidFile,
InvalidFrameHeader,
};
pub const ChunkType = enum(u16) {
OldPaletteA = 0x0004,
OldPaletteB = 0x0011,
Layer = 0x2004,
Cel = 0x2005,
CelExtra = 0x2006,
ColorProfile = 0x2007,
Mask = 0x2016,
Path = 0x2017,
Tags = 0x2018,
Palette = 0x2019,
UserData = 0x2020,
Slices = 0x2022,
Tileset = 0x2023,
_,
};
pub const ColorDepth = enum(u16) {
indexed = 8,
grayscale = 16,
rgba = 32,
};
pub const PaletteFlags = packed struct {
has_name: bool,
padding: u15 = 0,
};
pub const RGBA = struct {
r: u8,
g: u8,
b: u8,
a: u8,
pub fn deserializeOld(reader: Reader) !RGBA {
return RGBA{
.r = try reader.readIntLittle(u8),
.g = try reader.readIntLittle(u8),
.b = try reader.readIntLittle(u8),
.a = 255,
};
}
pub fn deserializeNew(reader: Reader) !RGBA {
return RGBA{
.r = try reader.readIntLittle(u8),
.g = try reader.readIntLittle(u8),
.b = try reader.readIntLittle(u8),
.a = try reader.readIntLittle(u8),
};
}
pub fn format(self: RGBA, comptime fmt: []const u8, options: std.fmt.FormatOptions, stream: anytype) !void {
_ = fmt;
_ = options;
try stream.print("RGBA({d:>3}, {d:>3}, {d:>3}, {d:>3})", .{ self.r, self.g, self.b, self.a });
}
};
pub const Palette = struct {
colors: []RGBA,
/// index for transparent color in indexed sprites
transparent_index: u8,
names: [][]const u8,
pub fn deserializeOld(prev_pal: Palette, reader: Reader) !Palette {
var pal = prev_pal;
const packets = try reader.readIntLittle(u16);
var skip: usize = 0;
// var i: u16 = 0;
// while (i < packets) : (i += 1) {
for (0..packets) |i| {
skip += try reader.readIntLittle(u8);
const size: u16 = val: {
const s = try reader.readIntLittle(u8);
break :val if (s == 0) @as(u16, 256) else s;
};
for (pal.colors[skip .. skip + size], 0..) |*entry, j| {
entry.* = try RGBA.deserializeOld(reader);
pal.names[skip + j] = "";
}
}
return pal;
}
pub fn deserializeNew(prev_pal: Palette, allocator: Allocator, reader: Reader) !Palette {
var pal = prev_pal;
const size = try reader.readIntLittle(u32);
if (pal.colors.len != size) {
pal.colors = try allocator.realloc(pal.colors, size);
pal.names = try allocator.realloc(pal.names, size);
}
const from = try reader.readIntLittle(u32);
const to = try reader.readIntLittle(u32);
try reader.skipBytes(8, .{});
for (pal.colors[from .. to + 1], 0..) |*entry, i| {
const flags = try reader.readStruct(PaletteFlags);
entry.* = try RGBA.deserializeNew(reader);
if (flags.has_name)
pal.names[from + i] = try readSlice(u8, u16, allocator, reader)
else
pal.names[from + i] = "";
}
return pal;
}
};
pub const LayerFlags = packed struct {
visible: bool,
editable: bool,
lock_movement: bool,
background: bool,
prefer_linked_cels: bool,
collapsed: bool,
reference: bool,
padding: u9 = 0,
};
pub const LayerType = enum(u16) {
normal,
group,
tilemap,
};
pub const LayerBlendMode = enum(u16) {
normal,
multiply,
screen,
overlay,
darken,
lighten,
color_dodge,
color_burn,
hard_light,
soft_light,
difference,
exclusion,
hue,
saturation,
color,
luminosity,
addition,
subtract,
divide,
};
pub const Layer = struct {
flags: LayerFlags,
type: LayerType,
child_level: u16,
blend_mode: LayerBlendMode,
opacity: u8,
name: []const u8,
user_data: UserData,
pub fn deserialize(allocator: Allocator, reader: Reader) !Layer {
var result: Layer = undefined;
result.flags = try reader.readStruct(LayerFlags);
result.type = try reader.readEnum(LayerType, .Little);
result.child_level = try reader.readIntLittle(u16);
try reader.skipBytes(4, .{});
result.blend_mode = try reader.readEnum(LayerBlendMode, .Little);
result.opacity = try reader.readIntLittle(u8);
try reader.skipBytes(3, .{});
result.name = try readSlice(u8, u16, allocator, reader);
result.user_data = UserData{ .text = "", .color = [4]u8{ 0, 0, 0, 0 } };
return result;
}
};
pub const ImageCel = struct {
width: u16,
height: u16,
pixels: []u8,
pub fn deserialize(
color_depth: ColorDepth,
compressed: bool,
allocator: Allocator,
reader: Reader,
) !ImageCel {
var result: ImageCel = undefined;
result.width = try reader.readIntLittle(u16);
result.height = try reader.readIntLittle(u16);
const size = @intCast(usize, result.width) *
@intCast(usize, result.height) *
@intCast(usize, @enumToInt(color_depth) / 8);
result.pixels = try allocator.alloc(u8, size);
errdefer allocator.free(result.pixels);
if (compressed) {
var zlib_stream = try zlib.zlibStream(allocator, reader);
defer zlib_stream.deinit();
_ = try zlib_stream.reader().readAll(result.pixels);
} else {
try reader.readNoEof(result.pixels);
}
return result;
}
};
pub const LinkedCel = struct {
frame: u16,
pub fn deserialize(reader: Reader) !LinkedCel {
return LinkedCel{ .frame = try reader.readIntLittle(u16) };
}
};
pub const CelType = enum(u16) {
raw_image,
linked,
compressed_image,
compressed_tilemap,
};
pub const CelData = union(CelType) {
raw_image: ImageCel,
linked: LinkedCel,
compressed_image: ImageCel,
compressed_tilemap: void,
};
pub const Cel = struct {
layer: u16,
x: i16,
y: i16,
opacity: u8,
data: CelData,
extra: CelExtra,
user_data: UserData,
pub fn deserialize(color_depth: ColorDepth, allocator: Allocator, reader: Reader) !Cel {
var result: Cel = undefined;
result.layer = try reader.readIntLittle(u16);
result.x = try reader.readIntLittle(i16);
result.y = try reader.readIntLittle(i16);
result.opacity = try reader.readIntLittle(u8);
const cel_type = try reader.readEnum(CelType, .Little);
try reader.skipBytes(7, .{});
result.data = switch (cel_type) {
.raw_image => CelData{
.raw_image = try ImageCel.deserialize(color_depth, false, allocator, reader),
},
.linked => CelData{
.linked = try LinkedCel.deserialize(reader),
},
.compressed_image => CelData{
.compressed_image = try ImageCel.deserialize(color_depth, true, allocator, reader),
},
.compressed_tilemap => CelData{
.compressed_tilemap = void{},
},
};
result.extra = CelExtra{ .x = 0, .y = 0, .width = 0, .height = 0 };
result.user_data = UserData{ .text = "", .color = [4]u8{ 0, 0, 0, 0 } };
return result;
}
};
pub const CelExtraFlags = packed struct {
precise_bounds: bool,
padding: u31 = 0,
};
/// This contains values stored in fixed point numbers stored in u32's, do not try to use these values directly
pub const CelExtra = struct {
x: u32,
y: u32,
width: u32,
height: u32,
pub fn isEmpty(self: CelExtra) bool {
return @bitCast(u128, self) == 0;
}
pub fn deserialize(reader: Reader) !CelExtra {
const flags = try reader.readStruct(CelExtraFlags);
if (flags.precise_bounds) {
return CelExtra{
.x = try reader.readIntLittle(u32),
.y = try reader.readIntLittle(u32),
.width = try reader.readIntLittle(u32),
.height = try reader.readIntLittle(u32),
};
} else {
return CelExtra{
.x = 0,
.y = 0,
.width = 0,
.height = 0,
};
}
}
};
pub const ColorProfileType = enum(u16) {
none,
srgb,
icc,
};
pub const ColorProfileFlags = packed struct {
special_fixed_gamma: bool,
padding: u15 = 0,
};
pub const ColorProfile = struct {
type: ColorProfileType,
flags: ColorProfileFlags,
/// this is a fixed point value stored in a u32, do not try to use it directly
gamma: u32,
icc_data: []const u8,
pub fn deserialize(allocator: Allocator, reader: Reader) !ColorProfile {
var result: ColorProfile = undefined;
result.type = try reader.readEnum(ColorProfileType, .Little);
result.flags = try reader.readStruct(ColorProfileFlags);
result.gamma = try reader.readIntLittle(u32);
try reader.skipBytes(8, .{});
// zig fmt: off
result.icc_data = if (result.type == .icc)
try readSlice(u8, u32, allocator, reader)
else
&[0]u8{};
// zig fmt: on
return result;
}
};
pub const AnimationDirection = enum(u8) {
forward,
reverse,
pingpong,
};
pub const Tag = struct {
from: u16,
to: u16,
direction: AnimationDirection,
color: [3]u8,
name: []const u8,
pub fn deserialize(allocator: Allocator, reader: Reader) !Tag {
var result: Tag = undefined;
result.from = try reader.readIntLittle(u16);
result.to = try reader.readIntLittle(u16);
result.direction = try reader.readEnum(AnimationDirection, .Little);
try reader.skipBytes(8, .{});
result.color = try reader.readBytesNoEof(3);
try reader.skipBytes(1, .{});
result.name = try readSlice(u8, u16, allocator, reader);
return result;
}
pub fn deserializeAll(allocator: Allocator, reader: Reader) ![]Tag {
const len = try reader.readIntLittle(u16);
try reader.skipBytes(8, .{});
const result = try allocator.alloc(Tag, len);
errdefer allocator.free(result);
for (result) |*tag| {
tag.* = try Tag.deserialize(allocator, reader);
}
return result;
}
};
pub const UserDataFlags = packed struct {
has_text: bool,
has_color: bool,
padding: u14 = 0,
};
pub const UserData = struct {
text: []const u8,
color: [4]u8,
pub const empty = UserData{ .text = "", .color = [4]u8{ 0, 0, 0, 0 } };
pub fn isEmpty(user_data: UserData) bool {
return user_data.text.len == 0 and @bitCast(u32, user_data.color) == 0;
}
pub fn deserialize(allocator: Allocator, reader: Reader) !UserData {
var result: UserData = undefined;
const flags = try reader.readStruct(UserDataFlags);
// zig fmt: off
result.text = if (flags.has_text)
try readSlice(u8, u16, allocator, reader)
else
"";
result.color = if (flags.has_color)
try reader.readBytesNoEof(4)
else
[4]u8{ 0, 0, 0, 0 };
// zig fmt: on
return result;
}
};
const UserDataChunks = union(enum) {
Layer: *Layer,
Cel: *Cel,
Slice: *Slice,
pub fn new(pointer: anytype) UserDataChunks {
const name = comptime value: {
const type_name = @typeName(@typeInfo(@TypeOf(pointer)).Pointer.child);
var iterator = std.mem.splitBackwards(u8, type_name, ".");
break :value iterator.first();
};
return @unionInit(UserDataChunks, name, pointer);
}
pub fn setUserData(self: UserDataChunks, user_data: UserData) void {
switch (self) {
.Layer => |p| p.*.user_data = user_data,
.Cel => |p| p.*.user_data = user_data,
.Slice => |p| p.*.user_data = user_data,
}
}
};
pub const SliceFlags = packed struct {
nine_patch: bool,
has_pivot: bool,
padding: u30 = 0,
};
pub const SliceKey = struct {
frame: u32,
x: i32,
y: i32,
width: u32,
height: u32,
center: struct {
x: i32,
y: i32,
width: u32,
height: u32,
},
pivot: struct {
x: i32,
y: i32,
},
pub fn deserialize(flags: SliceFlags, reader: Reader) !SliceKey {
var result: SliceKey = undefined;
result.frame = try reader.readIntLittle(u32);
result.x = try reader.readIntLittle(i32);
result.y = try reader.readIntLittle(i32);
result.width = try reader.readIntLittle(u32);
result.height = try reader.readIntLittle(u32);
result.center = if (flags.nine_patch) .{
.x = try reader.readIntLittle(i32),
.y = try reader.readIntLittle(i32),
.width = try reader.readIntLittle(u32),
.height = try reader.readIntLittle(u32),
} else .{
.x = 0,
.y = 0,
.width = 0,
.height = 0,
};
result.pivot = if (flags.has_pivot) .{
.x = try reader.readIntLittle(i32),
.y = try reader.readIntLittle(i32),
} else .{
.x = 0,
.y = 0,
};
return result;
}
};
pub const Slice = struct {
flags: SliceFlags,
name: []const u8,
keys: []SliceKey,
user_data: UserData,
pub fn deserialize(allocator: Allocator, reader: Reader) !Slice {
var result: Slice = undefined;
const key_len = try reader.readIntLittle(u32);
result.flags = try reader.readStruct(SliceFlags);
try reader.skipBytes(4, .{});
result.name = try readSlice(u8, u16, allocator, reader);
errdefer allocator.free(result.name);
result.keys = try allocator.alloc(SliceKey, key_len);
errdefer allocator.free(result.keys);
for (result.keys) |*key| {
key.* = try SliceKey.deserialize(result.flags, reader);
}
result.user_data = UserData{ .text = "", .color = [4]u8{ 0, 0, 0, 0 } };
return result;
}
};
pub const Frame = struct {
/// frame duration in miliseconds
duration: u16,
/// images contained within the frame
cels: []Cel,
pub const magic: u16 = 0xF1FA;
};
pub const FileHeaderFlags = packed struct {
layer_with_opacity: bool,
padding: u31 = 0,
};
pub const AsepriteImport = struct {
width: u16,
height: u16,
color_depth: ColorDepth,
flags: FileHeaderFlags,
pixel_width: u8,
pixel_height: u8,
grid_x: i16,
grid_y: i16,
/// zero if no grid
grid_width: u16,
/// zero if no grid
grid_height: u16,
palette: Palette,
color_profile: ColorProfile,
layers: []Layer,
slices: []Slice,
tags: []Tag,
frames: []Frame,
pub const magic: u16 = 0xA5E0;
pub fn deserialize(allocator: Allocator, reader: Reader) !AsepriteImport {
var result: AsepriteImport = undefined;
try reader.skipBytes(4, .{});
if (magic != try reader.readIntLittle(u16)) {
return error.InvalidFile;
}
const frame_count = try reader.readIntLittle(u16);
result.width = try reader.readIntLittle(u16);
result.height = try reader.readIntLittle(u16);
result.color_depth = try reader.readEnum(ColorDepth, .Little);
result.flags = try reader.readStruct(FileHeaderFlags);
try reader.skipBytes(10, .{});
const transparent_index = try reader.readIntLittle(u8);
try reader.skipBytes(3, .{});
var color_count = try reader.readIntLittle(u16);
result.pixel_width = try reader.readIntLittle(u8);
result.pixel_height = try reader.readIntLittle(u8);
result.grid_x = try reader.readIntLittle(i16);
result.grid_y = try reader.readIntLittle(i16);
result.grid_width = try reader.readIntLittle(u16);
result.grid_height = try reader.readIntLittle(u16);
if (color_count == 0)
color_count = 256;
if (result.pixel_width == 0 or result.pixel_height == 0) {
result.pixel_width = 1;
result.pixel_height = 1;
}
try reader.skipBytes(84, .{});
result.palette = Palette{
.colors = try allocator.alloc(RGBA, color_count),
.transparent_index = transparent_index,
.names = try allocator.alloc([]const u8, color_count),
};
errdefer {
allocator.free(result.palette.colors);
allocator.free(result.palette.names);
}
result.slices = &.{};
result.tags = &.{};
result.frames = try allocator.alloc(Frame, frame_count);
errdefer allocator.free(result.frames);
var layers = try ArrayListUnmanaged(Layer).initCapacity(allocator, 1);
errdefer layers.deinit(allocator);
var slices = try ArrayListUnmanaged(Slice).initCapacity(allocator, 0);
errdefer slices.deinit(allocator);
var using_new_palette = false;
var last_with_user_data: ?UserDataChunks = null;
for (result.frames) |*frame| {
var cels = try ArrayListUnmanaged(Cel).initCapacity(allocator, 0);
errdefer cels.deinit(allocator);
var last_cel: ?*Cel = null;
try reader.skipBytes(4, .{});
if (Frame.magic != try reader.readIntLittle(u16)) {
return error.InvalidFrameHeader;
}
const old_chunks = try reader.readIntLittle(u16);
frame.duration = try reader.readIntLittle(u16);
try reader.skipBytes(2, .{});
const new_chunks = try reader.readIntLittle(u32);
const chunks = if (old_chunks == 0xFFFF and old_chunks < new_chunks)
new_chunks
else
old_chunks;
// var i: u32 = 0;
// while (i < chunks) : (i += 1) {
for (0..chunks) |i| {
const chunk_start = try reader.context.getPos();
const chunk_size = try reader.readIntLittle(u32);
const chunk_end = chunk_start + chunk_size;
const chunk_type = try reader.readEnum(ChunkType, .Little);
switch (chunk_type) {
.OldPaletteA, .OldPaletteB => {
if (!using_new_palette)
result.palette = try Palette.deserializeOld(result.palette, reader);
},
.Layer => {
try layers.append(allocator, try Layer.deserialize(allocator, reader));
last_with_user_data = UserDataChunks.new(&layers.items[layers.items.len - 1]);
},
.Cel => {
try cels.append(
allocator,
try Cel.deserialize(
result.color_depth,
allocator,
reader,
),
);
last_cel = &cels.items[cels.items.len - 1];
last_with_user_data = UserDataChunks.new(last_cel.?);
},
.CelExtra => {
const extra = try CelExtra.deserialize(reader);
if (last_cel) |c| {
c.extra = extra;
last_cel = null;
} else {
std.log.err("{s}\n", .{"Found extra cel chunk without cel to attach it to!"});
}
},
.ColorProfile => {
result.color_profile = try ColorProfile.deserialize(allocator, reader);
},
.Tags => {
result.tags = try Tag.deserializeAll(allocator, reader);
},
.Palette => {
using_new_palette = true;
result.palette = try Palette.deserializeNew(
result.palette,
allocator,
reader,
);
},
.UserData => {
const user_data = try UserData.deserialize(allocator, reader);
if (last_with_user_data) |chunk| {
chunk.setUserData(user_data);
last_with_user_data = null;
} else {
std.log.err("{s}\n", .{"Found user data chunk without chunk to attach it to!"});
}
},
.Slices => {
try slices.append(allocator, try Slice.deserialize(allocator, reader));
last_with_user_data = UserDataChunks.new(&slices.items[slices.items.len - 1]);
},
else => std.log.err("{s}: {x}\n", .{ "Unsupported chunk type", chunk_type }),
}
try reader.context.seekTo(chunk_end);
}
frame.cels = cels.toOwnedSlice(allocator);
errdefer allocator.free(frame.cels);
}
result.layers = layers.toOwnedSlice(allocator);
result.slices = slices.toOwnedSlice(allocator);
return result;
}
pub fn free(self: AsepriteImport, allocator: Allocator) void {
allocator.free(self.palette.colors);
for (self.palette.names) |name| {
if (name.len > 0)
allocator.free(name);
}
allocator.free(self.palette.names);
allocator.free(self.color_profile.icc_data);
for (self.layers) |layer| {
allocator.free(layer.name);
allocator.free(layer.user_data.text);
}
allocator.free(self.layers);
for (self.slices) |slice| {
allocator.free(slice.name);
allocator.free(slice.keys);
allocator.free(slice.user_data.text);
}
allocator.free(self.slices);
for (self.tags) |tag| {
allocator.free(tag.name);
}
allocator.free(self.tags);
for (self.frames) |frame| {
for (frame.cels) |cel| {
allocator.free(cel.user_data.text);
switch (cel.data) {
.raw_image => |raw| allocator.free(raw.pixels),
.compressed_image => |compressed| allocator.free(compressed.pixels),
else => {},
}
}
allocator.free(frame.cels);
}
allocator.free(self.frames);
}
};
fn readSlice(comptime SliceT: type, comptime LenT: type, allocator: Allocator, reader: Reader) ![]SliceT {
const len = (try reader.readIntLittle(LenT)) * @sizeOf(SliceT);
var bytes = try allocator.alloc(u8, len);
errdefer allocator.free(bytes);
try reader.readNoEof(bytes);
return std.mem.bytesAsSlice(SliceT, bytes);
}
pub fn import(allocator: Allocator, reader: Reader) !AsepriteImport {
return AsepriteImport.deserialize(allocator, reader);
}