pixel8 0.1.0

Pixel8 fantasy console SDK: write carts in Rust, compile to wasm32-unknown-unknown
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
//! # pixel8 — the Pixel8 fantasy console SDK
//!
//! Write tiny games in Rust, run them on a tiny console.
//!
//! ```no_run
//! use pixel8::*;
//!
//! struct MyGame {
//!     x: i16,
//!     y: i16,
//! }
//!
//! impl Game for MyGame {
//!     fn update(&mut self, ctx: &mut Context) {
//!         if ctx.is_button_down(Button::Right) {
//!             self.x += 1;
//!         }
//!     }
//!
//!     fn draw(&self, gfx: &mut Graphics) {
//!         gfx.clear(Color::BLACK);
//!         gfx.rect_fill(self.x, self.y, 8, 8, Color::WHITE).unwrap();
//!     }
//! }
//!
//! pixel8::game!(MyGame { x: 64, y: 64 });
//! ```
//!
//! Carts are built for `wasm32-unknown-unknown` as a `cdylib` and run in
//! a strict sandbox: the host functions wrapped by [`Context`] and
//! [`Graphics`] are the only doors out. The screen is 128x128, the
//! palette has 16 fixed colors, `update`/`draw` run at 60 fps (or 30,
//! if the game sets [`Game::FRAME_RATE`]). The constraints
//! are the point.
//!
//! For formatted on-screen text and debug logs, see the [`printf!`](crate::printf)
//! and [`logf!`](crate::logf) macros.
#![cfg_attr(not(feature = "std"), no_std)]

mod dim;
pub mod ffi;
mod flags;
mod fmt;
mod glue;
pub mod memstat;
mod motion;
mod music;
mod storage;

// Install the live-tracking allocator for `std` carts. It lives here, not in
// the `game!` macro, so the `feature = "std"` cfg is evaluated in this crate
// (where the feature is defined) rather than in the cart crate (which has no
// such feature). A library-defined global allocator is picked up by the cart
// cdylib that links it. Wasm-only: on the host it would perturb this crate's
// own allocation tests.
#[cfg(all(feature = "std", target_arch = "wasm32"))]
#[global_allocator]
static PIXEL8_ALLOC: memstat::TrackingAlloc = memstat::TrackingAlloc;

use crate::flags::bitflag_enum;
pub use crate::flags::{BitFlag, BitFlags, UnknownBits};
use core::ops::{Bound, RangeBounds};
pub use dim::{Dim, ZeroSize};
pub use glue::__internal;
pub use motion::Body;
pub use music::{Music, MusicBusy, PlayingMusic};
pub use storage::{StorageFull, StorageValue};

/// The screen is 128x128 pixels.
pub const SCREEN_WIDTH: u16 = 128;
pub const SCREEN_HEIGHT: u16 = 128;
/// The sprite sheet is 128x128 pixels.
pub const SPRITE_SHEET_WIDTH: u16 = 128;
pub const SPRITE_SHEET_HEIGHT: u16 = 128;
/// The map is 128x64 tiles (each tile is one 8x8 sprite cell).
pub const MAP_WIDTH_TILES: u16 = 128;
pub const MAP_HEIGHT_TILES: u16 = 64;

/// A point write addressed a coordinate off its surface; nothing was written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OutOfBounds;

/// Default logical frames per second.
pub const FPS: u32 = 60;

/// How many times per second a cart's `update` and `draw` run.
///
/// The default is [`FrameRate::Fps60`]; set [`Game::FRAME_RATE`] to
/// [`FrameRate::Fps30`] for a 30 fps game, where both `update` and `draw`
/// are called half as often.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameRate {
    /// 30 frames per second.
    Fps30,
    /// 60 frames per second (the default).
    Fps60,
}

impl FrameRate {
    /// The rate as a plain frames-per-second number.
    pub const fn fps(self) -> u32 {
        match self {
            FrameRate::Fps30 => 30,
            FrameRate::Fps60 => 60,
        }
    }
}

/// A color in the fixed 16-color palette.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Color(u8);

impl Color {
    pub const BLACK: Color = Color(0);
    pub const DARK_BLUE: Color = Color(1);
    pub const DARK_PURPLE: Color = Color(2);
    pub const DARK_GREEN: Color = Color(3);
    pub const BROWN: Color = Color(4);
    pub const DARK_GREY: Color = Color(5);
    pub const LIGHT_GREY: Color = Color(6);
    pub const WHITE: Color = Color(7);
    pub const RED: Color = Color(8);
    pub const ORANGE: Color = Color(9);
    pub const YELLOW: Color = Color(10);
    pub const GREEN: Color = Color(11);
    pub const BLUE: Color = Color(12);
    pub const LAVENDER: Color = Color(13);
    pub const PINK: Color = Color(14);
    pub const PEACH: Color = Color(15);

    /// A color from a palette index, or `None` if `i` is not in `0..16`.
    pub const fn new(i: u8) -> Option<Color> {
        if i < 16 {
            Some(Color(i))
        } else {
            None
        }
    }

    /// The palette index.
    pub const fn index(self) -> u8 {
        self.0
    }

    /// Wrap a host nibble (already `0..16`) into a color. Internal only.
    pub(crate) const fn from_index(i: u8) -> Color {
        Color(i & 0x0f)
    }
}

bitflag_enum! {
    /// The six console buttons.
    pub enum Button {
        Left = 1 << 0,
        Right = 1 << 1,
        Up = 1 << 2,
        Down = 1 << 3,
        /// "O" action button — Z, C or N on the keyboard.
        O = 1 << 4,
        /// "X" action button — X, V or M on the keyboard.
        X = 1 << 5,
    }
}

impl Button {
    /// `Left` and `Up` held together, as a set — `ctx.buttons_down().contains(Button::UP_LEFT)`.
    pub const UP_LEFT: BitFlags<Button> =
        // SAFETY: `Left` and `Up` are real `Button` flags, so the combined bits are valid.
        unsafe { BitFlags::from_bits_unchecked(Button::Left as u8 | Button::Up as u8) };
    /// `Right` and `Up` held together.
    pub const UP_RIGHT: BitFlags<Button> =
        // SAFETY: `Right` and `Up` are real `Button` flags.
        unsafe { BitFlags::from_bits_unchecked(Button::Right as u8 | Button::Up as u8) };
    /// `Left` and `Down` held together.
    pub const DOWN_LEFT: BitFlags<Button> =
        // SAFETY: `Left` and `Down` are real `Button` flags.
        unsafe { BitFlags::from_bits_unchecked(Button::Left as u8 | Button::Down as u8) };
    /// `Right` and `Down` held together.
    pub const DOWN_RIGHT: BitFlags<Button> =
        // SAFETY: `Right` and `Down` are real `Button` flags.
        unsafe { BitFlags::from_bits_unchecked(Button::Right as u8 | Button::Down as u8) };
}

/// The ABI button index (`0..=5`) for a [`Button`] flag.
const fn button_index(b: Button) -> u32 {
    (b as u8).trailing_zeros()
}

bitflag_enum! {
    /// One of a sprite's eight flags. The flags carry no fixed meaning — a cart
    /// assigns its own (e.g. "solid"). Used by [`Context::sprite_flags`] /
    /// [`Context::set_sprite_flags`] and the [`Graphics::map`] layer filter.
    pub enum SpriteFlag {
        Flag0 = 1 << 0,
        Flag1 = 1 << 1,
        Flag2 = 1 << 2,
        Flag3 = 1 << 3,
        Flag4 = 1 << 4,
        Flag5 = 1 << 5,
        Flag6 = 1 << 6,
        Flag7 = 1 << 7,
    }
}

