Repository navigation
Expand file tree
/
Copy pathPrepared.zig
More file actions
956 lines (891 loc) · 49.9 KB
/
Copy pathPrepared.zig
File metadata and controls
956 lines (891 loc) · 49.9 KB
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
//! The game's and mods' blocks as rendering needs them, prepared once from their assets so a
//! render never reads assets itself (docs/blocks.md#preparing-blocks), in six sections of the
//! prepared blocks file: `block_states`, `materials`, `colour_codes`, `texture_colours`, `colour_maps`
//! and `domains` (docs/storyblk/spec.md).
const Prepared = @This();
const std = @import("std");
const Io = std.Io;
const world = @import("world");
const console = @import("console");
const storyblk = @import("storyblk");
const Assets = @import("Assets.zig");
const BlockTypes = @import("BlockTypes.zig");
const textureColours = @import("TextureColours.zig");
const Tables = storyblk.Tables;
const TextureColours = Tables.TextureColours;
const Json = @import("Json.zig");
const Tint = @import("Tint.zig");
const stb = @import("stb_image");
arena: std.heap.ArenaAllocator,
gameVersion: []const u8 = "",
mods: []const storyblk.Mod = &.{},
/// The domains the game and mods have assets in.
domains: std.StringHashMapUnmanaged(void) = .empty,
/// Every block, by its code as a save names it.
blocks: std.StringHashMapUnmanaged(Block) = .empty,
pub const Block = struct {
/// Its index in the `block_states` section, from 0.
index: u32 = 0,
/// One of `BlockTypes.materials`, e.g. "Stone".
material: []const u8,
/// Its colour on the game's map, e.g. "land" or "forest" (docs/blocks.md#block-colours).
colorCode: []const u8,
/// Its texture's average colour and grain, from the textures the game's colour-accurate map
/// uses (`BlockTypes.Textures`), where readable.
colour: ?world.Rgb = null,
grain: []const world.Rgb = &.{},
/// The colour maps tinting it by climate and season, where it has them and they're readable.
climateColourMap: ?*const Tint.ColourMap = null,
seasonColourMap: ?*const Tint.ColourMap = null,
/// For a block the game draws as a plain cube, its faces' images; null for any other, or
/// one with a face that can't be read. Only while preparing (`prepare`): the file keeps its
/// sprites instead.
cube: ?world.CubeFaces = null,
/// How high its selection box reaches, in sixteenths of a block; null for the whole block.
height: ?u8 = null,
/// For a block the game draws in a shape other than the plain cube, the shapes it picks one
/// of for each block, by where it is (`BlockTypes.Block.shapes`), the first its own; empty for
/// any other, or one whose shapes can't be read. One with nothing to draw has no boxes. Only
/// while preparing, as `cube`.
shapes: []const world.Shape = &.{},
/// How it's moved off the middle of its place by where it is (`BlockTypes.Block.drawOffset`).
drawOffset: u8 = 0,
randomizeAxes: BlockTypes.Axes = .xyz,
/// Whether it's turned about its vertical middle by where it is.
randomizeRotations: bool = false,
/// How many eighths of a block of snow are drawn under it (`BlockTypes.Block.snowLayer`). Only
/// while preparing: the file keeps the sprite instead.
snowLayer: u8 = 0,
/// Glass, water or ice that shows what's behind it (`BlockTypes.Block.seeThrough`).
seeThrough: bool = false,
/// Its sprites, drawn from its `cube` or `shapes` (`Contents.useSprites`).
sprites: world.BlockSprites = .{},
};
const Image = world.Image;
/// How the six sections' contents are read from the game's assets: raise it when that changes,
/// so files prepared before are prepared again.
pub const generatorVersion: u16 = 29;
/// The game, as the file's `info` names it.
pub const game = "vintagestory";
/// Where the prepared blocks file goes when no path is given, relative to the current folder.
pub const defaultPath = game ++ ".storyblk";
/// Blocks the game registers itself rather than from a block type file.
const builtInBlocks = [_][]const u8{ "air", "mantle" };
pub fn deinit(self: *Prepared) void {
self.arena.deinit();
}
const SpriteFormat = storyblk.SpriteFormat;
/// The file's `header.hash` for blocks prepared from `assets`, with sprites drawn as `sprites`
/// says (spec §6): it changes with the container's and the sections' versions, the block width,
/// the game version and the mods (their names, sizes and times).
pub fn hash(io: Io, assets: *const Assets, sprites: SpriteFormat) !u64 {
var hasher: std.hash.Wyhash = .init(0);
std.hash.autoHash(&hasher, storyblk.version);
std.hash.autoHash(&hasher, Tables.layoutVersions);
std.hash.autoHash(&hasher, generatorVersion);
std.hash.autoHash(&hasher, sprites);
hasher.update(game);
hasher.update(&.{0});
hasher.update(assets.version orelse "");
for (assets.sources.items[1..]) |source| {
hasher.update(&.{0});
hasher.update(source.name);
switch (source.kind) {
.zip => |zip| {
const stat = try zip.file.stat(io);
hasher.update(std.mem.asBytes(&stat.size));
hasher.update(std.mem.asBytes(&stat.mtime.nanoseconds));
},
.folders => |folders| for (folders) |folder| {
const stat = try folder.dir.stat(io);
hasher.update(std.mem.asBytes(&stat.mtime.nanoseconds));
},
}
}
return hasher.final();
}
/// The six sections' contents before they're written: the blocks prepared from the assets,
/// with what drawing their sprites needs, and the tables they name.
pub const Contents = struct {
/// The sections `encode` makes.
pub const sectionCount = Tables.names.len;
gameVersion: []const u8,
mods: []const storyblk.Mod,
domains: []const []const u8,
textures: []const TextureColours,
colourMaps: []const Tint.ColourMap,
/// In the order of the `block_states` section.
blocks: []Entry,
pub const Entry = struct {
code: []const u8,
block: Block,
/// The textures in `textures` its colour and grain are from, and its colour maps in
/// `colourMaps`.
colour: ?u32 = null,
grain: ?u32 = null,
climateColourMap: ?u8 = null,
seasonColourMap: ?u8 = null,
};
/// Gives each block its sprites, by its index. The snow under a block is the first sprite of
/// the snow layer of its height.
pub fn useSprites(self: *Contents, sprites: []const world.BlockSprites) void {
std.debug.assert(sprites.len == self.blocks.len);
var snowLayers: [8]?u32 = @splat(null);
for (self.blocks, sprites) |entry, own| {
if (entry.code.len != "snowlayer-N".len or !std.mem.startsWith(u8, entry.code, "snowlayer-")) continue;
const eighths = std.fmt.charToDigit(entry.code["snowlayer-".len], 10) catch continue;
if (eighths < snowLayers.len and own.variants > 0) snowLayers[eighths] = own.first;
}
for (self.blocks, sprites) |*entry, own| {
entry.block.sprites = own;
if (entry.block.snowLayer > 0) entry.block.sprites.cover = snowLayers[entry.block.snowLayer];
}
}
/// The file's `info`, its list of mods kept in `arena`, so it can outlast these contents.
pub fn info(self: *const Contents, arena: std.mem.Allocator) !storyblk.Info {
return .{ .game = game, .gameVersion = self.gameVersion, .mods = try arena.dupe(storyblk.Mod, self.mods) };
}
/// The six sections, in the order of `Tables.names`, their bytes kept in `arena`. A count or
/// string that doesn't fit its field is an error.
pub fn encode(self: *const Contents, arena: std.mem.Allocator) ![Tables.names.len]storyblk.Section {
// Each material and colour code once, in the order blocks first name them.
var materials: std.StringArrayHashMapUnmanaged(void) = .empty;
var colourCodes: std.StringArrayHashMapUnmanaged(void) = .empty;
for (self.blocks) |entry| {
try materials.put(arena, entry.block.material, {});
try colourCodes.put(arena, entry.block.colorCode, {});
}
const colourMaps = try arena.alloc(Tables.ColourMap, self.colourMaps.len);
for (colourMaps, self.colourMaps) |*written, map| written.* = .{
.code = map.code,
.padding = @intCast(map.padding),
.tropical = map.tropical,
.width = @intCast(map.width),
.height = @intCast(map.height),
.pixels = map.pixels,
};
var encoder: Tables.Encoder = try .init(arena, .{
.materials = materials.keys(),
.colourCodes = colourCodes.keys(),
.textureColours = self.textures,
.colourMaps = colourMaps,
.domains = self.domains,
}, self.blocks.len);
for (self.blocks) |entry| {
const block = entry.block;
try encoder.add(.{
.name = entry.code,
.material = @intCast(materials.getIndex(block.material).?),
.colourCode = @intCast(colourCodes.getIndex(block.colorCode).?),
.colour = entry.colour,
.grain = entry.grain,
.climateColourMap = entry.climateColourMap,
.seasonColourMap = entry.seasonColourMap,
.height = block.height,
.drawOffset = block.drawOffset,
.flags = .{
.xz = block.randomizeAxes == .xz,
.turned = block.randomizeRotations,
.shape = block.sprites.shape,
.tinted = block.sprites.tinted,
.seeThrough = block.seeThrough,
},
.firstSprite = block.sprites.first,
.variants = block.sprites.variants,
.alternates = block.sprites.alternates,
.turns = block.sprites.turns,
.coverSprite = block.sprites.cover,
});
}
return encoder.finish(arena, generatorVersion);
}
};
/// How much of what one block type file took `prepare` keeps for the next.
const fileArenaLimit = 4 << 20;
/// Reads the blocks from `assets`, one block type file at a time, with what drawing their
/// sprites needs, keeping them in `arena`. What reading needs throughout and what one file takes
/// are in memory from `gpa`, the first freed before it returns and the second after each file.
/// Blocks with the same faces share their lists of variants, and blocks placed the same their
/// boxes: `isometric.drawSprites` tells them apart by those slices.
pub fn prepare(gpa: std.mem.Allocator, arena: std.mem.Allocator, io: Io, assets: *const Assets) !Contents {
var readingArena: std.heap.ArenaAllocator = .init(gpa);
defer readingArena.deinit();
const reading = readingArena.allocator();
var fileArena: std.heap.ArenaAllocator = .init(gpa);
defer fileArena.deinit();
const scratch = fileArena.allocator();
var reader: BlockTypes.Reader = try .init(reading, arena, io, assets);
var textures: Textures = .{ .arena = reading, .scratch = scratch, .io = io, .assets = assets };
var images: Images = .{ .arena = arena, .textures = &textures };
const colourMaps = try prepareColourMaps(arena, reading, io, assets);
// From `gpa`, as an arena would keep every size it grew through.
var entries: std.ArrayList(Contents.Entry) = .empty;
defer entries.deinit(gpa);
while (try reader.next(scratch)) |types| {
// A few files take many times what the rest do, and shouldn't hold that for those after.
defer _ = fileArena.reset(.{ .retain_with_limit = fileArenaLimit });
for (types) |block| {
try textures.select(block.textures);
try entries.append(gpa, .{
.code = try arena.dupe(u8, block.code),
.block = .{
.index = @intCast(entries.items.len),
.material = try arena.dupe(u8, block.material),
.colorCode = try arena.dupe(u8, block.colorCode),
.cube = try cubeOf(&images, block.cube),
.height = block.height,
.shapes = try shapesOf(arena, &images, block.shapes),
.drawOffset = block.drawOffset,
.randomizeAxes = block.randomizeAxes,
.randomizeRotations = block.randomizeRotations,
.snowLayer = block.snowLayer,
.seeThrough = block.seeThrough,
},
.colour = try textures.index(block.textures.colour),
.grain = try textures.index(block.textures.grain),
.climateColourMap = colourMapIndex(colourMaps, block.climateColorMap),
.seasonColourMap = colourMapIndex(colourMaps, block.seasonColorMap),
});
}
}
const blocks = try arena.dupe(Contents.Entry, entries.items);
// Pointing into the textures and colour maps once all are read.
const colours = try arena.dupe(TextureColours, textures.read.items);
for (blocks) |*entry| {
if (entry.colour) |i| entry.block.colour = colours[i].average;
if (entry.grain) |i| entry.block.grain = &colours[i].grain;
if (entry.climateColourMap) |i| entry.block.climateColourMap = &colourMaps[i];
if (entry.seasonColourMap) |i| entry.block.seasonColourMap = &colourMaps[i];
}
const mods = try arena.alloc(storyblk.Mod, assets.sources.items.len - 1);
for (mods, assets.sources.items[1..]) |*mod, source| mod.* = source.mod.?;
return .{
.gameVersion = assets.version orelse "",
.mods = mods,
.domains = assets.domains.keys(),
.textures = colours,
.colourMaps = colourMaps,
.blocks = blocks,
};
}
/// A block's cube faces, each layer the images of its variants; null without a cube, or for one
/// with a top, south or east face that can't be read, which is drawn in its colour instead. A
/// north or west face that can't be read is the opposite one's.
fn cubeOf(images: *Images, cube: ?BlockTypes.Cube) !?world.CubeFaces {
const faces = cube orelse return null;
const up = try faceOf(images, faces.up) orelse return null;
const south = try faceOf(images, faces.south) orelse return null;
const east = try faceOf(images, faces.east) orelse return null;
return .{
.up = up,
.south = south,
.east = east,
.north = try faceOf(images, faces.north) orelse south,
.west = try faceOf(images, faces.west) orelse east,
};
}
/// A cube face's layers' images; null for one that can't be read.
fn faceOf(images: *Images, from: BlockTypes.Face) !?world.CubeFaces.Face {
const face: world.CubeFaces.Face = .{ .plain = try images.list(from.plain), .tinted = try images.list(from.tinted) };
if ((from.plain != null and face.plain.len == 0) or (from.tinted != null and face.tinted.len == 0)) return null;
if (face.plain.len == 0 and face.tinted.len == 0) return null;
return face;
}
/// A block's shapes, each its geometry's boxes, one slice for each geometry, and its textures'
/// images. A shape with nothing to draw has no boxes or textures.
fn shapesOf(arena: std.mem.Allocator, images: *Images, shapes: []const BlockTypes.Shape) ![]const world.Shape {
if (shapes.len == 0) return &.{};
const out = try arena.alloc(world.Shape, shapes.len);
for (out, shapes) |*shape, from| {
if (from.geometry.boxes.len == 0) {
shape.* = .{ .boxes = &.{}, .textures = &.{} };
continue;
}
const textures = try arena.alloc(world.CubeFaces.Face, from.textures.len);
for (textures, from.textures) |*texture, face| texture.* = .{ .plain = try images.list(face.plain), .tinted = try images.list(face.tinted) };
shape.* = .{ .boxes = from.geometry.boxes, .textures = textures };
}
return out;
}
/// Cube faces' images, each made once: a texture with its overlays drawn over it, or half of
/// it, by index in the order they're first needed.
const Images = struct {
/// Where the images and their lists are kept; the tables finding them are in
/// `textures.arena`, and what's only needed to make them in `textures.scratch`.
arena: std.mem.Allocator,
textures: *Textures,
/// Each layer met so far, by its textures and half, and its index, or null if it can't be
/// made.
indexes: std.StringHashMapUnmanaged(?usize) = .empty,
made: std.ArrayList(*const Image) = .empty,
/// Each list of images made so far, by their indexes, as one slice.
lists: std.StringHashMapUnmanaged([]const *const Image) = .empty,
/// Each overlay met so far, by its location, or null if it can't be read. One overlay is drawn
/// over many textures, such as an ore over every rock.
overlays: std.StringHashMapUnmanaged(?Image) = .empty,
/// The images of the layer's variants (`variants`), the same slice for the same images;
/// none without a layer or if none can be made.
fn list(self: *Images, layer: ?BlockTypes.Layer) ![]const *const Image {
const indexes = try self.variants(layer) orelse return &.{};
const entry = try self.lists.getOrPut(self.textures.arena, std.mem.sliceAsBytes(indexes));
if (entry.found_existing) return entry.value_ptr.*;
entry.key_ptr.* = try self.textures.arena.dupe(u8, std.mem.sliceAsBytes(indexes));
const found = try self.arena.alloc(*const Image, indexes.len);
for (found, indexes) |*image, i| image.* = self.made.items[i];
entry.value_ptr.* = found;
return found;
}
/// The indexes of the layer's images, one for each of its variants that can be made, each
/// made the first time; null without a layer or if none can be made. Its variants are in the
/// game's order (vsapi `CompositeTexture.Bake`): its base's first file with its overlays,
/// then each of its alternates' first file with the alternate's overlays, then its base's
/// other files, without overlays.
fn variants(self: *Images, layer: ?BlockTypes.Layer) !?[]const usize {
const wanted = layer orelse return null;
const scratch = self.textures.scratch;
var found: std.ArrayList(usize) = .empty;
const files = try self.textures.paths(wanted.base);
if (files.len > 0) if (try self.index(wanted, files[0])) |i| try found.append(scratch, i);
for (wanted.alternates) |alternate| {
const alternateFiles = try self.textures.paths(alternate.base);
if (alternateFiles.len > 0) if (try self.index(alternate, alternateFiles[0])) |i| try found.append(scratch, i);
}
const bare: BlockTypes.Layer = .{ .base = wanted.base, .half = wanted.half, .quarterTurns = wanted.quarterTurns };
if (files.len > 1) for (files[1..]) |path| {
if (try self.index(bare, path)) |i| try found.append(scratch, i);
};
return if (found.items.len == 0) null else found.items;
}
/// The index of the layer's image with `path` as its base, made the first time, or null if
/// it can't be made.
fn index(self: *Images, layer: BlockTypes.Layer, path: []const u8) !?usize {
const arena = self.textures.arena;
var name: std.Io.Writer.Allocating = .init(self.textures.scratch);
try name.writer.print("{s}:{s}", .{ domainOf(layer.base), path });
for (layer.overlays) |overlay| try name.writer.print("+{s}", .{overlay});
if (layer.half) |half| try name.writer.print("#{t}", .{half});
if (layer.quarterTurns != 0) try name.writer.print("@{}", .{layer.quarterTurns});
const entry = try self.indexes.getOrPut(arena, name.written());
if (entry.found_existing) return entry.value_ptr.*;
entry.key_ptr.* = try arena.dupe(u8, name.written());
entry.value_ptr.* = null;
const made = try self.make(layer, path) orelse return null;
const image = try self.arena.create(Image);
image.* = made;
try self.made.append(arena, image);
entry.value_ptr.* = self.made.items.len - 1;
return entry.value_ptr.*;
}
/// The overlay at `location`, read the first time; null if it can't be.
fn readOverlay(self: *Images, location: []const u8) !?Image {
const arena = self.textures.arena;
const entry = try self.overlays.getOrPut(arena, location);
if (entry.found_existing) return entry.value_ptr.*;
entry.key_ptr.* = try arena.dupe(u8, location);
entry.value_ptr.* = null;
const png = try self.textures.readPng(location) orelse return null;
entry.value_ptr.* = try decode(arena, png);
return entry.value_ptr.*;
}
/// The layer's image in `arena`, whichever step's image is the last, so it's copied no further.
fn make(self: *Images, layer: BlockTypes.Layer, path: []const u8) !?Image {
const scratch = self.textures.scratch;
const turned = layer.quarterTurns != 0;
const domain = domainOf(layer.base);
const png = try self.textures.assets.read(scratch, self.textures.io, domain, path) orelse return null;
var image = try decode(if (layer.half == null and !turned) self.arena else scratch, png) orelse return null;
self.textures.takeColours(domain, path, image.pixels);
if (layer.half) |half| image = halfOf(if (turned) scratch else self.arena, image, half) orelse return null;
// An overlay that can't be read is left out, as the game leaves out a missing texture.
for (layer.overlays) |location| {
const overlay = try self.readOverlay(location) orelse continue;
drawOver(@constCast(image.pixels), image.width, image.height, overlay);
}
return try rotate(self.arena, image, layer.quarterTurns);
}
};
/// `image` turned anticlockwise by `quarterTurns`, as the game turns a texture's `rotation`.
fn rotate(arena: std.mem.Allocator, image: Image, quarterTurns: u2) !Image {
if (quarterTurns == 0) return image;
const width: usize = image.width;
const height: usize = image.height;
const sideways = quarterTurns != 2;
const pixels = try arena.alloc([4]u8, width * height);
const outWidth = if (sideways) height else width;
const outHeight = if (sideways) width else height;
for (0..outHeight) |row| for (0..outWidth) |column| {
const x, const y = switch (quarterTurns) {
0 => unreachable,
1 => [2]usize{ width - 1 - row, column },
2 => [2]usize{ width - 1 - column, height - 1 - row },
3 => [2]usize{ row, height - 1 - column },
};
pixels[row * outWidth + column] = image.pixels[y * width + x];
};
return .{ .width = @intCast(outWidth), .height = @intCast(outHeight), .pixels = pixels };
}
test rotate {
const a: [4]u8 = @splat(1);
const b: [4]u8 = @splat(2);
const c: [4]u8 = @splat(3);
const d: [4]u8 = @splat(4);
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const image: Image = .{ .width = 2, .height = 2, .pixels = &.{ a, b, c, d } };
try std.testing.expectEqualSlices([4]u8, &.{ b, d, a, c }, (try rotate(arena.allocator(), image, 1)).pixels);
try std.testing.expectEqualSlices([4]u8, &.{ d, c, b, a }, (try rotate(arena.allocator(), image, 2)).pixels);
try std.testing.expectEqualSlices([4]u8, &.{ c, a, d, b }, (try rotate(arena.allocator(), image, 3)).pixels);
// Wider than tall, it comes out taller than wide.
const wide = try rotate(arena.allocator(), .{ .width = 2, .height = 1, .pixels = &.{ a, b } }, 1);
try std.testing.expectEqual(1, wide.width);
try std.testing.expectEqualSlices([4]u8, &.{ b, a }, wide.pixels);
}
/// A PNG's pixels, copied into `arena`; null if it can't be decoded or is larger than an
/// `Image` holds.
fn decode(arena: std.mem.Allocator, png: []const u8) !?Image {
var width: c_int = 0;
var height: c_int = 0;
var channels: c_int = 0;
const data = stb.stbi_load_from_memory(png.ptr, @intCast(png.len), &width, &height, &channels, 4) orelse return null;
defer stb.stbi_image_free(data);
if (width > std.math.maxInt(u16) or height > std.math.maxInt(u16)) return null;
const count: usize = @intCast(width * height);
const pixels = try arena.dupe([4]u8, @as([*]const [4]u8, @ptrCast(data))[0..count]);
return .{ .width = @intCast(width), .height = @intCast(height), .pixels = pixels };
}
/// The left or right half of an image twice as wide as tall; null for any other.
fn halfOf(arena: std.mem.Allocator, image: Image, half: BlockTypes.Layer.Half) ?Image {
if (image.width != 2 * image.height) return null;
const side = image.height;
const pixels = arena.alloc([4]u8, @as(usize, side) * side) catch return null;
const offset: usize = if (half == .right) side else 0;
for (0..side) |row| @memcpy(pixels[row * side ..][0..side], image.pixels[row * image.width + offset ..][0..side]);
return .{ .width = side, .height = side, .pixels = pixels };
}
/// Draws `overlay` over `pixels`, by its opacity, stretched or shrunk to their size, taking
/// the nearest of its pixels.
fn drawOver(pixels: [][4]u8, width: u16, height: u16, overlay: Image) void {
for (0..height) |y| for (0..width) |x| {
const top = overlay.pixels[(y * overlay.height / height) * overlay.width + x * overlay.width / width];
const under = &pixels[y * width + x];
const a: u32 = top[3];
const below: u32 = @as(u32, under[3]) * (255 - a) / 255;
const alpha = a + below;
if (alpha == 0) continue;
for (0..3) |c| under[c] = @intCast((@as(u32, top[c]) * a + @as(u32, under[c]) * below) / alpha);
under[3] = @intCast(alpha);
};
}
test drawOver {
var pixels = [_][4]u8{ .{ 0, 0, 255, 255 }, .{ 0, 0, 255, 255 } };
// Opaque red on the left, half-transparent red on the right, from a 1 × 1 and 2 × 1 overlay.
drawOver(&pixels, 2, 1, .{ .width = 2, .height = 1, .pixels = &.{ .{ 255, 0, 0, 255 }, .{ 255, 0, 0, 128 } } });
try std.testing.expectEqual([4]u8{ 255, 0, 0, 255 }, pixels[0]);
try std.testing.expectEqual([4]u8{ 128, 0, 127, 255 }, pixels[1]);
}
/// The colour maps in the game's `config/colormaps.json` whose images can be read and decoded
/// and fit their fields, in the file's order, kept in `arena`.
fn prepareColourMaps(arena: std.mem.Allocator, temporary: std.mem.Allocator, io: Io, assets: *const Assets) ![]const Tint.ColourMap {
const file = "config/colormaps.json";
const bytes = try assets.read(temporary, io, Assets.gameDomain, file) orelse return &.{};
const json = Json.parse(temporary, bytes) catch |err| {
console.warn("{s}: could not read ({s}); nothing will be tinted", .{ file, @errorName(err) });
return &.{};
};
if (json != .array) return &.{};
var maps: std.ArrayList(Tint.ColourMap) = .empty;
for (json.array) |entry| {
const code = (entry.get("code") orelse continue).asString() orelse continue;
const base = ((entry.get("texture") orelse continue).get("base") orelse continue).asString() orelse continue;
const colon = std.mem.indexOfScalar(u8, base, ':');
const domain = if (colon) |c| base[0..c] else Assets.gameDomain;
const path = try std.fmt.allocPrint(temporary, "textures/{s}.png", .{if (colon) |c| base[c + 1 ..] else base});
const png = try assets.read(temporary, io, domain, path) orelse {
console.warn("colour map {s}: no image {s}:{s}", .{ code, domain, path });
continue;
};
const padding = integer(entry.get("padding"));
const map = if (padding <= std.math.maxInt(u8)) try Tint.ColourMap.decode(arena, try arena.dupe(u8, code), png, padding, integer(entry.get("extraFlags")) == 1) else null;
const usable = if (map) |decoded| decoded.width <= std.math.maxInt(u16) and decoded.height <= std.math.maxInt(u16) else false;
if (!usable) {
console.warn("colour map {s}: could not read its image {s}:{s}", .{ code, domain, path });
continue;
}
try maps.append(arena, map.?);
}
return maps.items;
}
/// A whole number in the game's JSON, or 0 without one.
fn integer(value: ?Json.Value) usize {
const number = value orelse return 0;
if (number != .number) return 0;
return std.fmt.parseInt(usize, number.number, 10) catch 0;
}
fn colourMapIndex(maps: []const Tint.ColourMap, code: ?[]const u8) ?u8 {
const wanted = code orelse return null;
for (maps, 0..) |map, i| if (std.mem.eql(u8, map.code, wanted)) return std.math.cast(u8, i);
return null;
}
/// The textures the blocks name, each read once, by index in the order they're first named.
const Textures = struct {
/// What lasts while the blocks are read: what's below.
arena: std.mem.Allocator,
/// What only reading one file of blocks needs, such as the textures' PNGs.
scratch: std.mem.Allocator,
io: Io,
assets: *const Assets,
/// Each location named so far, and its index, or null if it can't be read.
indexes: std.StringHashMapUnmanaged(?u32) = .empty,
read: std.ArrayList(TextureColours) = .empty,
/// Every texture file, listed the first time a location ends in `*`.
files: ?[]const Assets.Name = null,
/// The block's colour and grain textures not yet in `read`, each with its colours once its
/// file is decoded for one of the block's images.
current: [2]?Current = .{ null, null },
const Current = struct {
location: []const u8,
path: []const u8,
colours: ?TextureColours = null,
};
/// Sets the textures whose colours `takeColours` keeps.
fn select(self: *Textures, named: BlockTypes.Textures) !void {
self.current = .{ try self.currentOf(named.colour), try self.currentOf(named.grain) };
}
fn currentOf(self: *Textures, location: ?[]const u8) !?Current {
const wanted = location orelse return null;
if (self.indexes.contains(wanted)) return null;
const files = try self.paths(wanted);
return if (files.len == 0) null else .{ .location = wanted, .path = files[0] };
}
/// Keeps the colours of `pixels`, a file just decoded, if it's a current texture.
fn takeColours(self: *Textures, domain: []const u8, path: []const u8, pixels: []const [4]u8) void {
var colours: ?TextureColours = null;
for (&self.current) |*current| {
const texture = if (current.*) |*texture| texture else continue;
if (texture.colours != null or !std.mem.eql(u8, texture.path, path)) continue;
if (!std.mem.eql(u8, domainOf(texture.location), domain)) continue;
colours = colours orelse textureColours.of(pixels);
texture.colours = colours;
}
}
/// Reads the texture the first time; null without a location or if it can't be read.
fn index(self: *Textures, location: ?[]const u8) !?u32 {
const wanted = location orelse return null;
const entry = try self.indexes.getOrPut(self.arena, wanted);
if (entry.found_existing) return entry.value_ptr.*;
entry.key_ptr.* = try self.arena.dupe(u8, wanted);
entry.value_ptr.* = null;
const colours = try self.readColours(wanted) orelse return null;
try self.read.append(self.arena, colours);
entry.value_ptr.* = @intCast(self.read.items.len - 1);
return entry.value_ptr.*;
}
fn readColours(self: *Textures, location: []const u8) !?TextureColours {
for (self.current) |current| if (current) |texture| {
if (texture.colours != null and std.mem.eql(u8, texture.location, location)) return texture.colours;
};
const png = try self.readPng(location) orelse return null;
return textureColours.ofPng(png);
}
/// The texture's file, or for a location ending in `*`, the first file it starts; null if
/// there's none.
fn readPng(self: *Textures, location: []const u8) !?[]const u8 {
const files = try self.paths(location);
if (files.len == 0) return null;
return self.assets.read(self.scratch, self.io, domainOf(location), files[0]);
}
/// The texture's file, in its location's domain; or for a location ending in `*`, every file
/// it starts, by name: the first is the texture and the others its variants (vsapi
/// `CompositeTexture.Bake`).
fn paths(self: *Textures, location: []const u8) ![]const []const u8 {
const domain = domainOf(location);
const path = try std.fmt.allocPrint(self.scratch, "textures/{s}.png", .{location[domain.len + 1 ..]});
if (!std.mem.endsWith(u8, location, "*")) return self.scratch.dupe([]const u8, &.{path});
const start = path[0 .. path.len - "*.png".len];
const files = self.files orelse try self.assets.list(self.arena, self.io, "textures");
self.files = files;
var found: std.ArrayList([]const u8) = .empty;
for (files) |file| {
if (std.mem.eql(u8, file.domain, domain) and std.mem.startsWith(u8, file.path, start) and std.mem.endsWith(u8, file.path, ".png")) try found.append(self.scratch, file.path);
}
return found.items;
}
};
/// The domain of a location such as `game:block/stone/granite1`.
fn domainOf(location: []const u8) []const u8 {
return location[0..std.mem.indexOfScalar(u8, location, ':').?];
}
/// The blocks in the six sections of `file` (`Tables.read`), each block's sprites checked
/// against `spriteCount`, the `sprites` section's count. Their codes, materials, colour codes,
/// domains, grain and colour maps' pixels are where `file` is, which must outlive the result.
pub fn load(allocator: std.mem.Allocator, file: *const storyblk.File, spriteCount: usize) !Prepared {
var self: Prepared = .{ .arena = .init(allocator), .gameVersion = file.info.gameVersion, .mods = file.info.mods };
errdefer self.deinit();
const arena = self.arena.allocator();
const tables, var states = try Tables.read(arena, file, spriteCount);
for (tables.domains) |domain| try self.domains.put(arena, domain, {});
const colourMaps = try arena.alloc(Tint.ColourMap, tables.colourMaps.len);
for (colourMaps, tables.colourMaps) |*colourMap, read| colourMap.* = .{
.code = read.code,
.width = read.width,
.height = read.height,
.pixels = read.pixels,
.padding = read.padding,
.tropical = read.tropical,
};
try self.blocks.ensureTotalCapacity(arena, states.count);
while (try states.next()) |state| {
self.blocks.putAssumeCapacity(state.name, .{
.index = states.index - 1,
.material = tables.materials[state.material],
.colorCode = tables.colourCodes[state.colourCode],
.colour = if (state.colour) |i| tables.textureColours[i].average else null,
.grain = if (state.grain) |i| &tables.textureColours[i].grain else &.{},
.climateColourMap = if (state.climateColourMap) |i| &colourMaps[i] else null,
.seasonColourMap = if (state.seasonColourMap) |i| &colourMaps[i] else null,
.height = state.height,
.drawOffset = state.drawOffset,
.randomizeAxes = if (state.flags.xz) .xz else .xyz,
.randomizeRotations = state.flags.turned,
.seeThrough = state.flags.seeThrough,
.sprites = .{
.first = state.firstSprite,
.variants = state.variants,
.alternates = state.alternates,
.turns = state.turns,
.shape = state.flags.shape,
.tinted = state.flags.tinted,
.cover = state.coverSprite,
},
});
}
return self;
}
/// What a save's blocks have that the prepared blocks don't: the mods (domains) it lacks, and
/// how many codes in known domains it lacks, with an example.
pub const Unknown = struct {
mods: []const []const u8,
codes: usize,
example: ?[]const u8,
};
pub fn unknown(self: *const Prepared, allocator: std.mem.Allocator, codes: []const ?[]const u8) !Unknown {
var mods: std.ArrayList([]const u8) = .empty;
errdefer mods.deinit(allocator);
var count: usize = 0;
var example: ?[]const u8 = null;
codes: for (codes) |maybeCode| {
const code = maybeCode orelse continue;
if (self.blocks.contains(code)) continue;
for (builtInBlocks) |builtIn| if (std.mem.eql(u8, code, builtIn)) continue :codes;
const colon = std.mem.indexOfScalar(u8, code, ':');
const domain = if (colon) |c| code[0..c] else Assets.gameDomain;
if (!self.domains.contains(domain)) {
for (mods.items) |seen| {
if (std.mem.eql(u8, seen, domain)) break;
} else try mods.append(allocator, domain);
continue;
}
count += 1;
if (example == null) example = code;
}
return .{ .mods = try mods.toOwnedSlice(allocator), .codes = count, .example = example };
}
fn find(contents: *const Contents, code: []const u8) *const Block {
for (contents.blocks) |*entry| if (std.mem.eql(u8, entry.code, code)) return &entry.block;
unreachable;
}
fn expectTransformRow(expected: [4]f32, actual: [4]f32) !void {
for (expected, actual) |e, a| try std.testing.expectApproxEqAbs(e, a, 1e-6);
}
test "the snow under a block" {
const snowLayer: Block = .{ .material = "Snow", .colorCode = "snow" };
var blocks = [_]Contents.Entry{
.{ .code = "snowlayer-1", .block = snowLayer },
.{ .code = "snowlayer-2", .block = snowLayer },
.{ .code = "tallgrass-tall-snow2", .block = .{ .material = "Snow", .colorCode = "snow", .snowLayer = 2 } },
.{ .code = "tallgrass-tall-snow3", .block = .{ .material = "Snow", .colorCode = "snow", .snowLayer = 3 } },
};
var contents: Contents = .{ .gameVersion = "1.22.7", .mods = &.{}, .domains = &.{}, .textures = &.{}, .colourMaps = &.{}, .blocks = &blocks };
contents.useSprites(&.{ .{ .first = 0, .variants = 6 }, .{ .first = 6, .variants = 6 }, .{ .first = 12, .variants = 1 }, .{ .first = 13, .variants = 1 } });
try std.testing.expectEqual(null, blocks[0].block.sprites.cover);
try std.testing.expectEqual(6, blocks[2].block.sprites.cover);
// No snow layer of its height.
try std.testing.expectEqual(null, blocks[3].block.sprites.cover);
}
test "prepare, write, load and compare with a save" {
// Keeps the expected warnings off stderr, where the build runner would print them.
std.testing.log_level = .err;
defer std.testing.log_level = .warn;
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const files = [_][2][]const u8{
.{ "game/assets/version-1.22.7.txt", "" },
.{ "game/assets/survival/worldproperties/block/rock.json", "{ code: 'rock', variants: [ { code: 'granite' } ] }" },
.{ "game/assets/survival/blocktypes/rock.json", "{ code: 'rock', variantgroups: [ { loadFromProperties: 'block/rock' } ], textures: { all: { base: 'block/stone/{rock}*' } }, climateColorMap: 'climateTest', seasonColorMap: 'missing' }" },
.{ "game/assets/survival/textures/block/stone/granite1.png", @embedFile("testdata/red.png") },
.{ "game/assets/survival/config/colormaps.json", "[ { code: 'climateTest', texture: { base: 'environment/test' } }, { code: 'missing', texture: { base: 'environment/none' } } ]" },
.{ "game/assets/game/textures/environment/test.png", @embedFile("testdata/red.png") },
.{ "game/assets/survival/textures/block/stone/granite2.png", "not a PNG: a variant that can't be read is left out" },
.{ "game/assets/survival/textures/block/stone/granite3.png", @embedFile("testdata/red.png") },
.{ "game/assets/survival/blocktypes/soil.json", "{ code: 'soil', drawtype: 'TopSoil', textures: { all: { base: 'block/stone/granite*' }, specialSecondTexture: { base: 'block/grass' } } }" },
.{ "game/assets/survival/textures/block/grass.png", @embedFile("testdata/red.png") },
.{ "game/assets/survival/blocktypes/step.json", "{ code: 'step', shape: { base: 'block/step', alternates: [ { rotateY: 180 }, { base: 'block/missing' } ] }, textures: { all: { base: 'block/stone/granite*' } } }" },
.{ "game/assets/survival/shapes/block/step.json", "{ elements: [ { from: [ 0, 0, 0 ], to: [ 16, 8, 16 ], rotationOrigin: [ 8, 8, 8 ], rotationY: 90, faces: { north: { texture: '#all', uv: [ 0, 0, 16, 8 ] }, up: { texture: '#top' } } } ] }" },
.{ "game/assets/survival/blocktypes/ore.json", "{ code: 'ore', drawtype: 'Cube', textures: { all: { base: 'block/stone/granite*', overlays: [ 'block/grass' ], alternates: [ { base: 'block/grass' }, { base: 'block/missing' } ] } } }" },
.{ "data/Mods/testmod.zip", @embedFile("testdata/testmod.zip") },
};
for (files) |file| {
if (std.fs.path.dirname(file[0])) |parent| try tmp.dir.createDirPath(io, parent);
try tmp.dir.writeFile(io, .{ .sub_path = file[0], .data = file[1] });
}
var gameDir = try tmp.dir.openDir(io, "game", .{});
defer gameDir.close(io);
var dataDir = try tmp.dir.openDir(io, "data", .{});
defer dataDir.close(io);
var assets = try Assets.open(std.testing.allocator, io, gameDir, dataDir);
defer assets.close(io);
const sprites: SpriteFormat = .{ .generatorVersion = 4, .layoutVersion = 1, .blockWidth = 32 };
const first = try hash(io, &assets, sprites);
try std.testing.expectEqual(first, try hash(io, &assets, sprites));
try std.testing.expect(first != try hash(io, &assets, .{ .generatorVersion = 5, .layoutVersion = 1, .blockWidth = 32 }));
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
var contents = try prepare(std.testing.allocator, arena.allocator(), io, &assets);
// rock-granite, soil, step, ore, and the test mod's thing.
try std.testing.expectEqual(5, contents.blocks.len);
// The colour map without an image is left out.
try std.testing.expectEqual(1, contents.colourMaps.len);
// With a colour map, the rock's faces are its whole texture, tinted: granite1 and granite3,
// its variants that can be read, the same list on every face.
const rock = find(&contents, "rock-granite").cube.?;
try std.testing.expectEqual(0, rock.up.plain.len);
try std.testing.expectEqual(2, rock.up.tinted.len);
try std.testing.expectEqual(2, rock.up.tinted[0].width);
try std.testing.expect(rock.up.tinted[0] != rock.up.tinted[1]);
try std.testing.expectEqual(rock.up.tinted.ptr, rock.south.tinted.ptr);
// The soil's grass is half its second texture, the right on top and the left on the sides.
const soil = find(&contents, "soil").cube.?;
try std.testing.expectEqual(rock.up.tinted.ptr, soil.up.plain.ptr);
try std.testing.expectEqual(1, soil.up.tinted[0].width);
try std.testing.expectEqual(1, soil.south.tinted[0].width);
try std.testing.expectEqual(soil.south.tinted.ptr, soil.east.tinted.ptr);
try std.testing.expectEqual(rock.up.tinted[0].pixels[1], soil.up.tinted[0].pixels[0]);
try std.testing.expectEqual(rock.up.tinted[0].pixels[0], soil.south.tinted[0].pixels[0]);
try std.testing.expectEqual(0, find(&contents, "rock-granite").shapes.len);
// The ore's variants in the game's order: granite1 under its overlay, then its alternate, the
// grass whole, then granite3 without the overlay, the rock's own image; the missing
// alternate and the granite that can't be read are left out.
const ore = find(&contents, "ore").cube.?;
try std.testing.expectEqual(3, ore.up.plain.len);
try std.testing.expect(ore.up.plain[0] != rock.up.tinted[0]);
try std.testing.expectEqual(2, ore.up.plain[1].width);
try std.testing.expect(ore.up.plain[1] != rock.up.tinted[0] and ore.up.plain[1] != rock.up.tinted[1]);
try std.testing.expectEqual(rock.up.tinted[1], ore.up.plain[2]);
// The step's one box, turned a quarter about its origin, half a block high. Both its faces
// are the granite, untinted, the same images as the rock's: one by name, and one by `all`,
// naming a texture the block doesn't have.
const step = find(&contents, "step");
try std.testing.expectEqual(null, step.cube);
try std.testing.expectEqual(3, step.shapes.len);
const shape = step.shapes[0];
try std.testing.expectEqual(1, shape.boxes.len);
const box = shape.boxes[0];
try std.testing.expectEqual([3]f32{ 1, 0.5, 1 }, box.size);
try expectTransformRow(.{ 0, 0, 1, 0 }, box.transform[0]);
try expectTransformRow(.{ -1, 0, 0, 1 }, box.transform[2]);
try std.testing.expect(box.shade);
const north = box.faces[@backingInt(world.Shape.Side.north)].?;
try std.testing.expectEqual([4][2]f32{ .{ 1, 0.5 }, .{ 1, 0 }, .{ 0, 0 }, .{ 0, 0.5 } }, north.uv);
const up = box.faces[@backingInt(world.Shape.Side.up)].?;
try std.testing.expectEqual(2, shape.textures.len);
for ([_]world.Shape.Face{ north, up }) |face| {
try std.testing.expectEqual(rock.up.tinted.ptr, shape.textures[face.texture].plain.ptr);
try std.testing.expectEqual(0, shape.textures[face.texture].tinted.len);
}
try std.testing.expectEqual(null, box.faces[@backingInt(world.Shape.Side.down)]);
// Its alternates: the step turned half about the block's middle, in the same textures, and
// a shape with nothing to draw, which keeps its place.
const turned = step.shapes[1];
try std.testing.expectEqual(1, turned.boxes.len);
try std.testing.expect(turned.boxes.ptr != shape.boxes.ptr);
try std.testing.expectApproxEqAbs(1, turned.boxes[0].transform[0][3], 1e-5);
try std.testing.expectEqual(shape.textures[0].plain.ptr, turned.textures[0].plain.ptr);
try std.testing.expectEqual(0, step.shapes[2].boxes.len);
// The rock in two sprites, and the step in three; the others in none.
var drawn: [5]world.BlockSprites = @splat(.{});
drawn[find(&contents, "rock-granite").index] = .{ .first = 0, .variants = 2, .tinted = true };
drawn[step.index] = .{ .first = 2, .variants = 1, .alternates = 3, .shape = true, .cover = 1 };
contents.useSprites(&drawn);
const sections = try contents.encode(arena.allocator());
try storyblk.writeFile(io, tmp.dir, "prepared.storyblk", first, try contents.info(arena.allocator()), §ions);
const written = try tmp.dir.readFileAlloc(io, "prepared.storyblk", arena.allocator(), .unlimited);
const bytes = try arena.allocator().alignedAlloc(u8, .@"8", written.len);
@memcpy(bytes, written);
const file = try storyblk.parse(arena.allocator(), bytes);
try std.testing.expectEqualStrings(game, file.info.game);
var prepared = try load(std.testing.allocator, &file, 5);
defer prepared.deinit();
try std.testing.expectEqualStrings("1.22.7", prepared.gameVersion);
try std.testing.expectEqualDeep(storyblk.Mod{ .file = "testmod.zip", .id = "testmod", .version = "1.0.0" }, prepared.mods[0]);
try std.testing.expect(prepared.domains.contains("game") and prepared.domains.contains("testmod"));
const granite = prepared.blocks.get("rock-granite").?;
try std.testing.expectEqualStrings("Stone", granite.material);
try std.testing.expectEqualStrings("land", granite.colorCode);
// The transparent pixel counts for nothing.
try std.testing.expectEqual(world.Rgb{ 200, 40, 20 }, granite.colour.?);
try std.testing.expectEqualSlices(world.Rgb, find(&contents, "rock-granite").grain, granite.grain);
// The colour map's image, 2 × 1; the other one has none, so it isn't there.
try std.testing.expectEqualStrings("climateTest", granite.climateColourMap.?.code);
try std.testing.expectEqual(2, granite.climateColourMap.?.width);
try std.testing.expectEqualSlices(world.Rgb, contents.colourMaps[0].pixels, granite.climateColourMap.?.pixels);
try std.testing.expectEqual(null, granite.seasonColourMap);
try std.testing.expectEqual(world.BlockSprites{ .first = 0, .variants = 2, .tinted = true }, granite.sprites);
try std.testing.expectEqual(drawn[step.index], prepared.blocks.get("step").?.sprites);
try std.testing.expectEqual(null, prepared.blocks.get("testmod:thing").?.colour);
// Each block's index is its place in the file, and the file keeps their sprites, not what
// they're drawn from.
var blocks = prepared.blocks.iterator();
while (blocks.next()) |entry| {
const block = entry.value_ptr.*;
const before = find(&contents, entry.key_ptr.*);
try std.testing.expectEqual(before.index, block.index);
try std.testing.expectEqual(before.height, block.height);
try std.testing.expectEqual(before.randomizeAxes, block.randomizeAxes);
try std.testing.expectEqual(null, block.cube);
try std.testing.expectEqual(0, block.shapes.len);
}
// The step's sprites go past the last of 4.
try std.testing.expectError(error.NotPreparedBlocks, load(std.testing.allocator, &file, 4));
// A file without one of the sections, or with a block naming a material that isn't there,
// isn't one.
var missing = file;
missing.sections = file.sections[1..];
try std.testing.expectError(error.NotPreparedBlocks, load(std.testing.allocator, &missing, 5));
var changed = file;
const sectionsCopy = try arena.allocator().dupe(storyblk.Section, file.sections);
const blocksBytes = try arena.allocator().dupe(u8, sectionsCopy[0].bytes);
blocksBytes[6 + std.mem.readInt(u16, blocksBytes[4..6], .little)] = 200;
sectionsCopy[0].bytes = blocksBytes;
changed.sections = sectionsCopy;
try std.testing.expectError(error.NotPreparedBlocks, load(std.testing.allocator, &changed, 5));
// Nor is one with a colour map that's all padding, or wider than its pixels go.
var maps = file;
const mapSections = try arena.allocator().dupe(storyblk.Section, file.sections);
const mapBytes = try arena.allocator().dupe(u8, mapSections[4].bytes);
mapSections[4].bytes = mapBytes;
maps.sections = mapSections;
const paddingAt = 1 + 2 + "climateTest".len;
mapBytes[paddingAt] = 1;
try std.testing.expectError(error.NotPreparedBlocks, load(std.testing.allocator, &maps, 5));
mapBytes[paddingAt] = 0;
mapBytes[paddingAt + 2] = 200;
try std.testing.expectError(error.NotPreparedBlocks, load(std.testing.allocator, &maps, 5));
const codes = [_]?[]const u8{ "air", "rock-granite", "rock-basalt", null, "testmod:thing", "othermod:x", "othermod:y" };
const missingCodes = try prepared.unknown(std.testing.allocator, &codes);
defer std.testing.allocator.free(missingCodes.mods);
try std.testing.expectEqual(1, missingCodes.mods.len);
try std.testing.expectEqualStrings("othermod", missingCodes.mods[0]);
try std.testing.expectEqual(1, missingCodes.codes);
try std.testing.expectEqualStrings("rock-basalt", missingCodes.example.?);
}