desmack 0.2.0

Extracts the assets of a SMK ROM (SNES)
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
use std::fs;
use std::path::Path;

use anyhow::{Context, bail, ensure};

use crate::graphics::{cheep_cheep_frames, mode7, podium_mode7};
use crate::maps::{THEMES, bytes, long, near, stream, word};
use crate::rom::{Region, Rom};
use crate::textures::{palette, theme_stream, write_png};

/// Six blocks of 640 bytes: four 16×16 frames of 4 tiles each, then four 8×8 frames.
const ITEMS: usize = 0x40594;

/// Each item's blocks and sprite palette. The two shell blocks are its spin; the red shell is the
/// green one in another palette.
const ITEM_SETS: [(&str, &[usize], u16); 6] = [
	("banana", &[0], 6),
	("green-shell", &[1, 2], 6),
	("red-shell", &[1, 2], 5),
	("poison-mushroom", &[3], 5),
	("fireball", &[4], 6),
	("egg", &[5], 5),
];

/// The coin a driver spends or loses spins through three 16×16 tile words of the race sprites, in
/// palette 6. A fourth word follows, which the game never reaches.
const COIN: usize = 0x5E67F;
const COIN_FRAMES: usize = 3;

/// Course list group 2: a Theme's 57 hazard tiles, which the game loads at OBJ tile `0xC0`.
const HAZARD_TILES: usize = 2;
const HAZARD_BASE: usize = 0xC0;
/// A blank 16×16 OBJ tile that Ghost Valley's pillars pad their frames with.
const BLANK: u16 = 0x84;

const GHOST_VALLEY: usize = 0;
const MARIO_CIRCUIT: usize = 1;
const DONUT_PLAINS: usize = 2;
const CHOCO_ISLAND: usize = 3;
const KOOPA_BEACH: usize = 5;
const BOWSER_CASTLE: usize = 6;

/// Indices into [`Bank0::of`]'s scripts.
const PIRANHA: usize = 0;
const THWOMP: usize = 2;
const MOLE: usize = 3;
const PIPE: usize = 5;
const PILLAR: usize = 6;
const SHADOW: usize = 7;

/// Each hazard's name, graphics Theme, palette Theme and scripts, each with the value the game
/// XORs into its tile words. Donut Plains 1 draws Mario Circuit's pipes in palette 5; Vanilla
/// Lake's pipes are Mario Circuit's; Rainbow Road's Thwomps are Bowser Castle's, cycling through
/// palettes.
type Scripted = &'static [(usize, u16)];

const HAZARDS: [(&str, usize, usize, Scripted); 7] = [
	("pipe", MARIO_CIRCUIT, MARIO_CIRCUIT, &[(PIPE, 0)]),
	("orange-pipe", MARIO_CIRCUIT, DONUT_PLAINS, &[(PIPE, 0x400)]),
	("pillar", GHOST_VALLEY, GHOST_VALLEY, &[(PILLAR, 0)]),
	(
		"monty-mole",
		DONUT_PLAINS,
		DONUT_PLAINS,
		&[(MOLE, 0), (MOLE + 1, 0)],
	),
	(
		"piranha-plant",
		CHOCO_ISLAND,
		CHOCO_ISLAND,
		&[(PIRANHA, 0), (PIRANHA + 1, 0)],
	),
	(
		"cheep-cheep",
		KOOPA_BEACH,
		KOOPA_BEACH,
		&[(PIRANHA, 0), (PIRANHA + 1, 0)],
	),
	(
		"thwomp",
		BOWSER_CASTLE,
		BOWSER_CASTLE,
		&[(THWOMP, 0x600), (SHADOW, 0)],
	),
];

/// Where each Region keeps its sprite routines, hazard scripts and driver tables, in bank 0.
struct Bank0 {
	routines: usize,
	scripts: [usize; 8],
	drivers: usize,
}

impl Bank0 {
	fn of(region: Region) -> Bank0 {
		match region {
			Region::Japan => Bank0 {
				routines: 0xBC34,
				scripts: [
					0xE0E1, 0xE0FD, 0xE2E8, 0xE3E1, 0xE3FD, 0xE5A7, 0xE71C, 0xED31,
				],
				drivers: 0x9069,
			},
			Region::Usa => Bank0 {
				routines: 0xBC0F,
				scripts: [
					0xE0BC, 0xE0D8, 0xE2C3, 0xE3BC, 0xE3D8, 0xE582, 0xE716, 0xED2B,
				],
				drivers: 0x9090,
			},
			Region::Europe => Bank0 {
				routines: 0xBC34,
				scripts: [
					0xE0E1, 0xE0FD, 0xE2E8, 0xE3E1, 0xE3FD, 0xE5A7, 0xE73B, 0xED50,
				],
				drivers: 0x9077,
			},
		}
	}
}