bitflag_enum! {
    /// One of the four audio channels, shared by sfx and music. Reserve channels
    /// for music with [`Music::reserve_channels`].
    pub enum Channel {
        Channel0 = 1 << 0,
        Channel1 = 1 << 1,
        Channel2 = 1 << 2,
        Channel3 = 1 << 3,
    }
}

/// The ABI channel index (`0..=3`) for a [`Channel`] flag.
const fn channel_index(c: Channel) -> u32 {
    (c as u8).trailing_zeros()
}

/// A sprite on the 16x16 sprite sheet (`0..=255`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SpriteId(pub u8);

/// A sound effect slot (`0..=63`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SfxId(u8);

impl SfxId {
    /// A sound-effect slot, or `None` if `n` is not in `0..64`.
    pub const fn new(n: u8) -> Option<SfxId> {
        if n < 64 {
            Some(SfxId(n))
        } else {
            None
        }
    }

    /// The slot number.
    pub const fn index(self) -> u8 {
        self.0
    }
}

/// A music pattern (`0..=63`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MusicId(u8);

impl MusicId {
    /// A music pattern slot, or `None` if `n` is not in `0..64`.
    pub const fn new(n: u8) -> Option<MusicId> {
        if n < 64 {
            Some(MusicId(n))
        } else {
            None
        }
    }

    /// The pattern slot number.
    pub const fn index(self) -> u8 {
        self.0
    }
}

/// Game state and input, available during `update`.
///
/// Zero-sized handle over the host ABI; it exists so the borrow checker
/// can tell "update powers" apart from "draw powers".
pub struct Context {
    pub(crate) _private: (),
}

impl Context {
    /// Is a button currently held down?
    pub fn is_button_down(&self, b: Button) -> bool {
        unsafe { ffi::is_button_down(button_index(b)) != 0 }
    }

    /// Alias for [`Context::is_button_down`].
    pub fn btn(&self, b: Button) -> bool {
        self.is_button_down(b)
    }

    /// Was a button just pressed? Repeats after a short delay while held.
    pub fn is_button_pressed(&self, b: Button) -> bool {
        unsafe { ffi::is_button_pressed(button_index(b)) != 0 }
    }

    /// Alias for [`Context::is_button_pressed`].
    pub fn btnp(&self, b: Button) -> bool {
        self.is_button_pressed(b)
    }

    /// Every button currently held down, as a set.
    pub fn buttons_down(&self) -> BitFlags<Button> {
        BitFlags::from_bits(unsafe { ffi::buttons_down() } as u8)
            .expect("buttons_down returned an unknown button bit (pixel8 host/SDK ABI mismatch)")
    }

    /// Every button that fired this frame (with repeat), as a set.
    pub fn buttons_pressed(&self) -> BitFlags<Button> {
        BitFlags::from_bits(unsafe { ffi::buttons_pressed() } as u8)
            .expect("buttons_pressed returned an unknown button bit (pixel8 host/SDK ABI mismatch)")
    }

    /// The sprite number of a map tile (`SpriteId(0)` = empty), or `None` if
    /// `(x, y)` is off the 128x64 map. `x`/`y` are tile coordinates.
    pub fn map_tile(&self, x: i16, y: i16) -> Option<SpriteId> {
        if !in_bounds(x, y, MAP_WIDTH_TILES, MAP_HEIGHT_TILES) {
            return None;
        }
        Some(SpriteId(unsafe { ffi::map_tile(x as i32, y as i32) } as u8))
    }

    /// Alias for [`Context::map_tile`].
    pub fn mget(&self, x: i16, y: i16) -> Option<SpriteId> {
        self.map_tile(x, y)
    }

    /// Write a map tile (`x`/`y` are tile coordinates). Changes live in console
    /// RAM and are discarded on reload, like any self-respecting cartridge.
    /// `Err(OutOfBounds)` if `(x, y)` is off the map.
    pub fn set_map_tile(&mut self, x: i16, y: i16, sprite: SpriteId) -> Result<(), OutOfBounds> {
        if !in_bounds(x, y, MAP_WIDTH_TILES, MAP_HEIGHT_TILES) {
            return Err(OutOfBounds);
        }
        unsafe { ffi::set_map_tile(x as i32, y as i32, sprite.0 as u32) };
        Ok(())
    }

    /// Alias for [`Context::set_map_tile`].
    pub fn mset(&mut self, x: i16, y: i16, sprite: SpriteId) -> Result<(), OutOfBounds> {
        self.set_map_tile(x, y, sprite)
    }

    /// Read a pixel from the sprite sheet, or `None` if `(x, y)` is off the
    /// 128x128 sheet. `x`/`y` are sheet pixel coordinates.
    pub fn sprite_pixel(&self, x: i16, y: i16) -> Option<Color> {
        if !in_bounds(x, y, SPRITE_SHEET_WIDTH, SPRITE_SHEET_HEIGHT) {
            return None;
        }
        Some(Color::from_index(
            unsafe { ffi::sprite_pixel(x as i32, y as i32) } as u8,
        ))
    }

    /// Alias for [`Context::sprite_pixel`].
    pub fn sget(&self, x: i16, y: i16) -> Option<Color> {
        self.sprite_pixel(x, y)
    }

    /// Write a pixel on the sprite sheet (`x`/`y` are sheet pixel coordinates).
    /// RAM only, discarded on reload. `Err(OutOfBounds)` if `(x, y)` is off the
    /// sheet.
    pub fn set_sprite_pixel(&mut self, x: i16, y: i16, color: Color) -> Result<(), OutOfBounds> {
        if !in_bounds(x, y, SPRITE_SHEET_WIDTH, SPRITE_SHEET_HEIGHT) {
            return Err(OutOfBounds);
        }
        unsafe { ffi::set_sprite_pixel(x as i32, y as i32, color.0 as i32) };
        Ok(())
    }

    /// Alias for [`Context::set_sprite_pixel`].
    pub fn sset(&mut self, x: i16, y: i16, color: Color) -> Result<(), OutOfBounds> {
        self.set_sprite_pixel(x, y, color)
    }

    /// Every flag set on a sprite.
    pub fn sprite_flags(&self, sprite: SpriteId) -> BitFlags<SpriteFlag> {
        BitFlags::from_bits(unsafe { ffi::sprite_flags(sprite.0 as u32) } as u8).expect(
            "sprite_flags returned an unknown sprite-flag bit (pixel8 host/SDK ABI mismatch)",
        )
    }

    /// Alias for [`Context::sprite_flags`].
    pub fn fget(&self, sprite: SpriteId) -> BitFlags<SpriteFlag> {
        self.sprite_flags(sprite)
    }

    /// Whether a sprite has a particular flag set.
    pub fn has_sprite_flag(&self, sprite: SpriteId, flag: SpriteFlag) -> bool {
        self.sprite_flags(sprite).contains(flag)
    }

    /// Overwrite a sprite's flags.
    pub fn set_sprite_flags(&mut self, sprite: SpriteId, flags: impl Into<BitFlags<SpriteFlag>>) {
        unsafe { ffi::set_sprite_flags(sprite.0 as u32, flags.into().bits() as u32) }
    }

    /// Alias for [`Context::set_sprite_flags`].
    pub fn fset(&mut self, sprite: SpriteId, flags: impl Into<BitFlags<SpriteFlag>>) {
        self.set_sprite_flags(sprite, flags)
    }

    /// Play a sound effect on a free channel.
    pub fn sfx(&mut self, s: SfxId) {
        unsafe { ffi::sfx(s.0 as i32, -1) }
    }

