wasm96-sdk 0.1.2

SDK for building WASM apps that run under the wasm96 libretro core.
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
#![cfg_attr(not(feature = "std"), no_std)]

//! wasm96-sdk (handwritten)
//!
//! This crate is used by **guest** WASM apps that run inside the `wasm96` libretro core.
//!
//! ABI model (Immediate Mode):
//! - Host owns the framebuffer and handles rendering.
//! - Guest issues drawing commands.
//! - Guest exports `setup`, `update`, and `draw`.
//!
//! This file intentionally contains **no WIT** and **no codegen**.
//!
//! # Fonts & text: how it works
//!
//! wasm96 provides a **keyed font** model:
//! - You register a font under a `u64` key (the SDK hashes `&str` keys for you).
//! - Later you draw or measure text by referencing the same key.
//!
//! In the Rust SDK:
//! - Registration lives in [`graphics::font_register_ttf`], [`graphics::font_register_bdf`],
//!   and [`graphics::font_register_spleen`].
//! - Drawing & measuring live in [`graphics::text_key`] and [`graphics::text_measure_key`].
//!
//! ## Fallback behavior (important)
//!
//! The host (wasm96-core) implements a **fallback** if you try to measure/draw text using a
//! `font_key` that was never registered:
//! - `graphics::text_key(...)` falls back to the built-in **Spleen** font at **size 16**.
//! - `graphics::text_measure_key(...)` uses the same fallback (Spleen size 16).
//!
//! This means text “just works” out-of-the-box, but you should still register fonts when you
//! care about style, metric stability, or performance.
//!
//! ## Which font format should you use?
//!
//! - **Spleen (built-in, BDF)** via [`graphics::font_register_spleen`]
//!   - Great default for pixel UIs / debug text.
//!   - Supported sizes: **8, 16, 24, 32, 64** (other sizes currently fail and return `false`).
//! - **BDF (custom)** via [`graphics::font_register_bdf`]
//!   - Best for pixel-perfect fonts you control.
//!   - Host parses the BDF, builds a glyph map, and renders using the parsed bitmaps.
//! - **TTF/OTF (custom)** via [`graphics::font_register_ttf`]
//!   - Best for scalable fonts.
//!   - Host uses font rasterization and draws glyphs as alpha-blended bitmaps.
//!
//! ## Recommended usage pattern
//!
//! 1. Pick a stable string key for each font you use (e.g. `"ui"`, `"title"`, `"debug"`).
//! 2. Register fonts during `setup()` (once).
//! 3. Use `text_measure_key` for layout (e.g. centering).
//! 4. Use `text_key` to draw. Reuse keys; do not re-register each frame.
//!
//! Example (built-in Spleen):
//!
//! ```no_run
//! use wasm96_sdk::graphics;
//!
//! #[no_mangle]
//! pub extern "C" fn setup() {
//!     graphics::set_size(320, 240);
//!     // Register built-in Spleen under a key you control.
//!     graphics::font_register_spleen("ui", 16);
//! }
//!
//! #[no_mangle]
//! pub extern "C" fn draw() {
//!     graphics::background(0, 0, 0);
//!     graphics::set_color(255, 255, 255, 255);
//!
//!     let size = graphics::text_measure_key("ui", "Hello wasm96");
//!     let x = (320i32 - size.width as i32) / 2;
//!     let y = 20;
//!     graphics::text_key(x, y, "ui", "Hello wasm96");
//! }
//! ```
//!
//! ## Lifetimes and safety notes
//!
//! - `text_key` and `text_measure_key` pass pointers into guest memory to the host.
//!   The host reads the bytes immediately during the call, so the `&str` only needs to remain
//!   valid for the duration of the function call.
//! - `font_register_*` similarly passes pointers to font data; the host copies/decodes immediately.
//!
//! ## Unregistering fonts
//!
//! If you need to reclaim host-side font resources (rare for most games), call
//! [`graphics::font_unregister`]. The key will no longer map to a font. Subsequent text usage
//! with that key will again hit the host fallback (Spleen size 16).

#[cfg(not(feature = "std"))]
extern crate alloc;

use core::ffi::c_void;

/// Joypad button ids.
#[repr(u32)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Button {
    B = 0,
    Y = 1,
    Select = 2,
    Start = 3,
    Up = 4,
    Down = 5,
    Left = 6,
    Right = 7,
    A = 8,
    X = 9,
    L1 = 10,
    R1 = 11,
    L2 = 12,
    R2 = 13,
    L3 = 14,
    R3 = 15,
}

/// Text size dimensions.
#[repr(C)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct TextSize {
    pub width: u32,
    pub height: u32,
}

