aboutsummaryrefslogtreecommitdiffstats
path: root/src/render_loop.rs
blob: 628e6877d8cf9d6100dd1f5ec182312bec0911a6 (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use std::cell::UnsafeCell;
use std::rc::Rc;

use log::error;
use wasm_bindgen::prelude::*;

/// use `window.requestAnimationFrame()` to schedule calling a
/// function as long as the function returns true.
pub struct RenderLoop {
    inner: Rc<UnsafeCell<Closure<dyn FnMut(f64)>>>,
}

impl RenderLoop {
    fn request_animation_frame(f: &Closure<dyn FnMut(f64)>) -> Result<(), JsValue> {
        web_sys::window()
            .ok_or("no window")?
            .request_animation_frame(f.as_ref().unchecked_ref())?;
        Ok(())
    }

    /// `fun` takes a timestamp in the same space as the document
    /// timeline and returns a flag specifying whether we should
    /// schedule another frame..
    pub fn new<T: FnMut(f64) -> bool + 'static>(mut fun: T) -> Self {
        // init with stub closure because rust wants that, then change
        // it later once we have our rc clone.
        let inner = Rc::new(UnsafeCell::new(Closure::new(|_| {})));

        let rloop = inner.clone();
        let f = unsafe { &mut *inner.get() };
        *f = Closure::new(move |t| {
            if fun(t) {
                let cl = unsafe { &*rloop.get() };
                if let Err(e) = Self::request_animation_frame(cl) {
                    error!("couldn't request animation frame: {:?}", e);
                }
            }
        });

        Self { inner }
    }

    /// start animating.
    pub fn start(&self) -> Result<(), JsValue> {
        let cl = unsafe { &*self.inner.get() };
        Self::request_animation_frame(cl)?;
        Ok(())
    }
}

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