/// The drivers in the game's order, which the bank table follows, with their sprite palettes: two
/// drivers share each of sprite palettes 8–11.
pub const DRIVERS: [(&str, u16); 8] = [
	("mario", 1),
	("luigi", 2),
	("bowser", 0),
	("peach", 3),
	("dk-jr", 3),
	("koopa-troopa", 2),
	("toad", 1),
	("yoshi", 0),
];
const LUIGI: usize = 1;

/// The driver tables, from [`Bank0::of`]'s `drivers`: a (frame, layout) byte pair per frame code;
/// then each frame's address in a driver's bank; then, for Luigi, a word per frame code that picks
/// his own upper half, from the bank table after it. The banks come 16 bytes before.
///
/// The race codes are 11 scales, nearest first, of 16 angles from behind (0) to the front (15);
/// the game mirrors them for the other side. Far scales share a frame between angles. The
/// specials follow, which the game sets over the race codes.
const SCALES: usize = 11;
const ANGLES: usize = 16;
const SPECIALS: [&str; 5] = ["cheer-back", "look-back", "look-side", "cheer", "dazed"];
const FRAME_TABLE: usize = 0x16A;
const LUIGI_TABLE: usize = 0x202;
const LUIGI_TOPS: usize = 0x36C;
/// Luigi's upper halves are in bank `$84`; the rest of him is Mario's.
const LUIGI_BANK: usize = 0x84;
const MARIO_BANK: usize = 0xC0;

/// Lakitu, coins and the race's shared sprites: stream tiles 16–143 load at OBJ tile `0x40`, and
/// 12–15, the start lights, at `0xFB`.
const RACE_SPRITES: usize = 0x10000;
/// Lakitu's frames: a table of offsets from itself to metasprite records.
const LAKITU: usize = 0x5E264;
const LAKITU_FRAMES: usize = 14;
/// Lakitu's palette and his lights' are the same in every Theme.
pub const LAKITU_THEME: usize = MARIO_CIRCUIT;
/// The frame with the LAP sign. Its last sprite is the digit, tile `0xA2`; for laps 2–4 the game
/// swaps in `0xA1` + the lap, which shows from behind the sign.
const LAP_SIGN: usize = 11;
const LAP_DIGIT: u16 = 0xA1;

/// The podium's OBJ tiles are the first 320 of its stream. The game adds two heads per driver, the
/// upper halves of race frames: half rows of 2 tiles, `0x200` apart, from `0x40` and `0x5900`
/// (Luigi `0x2100`) past the address in this table, in [`DRIVERS`] order.
fn podium_heads(region: Region) -> usize {
	match region {
		Region::Usa => 0x59EEF,
		Region::Japan => 0x59EB2,
		Region::Europe => 0x59EF9,
	}
}
const PODIUM_OBJ: usize = 0x2800;
const HEAD_TILES: [usize; 8] = [0x140, 0x160, 0x144, 0x148, 0x14C, 0x164, 0x168, 0x16C];

