Skip to main content

repame_shell/
lib.rs

1//! App wiring: Repose platform runners, host helpers, and the portal.
2//!
3//! Games provide the root view; the `run_*` runners mount only, and stepping
4//! stays game-side via [`Sim::step`]. [`RetainedRoot`] keeps the mounted view
5//! alive across frames, and [`GamepadPoller`] drains hardware events from the
6//! shared platform backend into the UI nav and the game's own pad state.
7//!
8//! Around that sit the helpers a host game needs once: [`Staging`] as the one
9//! per-frame input snapshot (held keys, edges, clicks, aim, touches, pads),
10//! [`on_first_user_gesture`] for the browser's autoplay rule, [`RumbleBridge`]
11//! for haptics, [`PadBank`] and [`PadMotion`] for pads and their motion,
12//! [`apply_scheduler_levels`] for scheduler priority, [`Quit`] for the
13//! platform-specific exit, and the shared shortcut edges.
14//!
15//! [`portal`] is the part a hosted game cannot do without: ads with deadlines,
16//! cloud-save push and pull, host pause, lifecycle mute, and the [`Suspend`]
17//! gate that decides whether the clock runs this frame. It is a module of its
18//! own because those rules are worth reading in one place.
19use std::collections::HashSet;
20use web_time::Duration;
21
22use anyhow::Result;
23pub use repame_sim::{Sim, SimTime};
24pub use repame_view2d::{Camera2d, PickEvent, SpriteInstance};
25use repose_core::View;
26pub use repose_core::input::{GamepadEvent, GamepadId};
27use repose_platform::gamepad::{GamepadBackend, create_backend};
28
29mod gesture;
30mod haptics;
31mod levels;
32mod motion;
33mod pads;
34pub mod portal;
35mod quit;
36mod shortcuts;
37mod staging;
38pub use gesture::{on_first_user_gesture, user_gesture_seen};
39pub use haptics::{RUMBLE_REFRESH, RUMBLE_UPLOAD_MS, RumbleBridge};
40pub use levels::apply_scheduler_levels;
41pub use motion::{MotionPoller, PadMotion};
42pub use pads::{PadBank, PadBridge, TRIGGER_HELD};
43pub use portal::{AdKind, AdOutcome, GameState, PortalHost, PortalReport, Suspend};
44pub use quit::Quit;
45pub use shortcuts::{
46    SharedEdges, ShortcutEdges, game_shortcut_map, install_game_shortcuts, install_handler_into,
47    install_map, shared_edges, shortcut_handler, take as take_shortcut_edges,
48};
49pub use staging::Staging;
50
51/// Per-frame hooks the game implements.
52pub trait ShellHooks {
53    /// Variable-rate hook (tweens, audio, autosave timers).
54    fn on_frame(&mut self, _sim: &mut Sim, _dt: Duration) {}
55}
56
57pub struct RetainedRoot {
58    key: String,
59    generation: u64,
60}
61
62impl RetainedRoot {
63    pub fn new() -> Self {
64        Self {
65            key: format!(
66                "repame.retained_root.{}",
67                repose_core::unique_component_id()
68            ),
69            generation: 0,
70        }
71    }
72
73    pub fn call<F>(&mut self, sched: &mut repose_core::runtime::Scheduler, build: F) -> View
74    where
75        F: FnOnce(&mut repose_core::runtime::Scheduler) -> View,
76    {
77        let key = &self.key;
78        let epoch = repose_core::timer::frame_count();
79        let generation = self.generation;
80        repose_core::scope!(key, sched, [epoch, generation], { build(sched) })
81    }
82
83    pub fn clear(&mut self) {
84        self.generation = self.generation.wrapping_add(1);
85    }
86}
87
88impl Default for RetainedRoot {
89    fn default() -> Self {
90        Self::new()
91    }
92}
93
94/// Desktop entry point. Mounts `root` with title and size.
95/// The root closure owns stepping and requests frames for continuity.
96/// The closure receives the live [`repose_core::runtime::Scheduler`] each frame, whose
97/// `held_keys` / `window_focused` / `mouse_*` fields are the single
98/// polled hardware snapshot (GML `keyboard_check` /
99/// `mouse_check_button` parity).
100#[cfg(all(not(target_os = "android"), not(target_arch = "wasm32")))]
101pub fn run_desktop(
102    title: &str,
103    size: (u32, u32),
104    mut root: impl FnMut(
105        &mut repose_core::runtime::Scheduler,
106        &repose_core::RenderContext,
107    ) -> repose_core::View
108    + 'static,
109) -> Result<()> {
110    let config = repose_app::AppConfig {
111        window_title: title.to_string(),
112        window_size: size,
113        ..Default::default()
114    };
115    let mut retained = RetainedRoot::new();
116    repose_platform::run_desktop_app_with_config(
117        move |sched, ctx| retained.call(sched, |sched| root(sched, ctx)),
118        config,
119    )?;
120    Ok(())
121}
122
123/// Web entry point. Mounts `root` with default options.
124#[cfg(target_arch = "wasm32")]
125pub fn run_web(
126    mut root: impl FnMut(
127        &mut repose_core::runtime::Scheduler,
128        &repose_core::RenderContext,
129    ) -> repose_core::View
130    + 'static,
131) -> Result<(), wasm_bindgen::JsValue> {
132    let mut options = repose_platform::web::WebOptions::new(None);
133    options.set_prevent_default(true);
134    let mut retained = RetainedRoot::new();
135    repose_platform::web::run_web_app(
136        move |sched, ctx| retained.call(sched, |sched| root(sched, ctx)),
137        options,
138    )
139}
140
141/// Android entry point. Mounts `root` with default options.
142#[cfg(target_os = "android")]
143pub fn run_android(
144    app: winit::platform::android::activity::AndroidApp,
145    mut root: impl FnMut(
146        &mut repose_core::runtime::Scheduler,
147        &repose_core::RenderContext,
148    ) -> repose_core::View
149    + 'static,
150) -> Result<()> {
151    let mut retained = RetainedRoot::new();
152    repose_platform::android::run_android_app_with_options(
153        app,
154        move |sched, ctx| retained.call(sched, |sched| root(sched, ctx)),
155        repose_app::AndroidOptions::default(),
156    )
157}
158
159/// Gamepad polling on the shared platform backend. Events feed
160/// `ReposeRuntime::handle_gamepad` (UI nav) and `rt.gamepads` (gameplay).
161pub struct GamepadPoller {
162    backend: Option<Box<dyn GamepadBackend>>,
163    connected: HashSet<u32>,
164}
165
166impl GamepadPoller {
167    pub fn new() -> Self {
168        Self {
169            backend: create_backend().map(|b| Box::new(b) as Box<dyn GamepadBackend>),
170            // Boot-plugged pads report on first poll; no press needed.
171            connected: HashSet::new(),
172        }
173    }
174
175    /// Drain hardware events since the last call. Tracks connection state
176    /// so `connected_ids` stays live.
177    pub fn poll(&mut self) -> Vec<GamepadEvent> {
178        let Some(backend) = &mut self.backend else {
179            return Vec::new();
180        };
181        let events = backend.poll();
182        for ev in &events {
183            match ev {
184                GamepadEvent::Connected { id, .. } => {
185                    self.connected.insert(id.0);
186                }
187                GamepadEvent::Disconnected { id } => {
188                    self.connected.remove(&id.0);
189                }
190                GamepadEvent::Button { id, .. } | GamepadEvent::Axis { id, .. } => {
191                    self.connected.insert(id.0);
192                }
193            }
194        }
195        events
196    }
197
198    pub fn connected_ids(&self) -> Vec<GamepadId> {
199        let mut ids: Vec<GamepadId> = self.connected.iter().copied().map(GamepadId).collect();
200        ids.sort_by_key(|id| id.0);
201        ids
202    }
203
204    pub fn connected_count(&self) -> usize {
205        self.connected.len()
206    }
207}
208
209impl Default for GamepadPoller {
210    fn default() -> Self {
211        Self::new()
212    }
213}