Skip to main content

gasm/
lib.rs

1//! Rust bindings for the gasm game ABI v0 — see `spec/ABI.md`.
2//!
3//! ```ignore
4//! struct MyGame { t: u32 }
5//! impl gasm::Game for MyGame {
6//!     fn init() -> Result<Self, String> { gasm::set_frame_rate(60.0); Ok(MyGame { t: 0 }) }
7//!     fn frame(&mut self) { self.t += 1; /* simulate, draw */ }
8//! }
9//! gasm::game!(MyGame);
10//! ```
11//!
12//! Build with `--target wasm32-unknown-unknown` and `crate-type = ["cdylib"]`.
13//! On native targets the same code links against an in-process stub host
14//! ([`native`]) for tests and benchmarks.
15
16pub mod sys;
17
18pub mod gles;
19pub mod sync;
20pub mod thread;
21
22#[cfg(not(target_arch = "wasm32"))]
23pub mod native;
24
25use std::cell::UnsafeCell;
26
27pub const ABI_VERSION: i32 = 0;
28
29// ---- core --------------------------------------------------------------------
30
31pub fn log(msg: &str) {
32    unsafe { sys::log(msg.as_ptr(), msg.len() as u32) }
33}
34
35/// `format!`-style logging: `gasm::log!("x = {x}")`.
36#[macro_export]
37macro_rules! log {
38    ($($t:tt)*) => { $crate::log(&::std::format!($($t)*)) };
39}
40
41/// Monotonic milliseconds (virtual, frame-derived time in headless runs).
42pub fn time_ms() -> f64 {
43    unsafe { sys::time_ms() }
44}
45
46/// The player's time zone now: minutes east of UTC, daylight saving included
47/// (120 for CEST). 0 in headless runs, and on older runners without it.
48pub fn utc_offset_minutes() -> i32 {
49    if has("gasm.utc_offset_minutes") { unsafe { sys::utc_offset_minutes() } } else { 0 }
50}
51
52/// Does the runner provide an import? A module (`"gasm:gfx"`) or a function in
53/// one (`"gasm.asset_size64"`, `"gasm:gfx.destroy"`). Calling an import the
54/// runner lacks traps, so probe optional features first.
55pub fn has(name: &str) -> bool {
56    unsafe { sys::has(name.as_ptr(), name.len() as u32) == 1 }
57}
58
59/// Rate at which the runner calls `frame()`. Default 60.
60pub fn set_frame_rate(hz: f64) {
61    unsafe { sys::set_frame_rate(hz) }
62}
63
64/// Show `video_present` frames at display aspect `num:den` (e.g. 4:3 for a
65/// 320×200 game drawn for a CRT) instead of square pixels; `(0, 0)` resets.
66/// Returns false on runners without it: the game then corrects the aspect itself
67/// (or accepts square pixels). Display only: hashes don't change.
68pub fn video_set_aspect(num: u32, den: u32) -> bool {
69    static SUPPORTED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
70    let ok = *SUPPORTED.get_or_init(|| has("gasm.video_set_aspect"));
71    if ok {
72        unsafe { sys::video_set_aspect(num, den) }
73    }
74    ok
75}
76
77/// The game's built-in title (custom section `gasm.title`): runners show it
78/// (and launchers list it) before the game runs and while it hasn't called
79/// [`set_title`]. Use once, at the top level: `gasm::title!("Sumo");`
80#[macro_export]
81macro_rules! title {
82    ($t:literal) => {
83        // a wasm custom section; native builds of a game (tests, parity) just keep the bytes
84        #[cfg_attr(target_arch = "wasm32", unsafe(link_section = "gasm.title"))]
85        #[used]
86        static __GASM_TITLE: [u8; $t.len()] = $crate::__title_bytes($t);
87    };
88}
89
90#[doc(hidden)]
91pub const fn __title_bytes<const N: usize>(s: &str) -> [u8; N] {
92    let b = s.as_bytes();
93    let mut out = [0u8; N];
94    let mut i = 0;
95    while i < N {
96        out[i] = b[i];
97        i += 1;
98    }
99    out
100}
101
102/// Name the game's window or browser tab (runners add their own suffix, e.g.
103/// "DOOM — gasm"). Control characters are dropped, at most 256 bytes are kept,
104/// and `""` restores the default (the file name). Does nothing on runners
105/// without it.
106pub fn set_title(title: &str) {
107    static SUPPORTED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
108    if *SUPPORTED.get_or_init(|| has("gasm.set_title")) {
109        unsafe { sys::set_title(title.as_ptr(), title.len() as u32) }
110    }
111}
112
113/// Launch parameter (`--param k=v` natively, `?k=v` in the browser).
114pub fn param(name: &str) -> Option<String> {
115    let len = unsafe { sys::param(name.as_ptr(), name.len() as u32, std::ptr::null_mut(), 0) };
116    if len < 0 {
117        return None;
118    }
119    let mut buf = vec![0u8; len as usize];
120    unsafe { sys::param(name.as_ptr(), name.len() as u32, buf.as_mut_ptr(), len as u32) };
121    Some(String::from_utf8_lossy(&buf).into_owned())
122}
123
124/// End the game (WASI `proc_exit`). Runners treat code 0 as a clean exit.
125pub fn exit(code: i32) -> ! {
126    unsafe { sys::proc_exit(code) }
127}
128
129// ---- video / audio / input / assets --------------------------------------------
130
131/// Present an RGBA8 frame (`stride` bytes per row; 1-4096 pixels each way).
132pub fn present(rgba: &[u8], width: u32, height: u32, stride: u32) {
133    let need = (stride as u64)
134        .checked_mul(height.saturating_sub(1) as u64)
135        .and_then(|n| n.checked_add(width as u64 * 4))
136        .filter(|_| width > 0 && height > 0 && stride as u64 >= width as u64 * 4);
137    assert!(need.is_some_and(|n| rgba.len() as u64 >= n), "present: bad geometry or buffer too small");
138    unsafe { sys::video_present(rgba.as_ptr(), width, height, stride) }
139}
140
141pub mod audio {
142    use std::sync::atomic::{AtomicU32, Ordering};
143    static CHANNELS: AtomicU32 = AtomicU32::new(2);
144
145    /// Format for [`push`]: sample rate (8–192 kHz) and 1 or 2 channels. Other
146    /// values are ignored (by the runner too): the format stays as it was.
147    pub fn config(sample_rate: u32, channels: u32) {
148        if (8000..=192_000).contains(&sample_rate) && (channels == 1 || channels == 2) {
149            CHANNELS.store(channels, Ordering::Relaxed);
150        }
151        unsafe { crate::sys::audio_config(sample_rate, channels) }
152    }
153
154    /// Queue interleaved f32 samples in [-1, 1] (whole frames: a length that is a
155    /// multiple of the channel count).
156    pub fn push(samples: &[f32]) {
157        let ch = CHANNELS.load(Ordering::Relaxed);
158        debug_assert!(samples.len() % ch as usize == 0, "audio::push: not a whole number of frames");
159        unsafe { crate::sys::audio_push(samples.as_ptr(), samples.len() as u32 / ch) }
160    }
161}
162
163/// Virtual gamepad buttons (bit positions per spec/ABI.md).
164#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
165pub struct Buttons(pub u32);
166
167impl Buttons {
168    pub const A: u32 = sys::GASM_BTN_A;
169    pub const B: u32 = sys::GASM_BTN_B;
170    pub const X: u32 = sys::GASM_BTN_X;
171    pub const Y: u32 = sys::GASM_BTN_Y;
172    pub const L: u32 = sys::GASM_BTN_L;
173    pub const R: u32 = sys::GASM_BTN_R;
174    pub const SELECT: u32 = sys::GASM_BTN_SELECT;
175    pub const START: u32 = sys::GASM_BTN_START;
176    pub const UP: u32 = sys::GASM_BTN_UP;
177    pub const DOWN: u32 = sys::GASM_BTN_DOWN;
178    pub const LEFT: u32 = sys::GASM_BTN_LEFT;
179    pub const RIGHT: u32 = sys::GASM_BTN_RIGHT;
180
181    pub fn held(self, mask: u32) -> bool {
182        self.0 & mask != 0
183    }
184}
185
186/// Buttons held on virtual pad `player` (0..=3) this frame.
187pub fn pad(player: u32) -> Buttons {
188    Buttons(unsafe { sys::input_pad(player) })
189}
190
191/// Text typed since the previous frame (`'\u{8}'` = backspace, `'\n'` = enter),
192/// or `None` if the runner has no keyboard.
193pub fn text_input() -> Option<String> {
194    let len = unsafe { sys::text_input(std::ptr::null_mut(), 0) };
195    if len < 0 {
196        return None;
197    }
198    let mut buf = vec![0u8; len as usize];
199    if len > 0 {
200        unsafe { sys::text_input(buf.as_mut_ptr(), len as u32) };
201    }
202    Some(String::from_utf8_lossy(&buf).into_owned())
203}
204
205/// All asset names, sorted (by UTF-8 bytes). Folder entries keep their on-disk case.
206pub fn asset_names() -> Vec<String> {
207    let n = unsafe { sys::asset_count() };
208    (0..n)
209        .filter_map(|i| {
210            let len = unsafe { sys::asset_name(i, std::ptr::null_mut(), 0) };
211            if len < 0 {
212                return None;
213            }
214            let mut buf = vec![0u8; len as usize];
215            if len > 0 {
216                unsafe { sys::asset_name(i, buf.as_mut_ptr(), len as u32) };
217            }
218            Some(String::from_utf8_lossy(&buf).into_owned())
219        })
220        .collect()
221}
222
223/// Size of an asset in bytes (any size), or `None` if it doesn't exist.
224pub fn asset_size(name: &str) -> Option<u64> {
225    let n = unsafe { sys::asset_size64(name.as_ptr(), name.len() as u32) };
226    (n >= 0).then_some(n as u64)
227}
228
229/// An asset's version, or `None` if it doesn't exist: 0 for assets given at
230/// launch, a new, larger number each time the embedder replaces it while the game
231/// runs. Poll it to notice new data. Older runners: always 0.
232pub fn asset_version(name: &str) -> Option<u32> {
233    if !has("gasm.asset_version") {
234        return asset_size(name).map(|_| 0);
235    }
236    let v = unsafe { sys::asset_version(name.as_ptr(), name.len() as u32) };
237    (v >= 0).then_some(v as u32)
238}
239
240/// Read a whole asset (it must fit in memory: under 2 GiB).
241pub fn asset(name: &str) -> Option<Vec<u8>> {
242    let n = unsafe { sys::asset_size(name.as_ptr(), name.len() as u32) };
243    if n < 0 {
244        return None;
245    }
246    let mut buf = vec![0u8; n as usize];
247    let got = unsafe { sys::asset_read(name.as_ptr(), name.len() as u32, buf.as_mut_ptr(), n as u32) };
248    buf.truncate(got.max(0) as usize);
249    Some(buf)
250}
251
252/// Read up to `buf.len()` bytes of an asset starting at `offset` (for streaming
253/// large assets). Returns bytes read (0 at the end), or `None` if missing.
254pub fn asset_read_at(name: &str, offset: u64, buf: &mut [u8]) -> Option<usize> {
255    let len = buf.len().min(u32::MAX as usize) as u32;
256    let n = unsafe { sys::asset_read_at64(name.as_ptr(), name.len() as u32, offset, buf.as_mut_ptr(), len) };
257    (n >= 0).then_some(n as usize)
258}
259
260// ---- storage ------------------------------------------------------------------------
261
262/// Persistent per-game key/value store (`gasm:storage`): saves, settings, scores.
263///
264/// Keys: 1–128 bytes of `[A-Za-z0-9._-]`. Values up to 1 MiB, 16 MiB per game.
265/// The runner picks the namespace; headless runs start with an empty store.
266pub mod storage {
267    use crate::sys;
268
269    pub fn get(key: &str) -> Option<Vec<u8>> {
270        let n = unsafe { sys::storage_get(key.as_ptr(), key.len() as u32, std::ptr::null_mut(), 0) };
271        if n < 0 {
272            return None;
273        }
274        let mut buf = vec![0u8; n as usize];
275        unsafe { sys::storage_get(key.as_ptr(), key.len() as u32, buf.as_mut_ptr(), n as u32) };
276        Some(buf)
277    }
278
279    /// Why [`try_set`] failed.
280    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
281    pub enum Error {
282        /// not 1–128 bytes of `[A-Za-z0-9._-]`
283        Key,
284        /// value over 1 MiB
285        Size,
286        /// the game's 16 MiB are used up
287        Quota,
288        /// the runner couldn't write it
289        Io,
290    }
291
292    /// Store a value.
293    pub fn try_set(key: &str, value: &[u8]) -> Result<(), Error> {
294        match unsafe { sys::storage_set(key.as_ptr(), key.len() as u32, value.as_ptr(), value.len() as u32) } {
295            sys::GASM_STORAGE_OK => Ok(()),
296            sys::GASM_STORAGE_ERR_KEY => Err(Error::Key),
297            sys::GASM_STORAGE_ERR_SIZE => Err(Error::Size),
298            sys::GASM_STORAGE_ERR_QUOTA => Err(Error::Quota),
299            _ => Err(Error::Io),
300        }
301    }
302
303    /// Store a value. False on invalid key, size/quota limits or I/O error ([`try_set`] says which).
304    pub fn set(key: &str, value: &[u8]) -> bool {
305        try_set(key, value).is_ok()
306    }
307
308    /// Delete a key. False if it didn't exist.
309    pub fn delete(key: &str) -> bool {
310        unsafe { sys::storage_delete(key.as_ptr(), key.len() as u32) == 0 }
311    }
312
313    /// All keys of this game, sorted.
314    pub fn keys() -> Vec<String> {
315        let n = unsafe { sys::storage_count() };
316        (0..n)
317            .filter_map(|i| {
318                let len = unsafe { sys::storage_key(i, std::ptr::null_mut(), 0) };
319                if len < 0 {
320                    return None;
321                }
322                let mut buf = vec![0u8; len as usize];
323                unsafe { sys::storage_key(i, buf.as_mut_ptr(), len as u32) };
324                Some(String::from_utf8_lossy(&buf).into_owned())
325            })
326            .collect()
327    }
328}
329
330/// Text on the system clipboard (`gasm:clipboard`, optional: check [`clipboard::available`]).
331/// Copying is always allowed; pasted text is readable only during the frame that carries
332/// the player's paste key press (Ctrl+V, Cmd+V on macOS).
333pub mod clipboard {
334    use crate::sys;
335
336    /// Whether the runner has a clipboard.
337    pub fn available() -> bool {
338        crate::has("gasm:clipboard")
339    }
340
341    /// Put text on the clipboard (after this frame). False if refused (over 1 MiB, no clipboard).
342    pub fn set_text(text: &str) -> bool {
343        unsafe { sys::clipboard_set_text(text.as_ptr(), text.len() as u32) == 0 }
344    }
345
346    /// The text the player pasted this frame, or None (not a paste frame, nothing to paste).
347    pub fn pasted() -> Option<String> {
348        let n = unsafe { sys::clipboard_get_text(std::ptr::null_mut(), 0) };
349        if n < 0 {
350            return None;
351        }
352        let mut buf = vec![0u8; n as usize];
353        unsafe { sys::clipboard_get_text(buf.as_mut_ptr(), n as u32) };
354        Some(String::from_utf8_lossy(&buf).into_owned())
355    }
356}
357
358/// Files for the player (`gasm:files`, optional: check [`files::available`]): `save` hands
359/// the runner a copy to keep where the player finds it (Pictures/<game>/ for images,
360/// Downloads/<game>/ otherwise, a download in browsers). The game never learns the path.
361pub mod files {
362    use crate::sys;
363
364    /// Whether the runner can save files for the player.
365    pub fn available() -> bool {
366        crate::has("gasm:files")
367    }
368
369    /// A save handed to the runner: poll [`Save::state`].
370    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
371    pub struct Save(i32);
372
373    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
374    pub enum State {
375        Pending,
376        Saved,
377        /// cancelled or not written
378        Failed,
379    }
380
381    impl Save {
382        pub fn state(self) -> State {
383            match unsafe { sys::files_state(self.0) } {
384                sys::GASM_FILES_PENDING => State::Pending,
385                sys::GASM_FILES_SAVED => State::Saved,
386                _ => State::Failed,
387            }
388        }
389    }
390
391    /// Save `data` as `name` (a file name, e.g. "photo-001.png") of type `mime`
392    /// ("image/png"). None if the runner refused (saving off, bad name or type, too big).
393    pub fn save(name: &str, mime: &str, data: &[u8]) -> Option<Save> {
394        let h = unsafe { sys::files_save(name.as_ptr(), name.len() as u32, mime.as_ptr(), mime.len() as u32, data.as_ptr(), data.len() as u32) };
395        (h > 0).then(|| Save(h))
396    }
397}
398
399// ---- raw input ---------------------------------------------------------------------
400
401/// Raw keyboard, pointer and gamepads (next to the virtual [`pad`]s).
402///
403/// ```ignore
404/// use gasm::{input, keys};
405/// input::set_mode(input::KEYS_RAW);              // read the keyboard directly, no keymap pads
406/// let k = input::keys().unwrap_or_default();
407/// if k.held(keys::SHIFT_LEFT) && k.held(keys::ARROW_LEFT) { … }
408/// if let Some(p) = input::pointer() && p.pressed & input::MOUSE_LEFT != 0 { click(p.frame_x, p.frame_y) }
409/// ```
410pub mod input {
411    use crate::sys;
412
413    /// The runner stops mapping the keyboard to pads (gamepads still map).
414    pub const KEYS_RAW: u32 = sys::GASM_INPUT_KEYS_RAW;
415    /// Hide the system cursor over the game.
416    pub const POINTER_HIDDEN: u32 = sys::GASM_INPUT_POINTER_HIDDEN;
417    /// Capture the pointer for relative motion (best effort; the browser needs a click).
418    pub const POINTER_LOCKED: u32 = sys::GASM_INPUT_POINTER_LOCKED;
419
420    pub const MOUSE_LEFT: u32 = sys::GASM_MOUSE_LEFT;
421    pub const MOUSE_RIGHT: u32 = sys::GASM_MOUSE_RIGHT;
422    pub const MOUSE_MIDDLE: u32 = sys::GASM_MOUSE_MIDDLE;
423    pub const MOUSE_BACK: u32 = sys::GASM_MOUSE_BACK;
424    pub const MOUSE_FORWARD: u32 = sys::GASM_MOUSE_FORWARD;
425
426    const KEY_BYTES: usize = sys::GASM_KEY_STATE_BYTES as usize;
427    const POINTER_BYTES: usize = sys::GASM_POINTER_BYTES as usize;
428    const GAMEPAD_BYTES: usize = sys::GASM_GAMEPAD_BYTES as usize;
429
430    /// `KEYS_RAW | POINTER_HIDDEN | POINTER_LOCKED`, any combination.
431    pub fn set_mode(flags: u32) {
432        unsafe { sys::input_mode(flags) }
433    }
434
435    /// Keys held this frame; index with [`crate::keys`] constants.
436    #[derive(Clone, Copy, Default, PartialEq, Eq)]
437    pub struct Keys(pub [u8; KEY_BYTES]);
438
439    impl Keys {
440        pub fn held(&self, code: u32) -> bool {
441            (code as usize) < KEY_BYTES * 8 && self.0[code as usize / 8] & (1 << (code % 8)) != 0
442        }
443    }
444
445    /// `None` if the runner has no keyboard.
446    pub fn keys() -> Option<Keys> {
447        let mut k = Keys::default();
448        (unsafe { sys::key_state(k.0.as_mut_ptr(), KEY_BYTES as u32) } >= 0).then_some(k)
449    }
450
451    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
452    pub struct KeyEvent {
453        pub code: u32,
454        pub down: bool,
455    }
456
457    /// Presses and releases since the previous frame, in order (`None`: no keyboard).
458    pub fn key_events() -> Option<Vec<KeyEvent>> {
459        let n = unsafe { sys::key_events(std::ptr::null_mut(), 0) };
460        if n < 0 {
461            return None;
462        }
463        let mut b = vec![0u8; n as usize];
464        if n > 0 {
465            unsafe { sys::key_events(b.as_mut_ptr(), n as u32) };
466        }
467        Some(b.chunks_exact(sys::GASM_KEY_EVENT_BYTES as usize).map(|e| KeyEvent { code: u16::from_le_bytes([e[0], e[1]]) as u32, down: e[2] != 0 }).collect())
468    }
469
470    #[derive(Clone, Copy, Debug, Default, PartialEq)]
471    pub struct Pointer {
472        /// position in drawable pixels (gfx width/height space)
473        pub x: f32,
474        pub y: f32,
475        /// position in the last presented frame's pixels (2D games)
476        pub frame_x: f32,
477        pub frame_y: f32,
478        /// relative motion since the previous frame (also while locked)
479        pub dx: f32,
480        pub dy: f32,
481        /// about 1 per wheel notch; y > 0 = down
482        pub wheel_x: f32,
483        pub wheel_y: f32,
484        pub buttons: u32,
485        /// went down / up since the previous frame (a quick click shows in both)
486        pub pressed: u32,
487        pub released: u32,
488        pub flags: u32,
489    }
490
491    impl Pointer {
492        pub fn inside(&self) -> bool {
493            self.flags & 1 != 0
494        }
495        pub fn locked(&self) -> bool {
496            self.flags & 4 != 0
497        }
498    }
499
500    /// `None` if the runner has no pointer.
501    pub fn pointer() -> Option<Pointer> {
502        let mut b = [0u8; POINTER_BYTES];
503        if unsafe { sys::pointer(b.as_mut_ptr(), POINTER_BYTES as u32) } < 0 {
504            return None;
505        }
506        let f = |o: u32| { let i = o as usize; f32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) };
507        let u = |o: u32| { let i = o as usize; u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) };
508        Some(Pointer {
509            x: f(sys::GASM_POINTER_OFF_X), y: f(sys::GASM_POINTER_OFF_Y),
510            frame_x: f(sys::GASM_POINTER_OFF_FX), frame_y: f(sys::GASM_POINTER_OFF_FY),
511            dx: f(sys::GASM_POINTER_OFF_DX), dy: f(sys::GASM_POINTER_OFF_DY),
512            wheel_x: f(sys::GASM_POINTER_OFF_WHEEL_X), wheel_y: f(sys::GASM_POINTER_OFF_WHEEL_Y),
513            buttons: u(sys::GASM_POINTER_OFF_BUTTONS), pressed: u(sys::GASM_POINTER_OFF_PRESSED),
514            released: u(sys::GASM_POINTER_OFF_RELEASED), flags: u(sys::GASM_POINTER_OFF_FLAGS),
515        })
516    }
517
518    /// Raw gamepad or joystick. With `standard`, W3C order: buttons 0 south, 1 east,
519    /// 2 west, 3 north, 4/5 shoulders, 6/7 triggers, 8 select, 9 start, 10/11 sticks,
520    /// 12-15 d-pad, 16 home; axes 0/1 left stick, 2/3 right stick (y > 0 = down).
521    #[derive(Clone, Debug, Default, PartialEq)]
522    pub struct Gamepad {
523        pub connected: bool,
524        pub standard: bool,
525        pub buttons: Vec<f32>,
526        pub axes: Vec<f32>,
527    }
528
529    /// Slot 0-3 (connection order). `None` if the runner has no gamepad support.
530    pub fn gamepad(slot: u32) -> Option<Gamepad> {
531        let mut b = [0u8; GAMEPAD_BYTES];
532        if unsafe { sys::gamepad(slot, b.as_mut_ptr(), GAMEPAD_BYTES as u32) } < 0 {
533            return None;
534        }
535        let u = |i: usize| u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]);
536        let f = |i: usize| f32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]);
537        let (flags, nb, na) = (
538            u(sys::GASM_GAMEPAD_OFF_FLAGS as usize),
539            (u(sys::GASM_GAMEPAD_OFF_BUTTON_COUNT as usize) as usize).min(sys::GASM_GAMEPAD_BUTTONS as usize),
540            (u(sys::GASM_GAMEPAD_OFF_AXIS_COUNT as usize) as usize).min(sys::GASM_GAMEPAD_AXES as usize),
541        );
542        Some(Gamepad {
543            connected: flags & sys::GASM_GAMEPAD_CONNECTED != 0,
544            standard: flags & sys::GASM_GAMEPAD_STANDARD != 0,
545            buttons: (0..nb).map(|i| f(sys::GASM_GAMEPAD_OFF_BUTTONS as usize + i * 4)).collect(),
546            axes: (0..na).map(|i| f(sys::GASM_GAMEPAD_OFF_AXES as usize + i * 4)).collect(),
547        })
548    }
549
550    /// Device name, if a gamepad is connected in `slot`.
551    pub fn gamepad_name(slot: u32) -> Option<String> {
552        let n = unsafe { sys::gamepad_name(slot, std::ptr::null_mut(), 0) };
553        if n < 0 {
554            return None;
555        }
556        let mut b = vec![0u8; n as usize];
557        if n > 0 {
558            unsafe { sys::gamepad_name(slot, b.as_mut_ptr(), n as u32) };
559        }
560        Some(String::from_utf8_lossy(&b).into_owned())
561    }
562}
563
564/// Raw key codes (`GASM_KEY_*`, W3C `KeyboardEvent.code` names in [`keys::NAMES`]).
565pub use sys::keys;
566
567// ---- gfx ---------------------------------------------------------------------------
568
569/// GPU rendering through `gasm:gfx` (a WebGPU subset; descriptors are JSON).
570pub mod gfx {
571    use crate::sys;
572
573    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
574    pub struct Shader(pub u32);
575    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
576    pub struct Buffer(pub u32);
577    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
578    pub struct Pipeline(pub u32);
579    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
580    pub struct BindGroup(pub u32);
581    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
582    pub struct BindGroupLayout(pub u32);
583    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
584    pub struct Texture(pub u32);
585    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
586    pub struct Sampler(pub u32);
587
588    pub const COPY_DST: u32 = sys::GASM_BUF_COPY_DST;
589    pub const INDEX: u32 = sys::GASM_BUF_INDEX;
590    pub const VERTEX: u32 = sys::GASM_BUF_VERTEX;
591    pub const UNIFORM: u32 = sys::GASM_BUF_UNIFORM;
592    pub const STORAGE: u32 = sys::GASM_BUF_STORAGE;
593
594    /// Bind group layout entry visibility.
595    pub const STAGE_VERTEX: u32 = sys::GASM_STAGE_VERTEX;
596    pub const STAGE_FRAGMENT: u32 = sys::GASM_STAGE_FRAGMENT;
597    /// Dynamic offsets must be multiples of this.
598    pub const OFFSET_ALIGNMENT: u32 = 256;
599
600    #[derive(Clone, Copy)]
601    pub enum IndexFormat {
602        U16 = sys::GASM_INDEX_U16 as isize,
603        U32 = sys::GASM_INDEX_U32 as isize,
604    }
605
606    /// Any object handle (for [`destroy`]).
607    pub trait Handle {
608        fn raw(&self) -> u32;
609    }
610    macro_rules! handles {
611        ($($t:ident),*) => { $(impl Handle for $t { fn raw(&self) -> u32 { self.0 } })* };
612    }
613    handles!(Shader, Buffer, Pipeline, BindGroup, BindGroupLayout, Texture, Sampler);
614
615    /// Plain-old-data that can be uploaded byte for byte.
616    ///
617    /// # Safety
618    /// Implementors must have no padding and no pointers.
619    pub unsafe trait Pod: Copy {}
620    unsafe impl Pod for u8 {}
621    unsafe impl Pod for u16 {}
622    unsafe impl Pod for u32 {}
623    unsafe impl Pod for f32 {}
624    unsafe impl<T: Pod, const N: usize> Pod for [T; N] {}
625
626    pub fn as_bytes<T: Pod>(data: &[T]) -> &[u8] {
627        unsafe { std::slice::from_raw_parts(data.as_ptr() as *const u8, std::mem::size_of_val(data)) }
628    }
629
630    /// Drawable size in pixels.
631    pub fn size() -> (u32, u32) {
632        unsafe { (sys::gfx_width(), sys::gfx_height()) }
633    }
634    pub fn create_shader(wgsl: &str) -> Shader {
635        Shader(unsafe { sys::gfx_create_shader(wgsl.as_ptr(), wgsl.len() as u32) })
636    }
637    pub fn create_buffer(size: u32, usage: u32) -> Buffer {
638        Buffer(unsafe { sys::gfx_create_buffer(size, usage) })
639    }
640    /// WebGPU `GPURenderPipelineDescriptor` as JSON (handles as numbers,
641    /// color format `"surface"`, depth format `"depth24plus"`).
642    pub fn create_pipeline(json: &str) -> Pipeline {
643        Pipeline(unsafe { sys::gfx_create_pipeline(json.as_ptr(), json.len() as u32) })
644    }
645    /// `{"layout":L,"entries":[...]}` or `{"pipeline":P,"group":0,"entries":[...]}`; entries
646    /// `{"binding":0,"buffer":B,"offset":0,"size":N}`, `{"binding":1,"texture":T}`, `{"binding":2,"sampler":S}`.
647    pub fn create_bind_group(json: &str) -> BindGroup {
648        BindGroup(unsafe { sys::gfx_create_bind_group(json.as_ptr(), json.len() as u32) })
649    }
650    /// `{"entries":[{"binding":0,"visibility":STAGE_VERTEX,"buffer":{"type":"uniform","hasDynamicOffset":true}}, ...]}`.
651    /// Bind groups made from it work with every pipeline whose `"layout":[...]` lists it.
652    pub fn create_bind_group_layout(json: &str) -> BindGroupLayout {
653        BindGroupLayout(unsafe { sys::gfx_create_bind_group_layout(json.as_ptr(), json.len() as u32) })
654    }
655    /// `{"size":[w,h],"format":"rgba8unorm","mipLevelCount":n}`
656    pub fn create_texture(json: &str) -> Texture {
657        Texture(unsafe { sys::gfx_create_texture(json.as_ptr(), json.len() as u32) })
658    }
659    /// Upload a tightly packed RGBA8 region (`rgba.len() == w * h * 4`) of mip level `mip`.
660    pub fn write_texture(t: Texture, mip: u32, x: u32, y: u32, w: u32, h: u32, rgba: &[u8]) {
661        unsafe { sys::gfx_write_texture(t.0, mip, x, y, w, h, rgba.as_ptr(), rgba.len() as u32) }
662    }
663    /// `{"addressModeU":"repeat","magFilter":"linear","minFilter":"linear","mipmapFilter":"linear"}`
664    pub fn create_sampler(json: &str) -> Sampler {
665        Sampler(unsafe { sys::gfx_create_sampler(json.as_ptr(), json.len() as u32) })
666    }
667    /// Offset and byte length must be multiples of 4.
668    pub fn write_buffer<T: Pod>(buf: Buffer, offset: u32, data: &[T]) {
669        let b = as_bytes(data);
670        unsafe { sys::gfx_write_buffer(buf.0, offset, b.as_ptr(), b.len() as u32) }
671    }
672    /// Returns false if the runner will discard this frame (you may skip drawing).
673    pub fn begin_frame(clear: [f32; 4]) -> bool {
674        unsafe { sys::gfx_begin_frame(clear[0], clear[1], clear[2], clear[3]) != 0 }
675    }
676    pub fn set_pipeline(p: Pipeline) {
677        unsafe { sys::gfx_set_pipeline(p.0) }
678    }
679    pub fn set_bind_group(index: u32, bg: BindGroup) {
680        unsafe { sys::gfx_set_bind_group(index, bg.0) }
681    }
682    /// One offset (multiple of [`OFFSET_ALIGNMENT`]) per dynamic-offset entry, in binding order.
683    pub fn set_bind_group_offsets(index: u32, bg: BindGroup, offsets: &[u32]) {
684        unsafe { sys::gfx_set_bind_group_offsets(index, bg.0, offsets.as_ptr(), offsets.len() as u32) }
685    }
686    /// Viewport in drawable pixels (clamped to the drawable), depth range 0..=1.
687    pub fn set_viewport(x: f32, y: f32, w: f32, h: f32, min_depth: f32, max_depth: f32) {
688        unsafe { sys::gfx_set_viewport(x, y, w, h, min_depth, max_depth) }
689    }
690    /// Scissor rectangle in drawable pixels (clamped to the drawable).
691    pub fn set_scissor_rect(x: u32, y: u32, w: u32, h: u32) {
692        unsafe { sys::gfx_set_scissor_rect(x, y, w, h) }
693    }
694    pub fn set_vertex_buffer(slot: u32, buf: Buffer, offset: u32) {
695        unsafe { sys::gfx_set_vertex_buffer(slot, buf.0, offset) }
696    }
697    pub fn set_index_buffer(buf: Buffer, format: IndexFormat, offset: u32) {
698        unsafe { sys::gfx_set_index_buffer(buf.0, format as u32, offset) }
699    }
700    pub fn draw(vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) {
701        unsafe { sys::gfx_draw(vertices, instances, first_vertex, first_instance) }
702    }
703    pub fn draw_indexed(indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) {
704        unsafe { sys::gfx_draw_indexed(indices, instances, first_index, base_vertex, first_instance) }
705    }
706    pub fn end_frame() {
707        unsafe { sys::gfx_end_frame() }
708    }
709    /// Release an object (its handle traps from now on); objects made from it stay
710    /// valid. Check `gasm::has("gasm:gfx.destroy")` first on older runners.
711    pub fn destroy(h: impl Handle) {
712        unsafe { sys::gfx_destroy(h.raw()) }
713    }
714}
715
716// ---- net ---------------------------------------------------------------------------
717
718/// Message connections through `gasm:net` (WebSocket semantics, non-blocking).
719pub mod net {
720    use crate::sys;
721
722    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
723    pub enum State {
724        Connecting,
725        Open,
726        Closed,
727        Error,
728    }
729
730    pub enum Recv {
731        Message(Vec<u8>),
732        Empty,
733        Closed,
734    }
735
736    #[derive(Debug)]
737    pub struct Conn(i32);
738
739    impl Conn {
740        /// Open `ws://` / `wss://`. `None` if the runner denies it.
741        pub fn open(url: &str) -> Option<Conn> {
742            let h = unsafe { sys::net_open(url.as_ptr(), url.len() as u32) };
743            (h > 0).then(|| Conn(h)) // not then_some: a Conn(-1) would be dropped, closing -1 (a trap)
744        }
745        pub fn state(&self) -> State {
746            match unsafe { sys::net_state(self.0) } {
747                0 => State::Connecting,
748                1 => State::Open,
749                2 => State::Closed,
750                _ => State::Error,
751            }
752        }
753        /// Send one message. False if the connection is not open.
754        pub fn send(&self, msg: &[u8]) -> bool {
755            !msg.is_empty() && unsafe { sys::net_send(self.0, msg.as_ptr(), msg.len() as u32) } == 0
756        }
757        /// Next queued message, if any.
758        pub fn recv(&self) -> Recv {
759            let mut buf = [0u8; 1024];
760            let n = unsafe { sys::net_recv(self.0, buf.as_mut_ptr(), buf.len() as u32) };
761            match n {
762                0 => Recv::Empty,
763                n if n < 0 => Recv::Closed,
764                n if n as usize <= buf.len() => Recv::Message(buf[..n as usize].to_vec()),
765                n => {
766                    let mut big = vec![0u8; n as usize];
767                    unsafe { sys::net_recv(self.0, big.as_mut_ptr(), n as u32) };
768                    Recv::Message(big)
769                }
770            }
771        }
772    }
773
774    impl Drop for Conn {
775        fn drop(&mut self) {
776            unsafe { sys::net_close(self.0) }
777        }
778    }
779}
780
781/// HTTP requests made by the runner (`gasm:fetch`, TLS included): start one, then
782/// poll it each frame. Runners may deny requests (natively: `--allow-net`, optionally a
783/// host list; browsers: the page, and CORS). Probe [`available`] first.
784///
785/// ```no_run
786/// let req = gasm::fetch::Request::get("https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=52&lon=21")
787///     .header("accept", "application/json")
788///     .send();
789/// // later, each frame:
790/// # let mut req = req.unwrap();
791/// if req.state() == gasm::fetch::State::Done {
792///     let json = req.read_to_end();
793/// }
794/// ```
795pub mod fetch {
796    use crate::sys;
797
798    /// Whether the runner has gasm:fetch.
799    pub fn available() -> bool {
800        crate::has("gasm:fetch")
801    }
802
803    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
804    pub enum State {
805        /// waiting for the response
806        Pending,
807        /// status and headers are in; the body is arriving
808        Headers,
809        /// the whole body has arrived (it may still be unread)
810        Done,
811        /// network error, timeout, too large, or refused by the browser
812        Failed,
813    }
814
815    /// A request to send. JSON-escapes what it's given.
816    #[derive(Clone, Debug)]
817    pub struct Request {
818        method: String,
819        url: String,
820        headers: Vec<(String, String)>,
821        body: Vec<u8>,
822    }
823
824    fn json_str(s: &str, out: &mut String) {
825        out.push('"');
826        for c in s.chars() {
827            match c {
828                '"' => out.push_str("\\\""),
829                '\\' => out.push_str("\\\\"),
830                c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
831                c => out.push(c),
832            }
833        }
834        out.push('"');
835    }
836
837    impl Request {
838        pub fn new(method: &str, url: &str) -> Request {
839            Request { method: method.to_owned(), url: url.to_owned(), headers: Vec::new(), body: Vec::new() }
840        }
841        pub fn get(url: &str) -> Request {
842            Request::new("GET", url)
843        }
844        pub fn post(url: &str, body: impl Into<Vec<u8>>) -> Request {
845            Request::new("POST", url).body(body)
846        }
847        pub fn header(mut self, name: &str, value: &str) -> Request {
848            self.headers.push((name.to_owned(), value.to_owned()));
849            self
850        }
851        pub fn body(mut self, body: impl Into<Vec<u8>>) -> Request {
852            self.body = body.into();
853            self
854        }
855        /// The JSON description `gasm_fetch_request` takes.
856        pub fn describe(&self) -> String {
857            let mut d = String::from("{\"method\":");
858            json_str(&self.method, &mut d);
859            d.push_str(",\"url\":");
860            json_str(&self.url, &mut d);
861            d.push_str(",\"headers\":{");
862            for (i, (k, v)) in self.headers.iter().enumerate() {
863                if i > 0 {
864                    d.push(',');
865                }
866                json_str(k, &mut d);
867                d.push(':');
868                json_str(v, &mut d);
869            }
870            d.push_str("}}");
871            d
872        }
873        /// Start it. `None` if the runner refuses (denied, invalid, too many open); the log says why.
874        pub fn send(&self) -> Option<Response> {
875            if !available() {
876                return None;
877            }
878            let d = self.describe();
879            let h = unsafe { sys::fetch_request(d.as_ptr(), d.len() as u32, self.body.as_ptr(), self.body.len() as u32) };
880            (h > 0).then(|| Response(h))
881        }
882    }
883
884    /// A request in flight; dropping it cancels it.
885    #[derive(Debug)]
886    pub struct Response(i32);
887
888    impl Response {
889        pub fn state(&self) -> State {
890            match unsafe { sys::fetch_state(self.0) } {
891                0 => State::Pending,
892                1 => State::Headers,
893                2 => State::Done,
894                _ => State::Failed,
895            }
896        }
897        /// HTTP status (after redirects), 0 before the headers or after a failure.
898        pub fn status(&self) -> i32 {
899            unsafe { sys::fetch_status(self.0) }
900        }
901        /// Response headers (names lowercase), once they are in.
902        pub fn headers(&self) -> Option<Vec<(String, String)>> {
903            let n = unsafe { sys::fetch_headers(self.0, std::ptr::null_mut(), 0) };
904            if n < 0 {
905                return None;
906            }
907            let mut buf = vec![0u8; n as usize];
908            unsafe { sys::fetch_headers(self.0, buf.as_mut_ptr(), n as u32) };
909            let text = String::from_utf8_lossy(&buf);
910            Some(text.lines().filter_map(|l| l.split_once(": ").map(|(k, v)| (k.to_owned(), v.to_owned()))).collect())
911        }
912        /// One header's value (`name` lowercase).
913        pub fn header(&self, name: &str) -> Option<String> {
914            self.headers()?.into_iter().find(|(k, _)| k == name).map(|(_, v)| v)
915        }
916        /// Body bytes that have arrived: `Some(n)` copied (0: none yet), `None` when the
917        /// body is done and drained or the request failed.
918        pub fn read(&mut self, buf: &mut [u8]) -> Option<usize> {
919            let n = unsafe { sys::fetch_read(self.0, buf.as_mut_ptr(), buf.len() as u32) };
920            (n >= 0).then_some(n as usize)
921        }
922        /// Everything that has arrived so far (all of it once the state is [`State::Done`]).
923        pub fn read_to_end(&mut self) -> Vec<u8> {
924            let mut out = Vec::new();
925            let mut buf = vec![0u8; 64 * 1024];
926            while let Some(n @ 1..) = self.read(&mut buf) {
927                out.extend_from_slice(&buf[..n]);
928            }
929            out
930        }
931    }
932
933    impl Drop for Response {
934        fn drop(&mut self) {
935            unsafe { sys::fetch_close(self.0) }
936        }
937    }
938}
939
940// ---- game entry points ----------------------------------------------------------------
941
942/// A gasm game. `init` runs once; `frame` runs at the configured frame rate.
943pub trait Game: Sized + 'static {
944    fn init() -> Result<Self, String>;
945    fn frame(&mut self);
946    /// Called (best effort) when the player closes the game: flush saves here.
947    /// Not called after `gasm::exit`, a trap, or a crash, so also save periodically.
948    fn exit(&mut self) {}
949}
950
951#[doc(hidden)]
952pub struct GameCell<T>(pub UnsafeCell<Option<T>>);
953// Wasm guests are single-threaded and the runner never calls exports concurrently,
954// so a game needn't be Send there (it may hold Rc, egui state, ...); natively (tests,
955// the stub host) the exports must not be called from several threads at once.
956#[cfg(target_arch = "wasm32")]
957unsafe impl<T> Sync for GameCell<T> {}
958#[cfg(not(target_arch = "wasm32"))]
959unsafe impl<T: Send> Sync for GameCell<T> {}
960
961/// # Safety
962/// Not reentrant: call only from the exports [`game!`] defines, never concurrently.
963#[doc(hidden)]
964pub unsafe fn __init<G: Game>(cell: &GameCell<G>) -> i32 {
965    std::panic::set_hook(Box::new(|info| log(&format!("panic: {info}"))));
966    match G::init() {
967        Ok(g) => {
968            unsafe { *cell.0.get() = Some(g) };
969            0
970        }
971        Err(e) => {
972            log(&format!("init failed: {e}"));
973            1
974        }
975    }
976}
977
978/// # Safety
979/// As [`__init`].
980#[doc(hidden)]
981pub unsafe fn __frame<G: Game>(cell: &GameCell<G>) {
982    if let Some(g) = unsafe { (*cell.0.get()).as_mut() } {
983        g.frame();
984    }
985}
986
987/// # Safety
988/// As [`__init`].
989#[doc(hidden)]
990pub unsafe fn __exit<G: Game>(cell: &GameCell<G>) {
991    if let Some(g) = unsafe { (*cell.0.get()).as_mut() } {
992        g.exit();
993    }
994}
995
996/// Export the gasm entry points for a [`Game`] type.
997#[macro_export]
998macro_rules! game {
999    ($t:ty) => {
1000        static __GASM_GAME: $crate::GameCell<$t> = $crate::GameCell(::std::cell::UnsafeCell::new(None));
1001
1002        #[unsafe(no_mangle)]
1003        pub extern "C" fn gasm_abi_version() -> i32 {
1004            $crate::ABI_VERSION
1005        }
1006        #[unsafe(no_mangle)]
1007        pub extern "C" fn gasm_init() -> i32 {
1008            unsafe { $crate::__init::<$t>(&__GASM_GAME) }
1009        }
1010        #[unsafe(no_mangle)]
1011        pub extern "C" fn gasm_frame() {
1012            unsafe { $crate::__frame::<$t>(&__GASM_GAME) }
1013        }
1014        #[unsafe(no_mangle)]
1015        pub extern "C" fn gasm_exit() {
1016            unsafe { $crate::__exit::<$t>(&__GASM_GAME) }
1017        }
1018    };
1019}
1020
1021// ---- own main loop -------------------------------------------------------------------
1022
1023/// Games that keep their own main loop (`loop { update(); draw(); wait_frame(); }`)
1024/// instead of implementing [`Game`]. Same mechanism as the C SDK's `gasm_loop.h`:
1025/// [`main_loop!`] exports the entry points and runs your function on the first frame;
1026/// [`main_loop::wait_frame`] suspends it until the next frame: with Binaryen's
1027/// Asyncify inside the module (`gasm_frame`, any runner), or by the runner itself
1028/// when it switches stacks (`gasm_run`). Build, then post-process the `.wasm`:
1029///
1030/// ```text
1031/// wasm-opt game.wasm --asyncify --pass-arg=asyncify-removelist@gasm_frame,gasm_loop_frame -O2 -o game.wasm
1032/// wasm-opt game.wasm -O2 -o game-run.wasm    # runners with stack switching only: smaller, faster
1033/// ```
1034///
1035/// ```ignore
1036/// fn run() -> i32 {
1037///     loop {
1038///         if gasm::pad(0).held(gasm::Buttons::START) { return 0; }
1039///         draw();
1040///         gasm::main_loop::wait_frame();
1041///     }
1042/// }
1043/// gasm::main_loop!(run);
1044/// ```
1045///
1046/// `main_loop!(run, on_exit)` also exports `gasm_exit` (the player is quitting: flush
1047/// saves). wasm32 only: native builds of such a game run `run` straight through.
1048pub mod main_loop {
1049    // the suspend/resume state only exists on wasm32
1050    #![cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
1051
1052    #[cfg(target_arch = "wasm32")]
1053    mod asyncify {
1054        #[link(wasm_import_module = "asyncify")]
1055        unsafe extern "C" {
1056            pub fn start_unwind(data: *mut u8);
1057            pub fn stop_unwind();
1058            pub fn start_rewind(data: *mut u8);
1059            pub fn stop_rewind();
1060        }
1061    }
1062
1063    const STACK: usize = 1024 * 1024;
1064
1065    #[repr(C)]
1066    struct Data {
1067        cur: *mut u8,
1068        end: *mut u8,
1069    }
1070
1071    // One thread; these are only touched from the frame loop below.
1072    static mut DATA: Data = Data { cur: std::ptr::null_mut(), end: std::ptr::null_mut() };
1073    static mut STACK_BUF: [u8; STACK] = [0; STACK];
1074    static mut REWINDING: bool = false;
1075    static mut UNWINDING: bool = false;
1076    static mut STARTED: bool = false;
1077    static mut FINISHED: bool = false;
1078    static mut EXIT_CODE: i32 = 0;
1079    static mut MAIN: Option<fn() -> i32> = None;
1080    static mut FRAMES: u32 = 0;
1081    /// entered through `gasm_run`: the runner switches stacks (no Asyncify)
1082    static mut RUN_MODE: bool = false;
1083
1084    fn wait_impl() {
1085        #[cfg(target_arch = "wasm32")]
1086        unsafe {
1087            if RUN_MODE {
1088                crate::sys::yield_frame();
1089                FRAMES += 1;
1090                return;
1091            }
1092            if REWINDING {
1093                asyncify::stop_rewind();
1094                REWINDING = false;
1095                FRAMES += 1;
1096                return;
1097            }
1098            DATA.cur = (&raw mut STACK_BUF).cast::<u8>();
1099            DATA.end = DATA.cur.add(STACK);
1100            UNWINDING = true;
1101            asyncify::start_unwind((&raw mut DATA).cast::<u8>());
1102        }
1103    }
1104
1105    // Reached through a pointer: Asyncify instruments the callers of indirect calls,
1106    // while wait_impl itself stays plain (like an import).
1107    static mut WAIT: fn() = wait_impl;
1108
1109    /// Return to the runner; continues in the next frame (input and time are per frame).
1110    pub fn wait_frame() {
1111        if crate::thread::available() {
1112            return crate::thread::wait_frame(); // threaded_main_loop!
1113        }
1114        let f = unsafe { std::ptr::read_volatile(&raw const WAIT) };
1115        f()
1116    }
1117
1118    /// Frames waited so far.
1119    pub fn frames() -> u32 {
1120        if crate::thread::available() {
1121            return crate::thread::frames();
1122        }
1123        unsafe { FRAMES }
1124    }
1125
1126    #[doc(hidden)]
1127    pub fn set_main(f: fn() -> i32) {
1128        unsafe { MAIN = Some(f) }
1129    }
1130
1131    // Must be instrumented (and not inlined into the frame export): an unwind returns
1132    // from here at once instead of looking like the game's function ended.
1133    #[inline(never)]
1134    fn run_main() {
1135        unsafe {
1136            let rc = MAIN.map_or(0, |f| f());
1137            if !UNWINDING {
1138                EXIT_CODE = rc;
1139                FINISHED = true;
1140            }
1141        }
1142    }
1143
1144    /// The whole run for runners that switch stacks (`gasm_run`): frames end in
1145    /// the `yield_frame` import. A build without the Asyncify pass only works this way.
1146    #[doc(hidden)]
1147    pub fn __run() -> i32 {
1148        unsafe {
1149            RUN_MODE = true;
1150            STARTED = true;
1151            MAIN.map_or(0, |f| f())
1152        }
1153    }
1154
1155    /// The frame driver, inlined into the `gasm_loop_frame` export that
1156    /// [`main_loop!`](crate::main_loop!) defines: that export is on Asyncify's
1157    /// remove list (it is the one frame that must not unwind). Games that don't
1158    /// use the macro don't get it (nor the asyncify imports).
1159    #[doc(hidden)]
1160    #[inline(always)]
1161    pub fn __loop_frame() {
1162        unsafe {
1163            if FINISHED {
1164                return;
1165            }
1166            #[cfg(target_arch = "wasm32")]
1167            {
1168                if !STARTED {
1169                    STARTED = true;
1170                } else {
1171                    REWINDING = true;
1172                    asyncify::start_rewind((&raw mut DATA).cast::<u8>());
1173                }
1174                run_main();
1175                if UNWINDING {
1176                    asyncify::stop_unwind();
1177                    UNWINDING = false;
1178                    return;
1179                }
1180            }
1181            #[cfg(not(target_arch = "wasm32"))]
1182            {
1183                STARTED = true;
1184                run_main();
1185            }
1186            if FINISHED {
1187                crate::exit(EXIT_CODE);
1188            }
1189        }
1190    }
1191}
1192
1193/// Like [`main_loop!`], with cooperative threads ([`thread`], [`sync`]): `main`
1194/// runs as the first thread, [`thread::spawn`] starts more. The frame driver is the
1195/// thread scheduler. Asyncify only (no `gasm_run` export): run `wasm-opt --asyncify
1196/// --pass-arg=asyncify-removelist@gasm_frame,gasm_loop_frame` on the module.
1197#[macro_export]
1198macro_rules! threaded_main_loop {
1199    ($main:path) => {
1200        #[unsafe(no_mangle)]
1201        pub extern "C" fn gasm_abi_version() -> i32 {
1202            $crate::ABI_VERSION
1203        }
1204        #[unsafe(no_mangle)]
1205        pub extern "C" fn gasm_init() -> i32 {
1206            $crate::thread::__set_main($main);
1207            0
1208        }
1209        #[unsafe(no_mangle)]
1210        pub extern "C" fn gasm_frame() {
1211            gasm_loop_frame()
1212        }
1213        #[unsafe(no_mangle)]
1214        #[inline(never)]
1215        pub extern "C" fn gasm_loop_frame() {
1216            $crate::thread::__threaded_loop_frame()
1217        }
1218    };
1219    ($main:path, $exit:path) => {
1220        $crate::threaded_main_loop!($main);
1221        #[unsafe(no_mangle)]
1222        pub extern "C" fn gasm_exit() {
1223            $exit()
1224        }
1225    };
1226}
1227
1228/// Export the gasm entry points for a game with its own main loop (see [`main_loop`]).
1229#[macro_export]
1230macro_rules! main_loop {
1231    ($main:path) => {
1232        #[unsafe(no_mangle)]
1233        pub extern "C" fn gasm_abi_version() -> i32 {
1234            $crate::ABI_VERSION
1235        }
1236        #[unsafe(no_mangle)]
1237        pub extern "C" fn gasm_init() -> i32 {
1238            $crate::main_loop::set_main($main);
1239            0
1240        }
1241        #[unsafe(no_mangle)]
1242        pub extern "C" fn gasm_frame() {
1243            gasm_loop_frame()
1244        }
1245        #[unsafe(no_mangle)]
1246        #[inline(never)]
1247        pub extern "C" fn gasm_loop_frame() {
1248            $crate::main_loop::__loop_frame()
1249        }
1250        #[unsafe(no_mangle)]
1251        pub extern "C" fn gasm_run() -> i32 {
1252            $crate::main_loop::__run()
1253        }
1254    };
1255    ($main:path, $exit:path) => {
1256        $crate::main_loop!($main);
1257        #[unsafe(no_mangle)]
1258        pub extern "C" fn gasm_exit() {
1259            $exit()
1260        }
1261    };
1262}
1263
1264/// Embed the game's capabilities manifest (the `gasm.manifest` custom section): what it
1265/// requires, the hosts it reaches and whether it saves files, which runners check and
1266/// ask about once before it starts. Once per game, with a JSON string:
1267///
1268/// ```ignore
1269/// gasm::manifest!(r#"{ "manifest": 1, "name": "My Game", "hosts": ["api.example.org"], "files": true }"#);
1270/// ```
1271#[macro_export]
1272macro_rules! manifest {
1273    ($json:expr) => {
1274        #[cfg(target_arch = "wasm32")]
1275        #[unsafe(link_section = "gasm.manifest")]
1276        #[used]
1277        static __GASM_MANIFEST: [u8; $json.len()] = {
1278            let b = $json.as_bytes();
1279            let mut a = [0u8; $json.len()];
1280            let mut i = 0;
1281            while i < a.len() {
1282                a[i] = b[i];
1283                i += 1;
1284            }
1285            a
1286        };
1287    };
1288}