Commit eb8c895e authored by Rahix's avatar Rahix 🦀
Browse files

gamestate: Don't reschedule the loop

Turns out that e.g. an out-of-band event() will trigger the loop again,
thus leading to two loops running.  This of course kills performance
really quickly.
parent 4cf86eb5
......@@ -243,6 +243,7 @@ impl StateStorage {
pub struct StateMachine {
states: Vec<StateStorage>,
loop_handler: Option<closure::Closure<dyn FnMut(wasm_bindgen::JsValue)>>,
loop_scheduled: bool,
}
impl StateMachine {
......@@ -250,12 +251,23 @@ impl StateMachine {
let this = Rc::new(RefCell::new(StateMachine {
states: vec![StateStorage::new(initial)],
loop_handler: None,
loop_scheduled: false,
}));
// Sadly Rc::new_cyclic() isn't stable yet ...
let loop_handler = {
let this = this.clone();
closure::Closure::wrap(Box::new(move |_timestamp| {
{
let mut sm = this.borrow_mut();
if !sm.loop_scheduled {
// Running without being scheduled??
crate::console_warn!("Loop handler running without being scheduled!");
return;
}
sm.loop_scheduled = false;
}
// First, check if the event is still wanted by the current state
let t = {
let mut active = StateMachine::active(&this);
......@@ -303,13 +315,18 @@ impl StateMachine {
}
Transition::Loop => {
use wasm_bindgen::JsCast;
StateMachine::active(this).do_loop = Some(true);
let sm = this.borrow();
let loop_handler = sm.loop_handler.as_ref().unwrap();
utils::window()
.request_animation_frame(loop_handler.as_ref().unchecked_ref())
.unwrap();
// Only schedule if a loop was not already scheduled. Otherwise we'll end up
// with a lot of requestAnimationFrame() loops running in parallel.
if !this.borrow().loop_scheduled {
let mut sm = this.borrow_mut();
let loop_handler = sm.loop_handler.as_ref().unwrap();
utils::window()
.request_animation_frame(loop_handler.as_ref().unchecked_ref())
.unwrap();
sm.loop_scheduled = true;
}
None
}
Transition::Sleep => {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment