mirage-engine 0.2.0

Mirage, an immediate-mode 3D engine for simple games on desktop and the browser
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
use core::time::Duration;
use std::cell::Cell;
use std::future::Future;
use std::io;
use std::rc::Rc;

use js_sys::{Array, Uint8Array};
use rayon::ThreadBuilder;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;
use web_sys::{
    DedicatedWorkerGlobalScope, Document, Element, HtmlCanvasElement, Response, Worker,
    WorkerOptions, WorkerType,
};
use winit::application::ApplicationHandler;
use winit::platform::web::{EventLoopExtWebSys, WindowAttributesExtWebSys, WindowExtWebSys};
use winit::window::{CursorGrabMode, Window, WindowAttributes};

use crate::platform::Platform;
use crate::platform::threads::{DisplayEnd, GameEnd, Paced, Starting};
use crate::{Config, Error, Game};

/// The browser has no usable [`std::time::Instant`]; this one reads
/// `performance.now()` behind the same API.
pub use web_time::Instant;

/// What this build runs behind: a canvas in a browser page.
pub(crate) const PLATFORM: Platform = Platform::Browser;

/// What a player does after the device was lost, on this platform.
pub(crate) const AFTER_LOSS: &str = "Reload the page to try again. On a laptop with two GPUs, set the browser to use the high-performance one in the system's graphics settings (Windows: Settings, System, Display, Graphics).";

/// What a player does after the device ran out of memory, on this platform.
pub(crate) const AFTER_OUT_OF_MEMORY: &str =
    "Close other tabs and programs that use the GPU, then reload the page to try again.";

const CANVAS_STYLE: &str =
    "position:fixed;top:0;left:0;width:100%;height:100%;display:block;touch-action:none";

const OVERLAY_STYLE: &str = "position:fixed;top:0;left:0;right:0;bottom:0;margin:0;padding:1rem;\
     background:#101014;color:#ff9090;font:14px/1.5 monospace;white-space:pre-wrap;z-index:2147483647";

/// Where the page states the script its worker is started from: a file
/// beside the page, which `cargo mirage web` writes.
const WORKER_ATTRIBUTE: &str = "data-mirage-worker";

/// What the game thread posts to the page for each worker of the pool it
/// starts, beside the address of that worker; everything else the game
/// thread posts is what it stopped with.
const SPAWN: &str = "spawn";

/// What every error about the game thread's own worker names it.
const GAME_THREAD: &str = "the game thread";

/// What startup stops with on a page that is not cross-origin isolated. The
/// page `cargo mirage web` writes states this same text for itself, before it
/// reads the module; that page is a template of that command, which this crate
/// reads nothing of, so the two are kept in step by hand.
const NOT_ISOLATED: &str = "the page is not cross-origin isolated, so the game starts no worker. Serve it with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp. On itch.io that is the SharedArrayBuffer support setting in the project's embed options.";

pub(crate) fn install_diagnostics() {
    console_error_panic_hook::set_once();
    if let Err(error) = console_log::init_with_level(log::Level::Info) {
        web_sys::console::warn_1(&JsValue::from_str(&format!("mirage-engine: {error}")));
    }
}

pub(crate) fn spawn(future: impl Future<Output = ()> + 'static) {
    wasm_bindgen_futures::spawn_local(future);
}

/// Loads one asset source, resolved against the game's page; a relative
/// source is a file next to `index.html`.
pub(crate) async fn read(source: &str) -> Result<Vec<u8>, Error> {
    let failed = |what: &str, error: JsValue| {
        Error::msg(format!("the asset source `{source}` {what}: {error:?}"))
    };

    let window =
        web_sys::window().ok_or_else(|| Error::msg("mirage-engine needs a browser window"))?;
    let response: Response = JsFuture::from(window.fetch_with_str(source))
        .await
        .map_err(|error| failed("could not be fetched", error))?
        .dyn_into()
        .map_err(|_| Error::msg(format!("the fetch of `{source}` answered with no response")))?;
    if !response.ok() {
        return Err(Error::msg(format!(
            "the asset source `{source}` answered with status {}",
            response.status()
        )));
    }

    let buffer = JsFuture::from(
        response
            .array_buffer()
            .map_err(|error| failed("could not be read", error))?,
    )
    .await
    .map_err(|error| failed("could not be read", error))?;

    Ok(Uint8Array::new(&buffer).to_vec())
}