/// The podium's frames: pointer tables in a row, each followed by its frames, which are OAM
/// entries (x, y, tile, attribute) ending in `0xFFFF`. Each frame is copied to OAM from a slot,
/// which sets its sprites' sizes.
fn podium_tables(region: Region) -> (usize, PodiumTables) {
	match region {
		Region::Usa => (0x5A330, PODIUM_TABLES),
		Region::Japan => (0x5A2DE, PODIUM_TABLES_JAPAN),
		Region::Europe => (0x5A33A, PODIUM_TABLES),
	}
}
/// Each table's driver and the slot of each of its frames, the last one repeating: the driver's
/// poses, then the champagne they hold and its spray. In Japan Bowser sprays too and Peach holds a
/// bottle.
type PodiumTables = &'static [(usize, &'static [usize])];
const PODIUM_TABLES: PodiumTables = &[
	(0, &[94]),
	(0, &[90]),
	(0, &[82, 82, 83, 84]),
	(2, &[94]),
	(2, &[90]),
	(3, &[94]),
	(4, &[94, 94, 94, 94, 84]),
	(4, &[90]),
	(1, &[94]),
	(1, &[90]),
	(1, &[90, 82, 84]),
	(5, &[94]),
	(5, &[90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 84]),
	(6, &[94]),
	(6, &[90]),
	(7, &[94]),
];
const PODIUM_TABLES_JAPAN: PodiumTables = &[
	(0, &[94]),
	(0, &[90]),
	(0, &[82, 82, 83, 84]),
	(2, &[94]),
	(2, &[90]),
	(2, &[82]),
	(3, &[94, 94, 92]),
	(3, &[90]),
	(4, &[94, 94, 94, 94, 84]),
	(4, &[90]),
	(1, &[94]),
	(1, &[90]),
	(1, &[90, 82, 84]),
	(5, &[94]),
	(5, &[90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 84]),
	(6, &[94]),
	(6, &[90]),
	(7, &[94]),
];
/// The podium makes OAM slots 80–83, 90, 91 and 94 on 16×16, the rest 8×8.
fn big(slot: usize) -> bool {
	matches!(slot, 80..=83 | 90 | 91 | 94..)
}
/// The podium's single sprites, tile word tables in bank `$85`: (name, table, count, 16×16). The
/// cups' icons float in the sky, the Special Cup's cycling through all three; Cheep Cheep brings
/// the trophy for the player's rank; confetti flutters through three frames per piece; the pop
/// bursts as the champagne opens, its third frame a blank tile.
fn podium_singles(region: Region) -> [(&'static str, usize, usize, bool); 4] {
	let [cups, trophies, confetti, pop] = match region {
		Region::Usa => [0x5A040, 0x5A32A, 0x5AB43, 0x5AB89],
		Region::Japan => [0x59FCE, 0x5A2D8, 0x5AB1F, 0x5AB65],
		Region::Europe => [0x5A04A, 0x5A334, 0x5AB4D, 0x5AB93],
	};
	[
		("cups", cups, 3, true),
		("trophies", trophies, 3, true),
		("confetti", confetti, 18, false),
		("pop", pop, 2, true),
	]
}
/// Sprites from this line down are hidden.
const HIDDEN: i32 = 0xE0;

/// The race's effect tiles: water and grass at OBJ tile 0, dust and smoke at `0x100`.
const EFFECT_TILES: usize = 0x903;
fn dust_tiles(region: Region) -> usize {
	match region {
		Region::Usa => 0x49C19,
		Region::Japan | Region::Europe => 0x49C1C,
	}
}
/// Six metasprite tables in a row, each a list of offsets from itself to its records.
const EFFECT_TABLES: usize = 0x5EE00;
/// Each effect's table and the value the game XORs into its tile words, as bank 0's effect list
/// pairs them: `0x100` picks the dust tiles, `0x400` swaps sprite palette 15 for 13. Frames come
/// in fours, each four one looping animation. Table 0's first 48 frames are for a Time Trial
/// against a ghost, the rest for a kart shrunk by lightning. Table 2's frames 1 and 5 are the
/// ripple over a sunken kart, which the splash's animation ends by looping.
type Picks = fn(usize) -> bool;

const EFFECTS: [(&str, usize, u16, Picks); 12] = [
	("dust", 5, 0x100, |_| true),
	("smoke", 5, 0x500, |_| true),
	("dust-vs-ghost", 0, 0x100, |k| k < 48),
	("smoke-vs-ghost", 0, 0x500, |k| k < 48),
	("dust-small", 0, 0x100, |k| k >= 48),
	("smoke-small", 0, 0x500, |k| k >= 48),
	("spray", 1, 0, |_| true),
	("splash", 2, 0, |k| k != 1 && k != 5),
	("ripple", 2, 0, |k| k == 1 || k == 5),
	("grass", 3, 0, |_| true),
	("smoke-puff", 4, 0x100, |_| true),
	("dust-puff", 4, 0x500, |_| true),
];

/// One OAM entry: a position, a tile word (tile, palette, flips) and whether it is 16×16.
#[derive(Clone, Copy)]
pub struct Sprite {
	pub x: i32,
	pub y: i32,
	pub tile: u16,
	pub big: bool,
}

pub fn items(rom: &Rom, folder: &Path) -> anyhow::Result<()> {
	let tiles = stream(&rom.data, ITEMS)?;
	ensure!(tiles.len() == 6 * 640, "item graphics are not 6 items");
	let palette = palette(rom, MARIO_CIRCUIT)?;
	for (name, blocks, pal) in ITEM_SETS {
		let mut frames = Vec::new();
		for block in blocks {
			for k in 0..8 {
				let tile = (block * 640 / 32 + if k < 4 { k * 4 } else { 16 + k - 4 }) as u16;
				let sprite = |x, y, tile| Sprite {
					x,
					y,
					tile: tile | pal << 9,
					big: false,
				};
				frames.push(if k < 4 {
					vec![
						sprite(0, 0, tile),
						sprite(8, 0, tile + 1),
						sprite(0, 8, tile + 2),
						sprite(8, 8, tile + 3),
					]
				} else {
					vec![sprite(0, 0, tile)]
				});
			}
		}
		write_frames(
			&folder.join("sprites/items").join(name),
			&frames,
			&tiles,
			&palette,
		)?;
	}
	write_frames(
		&folder.join("sprites/items/coin"),
		&tile_words(&rom.data, COIN, COIN_FRAMES, true)?,
		&race_tiles(rom)?,
		&palette,
	)
}

/// One single-sprite frame per tile word of the table at `at`.
fn tile_words(data: &[u8], at: usize, count: usize, big: bool) -> anyhow::Result<Vec<Vec<Sprite>>> {
	(0..count)
		.map(|k| {
			Ok(vec![Sprite {
				x: 0,
				y: 0,
				tile: word(data, at + k * 2)? as u16,
				big,
			}])
		})
		.collect()
}

pub fn hazards(rom: &Rom, folder: &Path) -> anyhow::Result<()> {
	let Bank0 {
		routines, scripts, ..
	} = Bank0::of(rom.region);
	for (name, graphics, colours, uses) in HAZARDS {
		let mut frames = Vec::new();
		for &(script, xor) in uses {
			frames.extend(script_frames(&rom.data, routines, scripts[script], xor)?);
		}
		write_frames(
			&folder.join("sprites/hazards").join(name),
			&frames,
			&theme_stream(rom, HAZARD_TILES, graphics)?,
			&palette(rom, colours)?,
		)?;
	}
	Ok(())
}

/// OBJ tiles 0–255 as the race loads its shared sprites.
pub fn race_tiles(rom: &Rom) -> anyhow::Result<Vec<u8>> {
	let stream = stream(&rom.data, RACE_SPRITES)?;
	ensure!(stream.len() >= 144 * 32, "race sprites stop short");
	let mut tiles = vec![0; 0x100 * 32];
	tiles[0x40 * 32..0xC0 * 32].copy_from_slice(&stream[16 * 32..144 * 32]);
	tiles[0xFB * 32..0xFF * 32].copy_from_slice(&stream[12 * 32..16 * 32]);
	Ok(tiles)
}

/// Lakitu's frames, then the LAP sign for laps 2–4.
pub fn cast(rom: &Rom, folder: &Path) -> anyhow::Result<()> {
	let mut frames = (0..LAKITU_FRAMES)
		.map(|k| metasprite(&rom.data, LAKITU + word(&rom.data, LAKITU + k * 2)?))
		.collect::<anyhow::Result<Vec<_>>>()?;
	for lap in 2..=4 {
		let mut sign = frames[LAP_SIGN].clone();
		let digit = sign.last_mut().context("the LAP sign has no sprites")?;
		digit.tile = digit.tile & 0xFF00 | (LAP_DIGIT + lap);
		frames.push(sign);
	}
	write_frames(
		&folder.join("sprites/cast/lakitu"),
		&frames,
		&race_tiles(rom)?,
		&palette(rom, LAKITU_THEME)?,
	)?;

	let (podium, tiles, colours) = podium_mode7(rom)?;
	let objects = podium_tiles(rom, &podium)?;
	for (driver, frames) in podium_frames(rom)?.iter().enumerate() {
		write_frames(
			&folder.join("sprites/cast/podium").join(DRIVERS[driver].0),
			frames,
			&objects,
			&colours,
		)?;
	}
	for (name, at, count, big) in podium_singles(rom.region) {
		write_frames(
			&folder.join("sprites/cast/podium").join(name),
			&tile_words(&rom.data, at, count, big)?,
			&objects,
			&colours,
		)?;
	}

	// The podium's Cheep Cheep is no sprite, but a piece of the Mode 7 map.
	let dir = folder.join("sprites/cast/cheep-cheep");
	fs::create_dir_all(&dir)?;
	for (i, pieces) in cheep_cheep_frames(rom)?.iter().enumerate() {
		let (width, height, pixels) = mode7(&tiles, pieces);
		write_png(
			&dir.join(format!("{i:03}.png")),
			width,
			height,
			&colours,
			&pixels,
		)?;
	}
	Ok(())
}

/// OBJ tiles 0–511 as the podium loads them.
fn podium_tiles(rom: &Rom, podium: &[u8]) -> anyhow::Result<Vec<u8>> {
	let mut tiles = vec![0; 0x200 * 32];
	tiles[..PODIUM_OBJ].copy_from_slice(&podium[..PODIUM_OBJ]);
	let heads = podium_heads(rom.region);
	for (driver, tile) in HEAD_TILES.into_iter().enumerate() {
		let at = long(&rom.data, heads + driver * 3)?;
		let second = if driver == LUIGI { 0x2100 } else { 0x5900 };
		for row in 0..2 {
			for (k, head) in [0x40, second].into_iter().enumerate() {
				let to = (tile + row * 16 + k * 2) * 32;
				tiles[to..to + 0x40].copy_from_slice(bytes(
					&rom.data,
					at + head + row * 0x200,
					0x40,
				)?);
			}
		}
	}
	Ok(tiles)
}

/// Each driver's podium frames, in table order, without repeats or hidden sprites.
fn podium_frames(rom: &Rom) -> anyhow::Result<Vec<Vec<Vec<Sprite>>>> {
	let (mut at, tables) = podium_tables(rom.region);
	let mut frames = vec![Vec::new(); DRIVERS.len()];
	for &(driver, slots) in tables {
		let mut pointers: Vec<usize> = Vec::new();
		while pointers.iter().all(|&p| at + pointers.len() * 2 < p) {
			ensure!(pointers.len() < 16, "podium table at {at:#X} runs long");
			pointers.push(near(&rom.data, at + pointers.len() * 2)?);
		}
		let mut seen = Vec::new();
		for (k, &pointer) in pointers.iter().enumerate() {
			let slot = slots[k.min(slots.len() - 1)];
			let mut sprites = Vec::new();
			let mut entry = pointer;
			while word(&rom.data, entry)? != 0xFFFF {
				let [x, y, tile, attr] = bytes(&rom.data, entry, 4)?.try_into()?;
				if i32::from(y) < HIDDEN {
					sprites.push(Sprite {
						x: i32::from(x),
						y: i32::from(y),
						tile: u16::from(tile) | u16::from(attr) << 8,
						big: big(slot + (entry - pointer) / 4),
					});
				}
				entry += 4;
			}
			at = at.max(entry + 2);
			if !seen.contains(&pointer) {
				seen.push(pointer);
				frames[driver].push(sprites);
			}
		}
	}
	Ok(frames)
}

/// Effects take their colours from the Theme palette. An effect whose colours are the same in
/// every Theme is written once; otherwise each Theme gets its own folder.
pub fn effects(rom: &Rom, folder: &Path) -> anyhow::Result<()> {
	let mut tiles = vec![0; 0x200 * 32];
	let water = stream(&rom.data, EFFECT_TILES)?;
	let dust = stream(&rom.data, dust_tiles(rom.region))?;
	ensure!(
		water.len() <= 0x100 * 32 && dust.len() <= 0x100 * 32,
		"effect tiles run long"
	);
	tiles[..water.len()].copy_from_slice(&water);
	tiles[0x100 * 32..0x100 * 32 + dust.len()].copy_from_slice(&dust);
	let tables = stream(&rom.data, EFFECT_TABLES)?;
	let mut starts = vec![0];
	for _ in 1..6 {
		let table = starts[starts.len() - 1];
		let mut last = 0;
		for k in 0..word(&tables, table)? / 2 {
			last = last.max(word(&tables, table + k * 2)?);
		}
		let count = usize::from(bytes(&tables, table + last, 1)?[0]);
		starts.push(table + last + 1 + count * 4 + count / 4 + 1);
	}
	let palettes = (0..THEMES.len())
		.map(|theme| palette(rom, theme))
		.collect::<anyhow::Result<Vec<_>>>()?;
	for (name, table, xor, picks) in EFFECTS {
		let start = starts[table];
		let mut frames = Vec::new();
		for k in (0..word(&tables, start)? / 2).filter(|&k| picks(k)) {
			let mut sprites = metasprite(&tables, start + word(&tables, start + k * 2)?)?;
			for sprite in &mut sprites {
				sprite.tile ^= xor;
			}
			frames.push(draw(&sprites, &tiles)?);
		}
		let colours = |palette: &[u8]| -> Vec<u8> {
			frames
				.iter()
				.flat_map(|(_, _, pixels)| pixels)
				.filter(|&&p| p != 0)
				.flat_map(|&p| palette[usize::from(p) * 3..usize::from(p) * 3 + 3].to_vec())
				.collect()
		};
		let same = palettes
			.iter()
			.all(|p| colours(p) == colours(&palettes[MARIO_CIRCUIT]));
		let dir = folder.join("sprites/effects").join(name);
		let themes: Vec<_> = if same {
			vec![(dir, &palettes[MARIO_CIRCUIT])]
		} else {
			THEMES
				.iter()
				.zip(&palettes)
				.map(|(theme, palette)| (dir.join(theme), palette))
				.collect()
		};
		for (dir, palette) in themes {
			fs::create_dir_all(&dir)?;
			for (i, (width, height, pixels)) in frames.iter().enumerate() {
				write_png(
					&dir.join(format!("{i:03}.png")),
					*width,
					*height,
					palette,
					pixels,
				)?;
			}
		}
	}
	Ok(())
}

/// A metasprite record: a sprite count, then x and y as i8, the tile and the OAM attribute byte for
/// each sprite, then OAM's 2 high bits per sprite, of which the upper is the size.
fn metasprite(data: &[u8], at: usize) -> anyhow::Result<Vec<Sprite>> {
	let count = usize::from(bytes(data, at, 1)?[0]);
	let sizes = bytes(data, at + 1 + count * 4, count.div_ceil(4))?;
	(0..count)
		.map(|i| {
			let [x, y, tile, attr] = bytes(data, at + 1 + i * 4, 4)?.try_into()?;
			Ok(Sprite {
				x: i32::from(x as i8),
				y: i32::from(y as i8),
				tile: u16::from(tile) | u16::from(attr) << 8,
				big: sizes[i / 4] >> (i % 4 * 2 + 1) & 1 != 0,
			})
		})
		.collect()
}

/// Each driver's 76 frames, in frame table order. Two more frame codes draw from RAM the game fills
/// at run time, and are left out.
pub fn drivers(rom: &Rom, folder: &Path) -> anyhow::Result<()> {
	let codes = Bank0::of(rom.region).drivers;
	let palette = palette(rom, MARIO_CIRCUIT)?;
	for (driver, (name, pal)) in DRIVERS.into_iter().enumerate() {
		let dir = folder.join("sprites/drivers").join(name);
		let mut frames = Vec::new();
		for scale in 0..SCALES {
			let mut seen = Vec::new();
			for angle in 0..ANGLES {
				let code = scale * ANGLES + angle;
				if !seen.contains(&rom.data[codes + code * 2]) {
					seen.push(rom.data[codes + code * 2]);
					frames.push((code, format!("scale-{scale:02}/angle-{angle:02}.png")));
				}
			}
		}
		for (k, special) in SPECIALS.iter().enumerate() {
			frames.push((SCALES * ANGLES + k, format!("{special}.png")));
		}
		for (code, file) in frames {
			let path = dir.join(file);
			fs::create_dir_all(path.parent().unwrap())?;
			let (tiles, layout) = slot(&rom.data, codes, driver, code)?;
			let mut sprites = sprites_of(layout)?;
			for sprite in &mut sprites {
				sprite.tile |= pal << 9;
			}
			let (width, height, pixels) = draw(&sprites, &tiles)?;
			write_png(&path, width, height, &palette, &pixels)?;
		}
	}
	Ok(())
}

/// A driver's VRAM slot, 4 rows of 16 tiles, as the game fills it for a frame code: the layout's
/// low nibble counts rows, its high nibble is the bytes per row, and rows are `0x200` apart in the
/// bank. Luigi's 32×32 frames take their upper two rows from his own bank and the lower two from
/// Mario's; a flag word picks half-width rows (`0x200`) or upper rows only (`0x400`). The
/// half-width flag also marks every mirrored 32×32 frame, which the layout byte misses for two of
/// them, so the slot comes with the layout to draw it with.
fn slot(data: &[u8], codes: usize, driver: usize, code: usize) -> anyhow::Result<(Vec<u8>, u8)> {
	let frame = word(
		data,
		codes + FRAME_TABLE + usize::from(data[codes + code * 2]),
	)?;
	let mut layout = data[codes + code * 2 + 1];
	let luigi = word(data, codes + LUIGI_TABLE + code * 2)?;
	if luigi & 0x8200 == 0x200 {
		layout = 0x44;
	}
	let at = |bank: usize, address: usize| (bank & 0x3F) << 16 | address;
	let rows: Vec<(usize, usize)> = if driver == LUIGI && luigi & 0x8000 == 0 {
		let top = word(data, codes + LUIGI_TOPS + (luigi & 0xFF))?;
		let size = if luigi & 0x200 != 0 { 0x40 } else { 0x80 };
		let mut rows = vec![
			(at(LUIGI_BANK, top), size),
			(at(LUIGI_BANK, top + 0x200), size),
		];
		if luigi & 0x400 == 0 {
			rows.push((at(MARIO_BANK, frame + 0x400), size));
			rows.push((at(MARIO_BANK, frame + 0x600), size));
		}
		rows
	} else {
		let bank = word(
			data,
			codes - 16 + if driver == LUIGI { 0 } else { driver * 2 },
		)?;
		(0..usize::from(layout & 15))
			.map(|r| (at(bank, frame + r * 0x200), usize::from(layout & 0xF0)))
			.collect()
	};
	let mut slot = vec![0; 4 * 0x200];
	for (r, (source, size)) in rows.into_iter().enumerate() {
		slot[r * 0x200..r * 0x200 + size].copy_from_slice(bytes(data, source, size)?);
	}
	Ok((slot, layout))
}

/// How the game places a layout's sprites over the slot. Symmetric frames hold a half, drawn
/// again mirrored; the 24-pixel ones overlap it, 7 pixels to the right. The `0x41` frames stack
/// their two tiles.
fn sprites_of(layout: u8) -> anyhow::Result<Vec<Sprite>> {
	let s = |x, y, tile, big| Sprite { x, y, tile, big };
	Ok(match layout {
		0x84 => vec![
			s(0, 0, 0, true),
			s(16, 0, 2, true),
			s(0, 16, 32, true),
			s(16, 16, 34, true),
		],
		0x82 => vec![s(0, 0, 0, true), s(16, 0, 2, true)],
		0x44 => vec![
			s(0, 0, 0, true),
			s(16, 0, 0x4000, true),
			s(0, 16, 32, true),
			s(16, 16, 0x4000 | 32, true),
		],
		0x63 => vec![
			s(0, 0, 0, true),
			s(8, 0, 1, true),
			s(0, 8, 16, true),
			s(8, 8, 17, true),
		],
		0x43 => vec![
			s(0, 0, 0, true),
			s(7, 0, 0x4000, true),
			s(0, 8, 16, true),
			s(7, 8, 0x4000 | 16, true),
		],
		0x42 => vec![s(0, 0, 0, true)],
		0x41 => vec![s(0, 0, 0, false), s(0, 8, 1, false)],
		0x21 => vec![s(0, 0, 0, false)],
		_ => bail!("unknown driver layout {layout:#X}"),
	})
}

/// A hazard script is two op words, then frame records for 12 sizes, of which the game picks
/// from the first 11. A size that repeats the one before is the same frame.
fn script_frames(
	data: &[u8],
	routines: usize,
	script: usize,
	xor: u16,
) -> anyhow::Result<Vec<Vec<Sprite>>> {
	let mut frames = Vec::new();
	let mut last = None;
	for size in 0..11 {
		let record = word(data, script + 4 + size * 2)?;
		if last.replace(record) == Some(record) {
			continue;
		}
		let mut sprites = frame(data, routines, record)?;
		sprites.retain(|s| s.tile & 0x1FF != BLANK);
		for sprite in &mut sprites {
			let tile = usize::from(sprite.tile & 0x1FF)
				.checked_sub(HAZARD_BASE)
				.with_context(|| {
					format!("frame at {record:#X} uses a tile outside the hazard's")
				})?;
			sprite.tile = (sprite.tile & !0x1FF | tile as u16) ^ xor;
		}
		if !sprites.is_empty() {
			frames.push(sprites);
		}
	}
	Ok(frames)
}

/// A frame record starts with its sprite routine. Routines with 2 or 4 sprites point to their
/// (y, x) offsets and tile words; those with 1 sprite hold its tile word. Positions only matter
/// within a frame, so the routines' anchors and y adjustments are left out.
fn frame(data: &[u8], routines: usize, record: usize) -> anyhow::Result<Vec<Sprite>> {
	let routine = word(data, record)?;
	let (count, big) = match routine.wrapping_sub(routines) {
		0x00 | 0x08 => (2, true),
		0x0D | 0x15 => (2, false),
		0x6F | 0x77 => (4, true),
		0x7C | 0x84 => (4, false),
		0x147 | 0x14F | 0x157 => (1, true),
		0x15F | 0x167 | 0x16F => (1, false),
		// The script op that draws nothing.
		0xAD4 => return Ok(Vec::new()),
		_ => bail!("frame at {record:#X} uses unknown routine {routine:#X}"),
	};
	if count == 1 {
		let tile = word(data, record + 2)? as u16;
		return Ok(vec![Sprite {
			x: 0,
			y: 0,
			tile,
			big,
		}]);
	}
	let (offsets, tiles) = (word(data, record + 2)?, word(data, record + 4)?);
	(0..count)
		.map(|i| {
			Ok(Sprite {
				x: i32::from(word(data, offsets + i * 4 + 2)? as i16),
				y: i32::from(word(data, offsets + i * 4)? as i16),
				tile: word(data, tiles + i * 2)? as u16,
				big,
			})
		})
		.collect()
}

fn write_frames(
	dir: &Path,
	frames: &[Vec<Sprite>],
	tiles: &[u8],
	palette: &[u8],
) -> anyhow::Result<()> {
	fs::create_dir_all(dir)?;
	for (i, sprites) in frames.iter().enumerate() {
		let (width, height, pixels) = draw(sprites, tiles)?;
		write_png(
			&dir.join(format!("{i:03}.png")),
			width,
			height,
			palette,
			&pixels,
		)?;
	}
	Ok(())
}

/// Draws sprites from 4bpp planar OBJ tiles, cropped to their bounds. A 16×16 sprite is tiles
/// t, t + 1, t + 16 and t + 17, and the first sprite drawn wins, as in OAM. Colours are CGRAM's
/// sprite half: 128 + palette × 16 + colour.
pub fn draw(sprites: &[Sprite], tiles: &[u8]) -> anyhow::Result<(u32, u32, Vec<u8>)> {
	let size = |s: &Sprite| if s.big { 16 } else { 8 };
	let left = sprites.iter().map(|s| s.x).min().unwrap_or(0);
	let top = sprites.iter().map(|s| s.y).min().unwrap_or(0);
	let width = sprites.iter().map(|s| s.x + size(s)).max().unwrap_or(0) - left;
	let height = sprites.iter().map(|s| s.y + size(s)).max().unwrap_or(0) - top;
	let mut pixels = vec![0; (width * height) as usize];
	for s in sprites {
		let n = size(s);
		let colour = 128 + (s.tile >> 9 & 7) as u8 * 16;
		for y in 0..n {
			for x in 0..n {
				let sx = if s.tile & 0x4000 != 0 { n - 1 - x } else { x };
				let sy = if s.tile & 0x8000 != 0 { n - 1 - y } else { y };
				let tile = usize::from(s.tile & 0x1FF) + (sx / 8 + sy / 8 * 16) as usize;
				let row = bytes(tiles, tile * 32 + (sy % 8) as usize * 2, 18)?;
				let bit = 7 - sx % 8;
				let v = (row[0] >> bit & 1)
					| (row[1] >> bit & 1) << 1
					| (row[16] >> bit & 1) << 2
					| (row[17] >> bit & 1) << 3;
				let at = ((s.y - top + y) * width + s.x - left + x) as usize;
				if v != 0 && pixels[at] == 0 {
					pixels[at] = colour + v;
				}
			}
		}
	}
	Ok((width as u32, height as u32, pixels))
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn draw_flips_crops_and_keeps_the_first_sprite() {
		// Tile 0: one colour-1 pixel at the top left. Tile 1: a colour-15 pixel there.
		let mut tiles = vec![0; 64];
		tiles[0] = 0x80;
		tiles[32..34].copy_from_slice(&[0x80, 0x80]);
		tiles[48..50].copy_from_slice(&[0x80, 0x80]);
		let sprites = [
			// Palette 2, flipped both ways, at (-8, -8).
			Sprite {
				x: -8,
				y: -8,
				tile: 0xC400,
				big: false,
			},
			Sprite {
				x: -8,
				y: -8,
				tile: 0x0001,
				big: false,
			},
			Sprite {
				x: 0,
				y: 0,
				tile: 0x0001,
				big: false,
			},
		];
		let (width, height, pixels) = draw(&sprites, &tiles).unwrap();
		assert_eq!((width, height), (16, 16));
		assert_eq!(pixels[7 * 16 + 7], 128 + 32 + 1);
		assert_eq!(pixels[0], 128 + 15);
		assert_eq!(pixels[8 * 16 + 8], 128 + 15);
		assert_eq!(pixels.iter().filter(|&&p| p != 0).count(), 3);
	}

	#[test]
	fn smk_rom_sprites() {
		let Ok(path) = std::env::var("SMK_ROM") else {
			return;
		};
		let rom = Rom::parse(fs::read(path).unwrap()).unwrap();
		let folder = std::env::temp_dir().join(format!("desmack-sprites-{}", std::process::id()));
		drivers(&rom, &folder).unwrap();
		items(&rom, &folder).unwrap();
		hazards(&rom, &folder).unwrap();
		cast(&rom, &folder).unwrap();
		effects(&rom, &folder).unwrap();
		let count = |dir: &str| {
			fs::read_dir(folder.join("sprites").join(dir))
				.unwrap()
				.count()
		};
		assert_eq!(count("drivers/luigi"), SCALES + SPECIALS.len());
		assert_eq!(count("drivers/luigi/scale-00"), 12);
		assert_eq!(count("drivers/luigi/scale-10"), 2);
		assert_eq!(count("cast/lakitu"), LAKITU_FRAMES + 3);
		assert_eq!(count("cast/cheep-cheep"), 2);
		assert_eq!(count("cast/podium"), DRIVERS.len() + 4);
		assert_eq!(count("cast/podium/mario"), 2 + 3 + 7);
		assert_eq!(count("cast/podium/confetti"), 18);
		assert_eq!(count("effects/smoke"), 48);
		assert_eq!(count("effects/smoke-small"), 12);
		assert_eq!(count("effects/spray"), THEMES.len());
		assert_eq!(count("effects/spray/koopa-beach"), 48);
		assert_eq!(count("effects/splash/koopa-beach"), 8);
		assert_eq!(count("effects/ripple/koopa-beach"), 2);
		assert_eq!(count("items/green-shell"), 16);
		assert_eq!(count("items/coin"), COIN_FRAMES);
		assert_eq!(count("hazards/pipe"), 11);
		assert_eq!(count("hazards/piranha-plant"), 20);
		assert_eq!(count("hazards/thwomp"), 11 + 5);
		fs::remove_dir_all(&folder).unwrap();
	}
}