/// Low-level raw ABI imports.
#[allow(non_camel_case_types)]
pub mod sys {
    unsafe extern "C" {
        // Graphics
        #[link_name = "wasm96_graphics_set_size"]
        pub fn graphics_set_size(width: u32, height: u32);
        #[link_name = "wasm96_graphics_set_color"]
        pub fn graphics_set_color(r: u32, g: u32, b: u32, a: u32);
        #[link_name = "wasm96_graphics_background"]
        pub fn graphics_background(r: u32, g: u32, b: u32);
        #[link_name = "wasm96_graphics_point"]
        pub fn graphics_point(x: i32, y: i32);
        #[link_name = "wasm96_graphics_line"]
        pub fn graphics_line(x1: i32, y1: i32, x2: i32, y2: i32);
        #[link_name = "wasm96_graphics_rect"]
        pub fn graphics_rect(x: i32, y: i32, w: u32, h: u32);
        #[link_name = "wasm96_graphics_rect_outline"]
        pub fn graphics_rect_outline(x: i32, y: i32, w: u32, h: u32);
        #[link_name = "wasm96_graphics_circle"]
        pub fn graphics_circle(x: i32, y: i32, r: u32);
        #[link_name = "wasm96_graphics_circle_outline"]
        pub fn graphics_circle_outline(x: i32, y: i32, r: u32);
        #[link_name = "wasm96_graphics_image"]
        pub fn graphics_image(x: i32, y: i32, w: u32, h: u32, ptr: u32, len: u32);

        // One-shot (decode + draw at natural size)
        #[link_name = "wasm96_graphics_image_png"]
        pub fn graphics_image_png(x: i32, y: i32, ptr: u32, len: u32);
        #[link_name = "wasm96_graphics_image_jpeg"]
        pub fn graphics_image_jpeg(x: i32, y: i32, ptr: u32, len: u32);

        // Materials / textures (OBJ+MTL workflows)
        //
        // Given an `.mtl` file and one encoded texture blob (PNG/JPEG) + its filename, register the
        // decoded texture under `texture_key` if the filename appears as a `map_Kd` entry.
        #[link_name = "wasm96_graphics_mtl_register_texture"]
        pub fn graphics_mtl_register_texture(
            texture_key: u64,
            mtl_ptr: u32,
            mtl_len: u32,
            tex_filename_ptr: u32,
            tex_filename_len: u32,
            tex_ptr: u32,
            tex_len: u32,
        ) -> u32;

        // --- Keyed resources (hashed keys) ---
        // SVG
        #[link_name = "wasm96_graphics_svg_register"]
        pub fn graphics_svg_register(key: u64, data_ptr: u32, data_len: u32) -> u32;
        #[link_name = "wasm96_graphics_svg_draw_key"]
        pub fn graphics_svg_draw_key(key: u64, x: i32, y: i32, w: u32, h: u32);
        #[link_name = "wasm96_graphics_svg_unregister"]
        pub fn graphics_svg_unregister(key: u64);

        // GIF
        #[link_name = "wasm96_graphics_gif_register"]
        pub fn graphics_gif_register(key: u64, data_ptr: u32, data_len: u32) -> u32;
        #[link_name = "wasm96_graphics_gif_draw_key"]
        pub fn graphics_gif_draw_key(key: u64, x: i32, y: i32);
        #[link_name = "wasm96_graphics_gif_draw_key_scaled"]
        pub fn graphics_gif_draw_key_scaled(key: u64, x: i32, y: i32, w: u32, h: u32);
        #[link_name = "wasm96_graphics_gif_unregister"]
        pub fn graphics_gif_unregister(key: u64);

        // PNG
        #[link_name = "wasm96_graphics_png_register"]
        pub fn graphics_png_register(key: u64, data_ptr: u32, data_len: u32) -> u32;
        #[link_name = "wasm96_graphics_png_draw_key"]
        pub fn graphics_png_draw_key(key: u64, x: i32, y: i32);
        #[link_name = "wasm96_graphics_png_draw_key_scaled"]
        pub fn graphics_png_draw_key_scaled(key: u64, x: i32, y: i32, w: u32, h: u32);
        #[link_name = "wasm96_graphics_png_unregister"]
        pub fn graphics_png_unregister(key: u64);

        // JPEG
        #[link_name = "wasm96_graphics_jpeg_register"]
        pub fn graphics_jpeg_register(key: u64, data_ptr: u32, data_len: u32) -> u32;
        #[link_name = "wasm96_graphics_jpeg_draw_key"]
        pub fn graphics_jpeg_draw_key(key: u64, x: i32, y: i32);
        #[link_name = "wasm96_graphics_jpeg_draw_key_scaled"]
        pub fn graphics_jpeg_draw_key_scaled(key: u64, x: i32, y: i32, w: u32, h: u32);
        #[link_name = "wasm96_graphics_jpeg_unregister"]
        pub fn graphics_jpeg_unregister(key: u64);

        // Fonts + text (keyed by string)
        //
        // The host maintains a map of `u64 font_key -> font resource`.
        // Keys are arbitrary. The Rust SDK hashes `&str` keys with FNV-1a to a `u64`.
        //
        // Registration functions return 1 on success, 0 on failure.
        //
        // IMPORTANT HOST BEHAVIOR:
        // - If you call `graphics_text_key` / `graphics_text_measure_key` with a font_key that has
        //   never been registered, the host falls back to built-in Spleen at size 16.
        //
        // This makes text work out-of-the-box, but for stable metrics you should explicitly
        // register a font under a deterministic key during `setup()`.
        #[link_name = "wasm96_graphics_font_register_ttf"]
        pub fn graphics_font_register_ttf(key: u64, data_ptr: u32, data_len: u32) -> u32;
        #[link_name = "wasm96_graphics_font_register_bdf"]
        pub fn graphics_font_register_bdf(key: u64, data_ptr: u32, data_len: u32) -> u32;
        #[link_name = "wasm96_graphics_font_register_spleen"]
        pub fn graphics_font_register_spleen(key: u64, size: u32) -> u32;
        #[link_name = "wasm96_graphics_font_unregister"]
        pub fn graphics_font_unregister(key: u64);

        // Draw text with a keyed font.
        // - `text_ptr/text_len` are UTF-8 bytes in guest memory (host expects valid UTF-8).
        // - If `font_key` is unknown, host falls back to Spleen size 16.
        #[link_name = "wasm96_graphics_text_key"]
        pub fn graphics_text_key(x: i32, y: i32, font_key: u64, text_ptr: u32, text_len: u32);

        // Measure text with a keyed font.
        // - Returns a packed u64: (width<<32) | height.
        // - If `font_key` is unknown, host falls back to Spleen size 16.
        #[link_name = "wasm96_graphics_text_measure_key"]
        pub fn graphics_text_measure_key(font_key: u64, text_ptr: u32, text_len: u32) -> u64;

        #[link_name = "wasm96_graphics_triangle"]
        pub fn graphics_triangle(x1: i32, y1: i32, x2: i32, y2: i32, x3: i32, y3: i32);

        #[link_name = "wasm96_graphics_triangle_outline"]
        pub fn graphics_triangle_outline(x1: i32, y1: i32, x2: i32, y2: i32, x3: i32, y3: i32);

        #[link_name = "wasm96_graphics_bezier_quadratic"]
        pub fn graphics_bezier_quadratic(
            x1: i32,
            y1: i32,
            cx: i32,
            cy: i32,
            x2: i32,
            y2: i32,
            segments: u32,
        );

        #[link_name = "wasm96_graphics_bezier_cubic"]
        pub fn graphics_bezier_cubic(
            x1: i32,
            y1: i32,
            cx1: i32,
            cy1: i32,
            cx2: i32,
            cy2: i32,
            x2: i32,
            y2: i32,
            segments: u32,
        );

        #[link_name = "wasm96_graphics_pill"]
        pub fn graphics_pill(x: i32, y: i32, w: u32, h: u32);

        #[link_name = "wasm96_graphics_pill_outline"]
        pub fn graphics_pill_outline(x: i32, y: i32, w: u32, h: u32);

        // 3D Graphics
        #[link_name = "wasm96_graphics_set_3d"]
        pub fn graphics_set_3d(enable: u32);

        #[link_name = "wasm96_graphics_camera_look_at"]
        pub fn graphics_camera_look_at(
            eye_x: f32,
            eye_y: f32,
            eye_z: f32,
            target_x: f32,
            target_y: f32,
            target_z: f32,
            up_x: f32,
            up_y: f32,
            up_z: f32,
        );

        #[link_name = "wasm96_graphics_camera_perspective"]
        pub fn graphics_camera_perspective(fovy: f32, aspect: f32, near: f32, far: f32);

        #[link_name = "wasm96_graphics_mesh_create"]
        pub fn graphics_mesh_create(
            key: u64,
            v_ptr: *const f32,
            v_len: usize,
            i_ptr: *const u32,
            i_len: usize,
        ) -> u32;

        #[link_name = "wasm96_graphics_mesh_create_obj"]
        pub fn graphics_mesh_create_obj(key: u64, ptr: *const u8, len: usize) -> u32;

        #[link_name = "wasm96_graphics_mesh_create_stl"]
        pub fn graphics_mesh_create_stl(key: u64, ptr: *const u8, len: usize) -> u32;

        #[link_name = "wasm96_graphics_mesh_set_texture"]
        pub fn graphics_mesh_set_texture(mesh_key: u64, image_key: u64) -> u32;

        #[link_name = "wasm96_graphics_mesh_draw"]
        pub fn graphics_mesh_draw(
            key: u64,
            x: f32,
            y: f32,
            z: f32,
            rx: f32,
            ry: f32,
            rz: f32,
            sx: f32,
            sy: f32,
            sz: f32,
        );

        // Input
        #[link_name = "wasm96_input_is_button_down"]
        pub fn input_is_button_down(port: u32, btn: u32) -> u32;
        #[link_name = "wasm96_input_is_key_down"]
        pub fn input_is_key_down(key: u32) -> u32;
        #[link_name = "wasm96_input_get_mouse_x"]
        pub fn input_get_mouse_x() -> i32;
        #[link_name = "wasm96_input_get_mouse_y"]
        pub fn input_get_mouse_y() -> i32;
        #[link_name = "wasm96_input_is_mouse_down"]
        pub fn input_is_mouse_down(btn: u32) -> u32;

        // Audio
        #[link_name = "wasm96_audio_init"]
        pub fn audio_init(sample_rate: u32) -> u32;
        #[link_name = "wasm96_audio_push_samples"]
        pub fn audio_push_samples(ptr: u32, len: u32);

        #[link_name = "wasm96_audio_play_wav"]
        pub fn audio_play_wav(ptr: u32, len: u32);

        #[link_name = "wasm96_audio_play_qoa"]
        pub fn audio_play_qoa(ptr: u32, len: u32);

        #[link_name = "wasm96_audio_play_xm"]
        pub fn audio_play_xm(ptr: u32, len: u32);

        // Storage
        #[link_name = "wasm96_storage_save"]
        pub fn storage_save(key: u64, data_ptr: u32, data_len: u32);
        #[link_name = "wasm96_storage_load"]
        pub fn storage_load(key: u64) -> u64;
        #[link_name = "wasm96_storage_free"]
        pub fn storage_free(ptr: u32, len: u32);

        // System
        #[link_name = "wasm96_system_log"]
        pub fn system_log(ptr: u32, len: u32);
        #[link_name = "wasm96_system_millis"]
        pub fn system_millis() -> u64;
    }
}