    /// Play a sound effect on a specific channel.
    pub fn sfx_on(&mut self, s: SfxId, channel: Channel) {
        unsafe { ffi::sfx(s.0 as i32, channel_index(channel) as i32) }
    }

    /// Stop whatever is playing on a channel.
    pub fn sfx_stop(&mut self, channel: Channel) {
        unsafe { ffi::sfx(-1, channel_index(channel) as i32) }
    }

    /// Begin a music-playback request for pattern `m`.
    ///
    /// Nothing plays until [`Music::play`]; set a fade-in or reserved channels
    /// on the returned [`Music`] first.
    pub fn music(&mut self, m: MusicId) -> Music {
        Music::new(m)
    }

    /// Seconds since the cart started, in `1/`[`FRAME_RATE`] steps (1/60 s
    /// by default).
    ///
    /// [`FRAME_RATE`]: Game::FRAME_RATE
    pub fn time(&self) -> f32 {
        unsafe { ffi::time() }
    }

    /// A uniformly random `f32` from `range`.
    ///
    /// Accepts any range syntax — exclusive (`a..b`), inclusive (`a..=b`), or open on
    /// either end. An open lower bound is `f32::MIN`, an open upper bound is `f32::MAX`;
    /// bounds may be negative. A reversed or empty range yields its lower bound.
    pub fn random<R>(&mut self, range: R) -> f32
    where
        R: RangeBounds<f32>,
    {
        let (lo, hi) = f32_bounds(range);
        sample_f32(lo, hi, unsafe { ffi::rnd() })
    }

    /// Scalar shorthand for `random(0.0..max)`.
    pub fn rnd(&mut self, max: f32) -> f32 {
        self.random(0.0..max)
    }

    /// A uniformly random `i32` from `range`.
    ///
    /// Accepts any range syntax — exclusive (`a..b`), inclusive (`a..=b`), or open on
    /// either end. An open lower bound is `i32::MIN`, an open upper bound is `i32::MAX`;
    /// bounds may be negative. A reversed or empty range yields its lower bound.
    pub fn random_integer<R>(&mut self, range: R) -> i32
    where
        R: RangeBounds<i32>,
    {
        let (lo, count) = i32_bounds(range);
        sample_i32(lo, count, unsafe { ffi::rnd() })
    }

    /// Scalar shorthand for `random_integer(0..max)`.
    pub fn rndi(&mut self, max: i32) -> i32 {
        self.random_integer(0..max)
    }

    /// Seed the random sequence for deterministic runs.
    pub fn seed_rng(&mut self, seed: u32) {
        unsafe { ffi::seed_rng(seed) }
    }

    /// Alias for [`Context::seed_rng`].
    pub fn srand(&mut self, seed: u32) {
        self.seed_rng(seed)
    }

    /// Log a line to the Pixel8 console (visible after Esc). For
    /// `format!`-style arguments, see [`logf!`](crate::logf).
    pub fn log(&mut self, msg: &str) {
        unsafe { ffi::log(msg.as_ptr(), msg.len() as u32) }
    }

    /// Fraction (`0.0`–`1.0`) of last frame's `update` CPU budget used.
    ///
    /// Reports the previous completed frame: mid-`update` the current call's
    /// cost isn't known yet. A value near `1.0` means the budget was nearly
    /// exhausted (a call that fully spends it traps before this can report).
    pub fn cpu_update(&self) -> f32 {
        unsafe { ffi::cpu_update() }
    }

    /// Fraction (`0.0`–`1.0`) of last frame's `draw` CPU budget used.
    pub fn cpu_draw(&self) -> f32 {
        unsafe { ffi::cpu_draw() }
    }

    /// The cart's committed-memory high-water — the highest its footprint
    /// (shadow-stack reserve, statics and heap together) has ever reached — as
    /// a fraction (`0.0`–`1.0`) of the 128 K cap. It never decreases (wasm never
    /// returns pages) and counts freed-but-stranded memory, so it tracks real
    /// pressure closely. It is still not an exact OOM line: the allocator keeps
    /// a small reserve above the last allocation, so the cap can be reached
    /// while this reads a little under 100%.
    pub fn mem(&self) -> f32 {
        crate::memstat::used_fraction()
    }

    /// Actual measured frames per second. Equals the target rate (see
    /// [`Game::FRAME_RATE`]) until the host has measured a real one.
    pub fn fps(&self) -> f32 {
        unsafe { ffi::fps() }
    }
}

/// The screen, available during `draw`.
pub struct Graphics {
    pub(crate) _private: (),
}

impl Graphics {
    /// Fill the screen with a color.
    pub fn clear(&mut self, color: Color) {
        unsafe { ffi::clear(color.0 as i32) }
    }

    /// Alias for [`Graphics::clear`], for fingers that type `cls`.
    pub fn cls(&mut self, color: Color) {
        self.clear(color)
    }

    /// Offset all subsequent draws by `(-x, -y)`.
    pub fn camera(&mut self, x: i16, y: i16) {
        unsafe { ffi::camera(x as i32, y as i32) }
    }

    /// Restrict drawing to a rectangle in screen space. Errors on a zero/negative
    /// size.
    pub fn clip(&mut self, x: i16, y: i16, w: impl Dim, h: impl Dim) -> Result<(), ZeroSize> {
        let w = w.to_nonzero().ok_or(ZeroSize)?;
        let h = h.to_nonzero().ok_or(ZeroSize)?;
        unsafe { ffi::clip(x as i32, y as i32, w.get() as i32, h.get() as i32) };
        Ok(())
    }

    /// Remove the clip rectangle.
    pub fn clip_reset(&mut self) {
        unsafe { ffi::clip(0, 0, SCREEN_WIDTH as i32, SCREEN_HEIGHT as i32) }
    }

    /// Make a palette color transparent (or opaque) for sprite draws.
    pub fn set_transparent_color(&mut self, color: Color, transparent: bool) {
        unsafe { ffi::set_transparent_color(color.0 as i32, transparent as i32) }
    }

    /// Alias for [`Graphics::set_transparent_color`].
    pub fn palt(&mut self, color: Color, transparent: bool) {
        self.set_transparent_color(color, transparent)
    }

    /// Reset sprite transparency to the default (only color 0 transparent).
    pub fn reset_transparency(&mut self) {
        unsafe { ffi::reset_transparency() }
    }

    /// Remap a draw color: later draws of `from` are written as `to`.
    pub fn remap_color(&mut self, from: Color, to: Color) {
        unsafe { ffi::remap_color(from.0 as i32, to.0 as i32, 0) }
    }

    /// Alias for [`Graphics::remap_color`].
    pub fn pal(&mut self, from: Color, to: Color) {
        self.remap_color(from, to)
    }

    /// Remap a display color: `from` is shown as `to` across the whole screen.
    pub fn remap_display_color(&mut self, from: Color, to: Color) {
        unsafe { ffi::remap_color(from.0 as i32, to.0 as i32, 1) }
    }

    /// Alias for [`Graphics::remap_display_color`].
    pub fn pal_display(&mut self, from: Color, to: Color) {
        self.remap_display_color(from, to)
    }

    /// Reset both the draw and display palettes to identity.
    pub fn reset_palette(&mut self) {
        unsafe { ffi::reset_palette() }
    }

    /// Set one pixel.
    pub fn set_pixel(&mut self, x: i16, y: i16, color: Color) {
        unsafe { ffi::set_pixel(x as i32, y as i32, color.0 as i32) }
    }

    /// Alias for [`Graphics::set_pixel`].
    pub fn pset(&mut self, x: i16, y: i16, color: Color) {
        self.set_pixel(x, y, color)
    }

