aboutsummaryrefslogtreecommitdiffstats
path: root/src/render_loop.rs
blob: 9b8d8f5ab26ab43a347011c86d0147b8f5048bfa (plain)
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
use std::cell::RefCell;
use std::rc::Rc;

use wasm_bindgen::prelude::*;

pub struct RenderLoop {
    inner: Rc<RefCell<Closure<dyn FnMut(f64)>>>,
}

impl RenderLoop {
    fn request_animation_frame(f: &Closure<dyn FnMut(f64)>) {
        web_sys::window()
            .expect("no window")
            .request_animation_frame(f.as_ref().unchecked_ref())
            .expect("should register `requestAnimationFrame` OK");
    }

    pub fn new<T: FnMut(f64) -> bool + 'static>(mut fun: T) -> Self {
        let inner = Rc::new(RefCell::new(Closure::new(|_| {})));
        let rloop = inner.clone();

        *inner.borrow_mut() = Closure::new(move |t| {
            if fun(t) {
                Self::request_animation_frame(&rloop.borrow());
            }
        });
        Self { inner }
    }

    pub fn start(&self) -> Result<(), JsValue> {
        Self::request_animation_frame(&self.inner.borrow());
        Ok(())
    }
}

impl Clone for RenderLoop {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}