/// Graphics API.
pub mod graphics {
    use super::sys;
    use crate::TextSize;

    pub(crate) fn hash_key(key: &str) -> u64 {
        let mut hash: u64 = 0xcbf29ce484222325;
        for byte in key.bytes() {
            hash ^= byte as u64;
            hash = hash.wrapping_mul(0x100000001b3);
        }
        hash
    }

    /// Set the screen dimensions.
    pub fn set_size(width: u32, height: u32) {
        unsafe { sys::graphics_set_size(width, height) }
    }

    /// Set the current drawing color (RGBA).
    pub fn set_color(r: u8, g: u8, b: u8, a: u8) {
        unsafe { sys::graphics_set_color(r as u32, g as u32, b as u32, a as u32) }
    }

    /// Clear the screen with a specific color (RGB).
    pub fn background(r: u8, g: u8, b: u8) {
        unsafe { sys::graphics_background(r as u32, g as u32, b as u32) }
    }

    /// Draw a single pixel at (x, y).
    pub fn point(x: i32, y: i32) {
        unsafe { sys::graphics_point(x, y) }
    }

    /// Draw a line from (x1, y1) to (x2, y2).
    pub fn line(x1: i32, y1: i32, x2: i32, y2: i32) {
        unsafe { sys::graphics_line(x1, y1, x2, y2) }
    }