    /// Read one pixel in raw screen space (camera-independent), or `None` if
    /// `(x, y)` is off-screen.
    pub fn pixel(&self, x: i16, y: i16) -> Option<Color> {
        if !in_bounds(x, y, SCREEN_WIDTH, SCREEN_HEIGHT) {
            return None;
        }
        Some(Color::from_index(
            unsafe { ffi::pixel(x as i32, y as i32) } as u8
        ))
    }

    /// Alias for [`Graphics::pixel`].
    pub fn pget(&self, x: i16, y: i16) -> Option<Color> {
        self.pixel(x, y)
    }

    /// Line between two points, inclusive.
    pub fn line(&mut self, x0: i16, y0: i16, x1: i16, y1: i16, color: Color) {
        unsafe { ffi::line(x0 as i32, y0 as i32, x1 as i32, y1 as i32, color.0 as i32) }
    }

    /// Rectangle outline at `(x, y)` with size `w x h`. Errors on a zero/negative
    /// size.
    pub fn rect(
        &mut self,
        x: i16,
        y: i16,
        w: impl Dim,
        h: impl Dim,
        color: Color,
    ) -> Result<(), ZeroSize> {
        let w = w.to_nonzero().ok_or(ZeroSize)?;
        let h = h.to_nonzero().ok_or(ZeroSize)?;
        unsafe {
            ffi::rect(
                x as i32,
                y as i32,
                x as i32 + w.get() as i32 - 1,
                y as i32 + h.get() as i32 - 1,
                color.0 as i32,
            )
        };
        Ok(())
    }

    /// Filled rectangle at `(x, y)` with size `w x h`. Errors on a zero/negative
    /// size.
    pub fn rect_fill(
        &mut self,
        x: i16,
        y: i16,
        w: impl Dim,
        h: impl Dim,
        color: Color,
    ) -> Result<(), ZeroSize> {
        let w = w.to_nonzero().ok_or(ZeroSize)?;
        let h = h.to_nonzero().ok_or(ZeroSize)?;
        unsafe {
            ffi::rect_fill(
                x as i32,
                y as i32,
                x as i32 + w.get() as i32 - 1,
                y as i32 + h.get() as i32 - 1,
                color.0 as i32,
            )
        };
        Ok(())
    }

    /// Alias for [`Graphics::rect_fill`].
    pub fn rectfill(
        &mut self,
        x: i16,
        y: i16,
        w: impl Dim,
        h: impl Dim,
        color: Color,
    ) -> Result<(), ZeroSize> {
        self.rect_fill(x, y, w, h, color)
    }

    /// Circle outline. `r = 0` draws a single pixel.
    pub fn circle(&mut self, x: i16, y: i16, r: u16, color: Color) {
        unsafe { ffi::circle(x as i32, y as i32, r as i32, color.0 as i32) }
    }

    /// Alias for [`Graphics::circle`].
    pub fn circ(&mut self, x: i16, y: i16, r: u16, color: Color) {
        self.circle(x, y, r, color)
    }

    /// Filled circle. `r = 0` draws a single pixel.
    pub fn circle_fill(&mut self, x: i16, y: i16, r: u16, color: Color) {
        unsafe { ffi::circle_fill(x as i32, y as i32, r as i32, color.0 as i32) }
    }

    /// Alias for [`Graphics::circle_fill`].
    pub fn circfill(&mut self, x: i16, y: i16, r: u16, color: Color) {
        self.circle_fill(x, y, r, color)
    }

    /// Ellipse outline inside the `(x, y, w, h)` box. Errors on a zero/negative
    /// size.
    pub fn ellipse(
        &mut self,
        x: i16,
        y: i16,
        w: impl Dim,
        h: impl Dim,
        color: Color,
    ) -> Result<(), ZeroSize> {
        let w = w.to_nonzero().ok_or(ZeroSize)?;
        let h = h.to_nonzero().ok_or(ZeroSize)?;
        unsafe {
            ffi::ellipse(
                x as i32,
                y as i32,
                x as i32 + w.get() as i32 - 1,
                y as i32 + h.get() as i32 - 1,
                color.0 as i32,
            )
        };
        Ok(())
    }

    /// Alias for [`Graphics::ellipse`].
    pub fn oval(
        &mut self,
        x: i16,
        y: i16,
        w: impl Dim,
        h: impl Dim,
        color: Color,
    ) -> Result<(), ZeroSize> {
        self.ellipse(x, y, w, h, color)
    }

    /// Filled ellipse inside the `(x, y, w, h)` box. Errors on a zero/negative
    /// size.
    pub fn ellipse_fill(
        &mut self,
        x: i16,
        y: i16,
        w: impl Dim,
        h: impl Dim,
        color: Color,
    ) -> Result<(), ZeroSize> {
        let w = w.to_nonzero().ok_or(ZeroSize)?;
        let h = h.to_nonzero().ok_or(ZeroSize)?;
        unsafe {
            ffi::ellipse_fill(
                x as i32,
                y as i32,
                x as i32 + w.get() as i32 - 1,
                y as i32 + h.get() as i32 - 1,
                color.0 as i32,
            )
        };
        Ok(())
    }

    /// Alias for [`Graphics::ellipse_fill`].
    pub fn ovalfill(
        &mut self,
        x: i16,
        y: i16,
        w: impl Dim,
        h: impl Dim,
        color: Color,
    ) -> Result<(), ZeroSize> {
        self.ellipse_fill(x, y, w, h, color)
    }

    /// Set a two-color fill pattern for the filled shapes. Pattern-1 pixels use
    /// `secondary`. `pattern` is a 4x4 bitmask (bit 15 = top-left); 0 is solid.
    pub fn set_fill_pattern(&mut self, pattern: u16, secondary: Color) {
        unsafe { ffi::set_fill_pattern(pattern as i32, secondary.0 as i32, 0) }
    }

    /// Alias for [`Graphics::set_fill_pattern`] with a black secondary color.
    pub fn fillp(&mut self, pattern: u16) {
        self.set_fill_pattern(pattern, Color::BLACK)
    }

    /// Set a fill pattern whose pattern-1 pixels are left transparent.
    pub fn set_fill_pattern_transparent(&mut self, pattern: u16) {
        unsafe { ffi::set_fill_pattern(pattern as i32, 0, 1) }
    }

    /// Fill solid again (the default).
    pub fn clear_fill_pattern(&mut self) {
        unsafe { ffi::set_fill_pattern(0, 0, 0) }
    }

    /// Print text with the built-in 4x6 font. Returns the x position (as `i16`)
    /// after the last glyph. For `format!`-style arguments, see
    /// [`printf!`](crate::printf).
    pub fn print(&mut self, text: &str, x: i16, y: i16, color: Color) -> i16 {
        unsafe {
            ffi::print(
                text.as_ptr(),
                text.len() as u32,
                x as i32,
                y as i32,
                color.0 as i32,
            ) as i16
        }
    }

    /// Set the persistent pen color used by [`Graphics::print_pen`].
    pub fn set_pen_color(&mut self, color: Color) {
        unsafe { ffi::set_pen_color(color.0 as i32) }
    }

    /// Alias for [`Graphics::set_pen_color`].
    pub fn color(&mut self, color: Color) {
        self.set_pen_color(color)
    }

    /// Set the persistent text cursor used by [`Graphics::print_pen`].
    pub fn set_cursor(&mut self, x: i16, y: i16) {
        unsafe { ffi::set_cursor(x as i32, y as i32) }
    }

    /// Alias for [`Graphics::set_cursor`].
    pub fn cursor(&mut self, x: i16, y: i16) {
        self.set_cursor(x, y)
    }