pub(crate) fn window_attributes(config: &Config) -> Result<WindowAttributes, Error> {
    require_webgpu()?;
    let document = document()?;
    let canvas = match config.canvas_id() {
        Some(id) => page_canvas(&document, id)?,
        None => viewport_canvas(&document)?,
    };
    Ok(Window::default_attributes()
        .with_title(config.title())
        .with_canvas(Some(canvas)))
}

/// Runs `app` on the page's own event loop, which the browser drives after
/// this returns.
///
/// A worker has no page. The game's `main` runs there too, because the
/// worker starts this same module, so this returns at once and
/// [`mirage_worker_entry`] is what runs the game thread on it.
pub(crate) fn run_app(app: impl ApplicationHandler + 'static) {
    if web_sys::window().is_none() {
        return;
    }
    let Some(event_loop) = crate::platform::event_loop() else {
        return;
    };

    event_loop.spawn_app(app);
}

/// Runs the game thread the page posts to this worker, and returns once that
/// run is over.
///
/// The engine's own worker script calls this, once, with the number the
/// page posts beside the module and the memory. Nothing else may call it.
// `pub` because `#[wasm_bindgen]` takes a public function and nothing else;
// this module is private, so nothing outside the engine reaches it.
#[wasm_bindgen]
pub fn mirage_worker_entry(game: u32) {
    // SAFETY: the page keeps one boxed game thread per worker and posts the
    // address of it to that worker alone, which reads it once.
    let game = unsafe { Box::from_raw(game as usize as *mut Box<dyn FnOnce() + Send>) };
    game();
}

/// Runs the worker of the pool the page posts to this worker, and returns
/// once the pool drops it.
///
/// The engine's own worker script calls this, once, with the number the
/// page posts beside the module and the memory. Nothing else may call it.
// `pub` for `#[wasm_bindgen]`, as [`mirage_worker_entry`] is.
#[wasm_bindgen]
pub fn mirage_rayon_worker_entry(worker: u32) {
    // SAFETY: the game thread boxes one worker per spawn and the page posts
    // the address of it to that worker alone, which reads it once.
    let worker = unsafe { Box::from_raw(worker as usize as *mut ThreadBuilder) };
    worker.run();
}

/// The threads the page states this machine runs at once, or `1` where it
/// states none.
///
/// Read on the page's own thread, which is where a browser states the
/// number.
pub(crate) fn hardware_threads() -> usize {
    web_sys::window().map_or(1, |window| {
        window.navigator().hardware_concurrency() as usize
    })
}

/// Posts the page one spawn, which starts `worker`, one worker of the
/// engine's pool, over the page's own memory.
///
/// Called on the game thread, whose own worker posts to the page; the page
/// reads that post where it reads what the game thread stopped with.
pub(crate) fn spawn_worker(worker: ThreadBuilder) -> io::Result<()> {
    let scope = js_sys::global()
        .dyn_into::<DedicatedWorkerGlobalScope>()
        .map_err(|_| io::Error::other("a worker of the pool starts from the game thread alone"))?;
    let boxed = Boxed::of(worker);
    scope
        .post_message(&Array::of2(
            &JsValue::from_str(SPAWN),
            &JsValue::from(boxed.address()),
        ))
        .map_err(|error| {
            io::Error::other(format!("the page was asked for no worker: {error:?}"))
        })?;
    boxed.posted();

    Ok(())
}

/// Drops the canvas the engine created from the page; one the game named
/// is the page's own and stays.
pub(crate) fn close(window: &Window, config: &Config) {
    if config.canvas_id().is_some() {
        return;
    }
    if let Some(canvas) = window.canvas() {
        canvas.remove();
    }
}

/// The hold a page has on the pointer: whether the last frame set one,
/// which is what the next gesture of the player's requests the pointer
/// lock for.
pub(crate) struct PointerHold {
    set: bool,
}

impl PointerHold {
    /// The hold a run starts with, which holds nothing.
    pub(crate) fn released() -> Self {
        Self { set: false }
    }