    /// Draw a filled rectangle.
    pub fn rect(x: i32, y: i32, w: u32, h: u32) {
        unsafe { sys::graphics_rect(x, y, w, h) }
    }

    /// Draw a rectangle outline.
    pub fn rect_outline(x: i32, y: i32, w: u32, h: u32) {
        unsafe { sys::graphics_rect_outline(x, y, w, h) }
    }

    /// Draw a filled circle.
    pub fn circle(x: i32, y: i32, r: u32) {
        unsafe { sys::graphics_circle(x, y, r) }
    }

    /// Draw a circle outline.
    pub fn circle_outline(x: i32, y: i32, r: u32) {
        unsafe { sys::graphics_circle_outline(x, y, r) }
    }

    /// Draw an image/sprite.
    /// `data` is a slice of RGBA bytes (4 bytes per pixel).
    pub fn image(x: i32, y: i32, w: u32, h: u32, data: &[u8]) {
        unsafe { sys::graphics_image(x, y, w, h, data.as_ptr() as u32, data.len() as u32) }
    }

    /// Draw an image from raw PNG bytes.
    pub fn image_png(x: i32, y: i32, data: &[u8]) {
        unsafe { sys::graphics_image_png(x, y, data.as_ptr() as u32, data.len() as u32) }
    }

