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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use std::cell::RefCell;
use std::cell::Cell;
use std::rc::Rc;
use web_sys::{Window};
use log::{info};
use crate::errors::{Error};
use crate::window::{get_window};
#[derive(Copy, Clone, Debug)]
pub struct Timestamp {
pub time: f64,
pub delta: f64,
pub elapsed: f64,
}
pub fn start_raf_ticker_timestamp<F>(mut on_tick:F) -> Result<impl (FnOnce() -> ()), Error>
where F: (FnMut(Timestamp) -> ()) + 'static
{
let mut last_time:Option<f64> = None;
let mut first_time = 0f64;
start_raf_ticker(move |time| {
match last_time {
Some(last_time) => {
on_tick(Timestamp{
time,
delta: time - last_time,
elapsed: time - first_time
});
}
None => {
on_tick(Timestamp{
time,
delta: 0.0,
elapsed: 0.0,
});
first_time = time;
}
}
last_time = Some(time);
})
}
pub fn start_raf_ticker<F>(mut on_tick:F) -> Result<impl (FnOnce() -> ()), Error>
where F: (FnMut(f64) -> ()) + 'static
{
let f = Rc::new(RefCell::new(None));
let g = f.clone();
let keep_alive = Rc::new(Cell::new(true));
let mut raf_id:Option<i32> = None;
let window = get_window()?;
{
let keep_alive = Rc::clone(&keep_alive);
*g.borrow_mut() = Some(Closure::wrap(Box::new(move |time| {
if !keep_alive.get() {
if let Some(id) = raf_id {
info!("clearing raf id: {}", id);
window.cancel_animation_frame(id).unwrap();
}
f.borrow_mut().take();
} else {
on_tick(time);
raf_id = request_animation_frame(&window, f.borrow().as_ref().unwrap()).ok();
}
}) as Box<dyn FnMut(f64)-> ()>));
}
let window = get_window()?;
request_animation_frame(&window, g.borrow().as_ref().unwrap())?;
let cancel = move || keep_alive.set(false);
Ok(cancel)
}
fn request_animation_frame(window:&Window, f: &Closure<dyn FnMut(f64) -> ()>) -> Result<i32, Error> {
window.request_animation_frame(f.as_ref().unchecked_ref()).map_err(|e| e.into())
}