    /// Takes what a frame set, ends the pointer lock on `window` where a
    /// frame holds it no more, and reports whether the pointer is locked
    /// now.
    ///
    /// A browser takes the lock only from inside a gesture of the
    /// player's, so a frame that sets the hold is locked on their next
    /// press or touch, and reads false until then.
    pub(crate) fn set(&mut self, window: &Window, held: bool) -> bool {
        if core::mem::replace(&mut self.set, held) != held && !held {
            let _ = window.set_cursor_grab(CursorGrabMode::None);
        }
        held && holds(window)
    }

    /// Requests the pointer lock from inside the player's own gesture, the
    /// one place a browser takes the request from.
    ///
    /// A lock the browser does not take, and one the player ends with
    /// escape, is requested again on the gesture after it.
    pub(crate) fn see_gesture(&mut self, window: &Window) {
        if self.set && !holds(window) {
            let _ = window.set_cursor_grab(CursorGrabMode::Locked);
        }
    }

    /// Drops the hold, which no page keeps past its focus: a browser ends
    /// the lock as the canvas loses focus. The first frame to set a hold
    /// after either edge of the focus requests the lock again.
    pub(crate) fn see_focus_change(&mut self) {
        self.set = false;
    }
}

/// Whether the pointer is locked to `window`'s own canvas now.
fn holds(window: &Window) -> bool {
    let Some(canvas) = window.canvas() else {
        return false;
    };
    document()
        .ok()
        .and_then(|document| document.pointer_lock_element())
        .is_some_and(|held| held == *canvas.unchecked_ref::<Element>())
}

/// What the browser states of the adapter it hands a page beyond what wgpu
/// reads of it, requested as wgpu requests it; `None` where it states nothing.
pub(crate) async fn adapter_facts() -> Option<String> {
    let navigator = web_sys::window()?.navigator();
    let gpu = js_sys::Reflect::get(navigator.as_ref(), &JsValue::from_str("gpu")).ok()?;
    let request = js_sys::Reflect::get(&gpu, &JsValue::from_str("requestAdapter"))
        .ok()?
        .dyn_into::<js_sys::Function>()
        .ok()?;
    let options = js_sys::Object::new();
    js_sys::Reflect::set(
        &options,
        &JsValue::from_str("powerPreference"),
        &JsValue::from_str("high-performance"),
    )
    .ok()?;
    let requested = request
        .call1(&gpu, &options)
        .ok()?
        .dyn_into::<js_sys::Promise>()
        .ok()?;
    let adapter = JsFuture::from(requested).await.ok()?;
    let info = js_sys::Reflect::get(&adapter, &JsValue::from_str("info")).ok()?;
    let stated = |key: &str| {
        js_sys::Reflect::get(&info, &JsValue::from_str(key))
            .ok()
            .and_then(|value| value.as_string())
            .filter(|text| !text.is_empty())
    };
    let facts: Vec<String> = ["vendor", "architecture"]
        .into_iter()
        .filter_map(stated)
        .collect();

    (!facts.is_empty()).then(|| facts.join(" "))
}

/// Starts the game thread on a worker of its own, over the page's own linear
/// memory: the worker starts this module again and runs the game thread's
/// loop, which waits there between samples.
///
/// Fails where the page is not cross-origin isolated, where it names no
/// script, and where it starts no worker.
pub(crate) fn start_game<G: Game>(
    end: GameEnd,
    starting: Starting<G>,
) -> Result<GameThreadHandle, Error> {
    require_isolation()?;
    let script: Rc<str> = worker_script(&document()?)?.into();
    let failure = WorkerFailure::default();
    let pool = PoolWorkers::new(Rc::clone(&script), failure.clone());
    let run: Box<dyn FnOnce() + Send> = Box::new(move || {
        if let Some(mut paced) = Paced::started(&end, starting) {
            paced.run(&end);
        }
    });
    let game = Watched::started(&script, GAME_THREAD, Boxed::of(run), |worker| {
        failure.watching(
            worker,
            format!("the worker {script} never ran"),
            posting(pool.clone(), failure.clone()),
        )
    })?;

    Ok(GameThreadHandle {
        game,
        pool,
        failure,
    })
}

/// Reads what the game thread posts: a spawn starts one worker of the pool,
/// and everything else is what that thread stopped with.
fn posting(pool: PoolWorkers, failure: WorkerFailure) -> Closure<dyn FnMut(JsValue)> {
    Closure::new(move |event: JsValue| match spawned(&event) {
        Some(address) => pool.start(address),
        None => failure.write(stated(&event, "data", "the game thread stopped")),
    })
}