    /// Draw an image from raw JPEG bytes.
    pub fn image_jpeg(x: i32, y: i32, data: &[u8]) {
        unsafe { sys::graphics_image_jpeg(x, y, data.as_ptr() as u32, data.len() as u32) }
    }

    /// Register an encoded PNG (bytes) with the host under a string key.
    /// Register a GIF resource (encoded bytes) under a string key.
    /// Returns true on success.
    pub fn gif_register(key: &str, gif_bytes: &[u8]) -> bool {
        unsafe {
            sys::graphics_gif_register(
                hash_key(key),
                gif_bytes.as_ptr() as u32,
                gif_bytes.len() as u32,
            ) != 0
        }
    }

    /// Draw a registered GIF by key at natural size.
    pub fn gif_draw_key(key: &str, x: i32, y: i32) {
        unsafe { sys::graphics_gif_draw_key(hash_key(key), x, y) }
    }

    /// Draw a registered GIF by key scaled.
    pub fn gif_draw_key_scaled(key: &str, x: i32, y: i32, w: u32, h: u32) {
        unsafe { sys::graphics_gif_draw_key_scaled(hash_key(key), x, y, w, h) }
    }

    /// Unregister a GIF by key.
    pub fn gif_unregister(key: &str) {
        unsafe { sys::graphics_gif_unregister(hash_key(key)) }
    }

    /// Draw a filled triangle.
    pub fn triangle(x1: i32, y1: i32, x2: i32, y2: i32, x3: i32, y3: i32) {
        unsafe { sys::graphics_triangle(x1, y1, x2, y2, x3, y3) }
    }

    /// Draw a triangle outline.
    pub fn triangle_outline(x1: i32, y1: i32, x2: i32, y2: i32, x3: i32, y3: i32) {
        unsafe { sys::graphics_triangle_outline(x1, y1, x2, y2, x3, y3) }
    }

    /// Draw a quadratic Bezier curve.
    pub fn bezier_quadratic(x1: i32, y1: i32, cx: i32, cy: i32, x2: i32, y2: i32, segments: u32) {
        unsafe { sys::graphics_bezier_quadratic(x1, y1, cx, cy, x2, y2, segments) }
    }

    /// Draw a cubic Bezier curve.
    pub fn bezier_cubic(
        x1: i32,
        y1: i32,
        cx1: i32,
        cy1: i32,
        cx2: i32,
        cy2: i32,
        x2: i32,
        y2: i32,
        segments: u32,
    ) {
        unsafe { sys::graphics_bezier_cubic(x1, y1, cx1, cy1, cx2, cy2, x2, y2, segments) }
    }

    /// Draw a filled pill.
    pub fn pill(x: i32, y: i32, w: u32, h: u32) {
        unsafe { sys::graphics_pill(x, y, w, h) }
    }

    /// Draw a pill outline.
    pub fn pill_outline(x: i32, y: i32, w: u32, h: u32) {
        unsafe { sys::graphics_pill_outline(x, y, w, h) }
    }

    // =========================
    // 3D Graphics
    // =========================

    pub fn set_3d(enable: bool) {
        unsafe { sys::graphics_set_3d(enable as u32) }
    }

    pub fn camera_look_at(eye: (f32, f32, f32), target: (f32, f32, f32), up: (f32, f32, f32)) {
        unsafe {
            sys::graphics_camera_look_at(
                eye.0, eye.1, eye.2, target.0, target.1, target.2, up.0, up.1, up.2,
            )
        }
    }

    pub fn camera_perspective(fovy: f32, aspect: f32, near: f32, far: f32) {
        unsafe { sys::graphics_camera_perspective(fovy, aspect, near, far) }
    }

    pub fn mesh_create(key: &str, vertices: &[f32], indices: &[u32]) -> bool {
        let k = hash_key(key);
        unsafe {
            sys::graphics_mesh_create(
                k,
                vertices.as_ptr(),
                vertices.len(),
                indices.as_ptr(),
                indices.len(),
            ) != 0
        }
    }

    pub fn mesh_create_obj(key: &str, obj_data: &[u8]) -> bool {
        let k = hash_key(key);
        unsafe { sys::graphics_mesh_create_obj(k, obj_data.as_ptr(), obj_data.len()) != 0 }
    }

    pub fn mesh_create_stl(key: &str, stl_data: &[u8]) -> bool {
        let k = hash_key(key);
        unsafe { sys::graphics_mesh_create_stl(k, stl_data.as_ptr(), stl_data.len()) != 0 }
    }

    pub fn mesh_draw(
        key: &str,
        pos: (f32, f32, f32),
        rot: (f32, f32, f32),
        scale: (f32, f32, f32),
    ) {
        let k = hash_key(key);
        unsafe {
            sys::graphics_mesh_draw(
                k, pos.0, pos.1, pos.2, rot.0, rot.1, rot.2, scale.0, scale.1, scale.2,
            )
        }
    }

    /// Bind a keyed decoded image (PNG/JPEG) as the texture for a mesh.
    /// Returns true on success.
    ///
    /// Notes:
    /// - PNG alpha is respected (RGBA).
    /// - JPEG is treated as opaque (RGB), but may still be uploaded as RGBA with A=255 on host.
    pub fn mesh_set_texture(mesh_key: &str, image_key: &str) -> bool {
        unsafe { sys::graphics_mesh_set_texture(hash_key(mesh_key), hash_key(image_key)) != 0 }
    }

    /// Register an SVG resource under a string key.
    /// Register an SVG resource (encoded bytes) under a string key.
    /// Returns true on success.
    pub fn svg_register(key: &str, svg_bytes: &[u8]) -> bool {
        unsafe {
            sys::graphics_svg_register(
                hash_key(key),
                svg_bytes.as_ptr() as u32,
                svg_bytes.len() as u32,
            ) != 0
        }
    }

    /// Draw a keyed SVG.
    pub fn svg_draw_key(key: &str, x: i32, y: i32, w: u32, h: u32) {
        unsafe { sys::graphics_svg_draw_key(hash_key(key), x, y, w, h) }
    }

    /// Unregister a keyed SVG.
    pub fn svg_unregister(key: &str) {
        unsafe { sys::graphics_svg_unregister(hash_key(key)) }
    }

    /// Register a PNG resource (encoded bytes) under a string key.
    /// Returns true on success.
    pub fn png_register(key: &str, png_bytes: &[u8]) -> bool {
        unsafe {
            sys::graphics_png_register(
                hash_key(key),
                png_bytes.as_ptr() as u32,
                png_bytes.len() as u32,
            ) != 0
        }
    }

    /// Register an encoded texture referenced by an `.mtl` file (`map_Kd`) under `texture_key`.
    ///
    /// Usage pattern (guest-side):
    /// - You already have the `.mtl` bytes (`mtl_bytes`)
    /// - For each texture file referenced by `map_Kd`, call this passing:
    ///   - `texture_key`: the key you want to register the decoded image under
    ///   - `tex_filename`: the *exact* filename string as used in `map_Kd`
    ///   - `tex_bytes`: the encoded PNG/JPEG bytes for that filename
    ///
    /// Returns `true` if it registered (filename matched + decode succeeded), else `false`.
    pub fn mtl_register_texture(
        texture_key: &str,
        mtl_bytes: &[u8],
        tex_filename: &str,
        tex_bytes: &[u8],
    ) -> bool {
        unsafe {
            sys::graphics_mtl_register_texture(
                hash_key(texture_key),
                mtl_bytes.as_ptr() as u32,
                mtl_bytes.len() as u32,
                tex_filename.as_ptr() as u32,
                tex_filename.len() as u32,
                tex_bytes.as_ptr() as u32,
                tex_bytes.len() as u32,
            ) != 0
        }
    }

    /// Register a JPEG resource (encoded bytes) under a string key.
    /// Returns true on success.
    pub fn jpeg_register(key: &str, jpeg_bytes: &[u8]) -> bool {
        unsafe {
            sys::graphics_jpeg_register(
                hash_key(key),
                jpeg_bytes.as_ptr() as u32,
                jpeg_bytes.len() as u32,
            ) != 0
        }
    }

    /// Draw a registered PNG by key at natural size.
    pub fn png_draw_key(key: &str, x: i32, y: i32) {
        unsafe { sys::graphics_png_draw_key(hash_key(key), x, y) }
    }

    /// Draw a registered JPEG by key at natural size.
    pub fn jpeg_draw_key(key: &str, x: i32, y: i32) {
        unsafe { sys::graphics_jpeg_draw_key(hash_key(key), x, y) }
    }

    /// Draw a registered PNG by key scaled.
    pub fn png_draw_key_scaled(key: &str, x: i32, y: i32, w: u32, h: u32) {
        unsafe { sys::graphics_png_draw_key_scaled(hash_key(key), x, y, w, h) }
    }

    /// Draw a registered JPEG by key scaled.
    pub fn jpeg_draw_key_scaled(key: &str, x: i32, y: i32, w: u32, h: u32) {
        unsafe { sys::graphics_jpeg_draw_key_scaled(hash_key(key), x, y, w, h) }
    }

    /// Unregister a PNG by key.
    pub fn png_unregister(key: &str) {
        unsafe { sys::graphics_png_unregister(hash_key(key)) }
    }

