@@ -23,6 +23,53 @@ mod shaders {
2323 include ! ( concat!( env!( "OUT_DIR" ) , "/entry_points.rs" ) ) ;
2424}
2525
26+ /// Abstraction for getting timestamps even when `std::time` isn't supported.
27+ enum PortableInstant {
28+ #[ cfg( not( target_arch = "wasm32" ) ) ]
29+ Native ( std:: time:: Instant ) ,
30+
31+ #[ cfg( target_arch = "wasm32" ) ]
32+ Web {
33+ performance_timestamp_ms : f64 ,
34+
35+ // HACK(eddyb) cached `window().performance()` to speed up/simplify `elapsed`.
36+ cached_window_performance : web_sys:: Performance ,
37+ } ,
38+ }
39+
40+ impl PortableInstant {
41+ fn now ( ) -> Self {
42+ #[ cfg( not( target_arch = "wasm32" ) ) ]
43+ {
44+ Self :: Native ( std:: time:: Instant :: now ( ) )
45+ }
46+ #[ cfg( target_arch = "wasm32" ) ]
47+ {
48+ let performance = web_sys:: window ( )
49+ . expect ( "missing window" )
50+ . performance ( )
51+ . expect ( "missing window.performance" ) ;
52+ Self :: Web {
53+ performance_timestamp_ms : performance. now ( ) ,
54+ cached_window_performance : performance,
55+ }
56+ }
57+ }
58+
59+ fn elapsed_secs_f32 ( & self ) -> f32 {
60+ match self {
61+ #[ cfg( not( target_arch = "wasm32" ) ) ]
62+ Self :: Native ( instant) => instant. elapsed ( ) . as_secs_f32 ( ) ,
63+
64+ #[ cfg( target_arch = "wasm32" ) ]
65+ Self :: Web {
66+ performance_timestamp_ms,
67+ cached_window_performance,
68+ } => ( ( cached_window_performance. now ( ) - performance_timestamp_ms) / 1000.0 ) as f32 ,
69+ }
70+ }
71+ }
72+
2673fn mouse_button_index ( button : MouseButton ) -> usize {
2774 match button {
2875 MouseButton :: Left => 0 ,
@@ -143,7 +190,7 @@ async fn run(
143190 compiled_shader_modules,
144191 ) ;
145192
146- let start = std :: time :: Instant :: now ( ) ;
193+ let start = PortableInstant :: now ( ) ;
147194
148195 let ( mut cursor_x, mut cursor_y) = ( 0.0 , 0.0 ) ;
149196 let ( mut drag_start_x, mut drag_start_y) = ( 0.0 , 0.0 ) ;
@@ -262,7 +309,7 @@ async fn run(
262309 ..Default :: default ( )
263310 } ) ;
264311
265- let time = start. elapsed ( ) . as_secs_f32 ( ) ;
312+ let time = start. elapsed_secs_f32 ( ) ;
266313 for ( i, press_time) in mouse_button_press_time. iter_mut ( ) . enumerate ( ) {
267314 if ( mouse_button_press_since_last_frame & ( 1 << i) ) != 0 {
268315 * press_time = time;
0 commit comments