/// The address of the worker a spawn posted, or `None` where what was posted
/// is no spawn.
fn spawned(event: &JsValue) -> Option<u32> {
    let posted: Array = js_sys::Reflect::get(event, &JsValue::from_str("data"))
        .ok()?
        .dyn_into()
        .ok()?;
    if posted.get(0).as_string()? != SPAWN {
        return None;
    }

    Some(posted.get(1).as_f64()? as u32)
}

/// A value one worker of the run takes, and the entry of this module that
/// worker's script calls to run it.
trait RunOnWorker {
    /// The entry the worker calls on the address this value is boxed at.
    const ENTRY: &'static str;
}

impl RunOnWorker for Box<dyn FnOnce() + Send> {
    /// The entry the game thread's worker calls, which the script reads by
    /// this name out of the module it started.
    const ENTRY: &'static str = "mirage_worker_entry";
}

impl RunOnWorker for ThreadBuilder {
    /// The entry a worker of the pool calls, read by name the same way.
    const ENTRY: &'static str = "mirage_rayon_worker_entry";
}

/// A value boxed for one worker to run: it holds the box from the address
/// the page posts until that worker has it, and frees it where the post
/// never landed.
struct Boxed<T>(*mut T);

impl<T> Boxed<T> {
    /// `value` boxed for one worker, the one reader of its address.
    fn of(value: T) -> Self {
        Self(Box::into_raw(Box::new(value)))
    }

    /// The box at `address` again, to hand to the worker that runs it or to
    /// free where none does.
    ///
    /// The caller states that `address` is one this module boxed a `T` at and
    /// posted once, and that no worker has read it.
    unsafe fn from_address(address: u32) -> Self {
        Self(address as usize as *mut T)
    }

    /// The address the page posts, which the worker's entry reads once.
    fn address(&self) -> u32 {
        self.0 as usize as u32
    }

    /// Hands the box to the worker, which frees it; called where the post
    /// landed and nowhere else.
    fn posted(self) {
        core::mem::forget(self);
    }
}

impl<T> Drop for Boxed<T> {
    fn drop(&mut self) {
        // SAFETY: the address reached no worker, so this is the only pointer
        // to the box and nothing has read it.
        drop(unsafe { Box::from_raw(self.0) });
    }
}

/// One worker started on the page's thread, and the closures the browser
/// calls to report what it does; the worker runs, and they report, for as
/// long as this is held.
struct Watched {
    worker: Worker,
    _reporting: [Closure<dyn FnMut(JsValue)>; 2],
}

impl Watched {
    /// Starts the module worker `named` runs on, from `script`, and posts it
    /// the module, the memory both run over, the entry `boxed` is run by and
    /// the address it is boxed at; `watch` reads what the worker reports from
    /// then on.
    ///
    /// The box is the worker's from the post on. Where this fails the post
    /// never landed, and the box is freed here.
    fn started<T: RunOnWorker>(
        script: &str,
        named: &str,
        boxed: Boxed<T>,
        watch: impl FnOnce(&Worker) -> [Closure<dyn FnMut(JsValue)>; 2],
    ) -> Result<Self, Error> {
        let options = WorkerOptions::new();
        options.set_type(WorkerType::Module);
        let worker = Worker::new_with_options(script, &options).map_err(|error| {
            Error::msg(format!("the page started no worker for {named}: {error:?}"))
        })?;
        worker
            .post_message(&Array::of4(
                &wasm_bindgen::module(),
                &wasm_bindgen::memory(),
                &JsValue::from_str(T::ENTRY),
                &JsValue::from(boxed.address()),
            ))
            .map_err(|error| Error::msg(format!("{named} was handed nothing: {error:?}")))?;
        boxed.posted();

        Ok(Self {
            _reporting: watch(&worker),
            worker,
        })
    }
}

/// The workers of the engine's pool started on the page's thread, one per
/// spawn the game thread posted, each reporting what it failed with.
#[derive(Clone)]
struct PoolWorkers {
    script: Rc<str>,
    failure: WorkerFailure,
    /// A `Cell`, as the slot above it is: the page runs one closure at a
    /// time, and a take and a set cannot end the run where a borrow can.
    started: Rc<Cell<Started>>,
}