    /// Unregister a JPEG by key.
    pub fn jpeg_unregister(key: &str) {
        unsafe { sys::graphics_jpeg_unregister(hash_key(key)) }
    }

    /// Register a TTF/OTF font under a string key.
    ///
    /// ## What the host does
    /// - The host reads the encoded font bytes immediately during this call.
    /// - It attempts to parse them as a TTF/OTF via its font rasterizer.
    /// - On success it stores the font in a host-side table and associates it with `hash_key(key)`.
    ///
    /// ## When to call this
    /// Prefer calling during `setup()` (once), *not per-frame*.
    ///
    /// ## Return value
    /// Returns `true` if the host successfully parsed and registered the font.
    ///
    /// ## Notes
    /// - If you never register a font for a key, `text_key`/`text_measure_key` will still work due
    ///   to host fallback (Spleen size 16), but metrics/appearance may differ from what you expect.
    pub fn font_register_ttf(key: &str, data: &[u8]) -> bool {
        unsafe {
            sys::graphics_font_register_ttf(hash_key(key), data.as_ptr() as u32, data.len() as u32)
                != 0
        }
    }

    /// Register a BDF bitmap font under a string key.
    ///
    /// ## What the host does
    /// - The host reads `data` immediately and parses the BDF text.
    /// - It extracts the font bounding box (pixel width/height) and glyph bitmaps.
    /// - On success, the parsed font is stored and associated with `hash_key(key)`.
    ///
    /// ## When to use BDF
    /// Use BDF for crisp pixel fonts, debug overlays, and UIs where you want deterministic
    /// bitmap metrics and a retro look.
    ///
    /// ## Return value
    /// Returns `true` if parsing succeeded and the font was registered.
    pub fn font_register_bdf(key: &str, data: &[u8]) -> bool {
        unsafe {
            sys::graphics_font_register_bdf(hash_key(key), data.as_ptr() as u32, data.len() as u32)
                != 0
        }
    }

    /// Register the built-in Spleen font under a string key.
    ///
    /// Spleen is a bitmap font family bundled with the host (wasm96-core).
    /// This function associates a chosen Spleen size with your `key`, so you can refer to it
    /// via `text_key`/`text_measure_key`.
    ///
    /// ## Supported sizes
    /// The host currently supports: **8, 16, 24, 32, 64**.
    /// Other sizes return `false`.
    ///
    /// ## Why register Spleen if there is already a fallback?
    /// The host fallback is Spleen size 16 **only when the key is missing**.
    /// If you want a different size (or want to be explicit for layout stability),
    /// register it under your own key.
    ///
    /// Returns `true` if successful.
    pub fn font_register_spleen(key: &str, size: u32) -> bool {
        unsafe { sys::graphics_font_register_spleen(hash_key(key), size) != 0 }
    }

    /// Unregister a font by key.
    ///
    /// After unregistering:
    /// - The mapping from `hash_key(key)` to the font resource is removed on the host.
    /// - Future calls to `text_key`/`text_measure_key` using this key will use the host fallback
    ///   (Spleen size 16) unless you register another font under the same key.
    ///
    /// This is mainly useful for apps that dynamically load/unload large fonts and want to
    /// reclaim host-side memory.
    pub fn font_unregister(key: &str) {
        unsafe { sys::graphics_font_unregister(hash_key(key)) }
    }

    /// Draw text using a keyed font.
    ///
    /// ## Parameters
    /// - `x`, `y`: top-left origin where the text will be drawn in screen coordinates.
    /// - `font_key`: the font key you previously registered (or any string; see fallback).
    /// - `text`: UTF-8 text to draw.
    ///
    /// ## Fallback
    /// If `font_key` is not registered, the host will draw using built-in Spleen size 16.
    ///
    /// ## Performance tips
    /// - Keep `text` reasonably small per call; prefer drawing fewer, longer strings vs many
    ///   single-character calls.
    /// - Register fonts once in `setup()`; do not register fonts in `draw()`.
    pub fn text_key(x: i32, y: i32, font_key: &str, text: &str) {
        unsafe {
            sys::graphics_text_key(
                x,
                y,
                hash_key(font_key),
                text.as_ptr() as u32,
                text.len() as u32,
            )
        }
    }

