Skip to main content

sg_guest/
lib.rs

1//! Guest SDK for 0x1 games (target `wasm32-unknown-unknown`).
2//!
3//! - [`gpu`]: a wgpu custom backend. `sg_guest::gpu::instance()` returns a normal
4//!   `wgpu::Instance`, so existing wgpu code runs unchanged on the host GPU.
5//! - Safe wrappers for the rest of the `sg` API: clock, input, TCP, HTTP fetch,
6//!   key/value storage, audio, and workers/messages.
7//! - `log` integration and a panic hook that reports through the host log.
8//!
9//! A game exports `sg_init() -> i32` and `sg_frame(t: f64, dt: f64)`; worker
10//! instances export `sg_worker_init() -> i32` and `sg_worker_tick(t: f64) -> i32`.
11
12pub mod display;
13pub mod gpu;
14pub mod sys;
15
16pub use sg_abi as abi;
17use sg_abi::input::{RawEvent, EVENT_SIZE};
18
19/// Writes a line to the host log.
20pub fn log_str(s: &str) {
21    unsafe { sys::log(s.as_ptr(), s.len().min(1 << 20)) }
22}
23
24struct HostLogger;
25
26impl log::Log for HostLogger {
27    fn enabled(&self, m: &log::Metadata) -> bool {
28        m.level() <= log::max_level()
29    }
30    fn log(&self, r: &log::Record) {
31        if self.enabled(r.metadata()) {
32            log_str(&format!("{} {}: {}", r.level(), r.target(), r.args()));
33        }
34    }
35    fn flush(&self) {}
36}
37
38/// Installs the `log` backend and a panic hook. Call first in `sg_init`.
39pub fn init(level: log::LevelFilter) {
40    let _ = log::set_logger(&HostLogger);
41    log::set_max_level(level);
42    std::panic::set_hook(Box::new(|info| log_str(&format!("PANIC: {info}"))));
43}
44
45pub fn set_title(s: &str) {
46    unsafe { sys::set_title(s.as_ptr(), s.len().min(256)) }
47}
48
49pub fn surface_size() -> (u32, u32) {
50    let v = unsafe { sys::surface_size() };
51    ((v >> 32) as u32, v as u32)
52}
53
54/// Milliseconds since the instance started (monotonic, like `performance.now()`).
55pub fn now_ms() -> f64 {
56    unsafe { sys::now_ms() }
57}
58
59/// Unix time in milliseconds (like `Date.now()`).
60pub fn wall_ms() -> f64 {
61    unsafe { sys::wall_ms() }
62}
63
64pub fn random_bytes(b: &mut [u8]) {
65    for c in b.chunks_mut(1 << 20) {
66        unsafe { sys::random_fill(c.as_mut_ptr(), c.len()) }
67    }
68}
69
70/// The game's launch arguments: the manifest URL's query string.
71pub fn args() -> String {
72    let n = unsafe { sys::args(std::ptr::null_mut(), 0) } as usize;
73    let mut v = vec![0u8; n];
74    unsafe { sys::args(v.as_mut_ptr(), n) };
75    String::from_utf8(v).unwrap_or_default()
76}
77
78/// Parsed launch arguments (`a=1&b=x` → [("a","1"), ("b","x")]), percent-decoded.
79pub fn arg_pairs() -> Vec<(String, String)> {
80    fn dec(s: &str) -> String {
81        let b = s.as_bytes();
82        let mut out = Vec::with_capacity(b.len());
83        let mut i = 0;
84        while i < b.len() {
85            match b[i] {
86                b'+' => out.push(b' '),
87                b'%' if i + 2 < b.len() => {
88                    if let Ok(v) = u8::from_str_radix(std::str::from_utf8(&b[i + 1..i + 3]).unwrap_or("zz"), 16) {
89                        out.push(v);
90                        i += 2;
91                    } else {
92                        out.push(b'%');
93                    }
94                }
95                c => out.push(c),
96            }
97            i += 1;
98        }
99        String::from_utf8_lossy(&out).into_owned()
100    }
101    args()
102        .split('&')
103        .filter(|s| !s.is_empty())
104        .map(|kv| match kv.split_once('=') {
105            Some((k, v)) => (dec(k), dec(v)),
106            None => (dec(kv), String::new()),
107        })
108        .collect()
109}
110
111/// Looks up one launch argument (like `URLSearchParams.get`).
112pub fn arg(name: &str) -> Option<String> {
113    arg_pairs().into_iter().find(|(k, _)| k == name).map(|(_, v)| v)
114}
115
116/// 0 in the main instance, else this worker's id.
117pub fn worker_id() -> u32 {
118    unsafe { sys::is_worker() }
119}
120
121pub fn quit() {
122    unsafe { sys::quit() }
123}
124
125// ---------------------------------------------------------------- input
126
127/// Drains pending input events.
128pub fn poll_input() -> Vec<RawEvent> {
129    let mut out = Vec::new();
130    let mut buf = vec![0u8; 256 * EVENT_SIZE];
131    loop {
132        let n = unsafe { sys::input_poll(buf.as_mut_ptr(), 256) } as usize;
133        out.extend(buf[..n * EVENT_SIZE].chunks_exact(EVENT_SIZE).map(RawEvent::from_bytes));
134        if n < 256 {
135            return out;
136        }
137    }
138}
139
140pub fn set_pointer_lock(on: bool) {
141    unsafe { sys::pointer_lock(on as u32) }
142}
143
144pub fn pointer_locked() -> bool {
145    unsafe { sys::pointer_locked() != 0 }
146}
147
148pub fn window_focused() -> bool {
149    unsafe { sys::window_focused() != 0 }
150}
151
152// ---------------------------------------------------------------- assets
153
154pub fn asset(name: &str) -> Option<Vec<u8>> {
155    let n = unsafe { sys::asset_size(name.as_ptr(), name.len()) };
156    if n < 0 {
157        return None;
158    }
159    let mut v = vec![0u8; n as usize];
160    unsafe { sys::asset_read(name.as_ptr(), name.len(), 0, v.as_mut_ptr(), v.len()) };
161    Some(v)
162}
163
164// ---------------------------------------------------------------- TCP
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub enum TcpState {
168    Connecting,
169    Open,
170    Closed,
171    Failed,
172}
173
174/// A non-blocking TCP stream to a destination declared in the manifest.
175pub struct TcpStream(u32);
176
177impl TcpStream {
178    /// Starts connecting. Traps if `host:port` is not declared in the manifest.
179    pub fn connect(host: &str, port: u16) -> TcpStream {
180        TcpStream(unsafe { sys::tcp_connect(host.as_ptr(), host.len(), port as u32) })
181    }
182
183    pub fn state(&self) -> (TcpState, String) {
184        let mut e = [0u8; 256];
185        let s = unsafe { sys::tcp_status(self.0, e.as_mut_ptr(), e.len()) };
186        let n = e.iter().position(|b| *b == 0).unwrap_or(e.len());
187        let st = match s {
188            0 => TcpState::Connecting,
189            1 => TcpState::Open,
190            2 => TcpState::Closed,
191            _ => TcpState::Failed,
192        };
193        (st, String::from_utf8_lossy(&e[..n]).into_owned())
194    }
195
196    /// Reads what has arrived (possibly nothing).
197    pub fn recv(&self, buf: &mut [u8]) -> usize {
198        unsafe { sys::tcp_recv(self.0, buf.as_mut_ptr(), buf.len()) as usize }
199    }
200
201    /// Queues bytes; returns how many were accepted.
202    pub fn send(&self, data: &[u8]) -> usize {
203        unsafe { sys::tcp_send(self.0, data.as_ptr(), data.len()) as usize }
204    }
205}
206
207impl Drop for TcpStream {
208    fn drop(&mut self) {
209        unsafe { sys::tcp_close(self.0) }
210    }
211}
212
213// ---------------------------------------------------------------- fetch
214
215pub enum FetchState {
216    Pending,
217    Done { status: u16 },
218    Failed(String),
219}
220
221/// An HTTP(S) request to a URL prefix declared in the manifest.
222pub struct Fetch(u32);
223
224impl Fetch {
225    /// `headers` may contain Range, Accept, If-None-Match, If-Modified-Since.
226    pub fn get(url: &str, headers: &[(&str, &str)]) -> Fetch {
227        Self::start(url, "GET", headers)
228    }
229
230    pub fn head(url: &str) -> Fetch {
231        Self::start(url, "HEAD", &[])
232    }
233
234    fn start(url: &str, method: &str, headers: &[(&str, &str)]) -> Fetch {
235        let req = serde_json::json!({"url": url, "method": method, "headers": headers}).to_string();
236        Fetch(unsafe { sys::fetch_start(req.as_ptr(), req.len()) })
237    }
238
239    pub fn state(&self) -> FetchState {
240        let s = unsafe { sys::fetch_status(self.0) };
241        match s & 0xff {
242            0 => FetchState::Pending,
243            1 => FetchState::Done { status: (s >> 8) as u16 },
244            _ => FetchState::Failed(self.meta()["error"].as_str().unwrap_or("").to_string()),
245        }
246    }
247
248    /// {"status", "headers": [[k, v]], "error"}
249    pub fn meta(&self) -> serde_json::Value {
250        let n = unsafe { sys::fetch_meta(self.0, std::ptr::null_mut(), 0) } as usize;
251        let mut v = vec![0u8; n];
252        unsafe { sys::fetch_meta(self.0, v.as_mut_ptr(), n) };
253        serde_json::from_slice(&v).unwrap_or(serde_json::Value::Null)
254    }
255
256    pub fn header(&self, name: &str) -> Option<String> {
257        self.meta()["headers"].as_array()?.iter().find(|h| h[0].as_str().is_some_and(|k| k.eq_ignore_ascii_case(name))).and_then(|h| h[1].as_str().map(String::from))
258    }
259
260    pub fn body(&self) -> Vec<u8> {
261        let n = unsafe { sys::fetch_body_len(self.0) }.max(0) as usize;
262        let mut v = vec![0u8; n];
263        let mut off = 0;
264        while off < n {
265            let k = unsafe { sys::fetch_read(self.0, off as u64, v[off..].as_mut_ptr(), (n - off).min(64 << 20)) } as usize;
266            if k == 0 {
267                break;
268            }
269            off += k;
270        }
271        v.truncate(off);
272        v
273    }
274}
275
276impl Drop for Fetch {
277    fn drop(&mut self) {
278        unsafe { sys::fetch_free(self.0) }
279    }
280}
281
282// ---------------------------------------------------------------- storage
283
284/// Per-game persistent key/value storage (requires `storage_mb` in the manifest).
285pub mod kv {
286    use super::sys;
287
288    pub fn get(key: &[u8]) -> Option<Vec<u8>> {
289        let n = unsafe { sys::kv_size(key.as_ptr(), key.len()) };
290        if n < 0 {
291            return None;
292        }
293        let mut v = vec![0u8; n as usize];
294        let r = unsafe { sys::kv_read(key.as_ptr(), key.len(), 0, v.as_mut_ptr(), v.len()) };
295        if r < 0 {
296            return None;
297        }
298        v.truncate(r as usize);
299        Some(v)
300    }
301
302    pub fn get_str(key: &str) -> Option<String> {
303        get(key.as_bytes()).and_then(|v| String::from_utf8(v).ok())
304    }
305
306    /// Returns false if the storage quota would be exceeded.
307    pub fn set(key: &[u8], val: &[u8]) -> bool {
308        unsafe { sys::kv_write(key.as_ptr(), key.len(), val.as_ptr(), val.len()) != 0 }
309    }
310
311    pub fn set_str(key: &str, val: &str) -> bool {
312        set(key.as_bytes(), val.as_bytes())
313    }
314
315    pub fn delete(key: &[u8]) {
316        unsafe { sys::kv_delete(key.as_ptr(), key.len()) }
317    }
318
319    pub fn list(prefix: &[u8]) -> Vec<Vec<u8>> {
320        let n = unsafe { sys::kv_list(prefix.as_ptr(), prefix.len(), std::ptr::null_mut(), 0) } as usize;
321        let mut v = vec![0u8; n];
322        let m = unsafe { sys::kv_list(prefix.as_ptr(), prefix.len(), v.as_mut_ptr(), n) } as usize;
323        if m != n {
324            return vec![];
325        }
326        let mut out = Vec::new();
327        let mut i = 0;
328        while i + 4 <= v.len() {
329            let l = u32::from_le_bytes(v[i..i + 4].try_into().unwrap()) as usize;
330            i += 4;
331            out.push(v[i..i + l].to_vec());
332            i += l;
333        }
334        out
335    }
336}
337
338// ---------------------------------------------------------------- audio
339
340pub mod audio {
341    use super::sys;
342
343    /// Uploaded PCM. `channels` 1 or 2.
344    pub struct Sound(pub u32);
345
346    impl Sound {
347        pub fn from_f32(samples: &[f32], channels: u32, rate: u32) -> Sound {
348            let b: Vec<u8> = samples.iter().flat_map(|s| s.to_le_bytes()).collect();
349            Sound(unsafe { sys::sound_create(b.as_ptr(), b.len(), 0, channels, rate) })
350        }
351
352        pub fn from_i16(samples: &[i16], channels: u32, rate: u32) -> Sound {
353            let b: Vec<u8> = samples.iter().flat_map(|s| s.to_le_bytes()).collect();
354            Sound(unsafe { sys::sound_create(b.as_ptr(), b.len(), 1, channels, rate) })
355        }
356
357        /// Starts a voice; 0 if the voice limit is reached.
358        pub fn play(&self, volume: f32, pan: f32, pitch: f32, looping: bool) -> u32 {
359            unsafe { sys::voice_play(self.0, volume, pan, pitch, looping as u32) }
360        }
361    }
362
363    impl Drop for Sound {
364        fn drop(&mut self) {
365            unsafe { sys::sound_free(self.0) }
366        }
367    }
368
369    pub fn set(voice: u32, volume: f32, pan: f32, pitch: f32) -> bool {
370        unsafe { sys::voice_set(voice, volume, pan, pitch) != 0 }
371    }
372
373    pub fn stop(voice: u32) {
374        unsafe { sys::voice_stop(voice) };
375    }
376
377    /// A voice's effects: a one-pole low-pass corner in Hz (>= 19999 or non-finite: none)
378    /// and its send (0..1) to the host's one reverb bus. False if the voice has finished.
379    pub fn fx(voice: u32, lowpass_hz: f32, send: f32) -> bool {
380        unsafe { sys::voice_fx(voice, lowpass_hz, send) != 0 }
381    }
382
383    /// The reverb bus's room: RT60 in s (0..12, 0 = off), the damping corner in Hz
384    /// (100..20000), the pre-delay in ms (0..100) and the early reflections' gain (0..1).
385    /// Changes glide over about 150 ms.
386    pub fn reverb(rt60: f32, damp_hz: f32, predelay_ms: f32, early: f32) {
387        unsafe { sys::reverb_set(rt60, damp_hz, predelay_ms, early) }
388    }
389
390    pub fn active(voice: u32) -> bool {
391        unsafe { sys::voice_active(voice) != 0 }
392    }
393
394    pub fn master(v: f32) {
395        unsafe { sys::audio_master(v) }
396    }
397}
398
399// ---------------------------------------------------------------- workers
400
401/// WebRTC data channels to other players, browsers included (manifest permission `rtc`). The game
402/// carries the SDP strings itself (non-trickle: candidates are inside them). Each connection has
403/// one reliable, ordered channel.
404pub mod rtc {
405    use super::sys;
406
407    #[derive(Debug, Clone, PartialEq)]
408    pub enum Event {
409        /// Our offer for a new connection `peer` (send `sdp` to the other side).
410        Offer { req: u32, peer: u64, sdp: String },
411        /// Our answer to an offer, for a new connection `peer` (send `sdp` back).
412        Answer { req: u32, peer: u64, sdp: String },
413        Failed { req: u32, error: String },
414        Open { peer: u64 },
415        Data { peer: u64, data: Vec<u8> },
416        Closed { peer: u64 },
417    }
418
419    /// Whether this game may link to other players (the manifest asked for `rtc` and it was granted).
420    pub fn available() -> bool {
421        unsafe { sys::rtc_available() != 0 }
422    }
423
424    /// The world's STUN and TURN servers (its `/ice` answer), before the first connection; true if taken.
425    pub fn set_ice(json: &str) -> bool {
426        unsafe { sys::rtc_ice(json.as_ptr(), json.len()) != 0 }
427    }
428
429    /// Starts an offer; 0 if no more connections are allowed.
430    pub fn offer() -> u32 {
431        unsafe { sys::rtc_offer() }
432    }
433    pub fn accept_offer(sdp: &str) -> u32 {
434        unsafe { sys::rtc_accept_offer(sdp.as_ptr(), sdp.len()) }
435    }
436    pub fn accept_answer(peer: u64, sdp: &str) -> u32 {
437        unsafe { sys::rtc_accept_answer(peer, sdp.as_ptr(), sdp.len()) }
438    }
439    /// Queues a message (at most 256 KiB); false if `peer` is not a connection of ours.
440    pub fn send(peer: u64, data: &[u8]) -> bool {
441        unsafe { sys::rtc_send(peer, data.as_ptr(), data.len()) != 0 }
442    }
443    pub fn close(peer: u64) {
444        unsafe { sys::rtc_close(peer) }
445    }
446
447    /// The next event, if any.
448    pub fn poll() -> Option<Event> {
449        let mut buf = vec![0u8; 4096];
450        let mut n = unsafe { sys::rtc_poll(buf.as_mut_ptr(), buf.len()) };
451        if n < 0 {
452            return None;
453        }
454        if n as usize > buf.len() {
455            buf.resize(n as usize, 0);
456            n = unsafe { sys::rtc_poll(buf.as_mut_ptr(), buf.len()) };
457            if n < 0 {
458                return None;
459            }
460        }
461        decode(&buf[..n as usize])
462    }
463
464    pub fn decode(b: &[u8]) -> Option<Event> {
465        if b.len() < 13 {
466            return None;
467        }
468        let req = u32::from_le_bytes(b[1..5].try_into().ok()?);
469        let peer = u64::from_le_bytes(b[5..13].try_into().ok()?);
470        let p = &b[13..];
471        let text = || String::from_utf8_lossy(p).into_owned();
472        Some(match b[0] {
473            1 => Event::Offer { req, peer, sdp: text() },
474            2 => Event::Answer { req, peer, sdp: text() },
475            3 => Event::Failed { req, error: text() },
476            4 => Event::Open { peer },
477            5 => Event::Data { peer, data: p.to_vec() },
478            6 => Event::Closed { peer },
479            _ => return None,
480        })
481    }
482}
483
484pub mod worker {
485    use super::sys;
486
487    /// Starts a worker instance of this module; `arg` is its first message.
488    pub fn spawn(arg: &[u8]) -> u32 {
489        unsafe { sys::worker_spawn(arg.as_ptr(), arg.len()) }
490    }
491
492    pub fn terminate(id: u32) {
493        unsafe { sys::worker_terminate(id) }
494    }
495
496    /// `to`: a worker id (from the main instance) or 0 (from a worker to its parent).
497    /// Returns false if the receiver's queue is full.
498    pub fn post(to: u32, msg: &[u8]) -> bool {
499        unsafe { sys::msg_post(to, msg.as_ptr(), msg.len()) != 0 }
500    }
501
502    /// Next message as (sender, bytes). A sender with the high bit set reports
503    /// that worker `sender & 0x7fffffff` died (the bytes are the reason).
504    pub fn recv() -> Option<(u32, Vec<u8>)> {
505        let n = unsafe { sys::msg_peek() };
506        if n < 0 {
507            return None;
508        }
509        let mut v = vec![0u8; n as usize];
510        let from = unsafe { sys::msg_recv(v.as_mut_ptr(), v.len()) };
511        (from >= 0).then_some((from as u32, v))
512    }
513}