    /// Print at the cursor in the pen color, advancing the cursor one line.
    /// Returns the x position (as `i16`) after the last glyph. The cursor
    /// advances by a single line regardless of any newlines embedded in `text`.
    pub fn print_pen(&mut self, text: &str) -> i16 {
        unsafe { ffi::print_pen(text.as_ptr(), text.len() as u32) as i16 }
    }

    /// Draw a sprite at `(x, y)`. Color 0 is transparent.
    pub fn sprite(&mut self, sprite: SpriteId, x: i16, y: i16) {
        // A whole 8x8 cell, in pixels.
        unsafe { ffi::sprite(sprite.0 as u32, x as i32, y as i32, 8, 8, 0, 0) }
    }

    /// Alias for [`Graphics::sprite`].
    pub fn spr(&mut self, sprite: SpriteId, x: i16, y: i16) {
        self.sprite(sprite, x, y)
    }

    /// Draw a `w x h`-pixel sprite block, optionally flipped. `w`/`h` are in pixels:
    /// `8` is one cell, `4` a half-cell slice. Errors on a zero/negative size.
    #[allow(clippy::too_many_arguments)]
    pub fn sprite_ext(
        &mut self,
        sprite: SpriteId,
        x: i16,
        y: i16,
        w: impl Dim,
        h: impl Dim,
        flip_x: bool,
        flip_y: bool,
    ) -> Result<(), ZeroSize> {
        let w = w.to_nonzero().ok_or(ZeroSize)?;
        let h = h.to_nonzero().ok_or(ZeroSize)?;
        unsafe {
            ffi::sprite(
                sprite.0 as u32,
                x as i32,
                y as i32,
                w.get() as i32,
                h.get() as i32,
                flip_x as i32,
                flip_y as i32,
            )
        };
        Ok(())
    }

    /// Draw a sheet rectangle `(sx,sy,sw,sh)` stretched into a screen rectangle
    /// `(dx,dy,dw,dh)`. Honors transparency and the draw palette. Errors if any
    /// size is zero.
    #[allow(clippy::too_many_arguments)]
    pub fn sprite_stretch(
        &mut self,
        sx: i16,
        sy: i16,
        sw: impl Dim,
        sh: impl Dim,
        dx: i16,
        dy: i16,
        dw: impl Dim,
        dh: impl Dim,
        flip_x: bool,
        flip_y: bool,
    ) -> Result<(), ZeroSize> {
        let sw = sw.to_nonzero().ok_or(ZeroSize)?;
        let sh = sh.to_nonzero().ok_or(ZeroSize)?;
        let dw = dw.to_nonzero().ok_or(ZeroSize)?;
        let dh = dh.to_nonzero().ok_or(ZeroSize)?;
        unsafe {
            ffi::sprite_stretch(
                sx as i32,
                sy as i32,
                sw.get() as i32,
                sh.get() as i32,
                dx as i32,
                dy as i32,
                dw.get() as i32,
                dh.get() as i32,
                flip_x as i32,
                flip_y as i32,
            )
        };
        Ok(())
    }

    /// Alias for [`Graphics::sprite_stretch`].
    #[allow(clippy::too_many_arguments)]
    pub fn sspr(
        &mut self,
        sx: i16,
        sy: i16,
        sw: impl Dim,
        sh: impl Dim,
        dx: i16,
        dy: i16,
        dw: impl Dim,
        dh: impl Dim,
        flip_x: bool,
        flip_y: bool,
    ) -> Result<(), ZeroSize> {
        self.sprite_stretch(sx, sy, sw, sh, dx, dy, dw, dh, flip_x, flip_y)
    }

    /// Draw a region of the map: `cel_w x cel_h` tiles starting at tile
    /// `(cel_x, cel_y)`, at screen position `(sx, sy)`. With an empty
    /// `layers` set every tile is drawn; otherwise only tiles whose sprite
    /// flags intersect `layers`.
    ///
    /// Returns `Err(ZeroSize)` if `cel_w` or `cel_h` is zero.
    #[allow(clippy::too_many_arguments)]
    pub fn map(
        &mut self,
        cel_x: i16,
        cel_y: i16,
        sx: i16,
        sy: i16,
        cel_w: impl Dim,
        cel_h: impl Dim,
        layers: impl Into<BitFlags<SpriteFlag>>,
    ) -> Result<(), ZeroSize> {
        let cel_w = cel_w.to_nonzero().ok_or(ZeroSize)?;
        let cel_h = cel_h.to_nonzero().ok_or(ZeroSize)?;
        let layers = layers.into().bits() as u32;
        unsafe {
            ffi::map(
                cel_x as i32,
                cel_y as i32,
                sx as i32,
                sy as i32,
                cel_w.get() as i32,
                cel_h.get() as i32,
                layers,
            )
        };
        Ok(())
    }
}

/// Implement this for your game state, then hand it to [`game!`].
pub trait Game {
    /// The logical frame rate. Set this to [`FrameRate::Fps30`] to run
    /// `update` and `draw` at 30 fps instead of the default 60.
    const FRAME_RATE: FrameRate = FrameRate::Fps60;
    /// Called [`FRAME_RATE`](Game::FRAME_RATE) times per second. Read
    /// input, move the world.
    fn update(&mut self, ctx: &mut Context);
    /// Called after `update`. Draw the world.
    fn draw(&self, gfx: &mut Graphics);
}

/// Declare your game's entry point.
///
/// The common form takes a struct literal that builds the initial state:
///
/// ```ignore
/// pixel8::game!(MyGame { x: 64, y: 64 });
/// ```
///
/// Any other constructor works with the `Type = expr` form, and a type
/// implementing [`Default`] needs no initializer:
///
/// ```ignore
/// pixel8::game!(MyGame = MyGame::new());
/// pixel8::game!(MyGame);
/// ```
#[macro_export]
macro_rules! game {
    ($game:ty = $init:expr) => {
        static GAME: $crate::__internal::Slot<$game> = $crate::__internal::Slot::new();

        #[no_mangle]
        pub extern "C" fn pixel8_init() {
            GAME.init(|| $init);
        }

        #[no_mangle]
        pub extern "C" fn pixel8_fps() -> u32 {
            GAME.fps()
        }

        #[no_mangle]
        pub extern "C" fn pixel8_mem_used() -> u32 {
            $crate::memstat::used_bytes() as u32
        }

        #[no_mangle]
        pub extern "C" fn pixel8_update() {
            GAME.update();
        }

        #[no_mangle]
        pub extern "C" fn pixel8_draw() {
            GAME.draw();
        }
    };
    ($game:ident { $($field:tt)* }) => {
        $crate::game!($game = $game { $($field)* });
    };
    ($game:ident) => {
        $crate::game!($game = <$game as ::core::default::Default>::default());
    };
}

/// Print formatted text to the screen — like [`Graphics::print`], but with
/// `format!`-style arguments. Returns the cursor x (as `i16`) after the last
/// glyph.
///
/// The text is formatted into a fixed stack buffer: no allocator, no
/// dependencies. The default buffer holds one screen line (32 characters); a
/// leading integer-literal `N;` sizes it yourself. Overflow is truncated.
///
/// ```ignore
/// use pixel8::*;
///
/// fn draw(&self, gfx: &mut Graphics) {
///     pixel8::printf!(gfx, 2, 2, Color::YELLOW, "coins {}", self.coins);
///     // A longer line needs a bigger buffer:
///     pixel8::printf!(256; gfx, 0, 8, Color::WHITE, "pos {} {}", self.x, self.y);
/// }
/// ```
#[macro_export]
macro_rules! printf {
    ($cap:literal; $gfx:expr, $x:expr, $y:expr, $color:expr, $($arg:tt)*) => {{
        let __buf = $crate::__internal::format_args_to_buf::<$cap>(::core::format_args!($($arg)*));
        $gfx.print(__buf.as_str(), $x, $y, $color)
    }};
    ($gfx:expr, $x:expr, $y:expr, $color:expr, $($arg:tt)*) => {{
        let __buf = $crate::__internal::format_args_to_buf::<{ $crate::__internal::LINE_CAP }>(
            ::core::format_args!($($arg)*),
        );
        $gfx.print(__buf.as_str(), $x, $y, $color)
    }};
}