    /// Measure text using a keyed font.
    ///
    /// This is intended for UI/layout work (centering, right-aligning, wrapping decisions).
    ///
    /// ## Return value
    /// Returns a [`TextSize`] where:
    /// - `width` is the pixel width of the rendered text
    /// - `height` is the pixel height of the rendered text
    ///
    /// Internally, the host returns a packed `u64`:
    /// `(width << 32) | height`.
    ///
    /// ## Fallback
    /// If `font_key` is not registered, the host measures with Spleen size 16, matching
    /// the draw fallback behavior of [`text_key`].
    ///
    /// ## Caveats
    /// - The host expects `text` to be valid UTF-8.
    /// - Metrics are defined by host-side font implementation; if you change fonts or sizes,
    ///   your layout can change accordingly.
    pub fn text_measure_key(font_key: &str, text: &str) -> TextSize {
        let packed = unsafe {
            sys::graphics_text_measure_key(
                hash_key(font_key),
                text.as_ptr() as u32,
                text.len() as u32,
            )
        };

        TextSize {
            width: (packed >> 32) as u32,
            height: (packed & 0xFFFF_FFFF) as u32,
        }
    }
}

/// Input API.
pub mod input {
    use super::{Button, sys};

    /// Returns true if the specified button is currently held down.
    pub fn is_button_down(port: u32, btn: Button) -> bool {
        unsafe { sys::input_is_button_down(port, btn as u32) != 0 }
    }

    /// Returns true if the specified key is currently held down.
    pub fn is_key_down(key: u32) -> bool {
        unsafe { sys::input_is_key_down(key) != 0 }
    }

    /// Get current mouse X position.
    pub fn get_mouse_x() -> i32 {
        unsafe { sys::input_get_mouse_x() }
    }

    /// Get current mouse Y position.
    pub fn get_mouse_y() -> i32 {
        unsafe { sys::input_get_mouse_y() }
    }

    /// Returns true if the specified mouse button is held down.
    /// 0 = Left, 1 = Right, 2 = Middle.
    pub fn is_mouse_down(btn: u32) -> bool {
        unsafe { sys::input_is_mouse_down(btn) != 0 }
    }
}

/// Audio API.
pub mod audio {
    use super::sys;

    /// Initialize audio system.
    pub fn init(sample_rate: u32) -> u32 {
        unsafe { sys::audio_init(sample_rate) }
    }

    /// Push a chunk of audio samples.
    /// Samples are interleaved stereo (L, R, L, R...) signed 16-bit integers.
    pub fn push_samples(samples: &[i16]) {
        unsafe { sys::audio_push_samples(samples.as_ptr() as u32, samples.len() as u32) }
    }

    /// Play a WAV file.
    /// The WAV data is decoded and played as a one-shot audio channel.
    pub fn play_wav(data: &[u8]) {
        unsafe { sys::audio_play_wav(data.as_ptr() as u32, data.len() as u32) }
    }

    /// Play a QOA file.
    /// The QOA data is decoded and played as a looping audio channel.
    pub fn play_qoa(data: &[u8]) {
        unsafe { sys::audio_play_qoa(data.as_ptr() as u32, data.len() as u32) }
    }

    /// Play an XM file.
    /// Play an XM file.
    /// The XM data is decoded using xmrsplayer and played as a looping audio channel.
    pub fn play_xm(data: &[u8]) {
        unsafe { sys::audio_play_xm(data.as_ptr() as u32, data.len() as u32) }
    }
}

/// Storage API.
pub mod storage {
    use super::sys;

    /// Save data to persistent storage.
    pub fn save(key: &str, data: &[u8]) {
        unsafe {
            sys::storage_save(
                super::graphics::hash_key(key),
                data.as_ptr() as u32,
                data.len() as u32,
            )
        }
    }

    /// Load data from persistent storage.
    /// Returns `Some(data)` if found, `None` otherwise.
    pub fn load(key: &str) -> Option<Vec<u8>> {
        let packed = unsafe { sys::storage_load(super::graphics::hash_key(key)) };
        if packed == 0 {
            return None;
        }

        let ptr = (packed >> 32) as u32;
        let len = packed as u32;

        // Read data from guest memory
        let mut data = Vec::with_capacity(len as usize);
        unsafe {
            core::ptr::copy_nonoverlapping(ptr as *const u8, data.as_mut_ptr(), len as usize);
            data.set_len(len as usize);
        }

        // Free the memory in guest space
        unsafe { sys::storage_free(ptr, len) };

        Some(data)
    }
}

/// System API.
pub mod system {
    use super::sys;

    /// Log a message to the host console.
    pub fn log(message: &str) {
        unsafe { sys::system_log(message.as_ptr() as u32, message.len() as u32) }
    }

    /// Get the number of milliseconds since the app started.
    pub fn millis() -> u64 {
        unsafe { sys::system_millis() }
    }
}

/// Convenience prelude for guest apps.
pub mod prelude {
    pub use crate::Button;
    pub use crate::TextSize;
    pub use crate::audio;
    pub use crate::graphics;
    pub use crate::input;
    pub use crate::storage;
    pub use crate::system;
}

// Keep `c_void` referenced so it doesn't look unused in some configurations.
#[allow(dead_code)]
const _C_VOID: *const c_void = core::ptr::null();