/// What the page has started for the pool: the workers it keeps for the rest
/// of the run, and the spawns it has read, which number each worker in what
/// it reports; a spawn that started no worker counts among them.
#[derive(Default)]
struct Started {
    spawns: usize,
    watched: Vec<Watched>,
}

impl PoolWorkers {
    /// No workers yet, to be started on `script` and to report into
    /// `failure`.
    fn new(script: Rc<str>, failure: WorkerFailure) -> Self {
        Self {
            script,
            failure,
            started: Rc::default(),
        }
    }

    /// Starts one worker of the pool on the boxed worker at `address`, and
    /// keeps it for the rest of the run.
    fn start(&self, address: u32) {
        let mut started = self.started.take();
        started.spawns += 1;
        let named = format!("worker {} of the pool", started.spawns);
        // SAFETY: the game thread boxed one worker per spawn and posted its
        // address to the page alone, which reads that spawn once, here.
        let boxed = unsafe { Boxed::<ThreadBuilder>::from_address(address) };
        let watched = Watched::started(&self.script, &named, boxed, |worker| {
            self.failure.watching(
                worker,
                format!("{named} never ran"),
                self.failure.writing("data", format!("{named} stopped")),
            )
        });
        match watched {
            Ok(watched) => started.watched.push(watched),
            Err(error) => self.failure.write(error.to_string()),
        }
        self.started.set(started);
    }

    /// Ends every worker where it stands, since a page waits for nothing.
    fn ended(&self) {
        for watched in self.started.take().watched {
            watched.worker.terminate();
        }
    }
}

/// The first error one worker reported: a module that never started, or one
/// the worker's own script caught.
#[derive(Clone, Default)]
struct WorkerFailure(Rc<Cell<Option<Error>>>);

impl WorkerFailure {
    /// Reads what `worker` reports of itself into this, as `never_ran`, and
    /// hands what it posts to `posted`. The two closures it returns report
    /// for as long as they are held.
    fn watching(
        &self,
        worker: &Worker,
        never_ran: String,
        posted: Closure<dyn FnMut(JsValue)>,
    ) -> [Closure<dyn FnMut(JsValue)>; 2] {
        let errored = self.writing("message", never_ran);
        worker.set_onerror(Some(errored.as_ref().unchecked_ref()));
        worker.set_onmessage(Some(posted.as_ref().unchecked_ref()));

        [errored, posted]
    }

    /// A closure that keeps `about`, and whatever an event states under `key`
    /// beside it, as the error the run ends with.
    fn writing(&self, key: &'static str, about: String) -> Closure<dyn FnMut(JsValue)> {
        let failure = self.clone();
        Closure::new(move |event: JsValue| failure.write(stated(&event, key, &about)))
    }

    /// Keeps `error` as what the run ends with, where nothing is kept yet.
    fn write(&self, error: String) {
        let first = self.0.take().unwrap_or_else(|| Error::msg(error));
        self.0.set(Some(first));
    }

    /// The error reported so far, taken out of this.
    fn taken(&self) -> Option<Error> {
        self.0.take()
    }
}

/// `about`, with whatever `event` states under `key` beside it.
fn stated(event: &JsValue, key: &str, about: &str) -> String {
    js_sys::Reflect::get(event, &JsValue::from_str(key))
        .ok()
        .and_then(|value| value.as_string())
        .map_or_else(|| about.to_owned(), |text| format!("{about}: {text}"))
}

/// The handle the display thread keeps on the game thread: the worker it runs
/// on, the workers of the pool started for it on the page's thread, and what
/// any of them has reported.
pub(crate) struct GameThreadHandle {
    game: Watched,
    pool: PoolWorkers,
    failure: WorkerFailure,
}

impl GameThreadHandle {
    /// The error a worker reported, taken out, or nothing where they have
    /// reported none.
    pub(crate) fn failed(&self) -> Option<Error> {
        self.failure.taken()
    }

    /// Ends the run: dropping `end` ends the wait for the next sample, and
    /// every worker is ended where it stands, since a page waits for nothing.
    pub(crate) fn ended(self, end: DisplayEnd) {
        drop(end);
        self.game.worker.terminate();
        self.pool.ended();
    }
}

pub(crate) fn report_fatal(error: &Error) {
    let message = format!("mirage-engine: {error}");
    web_sys::console::error_1(&JsValue::from_str(&message));
    let _ = overlay_message(&message);
}