/// Log formatted text to the debug console — like [`Context::log`], but with
/// `format!`-style arguments.
///
/// Same fixed-buffer behavior as [`printf!`]: one screen line by default, an
/// optional leading integer-literal `N;` for more, overflow truncated.
///
/// ```ignore
/// use pixel8::*;
///
/// fn update(&mut self, ctx: &mut Context) {
///     pixel8::logf!(ctx, "frame {} pos ({},{})", self.frame, self.x, self.y);
/// }
/// ```
#[macro_export]
macro_rules! logf {
    ($cap:literal; $ctx:expr, $($arg:tt)*) => {{
        let __buf = $crate::__internal::format_args_to_buf::<$cap>(::core::format_args!($($arg)*));
        $ctx.log(__buf.as_str());
    }};
    ($ctx:expr, $($arg:tt)*) => {{
        let __buf = $crate::__internal::format_args_to_buf::<{ $crate::__internal::LINE_CAP }>(
            ::core::format_args!($($arg)*),
        );
        $ctx.log(__buf.as_str());
    }};
}

/// Whether `(x, y)` falls inside a `w x h` surface anchored at the origin.
fn in_bounds(x: i16, y: i16, w: u16, h: u16) -> bool {
    x >= 0 && y >= 0 && (x as u16) < w && (y as u16) < h
}

/// The `(lo, hi)` of a float range; an open lower end is `f32::MIN`, an open upper
/// end is `f32::MAX`.
fn f32_bounds<R>(range: R) -> (f32, f32)
where
    R: RangeBounds<f32>,
{
    let lo = match range.start_bound() {
        Bound::Included(&v) | Bound::Excluded(&v) => v,
        Bound::Unbounded => f32::MIN,
    };
    let hi = match range.end_bound() {
        Bound::Included(&v) | Bound::Excluded(&v) => v,
        Bound::Unbounded => f32::MAX,
    };
    (lo, hi)
}

/// The `(lo, count)` of an integer range — the lower bound and the number of distinct
/// values, in `i64` so the full `i32` span doesn't overflow. An open lower end is
/// `i32::MIN`, an open upper end is `i32::MAX` (inclusive). `count <= 0` is a reversed
/// or empty range.
fn i32_bounds<R>(range: R) -> (i64, i64)
where
    R: RangeBounds<i32>,
{
    let lo = match range.start_bound() {
        Bound::Included(&v) => v as i64,
        Bound::Excluded(&v) => v as i64 + 1,
        Bound::Unbounded => i32::MIN as i64,
    };
    let hi = match range.end_bound() {
        Bound::Included(&v) => v as i64,
        Bound::Excluded(&v) => v as i64 - 1,
        Bound::Unbounded => i32::MAX as i64,
    };
    (lo, hi - lo + 1)
}

/// Map a raw `[0, 1)` draw onto `[lo, hi)`. A reversed or empty span yields `lo`.
/// Computed in `f64` so a span wider than `f32::MAX` (an open-ended range) stays finite.
fn sample_f32(lo: f32, hi: f32, raw: f32) -> f32 {
    let width = hi as f64 - lo as f64;
    if width <= 0.0 {
        lo
    } else {
        (lo as f64 + raw as f64 * width) as f32
    }
}

