Skip to content

Commit

Permalink
refactor: simplify the main update loop
Browse files Browse the repository at this point in the history
  • Loading branch information
FaultyRAM committed May 18, 2024
1 parent 43acac7 commit 927d87b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 19 deletions.
7 changes: 3 additions & 4 deletions core/src/game_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,18 @@ pub struct GameState {
}

impl GameState {
pub fn new() -> Self {
pub fn new(timestamp: Timestamp) -> Self {
let mut world = World::new();
let mut schedule = Schedule::default();
let timestamp = Timestamp::now();
world.insert_resource::<Time<Real>>(Time::at(timestamp));
world.insert_resource(Credits::new());
schedule.add_systems((update_credits, update_ui).chain());
Self { world, schedule }
}

pub fn update(&mut self, timestamp: f64) {
pub fn update(&mut self, timestamp: Timestamp) {
let mut real_time: Mut<Time<Real>> = self.world.resource_mut();
real_time.advance_to(Timestamp::at(timestamp));
real_time.advance_to(timestamp);
self.schedule.run(&mut self.world);
}
}
Expand Down
28 changes: 13 additions & 15 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,28 @@ mod time;
mod ui;

use game_state::GameState;
use std::{
cell::RefCell,
rc::Rc,
sync::{Mutex, OnceLock},
};
use std::sync::{Mutex, OnceLock};
use time::Timestamp;
use wasm_bindgen::prelude::*;

static GAME_STATE: OnceLock<Mutex<GameState>> = OnceLock::new();

fn request_animation_frame(f: &Closure<dyn Fn(f64)>) {
fn request_animation_frame(f: impl 'static + Fn(f64)) {
let update_cb: Closure<dyn Fn(f64)> = Closure::new(f);
let window = web_sys::window().unwrap();
let _ = window
.request_animation_frame(f.as_ref().unchecked_ref())
.request_animation_frame(update_cb.into_js_value().unchecked_ref())
.unwrap();
}

fn update(timestamp: f64) {
let timestamp = Timestamp::at(timestamp);
let game_state = GAME_STATE.get_or_init(|| Mutex::new(GameState::new(timestamp)));
game_state.lock().unwrap().update(timestamp);
request_animation_frame(update);
}

#[wasm_bindgen(start)]
fn run() {
GAME_STATE.set(Mutex::new(GameState::new())).unwrap();
let update_cb = Rc::new(RefCell::new(None));
let ucb_clone = update_cb.clone();
*ucb_clone.borrow_mut() = Some(Closure::new(move |timestamp| {
GAME_STATE.get().unwrap().lock().unwrap().update(timestamp);
request_animation_frame(update_cb.borrow().as_ref().unwrap());
}));
request_animation_frame(ucb_clone.borrow().as_ref().unwrap());
request_animation_frame(update);
}

0 comments on commit 927d87b

Please sign in to comment.