Repository navigation
Expand file tree
/
Copy pathisometric.zig
More file actions
2792 lines (2581 loc) · 143 KB
/
Copy pathisometric.zig
File metadata and controls
2792 lines (2581 loc) · 143 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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The isometric view, looking down from above, north-west or turned from there (`Rotation`):
//! every block drawn as a cube, its top, left and right faces lit differently. Everything here
//! works in the view's coordinates, the same in every rotation, and only blocks, the sides of
//! cubes and the corners of shapes are turned to it. In the `relief` style each is in its map
//! type's relief colour (`relief.zig`); in the `game` style, a block the game draws as a cube is in its
//! textures (`cubeLayers`), one the game draws in another shape is in that shape, or the one of
//! its shapes its place picks (`shapeSprite`), each sprite drawn once, when the game's blocks
//! are prepared (`drawSprites`), and any other block in its texture's average colour, each
//! tinted by the climate where it is, as the game tints grass, leaves and water. Otherwise,
//! plants aren't drawn, nor low blocks, such as loose stones, which a whole cube would make look
//! much larger than they are.
//!
//! Each tile follows its lines of sight (`Line`) from the top of the world, and draws the first
//! block each meets, as Mapcrafter does, and past it those behind it while one leaves parts of
//! its square empty, as a plant or a fence does. A chunk is read only when a line enters it, and
//! each worker keeps the chunks it has read (`ChunkCache`), so chunks hidden underground are
//! never read.
//!
//! A `Source` is a game's save, opened for reading, with:
//! - `chunkColumns: []const world.ChunkColumn`, those that may have blocks;
//! - `heights() world.Heights`;
//! - `blockCount() usize`, `mapType(id: i32) world.MapType`, `isVisible(id: i32) bool` and
//! `isLow(id: i32) bool`, a block taking up only the bottom of its place;
//! - for the `game` style, `colour(id: i32) world.Rgb`, `spritesOf(id: i32)
//! ?world.BlockSprites`, the block's sprites (`Options.sprites`), `isTinted(id: i32) bool`,
//! `isLiquid(id: i32) bool`, `isSeeThrough(id: i32) bool`, a block that shows what's behind it,
//! `surfaceHeight(id: i32) u8`, how high a block drawn as a cube reaches where none of its kind
//! is above it, as a liquid's surface does, in sixteenths of a block, 16 for all of its place,
//! `variant(id: i32, x: i64, y: i64, z: i64, count: u32) u32`, which of `count` variants of
//! its textures, `count` shapes or `count` turns the block at (x, y, z) shows, `drawOffset(id:
//! i32, x: i64, y: i64, z: i64) ?[2]f32`, how far east and south of the middle of its place
//! it's drawn, in blocks, and `isPlacedByPosition(id: i32) bool`, whether any of those depends
//! on more than its sprites and its position;
//! - `Reader`, one per thread: `init(source: *const Source, allocator, null) !Reader`,
//! `deinit(*Reader, allocator)`, `readChunk(*Reader, x: i32, y: i32, z: i32, chunk:
//! *world.Chunk) !bool`, false where there's no chunk to draw, and `chunksRead: usize`; for
//! the `game` style, `tint(*Reader, id: i32, x: i64, y: i64, z: i64) !world.Rgb`, the colour
//! multiplied into a tinted block's colour, or its faces' tinted layers, where it is.
const std = @import("std");
const builtin = @import("builtin");
const Io = std.Io;
const world = @import("world");
const tiles = @import("tiles");
const Style = @import("theme").Style;
const relief = @import("relief.zig");
const rasterizer = @import("rasterizer.zig");
pub const Sprites = @import("Sprites.zig");
/// Level-0 pixels from blocks: a block at (x, y, z) in the view's coordinates (`Rotation.toView`)
/// is drawn in the `blockWidth`-pixel square from ((x − z − 1) · `blockWidth` / 2,
/// (x + z) · `blockWidth` / 4 − (y + 1) · `blockWidth` / 2).
pub const projection = "isometric";
/// A block's width in level-0 pixels. Its top is a diamond this wide and half as tall, and its
/// sides reach down the other half of the square this size it fills.
pub const blockWidth = 32;
/// How far a block east or west is across the screen, and how far a block east or south is
/// down it, or a block below.
const across = blockWidth / 2;
const down = blockWidth / 4;
const below = blockWidth / 2;
const side = world.Chunk.side;
/// How far the viewer has moved clockwise, seen from above, from looking north-west. The view's
/// x runs right and down the screen and its z left and down, as east and south do at `deg0`, so
/// the sides of a cube it shows are those towards +z and +x.
pub const Rotation = enum(u2) {
deg0,
deg90,
deg180,
deg270,
pub fn degrees(self: Rotation) u16 {
return @as(u16, @backingInt(self)) * 90;
}
/// Its tiles' folder in the output.
pub fn folder(self: Rotation) []const u8 {
return switch (self) {
.deg0 => "isometric",
.deg90 => "isometric-90",
.deg180 => "isometric-180",
.deg270 => "isometric-270",
};
}
pub fn title(self: Rotation) []const u8 {
return switch (self) {
.deg0 => "Isometric",
.deg90 => "Isometric 90°",
.deg180 => "Isometric 180°",
.deg270 => "Isometric 270°",
};
}
/// The level-0 pixel at the middle of the top of the block at (x, z) in the world, at height
/// `y`.
pub fn toPixels(self: Rotation, x: i64, y: i64, z: i64) [2]i64 {
const viewX, const viewZ = self.toView(x, z);
return .{ (viewX - viewZ) * across, (viewX + viewZ + 1) * down - (y + 1) * below };
}
/// The view's coordinates of the block at (x, z) in the world.
fn toView(self: Rotation, x: i64, z: i64) [2]i64 {
return switch (self) {
.deg0 => .{ x, z },
.deg90 => .{ z, -1 - x },
.deg180 => .{ -1 - x, -1 - z },
.deg270 => .{ -1 - z, x },
};
}
/// The world's coordinates of the block at (x, z) in the view.
fn toWorld(self: Rotation, x: i64, z: i64) [2]i64 {
return switch (self) {
.deg0 => .{ x, z },
.deg90 => .{ -1 - z, x },
.deg180 => .{ -1 - x, -1 - z },
.deg270 => .{ z, -1 - x },
};
}
/// The view's coordinates of a point in a block, from 0 to 1 across it.
fn pointToView(self: Rotation, x: f32, z: f32) [2]f32 {
return switch (self) {
.deg0 => .{ x, z },
.deg90 => .{ z, 1 - x },
.deg180 => .{ 1 - x, 1 - z },
.deg270 => .{ 1 - z, x },
};
}
/// The world's coordinates of a point in a block, from 0 to 1 across it.
fn pointToWorld(self: Rotation, x: f32, z: f32) [2]f32 {
return switch (self) {
.deg0 => .{ x, z },
.deg90 => .{ 1 - z, x },
.deg180 => .{ 1 - x, 1 - z },
.deg270 => .{ z, 1 - x },
};
}
/// How far a distance east and south is along the view's x and z.
fn distanceToView(self: Rotation, east: f32, south: f32) [2]f32 {
return switch (self) {
.deg0 => .{ east, south },
.deg90 => .{ south, -east },
.deg180 => .{ -east, -south },
.deg270 => .{ -south, east },
};
}
/// The change in the world's x and z from one block on a line of sight to the next.
fn lineStep(self: Rotation) [2]i64 {
return switch (self) {
.deg0 => .{ -1, -1 },
.deg90 => .{ 1, -1 },
.deg180 => .{ 1, 1 },
.deg270 => .{ -1, 1 },
};
}
/// The faces of `cube` the view shows on its left and right.
fn sides(self: Rotation, cube: *const world.CubeFaces) [2]world.CubeFaces.Face {
return switch (self) {
.deg0 => .{ cube.south, cube.east },
.deg90 => .{ cube.west, cube.south },
.deg180 => .{ cube.north, cube.west },
.deg270 => .{ cube.east, cube.north },
};
}
};
test Rotation {
for (std.enums.values(Rotation)) |rotation| {
const x, const z = rotation.toView(5, -7);
try std.testing.expectEqual([2]i64{ 5, -7 }, rotation.toWorld(x, z));
const px, const pz = rotation.pointToView(0.25, 0.75);
try std.testing.expectEqual([2]f32{ 0.25, 0.75 }, rotation.pointToWorld(px, pz));
// Going further along a line of sight is one less in the view's x and z.
const step = rotation.lineStep();
try std.testing.expectEqual([2]i64{ x - 1, z - 1 }, rotation.toView(5 + step[0], -7 + step[1]));
}
// The way each rotation faces is away from the viewer, one less in the view's x and z.
try std.testing.expectEqual([2]f32{ -1, -1 }, Rotation.deg0.distanceToView(-1, -1));
try std.testing.expectEqual([2]f32{ -1, -1 }, Rotation.deg90.distanceToView(1, -1));
try std.testing.expectEqual([2]f32{ -1, -1 }, Rotation.deg180.distanceToView(1, 1));
try std.testing.expectEqual([2]f32{ -1, -1 }, Rotation.deg270.distanceToView(-1, 1));
}
pub const Stats = struct {
/// Tiles written, at every level.
tiles: usize = 0,
levels: usize = 0,
chunksRead: usize = 0,
/// Wall time of drawing and writing every tile; opening the source isn't in it.
duration: Io.Duration = .zero,
/// The time each part of the tile pipeline took, summed over all workers.
pipeline: tiles.Stats = .{},
};
pub const Options = struct {
/// How blocks are drawn: a theme's `isometric/style.txt`. The game has one style, `game`.
style: Style,
/// The sprites the `game` style draws blocks in (`drawSprites`), each block in those its
/// source gives it (`spritesOf`); without them, it draws every block in its colour.
sprites: ?*const Sprites = null,
rotation: Rotation = .deg0,
};
/// Renders `source` into `output` and returns the tiles written, at every level, owned by the
/// caller. A game style other than `game` is error.UnknownStyle, and more different looks
/// than a chunk can number error.TooManyLooks.
pub fn render(comptime Source: type, allocator: std.mem.Allocator, io: Io, source: *const Source, output: tiles.Output, options: Options, stats: *Stats) ![]tiles.Written {
const start: Io.Timestamp = .now(io, .awake);
const rotated = if (options.sprites) |sprites| sprites.ofRotation(@backingInt(options.rotation)) else null;
var view: View(Source) = try .init(allocator, source, options.style, if (rotated) |*sprites| sprites else null, options.rotation);
defer view.deinit(allocator);
const list = try tileList(allocator, source.chunkColumns, source.heights().world, options.rotation);
defer allocator.free(list);
var written: std.ArrayList(tiles.Written) = .empty;
errdefer written.deinit(allocator);
const rendered = try tiles.render(View(Source), allocator, io, &view, list, output, &written);
const result = try written.toOwnedSlice(allocator);
stats.* = .{
.tiles = rendered.tiles,
.levels = rendered.levels,
.chunksRead = view.chunksRead,
.duration = start.untilNow(io, .awake),
.pipeline = rendered,
};
return result;
}
/// Works out where `images` fall on the map, into `placements` (`tiles.place`).
pub fn placeImages(comptime Source: type, allocator: std.mem.Allocator, io: Io, source: *const Source, images: []const tiles.Image, threads: usize, options: Options, placements: []tiles.Placement) !void {
const rotated = if (options.sprites) |sprites| sprites.ofRotation(@backingInt(options.rotation)) else null;
var view: View(Source) = try .init(allocator, source, options.style, if (rotated) |*sprites| sprites else null, options.rotation);
defer view.deinit(allocator);
const list = try tileList(allocator, source.chunkColumns, source.heights().world, options.rotation);
defer allocator.free(list);
try tiles.place(View(Source), allocator, io, &view, list, images, threads, placements);
}
/// Where the blocks from (x0, y0, z0) to (x1, y1, z1), each included, in the view's coordinates,
/// are drawn, in level-0 pixels: from `left` and `top` up to but not including `right` and
/// `bottom`.
const Box = struct {
left: i64,
top: i64,
right: i64,
bottom: i64,
fn of(x0: i64, y0: i64, z0: i64, x1: i64, y1: i64, z1: i64) Box {
return .{
.left = (x0 - z1 - 1) * across,
.top = (x0 + z0) * down - (y1 + 1) * below,
.right = (x1 - z0 - 1) * across + blockWidth,
.bottom = (x1 + z1) * down - (y0 + 1) * below + blockWidth,
};
}
};
/// A line of sight: the blocks drawn on one square, each one less in the view's x and z and one
/// lower than the one before, further from the viewer. `u` is x − z and `v` is x + z − 2y, which
/// stay the same along it; they're both even or both odd.
const Line = struct {
u: i64,
v: i64,
/// The view's x and z of its block at height `y`.
fn at(self: Line, y: i64) [2]i64 {
const sum = self.v + 2 * y;
return .{ @divExact(sum + self.u, 2), @divExact(sum - self.u, 2) };
}
/// x + y + z of its block at height `y`, larger nearer.
fn depth(self: Line, y: i64) i64 {
return self.v + 3 * y;
}
/// Where its blocks are drawn, in level-0 pixels.
fn square(self: Line) Box {
const left = (self.u - 1) * across;
const top = (self.v - 2) * down;
return .{ .left = left, .top = top, .right = left + blockWidth, .bottom = top + blockWidth };
}
};
test Line {
const line: Line = .{ .u = 3, .v = -7 };
for ([_]i64{ 0, 1, 40, 255 }) |y| {
const x, const z = line.at(y);
try std.testing.expectEqual(line.u, x - z);
try std.testing.expectEqual(line.v, x + z - 2 * y);
try std.testing.expectEqual(x + y + z, line.depth(y));
try std.testing.expectEqual(Box.of(x, y, z, x, y, z), line.square());
}
}
/// The chunks a worker has read: how each of their blocks is drawn (`View.blockLooks`), or that
/// a chunk has nothing to draw, which takes no room. It holds a fixed number of each, set up
/// once, and makes room by forgetting the one used longest ago.
const ChunkCache = struct {
pub const Position = struct { x: i32, y: i32, z: i32 };
pub const Looks = [world.Chunk.volume]u16;
pub const Lookup = union(enum) { uncached, empty, slot: *const Slot };
/// A liquid at the same place as a block that doesn't fill it: `place` in `Looks`, and the
/// liquid's look.
pub const Liquid = struct { place: u16, look: u16 };
/// A chunk's looks: a place's block, and the liquids in the places of those that don't fill
/// theirs, by place.
pub const Slot = struct {
looks: Looks,
liquids: [maxLiquids]Liquid,
liquidCount: u16,
/// The test saves' fullest chunk has 980. Past it, a place shows without its liquid.
pub const maxLiquids = 4096;
fn addLiquid(self: *Slot, place: usize, look: u16) void {
if (self.liquidCount == maxLiquids) return;
self.liquids[self.liquidCount] = .{ .place = @intCast(place), .look = look };
self.liquidCount += 1;
}
/// The look of the liquid in `place`, with a block; 0 for none.
fn liquidAt(self: *const Slot, place: usize) u16 {
const list = self.liquids[0..self.liquidCount];
const i = std.sort.binarySearch(Liquid, list, place, struct {
fn order(target: usize, item: Liquid) std.math.Order {
return std.math.order(target, item.place);
}
}.order) orelse return 0;
return list[i].look;
}
};
/// Chunks remembered, and how many of them can have blocks to draw: 80 KiB each.
pub const defaultChunks = 4096;
pub const defaultChunksWithBlocks = 128;
const Entry = struct {
position: Position,
/// Where its looks are in `slots`, or null for a chunk with nothing to draw.
slot: ?u32,
/// When it was last used, by `clock`.
used: u64,
};
entries: []Entry,
count: usize = 0,
/// Each position's index in `entries`.
byPosition: std.AutoHashMapUnmanaged(Position, u32),
slots: []Slot,
/// Slots no entry holds, the first `freeCount` of them.
free: []u32,
freeCount: usize,
clock: u64 = 0,
fn init(allocator: std.mem.Allocator, chunks: u32, chunksWithBlocks: u32) !ChunkCache {
const entries = try allocator.alloc(Entry, chunks);
errdefer allocator.free(entries);
var byPosition: std.AutoHashMapUnmanaged(Position, u32) = .empty;
try byPosition.ensureTotalCapacity(allocator, chunks);
errdefer byPosition.deinit(allocator);
const slots = try allocator.alloc(Slot, chunksWithBlocks);
errdefer allocator.free(slots);
const free = try allocator.alloc(u32, chunksWithBlocks);
for (free, 0..) |*slot, i| slot.* = @intCast(i);
return .{ .entries = entries, .byPosition = byPosition, .slots = slots, .free = free, .freeCount = free.len };
}
fn deinit(self: *ChunkCache, allocator: std.mem.Allocator) void {
allocator.free(self.free);
allocator.free(self.slots);
self.byPosition.deinit(allocator);
allocator.free(self.entries);
}
fn get(self: *ChunkCache, position: Position) Lookup {
const index = self.byPosition.get(position) orelse return .uncached;
const entry = &self.entries[index];
self.clock += 1;
entry.used = self.clock;
return if (entry.slot) |slot| .{ .slot = &self.slots[slot] } else .empty;
}
/// Remembers `position`, which must not be cached yet, and returns where to write its looks
/// if it has `blocks`, or null.
fn put(self: *ChunkCache, position: Position, blocks: bool) ?*Slot {
var index: usize = undefined;
var slot: ?u32 = null;
if (blocks and self.freeCount == 0) {
// The chunk with blocks used longest ago makes room in both.
index = self.leastRecent(true);
slot = self.entries[index].slot;
_ = self.byPosition.remove(self.entries[index].position);
} else {
if (self.count < self.entries.len) {
index = self.count;
self.count += 1;
} else {
index = self.leastRecent(false);
_ = self.byPosition.remove(self.entries[index].position);
if (self.entries[index].slot) |freed| {
self.free[self.freeCount] = freed;
self.freeCount += 1;
}
}
if (blocks) {
self.freeCount -= 1;
slot = self.free[self.freeCount];
}
}
self.clock += 1;
self.entries[index] = .{ .position = position, .slot = slot, .used = self.clock };
self.byPosition.putAssumeCapacity(position, @intCast(index));
return if (slot) |s| &self.slots[s] else null;
}
/// The entry used longest ago, of those with blocks if `withBlocks`.
fn leastRecent(self: *const ChunkCache, withBlocks: bool) usize {
var oldest: usize = 0;
var oldestUse: u64 = std.math.maxInt(u64);
for (self.entries[0..self.count], 0..) |entry, i| {
if (withBlocks and entry.slot == null) continue;
if (entry.used < oldestUse) {
oldest = i;
oldestUse = entry.used;
}
}
return oldest;
}
};
test ChunkCache {
var cache: ChunkCache = try .init(std.testing.allocator, 3, 2);
defer cache.deinit(std.testing.allocator);
const a: ChunkCache.Position = .{ .x = 1, .y = 0, .z = 0 };
const b: ChunkCache.Position = .{ .x = 2, .y = 0, .z = 0 };
const c: ChunkCache.Position = .{ .x = 3, .y = 0, .z = 0 };
const d: ChunkCache.Position = .{ .x = 4, .y = 0, .z = 0 };
try std.testing.expect(cache.get(a) == .uncached);
cache.put(a, true).?.looks[0] = 7;
cache.put(b, true).?.looks[0] = 8;
try std.testing.expect(cache.put(c, false) == null);
try std.testing.expectEqual(7, cache.get(a).slot.looks[0]);
try std.testing.expect(cache.get(c) == .empty);
// No slot is free for d's blocks: b, used longest ago of the chunks with blocks, makes room.
cache.put(d, true).?.looks[0] = 9;
try std.testing.expect(cache.get(b) == .uncached);
try std.testing.expectEqual(9, cache.get(d).slot.looks[0]);
try std.testing.expectEqual(7, cache.get(a).slot.looks[0]);
// Every entry is taken: c, now used longest ago, makes room for an empty chunk.
try std.testing.expect(cache.put(b, false) == null);
try std.testing.expect(cache.get(c) == .uncached);
try std.testing.expect(cache.get(b) == .empty);
}
test "ChunkCache.Slot.liquidAt" {
const slot = try std.testing.allocator.create(ChunkCache.Slot);
defer std.testing.allocator.destroy(slot);
slot.liquidCount = 0;
try std.testing.expectEqual(0, slot.liquidAt(7));
slot.addLiquid(7, 3);
slot.addLiquid(900, 4);
try std.testing.expectEqual(3, slot.liquidAt(7));
try std.testing.expectEqual(4, slot.liquidAt(900));
try std.testing.expectEqual(0, slot.liquidAt(8));
// Past what it holds, a place has none.
for (0..ChunkCache.Slot.maxLiquids) |i| slot.addLiquid(1000 + i, 5);
try std.testing.expectEqual(ChunkCache.Slot.maxLiquids, slot.liquidCount);
try std.testing.expectEqual(5, slot.liquidAt(1000));
try std.testing.expectEqual(0, slot.liquidAt(1000 + ChunkCache.Slot.maxLiquids - 1));
}
/// The tiles the chunk columns are drawn on, from the bottom of the world to its top.
fn tileList(allocator: std.mem.Allocator, columns: []const world.ChunkColumn, height: u16, rotation: Rotation) ![]tiles.Tile {
var set: std.AutoArrayHashMapUnmanaged(tiles.Tile, void) = .empty;
defer set.deinit(allocator);
for (columns) |column| {
const x = @as(i64, column.x) * side;
const z = @as(i64, column.z) * side;
const ax, const az = rotation.toView(x, z);
const bx, const bz = rotation.toView(x + side - 1, z + side - 1);
const box: Box = .of(@min(ax, bx), 0, @min(az, bz), @max(ax, bx), @as(i64, height) - 1, @max(az, bz));
var ty = @divFloor(box.top, tiles.size);
while (ty * tiles.size < box.bottom) : (ty += 1) {
var tx = @divFloor(box.left, tiles.size);
while (tx * tiles.size < box.right) : (tx += 1) {
try set.put(allocator, .{ .x = @intCast(tx), .y = @intCast(ty) }, {});
}
}
}
return allocator.dupe(tiles.Tile, set.keys());
}
test tileList {
// One chunk column 256 blocks high: 64 blocks of x − z wide, and 64 of x + z plus 256 high,
// around screen x 0, from 256 blocks up down to its bottom corner.
const box = Box.of(0, 0, 0, 31, 255, 31);
try std.testing.expectEqual(Box{ .left = -32 * across, .top = -256 * below, .right = 32 * across, .bottom = 62 * down - below + blockWidth }, box);
const list = try tileList(std.testing.allocator, &.{.{ .x = 0, .z = 0 }}, 256, .deg0);
defer std.testing.allocator.free(list);
const columns = @divFloor(box.right - 1, tiles.size) - @divFloor(box.left, tiles.size) + 1;
const rows = @divFloor(box.bottom - 1, tiles.size) - @divFloor(box.top, tiles.size) + 1;
try std.testing.expectEqual(@as(usize, @intCast(columns * rows)), list.len);
// Turned half way, the column is in the blocks from −32 to −1 of the view.
const turned = try tileList(std.testing.allocator, &.{.{ .x = 0, .z = 0 }}, 256, .deg180);
defer std.testing.allocator.free(turned);
const far = Box.of(-32, 0, -32, -1, 255, -1);
try std.testing.expect(turned.len > 0);
for (turned) |tile| {
try std.testing.expect(tile.x * tiles.size < far.right and (tile.x + 1) * tiles.size > far.left);
try std.testing.expect(tile.y * tiles.size < far.bottom and (tile.y + 1) * tiles.size > far.top);
}
}
/// How each face of a block's square is lit, by pixel. The left and right faces are those towards
/// the view's +z and +x, which are south and east only at `Rotation.deg0`.
const Face = enum { none, top, left, right };
/// Which face each pixel of a block's square shows, by where its centre falls.
const faces: [blockWidth][blockWidth]Face = faces: {
@setEvalBranchQuota(10_000);
var out: [blockWidth][blockWidth]Face = undefined;
const a: f32 = across;
const d: f32 = down;
for (0..blockWidth) |row| for (0..blockWidth) |column| {
const x = @as(f32, @floatFromInt(column)) + 0.5;
const y = @as(f32, @floatFromInt(row)) + 0.5;
out[row][column] = if (@abs(x - a) / a + @abs(y - d) / d < 1)
.top
else if (x > a and y > 2 * d - (x - a) * d / a and y < 2 * d + below - (x - a) * d / a)
.right
else if (x < a and y > d + x * d / a and y < d + below + x * d / a)
.left
else
.none;
};
break :faces out;
};
test faces {
// The top face fills the middle of the top half, and the other two the left and right of the
// bottom half; the corners are empty.
const w = blockWidth;
try std.testing.expectEqual(Face.top, faces[w / 4][w / 2]);
try std.testing.expectEqual(Face.none, faces[0][0]);
try std.testing.expectEqual(Face.left, faces[w * 5 / 8][w / 4]);
try std.testing.expectEqual(Face.right, faces[w * 5 / 8][w * 3 / 4]);
try std.testing.expectEqual(Face.none, faces[w - 1][0]);
// Each face is a quarter of the square.
var counts: std.EnumArray(Face, usize) = .initFill(0);
for (faces) |row| for (row) |face| {
counts.getPtr(face).* += 1;
};
for ([_]Face{ .top, .left, .right }) |face| try std.testing.expectEqual(blockWidth * blockWidth / 4, counts.get(face));
// Blocks at the same depth, x + y + z, never cover the same pixel, so the depth buffer can
// draw blocks in any order.
var drawn: [6 * blockWidth][6 * blockWidth]bool = @splat(@splat(false));
for (0..3) |bx| for (0..3) |by| for (0..3) |bz| {
if (bx + by + bz != 3) continue;
const left = (bx + 2 - bz) * across;
const top = (bx + bz) * down + (2 - by) * below;
for (0..blockWidth) |row| for (0..blockWidth) |column| {
if (faces[row][column] == .none) continue;
try std.testing.expect(!drawn[top + row][left + column]);
drawn[top + row][left + column] = true;
};
};
}
/// Each face's light, in 256ths.
const light = std.EnumArray(Face, u16).init(.{ .none = 0, .top = 256, .left = 208, .right = 176 });
/// What a tile's depth buffer counts in: `depthSteps`ths of a block, of x + y + z of the point
/// each pixel shows in the view's coordinates, larger nearer.
const depthSteps = 256;
/// A tile's depth buffer, each pixel's depth counted from the tile's base (`Worker.depthBase`).
const Depths = [tiles.size * tiles.size]i32;
/// The depth of a pixel nothing is drawn on yet.
const emptyDepth = std.math.minInt(i32);
/// How many pixels lower than its place's the top of a cube `sixteenths` high is.
fn dropOf(sixteenths: u8) u8 {
return @intCast((16 - @as(usize, @min(sixteenths, 16))) * below / 16);
}
/// A pixel of a cube's sprite, and the face it's on.
const CubePixel = struct { face: Face, row: usize, column: usize };
/// The pixel of a cube's sprite that shows at (`row`, `column`) of its square when its top is
/// `drop` pixels lower: the top's, moved down, or a side's below it, the side's upper `drop`
/// pixels left out. Null where nothing shows.
fn loweredPixel(row: usize, column: usize, drop: usize) ?CubePixel {
if (row < drop) return null;
const moved = faces[row - drop][column];
if (moved == .top) return .{ .face = .top, .row = row - drop, .column = column };
const here = faces[row][column];
return if (moved != .none and moved == here) .{ .face = here, .row = row, .column = column } else null;
}
/// How much farther back a top `drop` pixels lower is, in `depthSteps`ths.
fn dropDepth(drop: usize) i32 {
return @intCast(drop * depthSteps / below);
}
test loweredPixel {
const w = blockWidth;
// Not lowered, every pixel is its own.
for (0..w) |row| for (0..w) |column| {
const pixel = loweredPixel(row, column, 0);
if (faces[row][column] == .none) {
try std.testing.expectEqual(null, pixel);
} else try std.testing.expectEqual(CubePixel{ .face = faces[row][column], .row = row, .column = column }, pixel.?);
};
// Lowered by 2: the top's first rows show nothing, and its middle is 2 rows down.
try std.testing.expectEqual(null, loweredPixel(1, w / 2, 2));
try std.testing.expectEqual(CubePixel{ .face = .top, .row = w / 4, .column = w / 2 }, loweredPixel(w / 4 + 2, w / 2, 2).?);
// Just under the top's old edge, a side's pixel is now the top's; lower down it's its own.
try std.testing.expectEqual(Face.top, loweredPixel(w / 2 + 1, w / 2 - 1, 2).?.face);
try std.testing.expectEqual(CubePixel{ .face = .left, .row = w * 3 / 4, .column = w / 4 }, loweredPixel(w * 3 / 4, w / 4, 2).?);
// The left edge's corner, where the side began, shows nothing.
try std.testing.expectEqual(null, loweredPixel(w / 4 + 1, 0, 2));
// A top a block lower is as far back as the block below's.
try std.testing.expectEqual(depthSteps, dropDepth(below));
try std.testing.expectEqual(0, dropOf(16));
try std.testing.expectEqual(2, dropOf(14));
}
/// How far into its block each pixel of a cube's square shows the cube: x + y + z of the point
/// there on the face it shows, the block being from 0 to 1, in `depthSteps`ths. At the middle of
/// a pixel, two cubes' faces are never less than a 64th of a block apart, so blocks keep the
/// order whole blocks' depths gave them.
const cubeDepths: [blockWidth][blockWidth]i16 = depths: {
@setEvalBranchQuota(20_000);
var out: [blockWidth][blockWidth]i16 = undefined;
const a: f32 = across;
const d: f32 = down;
const b: f32 = below;
for (0..blockWidth) |row| for (0..blockWidth) |column| {
const x = @as(f32, @floatFromInt(column)) + 0.5;
const y = @as(f32, @floatFromInt(row)) + 0.5;
// Where a point at (x, y, z) is drawn (`textureCoordinates`), turned round for each face.
const depth: f32 = switch (faces[row][column]) {
.none => 0,
.top => y / d + 1,
.left => x / a + (1 - (y - d * x / a - d) / b) + 1,
.right => 1 + (1 - (y - d - d * (2 - x / a)) / b) + (2 - x / a),
};
out[row][column] = @intFromFloat(@round(depth * depthSteps));
};
break :depths out;
};
test cubeDepths {
const w = blockWidth;
// The top's far corner, at the top of the square, is (0, 1, 0), and the near corner, where
// the three faces meet, is (1, 1, 1) on each of them.
try std.testing.expectApproxEqAbs(@as(f32, depthSteps), @as(f32, @floatFromInt(cubeDepths[0][w / 2])), depthSteps / 8);
for ([_][2]usize{ .{ w / 2 - 1, w / 2 - 1 }, .{ w / 2, w / 2 - 1 }, .{ w / 2, w / 2 } }) |at| {
try std.testing.expectApproxEqAbs(@as(f32, 3 * depthSteps), @as(f32, @floatFromInt(cubeDepths[at[0]][at[1]])), depthSteps / 8);
}
// The bottom corner is (1, 0, 1).
try std.testing.expectApproxEqAbs(@as(f32, 2 * depthSteps), @as(f32, @floatFromInt(cubeDepths[w - 1][w / 2])), depthSteps / 8);
}
/// Each map type's three face colours at each height in the relief style:
/// `(mapType * heights.world + y) * 3`, top, left, right.
fn reliefColours(allocator: std.mem.Allocator, palette: *const world.Palette, heights: world.Heights) ![]u32 {
const types = std.enums.values(world.MapType);
const colours = try allocator.alloc(u32, types.len * heights.world * 3);
const shades: relief.Heights = .of(heights);
for (types) |mapType| for (0..heights.world) |y| {
const base = palette.colours.get(mapType);
const colour = if (mapType.isLiquid()) relief.liquidColour(base, 0) else relief.groundColour(palette, base, @intCast(y), shades, 0);
const at = (@backingInt(mapType) * heights.world + y) * 3;
colours[at] = lit(colour, light.get(.top));
colours[at + 1] = lit(colour, light.get(.left));
colours[at + 2] = lit(colour, light.get(.right));
};
return colours;
}
/// A colour's top, left and right faces, lit.
fn faceColours(colour: world.Rgb) [3]u32 {
const pixel = tiles.rgba(colour[0], colour[1], colour[2], 255);
return .{ lit(pixel, light.get(.top)), lit(pixel, light.get(.left)), lit(pixel, light.get(.right)) };
}
const Sprite = Sprites.Sprite;
const SpriteLayers = Sprites.SpriteLayers;
/// Draws `cube`'s sprite in its variant `variant`, as `rotation` shows it, into `sections`.
fn cubeSprite(sections: *Sprites.Sections, cube: *const world.CubeFaces, variant: usize, fallback: world.Rgb, rotation: Rotation) !void {
const left, const right = rotation.sides(cube);
const room = try sections.add(.{
.left = 0,
.top = 0,
.width = blockWidth,
.height = blockWidth,
.flags = .{ .tinted = cube.up.tinted.len > 0 or left.tinted.len > 0 or right.tinted.len > 0, .fills = true },
});
cubeLayers(cube, variant, fallback, rotation, room.plain, room.tinted);
@memcpy(room.depths, @as(*const [blockWidth * blockWidth]i16, @ptrCast(&cubeDepths)));
}
/// Points sampled across and down each pixel of a sprite.
const samples = 2;
/// How many sprites `cube` has: as many as the most variants any of its layers has.
fn variantCount(cube: *const world.CubeFaces) usize {
var count: usize = 1;
for ([_]world.CubeFaces.Face{ cube.up, cube.south, cube.east, cube.north, cube.west }) |face| count = @max(count, face.plain.len, face.tinted.len);
return count;
}
/// Draws `cube` in its textures, as `rotation` shows it, each layer in its variant `variant`
/// (counting round again for a layer with fewer): each pixel of a layer is the average of its
/// texels under it. A plain pixel over only transparent texels is `fallback`. `plain` takes the
/// faces' plain layers, opaque on every face and transparent where none is, and `tinted`, where
/// any face has one, their tinted layers, lit but not yet tinted, each pixel's alpha how much of
/// it the layer covers.
fn cubeLayers(cube: *const world.CubeFaces, variant: usize, fallback: world.Rgb, rotation: Rotation, plain: []u32, tinted: ?[]u32) void {
const left, const right = rotation.sides(cube);
for (0..blockWidth) |row| for (0..blockWidth) |column| {
const p = row * blockWidth + column;
const face = faces[row][column];
const layers = switch (face) {
.none => {
plain[p] = tiles.transparent;
if (tinted) |out| out[p] = tiles.transparent;
continue;
},
.top => cube.up,
.left => left,
.right => right,
};
const texel = average(face, rotation, column, row, pick(layers.plain, variant));
const colour = if (texel[3] == 0) fallback else texel[0..3].*;
plain[p] = lit(tiles.rgba(colour[0], colour[1], colour[2], 255), light.get(face));
const out = tinted orelse continue;
var layer = average(face, rotation, column, row, pick(layers.tinted, variant));
// A face that's all tinted, as leaves are, has its holes filled with `fallback` to be
// tinted too, rather than showing what's under it untinted.
if (layers.plain.len == 0 and layers.tinted.len > 0) layer = if (layer[3] == 0) fallback ++ [1]u8{255} else layer[0..3].* ++ [1]u8{255};
out[p] = lit(tiles.rgba(layer[0], layer[1], layer[2], layer[3]), light.get(face));
};
}
/// A layer's variant `variant`, counting round again past its last; null without the layer.
fn pick(variants: []const *const world.Image, variant: usize) ?*const world.Image {
return if (variants.len == 0) null else variants[variant % variants.len];
}
/// The average of `image`'s texels under a pixel of a face, by their opacity, and how opaque
/// they are on average; transparent without an image.
fn average(face: Face, rotation: Rotation, column: usize, row: usize, image: ?*const world.Image) [4]u8 {
const texture = image orelse return @splat(0);
var sum: [4]u32 = @splat(0);
for (0..samples) |sy| for (0..samples) |sx| {
const x = @as(f32, @floatFromInt(column)) + (@as(f32, @floatFromInt(sx)) + 0.5) / samples;
const y = @as(f32, @floatFromInt(row)) + (@as(f32, @floatFromInt(sy)) + 0.5) / samples;
const u, const v = textureCoordinates(face, rotation, x, y);
const texel = texelAt(texture, u, v);
for (0..3) |c| sum[c] += @as(u32, texel[c]) * texel[3];
sum[3] += texel[3];
};
if (sum[3] == 0) return @splat(0);
return .{
@intCast(sum[0] / sum[3]),
@intCast(sum[1] / sum[3]),
@intCast(sum[2] / sum[3]),
@intCast(sum[3] / (samples * samples)),
};
}
/// A sprite's pixel: its tinted layer, times `tint`, drawn over its plain one by how much it
/// covers.
fn blend(plain: u32, layer: u32, tint: world.Rgb) u32 {
const top = std.mem.asBytes(&layer);
const a: u32 = top[3];
if (a == 0) return plain;
const under = std.mem.asBytes(&plain);
var out: [3]u8 = undefined;
for (&out, top[0..3], under[0..3], tint) |*channel, t, p, c| {
const tinted = @as(u32, t) * c / 255;
channel.* = @intCast((tinted * a + @as(u32, p) * (255 - a)) / 255);
}
return tiles.rgba(out[0], out[1], out[2], 255);
}
/// One row of a sprite's layers, or the part of it on a tile.
const SpriteRow = struct {
plain: []const u32,
tinted: ?[]const u32,
depths: []const i16,
};
/// Draws `span`, its depths counted from `base`, over the same number of `pixels` and their
/// `depths`, on each pixel where it shows something nearer than what's there; its tinted layer
/// tinted by `tint`. Returns whether it drew any.
fn drawSpriteRow(span: SpriteRow, base: i32, tint: world.Rgb, pixels: []u32, depths: []i32) bool {
var any = false;
var i: usize = 0;
// The vector code reads a pixel's channels from its bits, as they lie in little-endian.
if (builtin.cpu.arch.endian() == .little) {
const lanes = 8;
const Colours = @Vector(lanes, u32);
const Depths8 = @Vector(lanes, i32);
while (i + lanes <= pixels.len) : (i += lanes) {
const plain: Colours = span.plain[i..][0..lanes].*;
const spriteDepths: @Vector(lanes, i16) = span.depths[i..][0..lanes].*;
const point = @as(Depths8, @splat(base)) + @as(Depths8, spriteDepths);
var colour = plain;
var alphas = plain;
if (span.tinted) |layer| {
const tinted: Colours = layer[i..][0..lanes].*;
colour = blendLanes(lanes, plain, tinted, tint);
alphas |= tinted;
}
// Where it shows nothing, its depth can't beat even an empty pixel's, and what's
// behind it shows.
const shows = alphas >> @splat(24) != @as(Colours, @splat(0));
const old: Depths8 = depths[i..][0..lanes].*;
const nearer = @select(i32, shows, point, @as(Depths8, @splat(emptyDepth))) > old;
if (!@reduce(.Or, nearer)) continue;
depths[i..][0..lanes].* = @select(i32, nearer, point, old);
pixels[i..][0..lanes].* = @select(u32, nearer, colour, @as(Colours, pixels[i..][0..lanes].*));
any = true;
}
}
while (i < pixels.len) : (i += 1) {
const shows = span.plain[i] & 0xff000000 != 0 or if (span.tinted) |layer| layer[i] & 0xff000000 != 0 else false;
if (!shows) continue;
const point = base + span.depths[i];
if (point <= depths[i]) continue;
depths[i] = point;
pixels[i] = if (span.tinted) |layer| blend(span.plain[i], layer[i], tint) else span.plain[i];
any = true;
}
return any;
}
/// `blend` on `lanes` pixels at once. Dividing by 255 is `(x + 1 + (x >> 8)) >> 8`, exact for
/// every x up to 65,534, and `blend` divides at most 255 × 255.
fn blendLanes(comptime lanes: usize, plain: @Vector(lanes, u32), layer: @Vector(lanes, u32), tint: world.Rgb) @Vector(lanes, u32) {
const Colours = @Vector(lanes, u32);
const byte: Colours = @splat(0xff);
const div255 = struct {
fn f(x: Colours) Colours {
return (x + @as(Colours, @splat(1)) + (x >> @splat(8))) >> @splat(8);
}
}.f;
const a = layer >> @splat(24);
const rest = @as(Colours, @splat(255)) - a;
var out: Colours = @splat(0xff000000);
inline for (0..3) |k| {
const channelShift: Colours = @splat(8 * k);
const tinted = div255((layer >> channelShift & byte) * @as(Colours, @splat(tint[k])));
out |= div255(tinted * a + (plain >> channelShift & byte) * rest) << channelShift;
}
return @select(u32, a == @as(Colours, @splat(0)), plain, out);
}
test drawSpriteRow {
// Rows of 21 pixels, past two vectors, with random plain and tinted layers, alphas often 0,
// and depths around what's already there: the same as drawing each pixel on its own.
var prng: std.Random.DefaultPrng = .init(5);
const random = prng.random();
for (0..200) |_| {
var plain: [21]u32 = undefined;
var tinted: [21]u32 = undefined;
var spriteDepths: [21]i16 = undefined;
var pixels: [21]u32 = undefined;
var depths: [21]i32 = undefined;
for (&plain, &tinted, &spriteDepths, &pixels, &depths) |*p, *t, *d, *pixel, *depth| {
p.* = random.int(u32) & if (random.boolean()) @as(u32, 0x00ffffff) else 0xffffffff;
t.* = random.int(u32) & if (random.boolean()) @as(u32, 0x00ffffff) else 0xffffffff;
d.* = random.intRangeAtMost(i16, -300, 300);
pixel.* = random.int(u32);
depth.* = if (random.uintLessThan(u8, 4) == 0) emptyDepth else random.intRangeAtMost(i32, 900, 1300);
}
const tint: world.Rgb = .{ random.int(u8), random.int(u8), random.int(u8) };
for ([_]?[]const u32{ null, &tinted }) |layer| {
const span: SpriteRow = .{ .plain = &plain, .tinted = layer, .depths = &spriteDepths };
var expectedPixels = pixels;
var expectedDepths = depths;
for (0..plain.len) |i| {
const shows = plain[i] & 0xff000000 != 0 or if (layer) |l| l[i] & 0xff000000 != 0 else false;
const point = 1000 + @as(i32, spriteDepths[i]);
if (!shows or point <= depths[i]) continue;
expectedDepths[i] = point;
expectedPixels[i] = if (layer) |l| blend(plain[i], l[i], tint) else plain[i];
}
var gotPixels = pixels;
var gotDepths = depths;
_ = drawSpriteRow(span, 1000, tint, &gotPixels, &gotDepths);
try std.testing.expectEqualSlices(u32, &expectedPixels, &gotPixels);
try std.testing.expectEqualSlices(i32, &expectedDepths, &gotDepths);
}
}
}
/// `colour` multiplied by `tint`, each channel rounded down, as the game tints.
fn multiply(colour: world.Rgb, tint: world.Rgb) world.Rgb {
var out: world.Rgb = undefined;
for (&out, colour, tint) |*channel, c, t| channel.* = @intCast(@as(u16, c) * t / 255);
return out;
}
/// Where a point in a block's square falls on the texture of the face it's on: across and down
/// it, each from 0 to 1. A point at (x, y, z) in the view, block (0, 0, 0) being the cube from 0
/// to 1, is drawn at ((x − z + 1) · `across`, (x + z) · `down` − (y − 1) · `below`) in its square.
/// Seen from outside, a side's texture reads the same way round in every rotation, and a top's
/// turns with the view, as its north stays north.
fn textureCoordinates(face: Face, rotation: Rotation, x: f32, y: f32) [2]f32 {
const a: f32 = across;
const d: f32 = down;
const b: f32 = below;
const coordinates: [2]f32 = switch (face) {
.none => unreachable,
// At height 1.
.top => rotation.pointToWorld((x / a - 1 + y / d) / 2, (y / d - x / a + 1) / 2),
// At the view's z = 1.
.left => .{ x / a, 1 - ((x / a + 1) * d + b - y) / b },
// At the view's x = 1.
.right => .{ x / a - 1, 1 - ((3 - x / a) * d + b - y) / b },
};
return .{ std.math.clamp(coordinates[0], 0, 1), std.math.clamp(coordinates[1], 0, 1) };
}
test textureCoordinates {
const w: f32 = blockWidth;
// Each face's corners: the top's highest is its texture's top left (north-west), and its
// leftmost the bottom left (south-west).
try std.testing.expectEqual([2]f32{ 0, 0 }, textureCoordinates(.top, .deg0, w / 2, 0));
try std.testing.expectEqual([2]f32{ 0, 1 }, textureCoordinates(.top, .deg0, 0, w / 4));
try std.testing.expectEqual([2]f32{ 1, 1 }, textureCoordinates(.top, .deg0, w / 2, w / 2));
try std.testing.expectEqual([2]f32{ 0, 0 }, textureCoordinates(.left, .deg0, 0, w / 4));
try std.testing.expectEqual([2]f32{ 1, 1 }, textureCoordinates(.left, .deg0, w / 2, w));
try std.testing.expectEqual([2]f32{ 0, 0 }, textureCoordinates(.right, .deg0, w / 2, w / 2));
try std.testing.expectEqual([2]f32{ 1, 1 }, textureCoordinates(.right, .deg0, w, w * 3 / 4));
// The top's highest corner is the far one: north-east at 90°, south-east at 180° and
// south-west at 270°.
try std.testing.expectEqual([2]f32{ 1, 0 }, textureCoordinates(.top, .deg90, w / 2, 0));
try std.testing.expectEqual([2]f32{ 1, 1 }, textureCoordinates(.top, .deg180, w / 2, 0));
try std.testing.expectEqual([2]f32{ 0, 1 }, textureCoordinates(.top, .deg270, w / 2, 0));
// The sides are the same whichever faces they are.
try std.testing.expectEqual(textureCoordinates(.left, .deg0, 3, w / 2), textureCoordinates(.left, .deg180, 3, w / 2));
}
const texelAt = rasterizer.texelAt;
/// How many sprites `shape` has: as many as the most variants any of its textures has.
fn shapeVariants(shape: *const world.Shape) usize {
var count: usize = 1;
for (shape.textures) |texture| count = @max(count, texture.plain.len, texture.tinted.len);
return count;
}
/// How far beyond a cube's square a shape's sprite reaches, in pixels, each way: parts of a
/// shape farther out are cut off.
const reach = blockWidth;
/// How far a block moved off the middle of its place (`drawOffset`), less than half a block
/// east and south, can move its sprite, in pixels.
const shift = blockWidth / 2;
/// The side of what a shape's sprite is drawn in (`ShapeTarget`), in pixels.
const shapeSide = blockWidth + 2 * reach;
/// What a shape's sprite is drawn in first: `samples` × `samples` points for each of its
/// pixels, over the cube's square and `reach` around it.
const ShapeTarget = rasterizer.Target;
fn shapeTarget(allocator: std.mem.Allocator) !ShapeTarget {
return .init(allocator, shapeSide * samples, shapeSide * samples);
}
/// How many ways a block turned by where it is can be turned (`Drawable.turned`), about the
/// vertical line through the middle of its place: turn i by −22.5° + 45° · i, as vsapi
/// `TesselationMetaData.randomRotations` lists them, from east towards north.
pub const turns = 8;
/// A face of a shape as it's drawn: where its corners land in a `ShapeTarget`, its image, its light
/// and its layer, 1 for the plain one and 2 for the tinted.
const ShapeFace = struct { corners: [4]rasterizer.Corner, image: *const world.Image, light: u16, tag: u8 };
/// How many faces of a shape `shapeFaces` must have room for.