/// Map a raw `[0, 1)` draw onto `count` integers starting at `lo`. `count <= 0` (a
/// reversed or empty range) yields `lo`. Arithmetic is `i64` so the full `i32` span
/// (count up to 2^32) doesn't overflow.
fn sample_i32(lo: i64, count: i64, raw: f32) -> i32 {
    if count <= 0 {
        return lo as i32;
    }
    let idx = ((raw as f64 * count as f64) as i64).min(count - 1);
    (lo + idx) as i32
}

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

    #[test]
    fn color_new_validates_the_palette_range() {
        assert_eq!(Color::new(0), Some(Color::BLACK));
        assert_eq!(Color::new(15), Some(Color::PEACH));
        assert_eq!(Color::new(8).map(Color::index), Some(8));
        assert_eq!(Color::new(16), None);
        // `new` is const, so out-of-range constants fail at compile time.
        const ACCENT: Color = Color::new(8).unwrap();
        assert_eq!(ACCENT, Color::RED);
    }

    #[test]
    fn button_index_matches_abi_order() {
        assert_eq!(button_index(Button::Left), 0);
        assert_eq!(button_index(Button::Right), 1);
        assert_eq!(button_index(Button::Up), 2);
        assert_eq!(button_index(Button::Down), 3);
        assert_eq!(button_index(Button::O), 4);
        assert_eq!(button_index(Button::X), 5);
    }

    #[test]
    fn button_aliases_match_primaries() {
        let ctx = Context { _private: () };
        for b in [
            Button::Left,
            Button::Right,
            Button::Up,
            Button::Down,
            Button::O,
            Button::X,
        ] {
            assert_eq!(ctx.btn(b), ctx.is_button_down(b));
            assert_eq!(ctx.btnp(b), ctx.is_button_pressed(b));
        }
        // Native stubs report nothing held/pressed.
        assert!(ctx.buttons_down().is_empty());
        assert!(ctx.buttons_pressed().is_empty());
    }

    #[test]
    fn sprite_flag_and_tile_helpers() {
        let ctx = Context { _private: () };
        // Native stubs: fget -> 0 (no flags), mget -> 0.
        assert!(ctx.sprite_flags(SpriteId(1)).is_empty());
        assert_eq!(ctx.sprite_flags(SpriteId(1)), ctx.fget(SpriteId(1)));
        assert!(!ctx.has_sprite_flag(SpriteId(1), SpriteFlag::Flag0));
        assert_eq!(ctx.map_tile(0, 0), Some(SpriteId(0)));
        assert_eq!(ctx.map_tile(0, 0), ctx.mget(0, 0));
        assert_eq!(ctx.map_tile(-1, 0), None);
        assert_eq!(ctx.map_tile(0, MAP_HEIGHT_TILES as i16), None);
    }

    #[test]
    fn set_map_tile_is_bounds_checked() {
        let mut ctx = Context { _private: () };
        assert_eq!(ctx.set_map_tile(0, 0, SpriteId(3)), Ok(()));
        assert_eq!(ctx.mset(0, 0, SpriteId(3)), Ok(()));
        assert_eq!(
            ctx.set_map_tile(MAP_WIDTH_TILES as i16, 0, SpriteId(3)),
            Err(OutOfBounds)
        );
        assert_eq!(
            ctx.mset(0, MAP_HEIGHT_TILES as i16, SpriteId(3)),
            Err(OutOfBounds)
        );
    }

    #[test]
    fn button_mask_round_trips() {
        // bits 0, 3, 5 == Left, Down, X
        let mask = BitFlags::<Button>::from_bits(0b10_1001).unwrap();
        assert!(mask.contains(Button::Left));
        assert!(mask.contains(Button::Down));
        assert!(mask.contains(Button::X));
        assert!(!mask.contains(Button::Right));
    }

    #[test]
    fn diagonal_button_constants() {
        assert_eq!(Button::UP_LEFT, Button::Left | Button::Up);
        assert!(Button::UP_LEFT.contains(Button::Left));
        assert!(Button::UP_LEFT.contains(Button::Up));
        assert!(!Button::UP_LEFT.contains(Button::Right));
        // The four diagonals are distinct sets.
        for (a, b) in [
            (Button::UP_LEFT, Button::UP_RIGHT),
            (Button::UP_LEFT, Button::DOWN_LEFT),
            (Button::DOWN_RIGHT, Button::UP_LEFT),
        ] {
            assert_ne!(a, b);
        }
    }

    #[test]
    fn map_accepts_flag_set_forms() {
        let mut gfx = Graphics { _private: () };
        gfx.map(0, 0, 0, 0, 16, 16, BitFlags::empty()).unwrap();
        gfx.map(0, 0, 0, 0, 16, 16, SpriteFlag::Flag0).unwrap();
        gfx.map(0, 0, 0, 0, 16, 16, SpriteFlag::Flag0 | SpriteFlag::Flag3)
            .unwrap();
        assert_eq!(gfx.map(0, 0, 0, 0, 0, 16, BitFlags::empty()), Err(ZeroSize));
    }

    #[test]
    fn screen_pixel_read_is_bounds_checked() {
        let gfx = Graphics { _private: () };
        // In raw screen space the native stub reads 0; in bounds is `Some`.
        assert!(gfx.pixel(0, 0).is_some());
        assert_eq!(gfx.pixel(1, 1), gfx.pget(1, 1));
        // Off-screen reads are `None`.
        assert_eq!(gfx.pixel(-1, 0), None);
        assert_eq!(gfx.pixel(SCREEN_WIDTH as i16, 0), None);
        assert_eq!(gfx.pixel(0, SCREEN_HEIGHT as i16), None);
    }

    #[test]
    fn graphics_aliases_match_primaries() {
        let mut gfx = Graphics { _private: () };
        assert_eq!(gfx.pixel(1, 1), gfx.pget(1, 1));
        // Drawing aliases forward to primaries (no-op under native stubs).
        gfx.set_pixel(0, 0, Color::RED);
        gfx.pset(0, 0, Color::RED);
        gfx.circle(0, 0, 4, Color::RED);
        gfx.circ(0, 0, 4, Color::RED);
        gfx.circle_fill(0, 0, 4, Color::RED);
        gfx.circfill(0, 0, 4, Color::RED);
        gfx.rect_fill(0, 0, 4, 4, Color::RED).unwrap();
        gfx.rectfill(0, 0, 4, 4, Color::RED).unwrap();
        gfx.sprite(SpriteId(0), 0, 0);
        gfx.spr(SpriteId(0), 0, 0);
    }

    #[test]
    fn printf_formats_and_returns_cursor() {
        let mut gfx = Graphics { _private: () };
        // The native ffi::print stub returns 0; this exercises macro
        // expansion and the i16 return type. String content is covered by the
        // fmt::tests, since the stub does not capture the text.
        let cursor: i16 = printf!(gfx, 0, 0, Color::WHITE, "n={}", 3);
        assert_eq!(cursor, 0);
        // Capacity-override arm, multi-arg, and a no-arg literal all expand.
        let _: i16 = printf!(64; gfx, 0, 0, Color::WHITE, "{}-{}", 1, 2);
        let _: i16 = printf!(gfx, 0, 0, Color::WHITE, "literal");
    }

    #[test]
    fn logf_formats_and_runs() {
        let mut ctx = Context { _private: () };
        logf!(ctx, "frame {}", 9);
        logf!(128; ctx, "{}-{}", 1, 2);
        logf!(ctx, "literal");
    }

    #[test]
    fn context_sheet_and_rng_aliases() {
        let mut ctx = Context { _private: () };
        ctx.seed_rng(1);
        ctx.srand(1);
        ctx.set_sprite_pixel(0, 0, Color::RED).unwrap();
        ctx.sset(0, 0, Color::RED).unwrap();
        // Native stubs read 0; in-bounds reads are `Some`.
        assert_eq!(ctx.sprite_pixel(0, 0), Some(Color::from_index(0)));
        assert_eq!(ctx.sprite_pixel(0, 0), ctx.sget(0, 0));
        // Off the 128x128 sheet: reads are `None`, writes are `Err`.
        assert_eq!(ctx.sprite_pixel(-1, 0), None);
        assert_eq!(ctx.sprite_pixel(SPRITE_SHEET_WIDTH as i16, 0), None);
        assert_eq!(ctx.sprite_pixel(0, SPRITE_SHEET_HEIGHT as i16), None);
        assert_eq!(
            ctx.set_sprite_pixel(SPRITE_SHEET_WIDTH as i16, 0, Color::RED),
            Err(OutOfBounds)
        );
        assert_eq!(ctx.set_sprite_pixel(5, 5, Color::RED), Ok(()));
    }

    #[test]
    fn f32_bounds_fills_open_ends_with_extremes() {
        assert_eq!(f32_bounds(2.0..5.0), (2.0, 5.0));
        assert_eq!(f32_bounds(2.0..=5.0), (2.0, 5.0));
        assert_eq!(f32_bounds(-5.0..-1.0), (-5.0, -1.0));
        assert_eq!(f32_bounds(..44.0), (f32::MIN, 44.0));
        assert_eq!(f32_bounds(0.0..), (0.0, f32::MAX));
        assert_eq!(f32_bounds(..), (f32::MIN, f32::MAX));
    }

    #[test]
    fn i32_bounds_counts_and_fills_open_ends() {
        assert_eq!(i32_bounds(0..10), (0, 10));
        assert_eq!(i32_bounds(1..=6), (1, 6));
        assert_eq!(i32_bounds(-10..0), (-10, 10));
        assert_eq!(i32_bounds(-5..=5), (-5, 11));
        // Open ends use i32::MIN / i32::MAX (upper inclusive).
        assert_eq!(i32_bounds(5..), (5, i32::MAX as i64 - 5 + 1));
        assert_eq!(i32_bounds(..10), (i32::MIN as i64, 10 - i32::MIN as i64));
        assert_eq!(
            i32_bounds(..),
            (i32::MIN as i64, i32::MAX as i64 - i32::MIN as i64 + 1)
        );
        // Reversed -> non-positive count (built at runtime to avoid
        // clippy::reversed_empty_ranges); equal-bound empty is fine as a literal.
        let (a, b): (i32, i32) = (5, 2);
        assert_eq!(i32_bounds(a..b), (5, -3));
        assert_eq!(i32_bounds(5..5), (5, 0));
    }

    #[test]
    fn sample_f32_maps_guards_and_stays_finite() {
        assert_eq!(sample_f32(0.0, 10.0, 0.0), 0.0);
        assert!((sample_f32(0.0, 10.0, 0.5) - 5.0).abs() < 1e-5);
        assert_eq!(sample_f32(-5.0, 5.0, 0.0), -5.0);
        assert!(sample_f32(-5.0, 5.0, 0.5).abs() < 1e-5);
        // Reversed / empty -> lo.
        assert_eq!(sample_f32(5.0, 2.0, 0.5), 5.0);
        assert_eq!(sample_f32(3.0, 3.0, 0.5), 3.0);
        // Full f32 span stays finite (f64 intermediate); midpoint ~ 0.
        let mid = sample_f32(f32::MIN, f32::MAX, 0.5);
        assert!(mid.is_finite());
        assert!(mid.abs() < 1e30);
    }

    #[test]
    fn sample_i32_maps_clamps_and_guards() {
        assert_eq!(sample_i32(0, 10, 0.0), 0);
        assert_eq!(sample_i32(0, 10, 0.999_999), 9);
        assert_eq!(sample_i32(0, 10, 0.55), 5);
        // Inclusive top reachable: lo=1, count=6 -> 6.
        assert_eq!(sample_i32(1, 6, 0.999_999), 6);
        // Negative bounds.
        assert_eq!(sample_i32(-10, 10, 0.999_999), -1);
        // Reversed / empty -> lo.
        assert_eq!(sample_i32(5, -3, 0.5), 5);
        assert_eq!(sample_i32(5, 0, 0.5), 5);
        // Full i32 span (count = 2^32) doesn't overflow.
        let full = i32::MAX as i64 - i32::MIN as i64 + 1;
        assert_eq!(sample_i32(i32::MIN as i64, full, 0.0), i32::MIN);
        assert_eq!(sample_i32(i32::MIN as i64, full, 0.5), 0);
    }

    #[test]
    fn context_random_methods_forward() {
        let mut ctx = Context { _private: () };
        // Native ffi::rnd() stub returns 0.0, so each call yields the lower bound.
        assert_eq!(ctx.random(2.0..5.0), 2.0);
        assert_eq!(ctx.random(2.0..=5.0), 2.0);
        assert_eq!(ctx.random(0.0..), 0.0);
        assert_eq!(ctx.random(..44.0), f32::MIN);
        assert_eq!(ctx.random_integer(3..9), 3);
        assert_eq!(ctx.random_integer(3..=9), 3);
        assert_eq!(ctx.random_integer(5..), 5);
        assert_eq!(ctx.random_integer(..10), i32::MIN);
        assert_eq!(ctx.rnd(5.0), 0.0);
        assert_eq!(ctx.rndi(10), 0);
    }

    #[test]
    fn context_exposes_resource_stats() {
        // On native targets the ffi stubs return 0.0; this asserts the safe
        // wrappers compile and forward to them.
        let ctx = Context { _private: () };
        assert_eq!(ctx.cpu_update(), 0.0);
        assert_eq!(ctx.cpu_draw(), 0.0);
        assert_eq!(ctx.mem(), 0.0);
        assert_eq!(ctx.fps(), 0.0);
    }

    #[test]
    fn graphics_parity_aliases_compile_and_forward() {
        let mut gfx = Graphics { _private: () };
        gfx.set_transparent_color(Color::BLACK, true);
        gfx.palt(Color::BLACK, true);
        gfx.reset_transparency();
        gfx.remap_color(Color::RED, Color::BLUE);
        gfx.pal(Color::RED, Color::BLUE);
        gfx.remap_display_color(Color::RED, Color::BLUE);
        gfx.pal_display(Color::RED, Color::BLUE);
        gfx.reset_palette();
        gfx.sprite_stretch(0, 0, 8, 8, 0, 0, 16, 16, false, false)
            .unwrap();
        gfx.sspr(0, 0, 8, 8, 0, 0, 16, 16, true, true).unwrap();
        assert_eq!(
            gfx.sspr(0, 0, 8, 8, 0, 0, 0, 16, false, false),
            Err(ZeroSize)
        );
        gfx.ellipse(0, 0, 8, 6, Color::WHITE).unwrap();
        gfx.oval(0, 0, 8, 6, Color::WHITE).unwrap();
        gfx.ellipse_fill(0, 0, 8, 6, Color::WHITE).unwrap();
        gfx.ovalfill(0, 0, 8, 6, Color::WHITE).unwrap();
        gfx.set_fill_pattern(0b1010, Color::RED);
        gfx.fillp(0b1010);
        gfx.set_fill_pattern_transparent(0b1010);
        gfx.clear_fill_pattern();
        gfx.set_pen_color(Color::YELLOW);
        gfx.color(Color::YELLOW);
        gfx.set_cursor(4, 4);
        gfx.cursor(4, 4);
        let cursor: i16 = gfx.print_pen("hi");
        assert_eq!(cursor, 0, "native print_pen stub returns 0");
    }

    #[test]
    fn fallible_rect_and_ellipse() {
        let mut gfx = Graphics { _private: () };
        // Positive sizes succeed.
        assert_eq!(gfx.rect(0, 0, 4, 4, Color::RED), Ok(()));
        assert_eq!(gfx.rect_fill(0, 0, 4, 4, Color::RED), Ok(()));
        assert_eq!(gfx.ellipse(0, 0, 8, 6, Color::WHITE), Ok(()));
        assert_eq!(gfx.ellipse_fill(0, 0, 8, 6, Color::WHITE), Ok(()));
        // Zero or negative sizes are a ZeroSize error (nothing drawn).
        assert_eq!(gfx.rect_fill(0, 0, 0, 4, Color::RED), Err(ZeroSize));
        assert_eq!(gfx.rect(0, 0, 4, -1, Color::RED), Err(ZeroSize));
        // A computed i32 size (the case core's TryInto can't take) compiles.
        let w = 10 - 4;
        assert_eq!(gfx.rect(0, 0, w, 4, Color::RED), Ok(()));
    }

    #[test]
    fn clip_is_fallible_and_reset_is_not() {
        let mut gfx = Graphics { _private: () };
        assert_eq!(gfx.clip(0, 0, 64, 64), Ok(()));
        assert_eq!(gfx.clip(0, 0, 0, 64), Err(ZeroSize));
        gfx.clip_reset(); // Infallible.
    }

    #[test]
    fn surface_dimensions_and_out_of_bounds_exist() {
        assert_eq!((SPRITE_SHEET_WIDTH, SPRITE_SHEET_HEIGHT), (128, 128));
        assert_eq!((MAP_WIDTH_TILES, MAP_HEIGHT_TILES), (128, 64));
        // The error type is comparable, so writes can be asserted later.
        assert_eq!(OutOfBounds, OutOfBounds);
    }

    #[test]
    fn sprite_and_sprite_ext() {
        let mut gfx = Graphics { _private: () };
        gfx.sprite(SpriteId(0), 0, 0);
        gfx.spr(SpriteId(0), 0, 0);
        // Pixel dimensions: a full cell is 8, a half-cell slice is 4.
        assert_eq!(
            gfx.sprite_ext(SpriteId(0), 0, 0, 8, 8, false, false),
            Ok(())
        );
        assert_eq!(gfx.sprite_ext(SpriteId(0), 0, 0, 4, 8, true, false), Ok(()));
        assert_eq!(
            gfx.sprite_ext(SpriteId(0), 0, 0, 0, 8, false, false),
            Err(ZeroSize)
        );
    }

    #[test]
    fn channel_index_matches_abi_order() {
        assert_eq!(channel_index(Channel::Channel0), 0);
        assert_eq!(channel_index(Channel::Channel1), 1);
        assert_eq!(channel_index(Channel::Channel2), 2);
        assert_eq!(channel_index(Channel::Channel3), 3);
    }

    #[test]
    fn sfx_channel_methods_take_exactly_one_channel() {
        let mut ctx = Context { _private: () };
        ctx.sfx(SfxId::new(0).unwrap());
        ctx.sfx_on(SfxId::new(1).unwrap(), Channel::Channel2);
        ctx.sfx_stop(Channel::Channel2);
    }

    #[test]
    fn sfx_and_music_ids_validate_their_range() {
        assert_eq!(SfxId::new(0).map(SfxId::index), Some(0));
        assert_eq!(SfxId::new(63).map(SfxId::index), Some(63));
        assert_eq!(SfxId::new(64), None);
        assert_eq!(MusicId::new(63).map(MusicId::index), Some(63));
        assert_eq!(MusicId::new(64), None);
        // `new` is const, so out-of-range constants fail at compile time.
        const JUMP: SfxId = SfxId::new(5).unwrap();
        assert_eq!(JUMP.index(), 5);
    }
}