/// `None`: the browser states no double click interval of the machine's,
/// so a run in it counts by the engine's own.
pub(crate) fn double_click_interval() -> Option<Duration> {
    None
}

/// Text the store called `name` kept, out of the page's own store.
pub(crate) fn store_read(name: &str) -> Option<String> {
    match storage()?.get_item(&key(name)) {
        Ok(kept) => kept,
        Err(error) => {
            log::debug!("mirage-engine read nothing from the page: {error:?}");
            None
        }
    }
}

pub(crate) fn store_write(name: &str, text: &str) {
    let Some(storage) = storage() else {
        return;
    };
    if let Err(error) = storage.set_item(&key(name), text) {
        log::debug!("mirage-engine kept nothing in the page: {error:?}");
    }
}

fn storage() -> Option<web_sys::Storage> {
    web_sys::window()?.local_storage().ok()?
}

fn key(name: &str) -> String {
    format!("mirage-engine.{name}")
}

fn overlay_message(message: &str) -> Option<()> {
    let document = document().ok()?;
    let overlay = document.create_element("pre").ok()?;
    overlay.set_text_content(Some(message));
    overlay.set_attribute("style", OVERLAY_STYLE).ok()?;
    document.body()?.append_child(&overlay).ok()?;
    Some(())
}

// wgpu fails with a JS exception when `navigator.gpu` is absent, and no Rust
// error path catches it, so startup stops here and `report_fatal` states why.
// `Reflect`, not `web-sys`'s typed getter: that is still
// `web_sys_unstable_apis`-gated.
fn require_webgpu() -> Result<(), Error> {
    web_sys::window()
        .is_some_and(|window| {
            js_sys::Reflect::get(window.navigator().as_ref(), &JsValue::from_str("gpu"))
                .is_ok_and(|gpu| !gpu.is_undefined())
        })
        .then_some(())
        .ok_or_else(|| Error::msg("the browser has no WebGPU (navigator.gpu is missing)"))
}

// A page that is not cross-origin isolated fails at `new Worker` with an error
// naming no header, so startup stops here instead. `Reflect`, not a `web-sys`
// getter: `web-sys` has no binding for `crossOriginIsolated`.
fn require_isolation() -> Result<(), Error> {
    web_sys::window()
        .and_then(|window| {
            js_sys::Reflect::get(window.as_ref(), &JsValue::from_str("crossOriginIsolated")).ok()
        })
        .is_some_and(|isolated| isolated.is_truthy())
        .then_some(())
        .ok_or_else(|| Error::msg(NOT_ISOLATED))
}

fn document() -> Result<Document, Error> {
    web_sys::window()
        .and_then(|window| window.document())
        .ok_or_else(|| Error::msg("mirage-engine needs a browser window with a document"))
}

/// The script `document` states its worker is started from, which the engine
/// names no file of its own for.
fn worker_script(document: &Document) -> Result<String, Error> {
    document
        .body()
        .and_then(|body| body.get_attribute(WORKER_ATTRIBUTE))
        .filter(|script| !script.is_empty())
        .ok_or_else(|| {
            Error::msg(format!(
                "the page names no worker script in `{WORKER_ATTRIBUTE}` on its body"
            ))
        })
}

fn viewport_canvas(document: &Document) -> Result<HtmlCanvasElement, Error> {
    let canvas: HtmlCanvasElement = document
        .create_element("canvas")
        .map_err(|error| Error::msg(format!("the document refused a canvas: {error:?}")))?
        .dyn_into()
        .map_err(|_| Error::msg("the document made something other than a canvas"))?;
    canvas
        .set_attribute("style", CANVAS_STYLE)
        .map_err(|error| Error::msg(format!("the canvas refused its style: {error:?}")))?;

    let body = document
        .body()
        .ok_or_else(|| Error::msg("the page has no body to attach the canvas to"))?;
    body.append_child(&canvas)
        .map_err(|error| Error::msg(format!("the page refused the canvas: {error:?}")))?;

    Ok(canvas)
}

fn page_canvas(document: &Document, id: &str) -> Result<HtmlCanvasElement, Error> {
    document
        .get_element_by_id(id)
        .ok_or_else(|| Error::msg(format!("the page has no element with id `{id}`")))?
        .dyn_into()
        .map_err(|_| Error::msg(format!("the element with id `{id}` is not a canvas")))
}