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
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/*!
 * Time utilities
 */

pub use monotonic_clock::{
    Clock, TimeStats, FrameRateCounter, FloatDuration, FixedStep, VariableStep, FloatInstant
};
use rin_events::PropertyLastValue;
use std::time::Duration;
#[cfg(feature="web")]
use std::time::Instant;
#[cfg(feature="web")]
use std::mem;
use rinecs::{EntitiesThreadLocal, ResourcesThreadLocal, SystemThreadLocal};
use crate::Bundle;
#[cfg(feature="gl")]
use color::consts::*;
#[cfg(any(feature="desktop", feature="desktop_gles", feature="web"))]
use rin_window::{self as window, Window};
#[cfg(feature="gl")]
use rin_graphics::Mvp;
#[cfg(feature="gl")]
use rin_math::pnt2;
use rin_math::Pnt2;
use crate::DeferredScene;
#[cfg(gui)]
use rin_gui::{self as gui, ParameterGroup, EnumParam};
#[cfg(gui)]
use rin_events::{StreamExt, Property, RangedPropertyMut, RangedProperty, TryIter};

#[cfg(any(feature="desktop", feature="desktop_gles", feature="web"))]
use rin_gl as gl;
#[cfg(any(feature="desktop", feature="desktop_gles", feature="web"))]
use rinecs::system_thread_local;

#[cfg(gui)]
#[derive(EnumParam)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StepType{
    Variable,
    Fixed,
}

#[cfg(gui)]
#[derive(Clone, Copy, Debug)]
pub enum Step{
    Variable,
    Fixed(u32)
}

#[cfg(gui)]
#[derive(ParameterGroup)]
pub struct Time{
    time_factor: gui::group_v::Tuple<(
        gui::group_h::Tuple<(
            Property<'static, ()>,
            gui::SepH,
            gui::Styled<RangedPropertyMut<'static, f64>>
        )>,
        gui::FontRelativeSep,
        gui::group_h::Tuple<(
            gui::Styled<String>,
            gui::Styled<gui::AsControl<gui::TextBox<f64>, Property<'static, f64>>>,
        )>
    )>,

    fps: RangedProperty<'static, f32>,

    #[gui(not_parameter)]
    fps_p: Property<'static, f32>,

    time_last_frame: RangedProperty<'static, f32>,
    time_last_frame_min: RangedProperty<'static, f32>,
    time_last_frame_max: RangedProperty<'static, f32>,

    #[gui(not_parameter)]
    time_last_frame_p: Property<'static, f32>,
    #[gui(not_parameter)]
    time_last_frame_min_p: Property<'static, f32>,
    #[gui(not_parameter)]
    time_last_frame_max_p: Property<'static, f32>,

    step_type: Property<'static, StepType>,

    fixed_step: RangedPropertyMut<'static, u32>,
}

#[cfg(not(gui))]
pub struct Time{
}

impl Time {
    #[cfg(gui)]
    pub fn new() -> Time {
        let reset_button = Property::new(());
        let time_factor = reset_button.clone().stream().map(|_| 1.)
            .to_property(1.);
        let time_factor = RangedPropertyMut::from_property_log_scale(time_factor, 0. .. 10.);
        let time_label = "time factor: ".to_string();
        let fps_p = Property::new(60.);
        let fps = RangedProperty::new(fps_p.clone(), 0. .. 120.);
        let time_last_frame_p = Property::new(16.);
        let time_last_frame = RangedProperty::new(time_last_frame_p.clone(), 0. .. 1000.);
        let time_last_frame_min_p = Property::new(16.);
        let time_last_frame_min = RangedProperty::new(time_last_frame_min_p.clone(), 0. .. 1000.);
        let time_last_frame_max_p = Property::new(16.);
        let time_last_frame_max = RangedProperty::new(time_last_frame_max_p.clone(), 0. .. 1000.);
        let time_factor_p = time_factor.clone().into_property();
        let time_factor_textbox = gui::styled(
            gui::as_control!(gui::TextBox<f64>, time_factor_p),
            serde_json::from_str(r#"{
                "border": false
            }"#).unwrap());
        let time_factor = gui::styled(
            time_factor,
            serde_json::from_str(r#"{
                "label_as_textbox": false
            }"#).unwrap());
        let time_label = gui::styled(
            time_label,
            serde_json::from_str(r#"{
                "full_width": false
            }"#).unwrap());
        Time {
            time_factor: gui::group_v!{
                gui::group_h!(
                    reset_button,
                    gui::SepH(10.),
                    time_factor
                ),
                gui::FontRelativeSep::VLineGap(0.5),
                gui::group_h!(
                    time_label,
                    time_factor_textbox
                )
            },
            fps,
            fps_p,
            time_last_frame,
            time_last_frame_min,
            time_last_frame_max,
            time_last_frame_p,
            time_last_frame_min_p,
            time_last_frame_max_p,
            step_type: Property::new(StepType::Variable),
            fixed_step: RangedPropertyMut::new_log_scale(16, 0 .. 3000),
        }
    }

    #[cfg(not(gui))]
    pub fn new() -> Time{
        Time{}
    }

    #[cfg(gui)]
    fn parameters(&self) -> Parameters{
        let tuple_h = &self.time_factor.parameters().0;
        // let time_factor = tuple_h.parameters().0.clone().stream().map(|_| 1.)
        //     .connect_to_property(&mut tuple_h.parameters().2.parameter().clone().into_property())
        //     .merge(tuple_h.parameters().2.parameter().clone().stream())
        //     .to_property(1.);
        let mut time_factor = tuple_h.parameters().2.parameter()
            .clone()
            .into_property()
            .into_property_last_value();
        time_factor.last_value();
        let fps = self.fps_p.clone();
        let time_last_frame_min = self.time_last_frame_min_p.clone();
        let time_last_frame_max = self.time_last_frame_max_p.clone();
        let time_last_frame = self.time_last_frame_p.clone();
        Parameters{
            time_factor,
            fps,
            time_last_frame,
            time_last_frame_min,
            time_last_frame_max,
            time_last_frame_min_current: None,
            time_last_frame_max_current: None,
            time_last_second: None,
            step_type: self.step_type.clone(),
            fixed_step: self.fixed_step.clone().into_property(),
            step: self.step_type.clone().zip(self.fixed_step.clone().into_property())
                .map(|(ty, fixed)|{
                    match ty{
                        StepType::Variable => Step::Variable,
                        StepType::Fixed => Step::Fixed(fixed)
                    }
                })
        }
    }
}

#[cfg(gui)]
pub struct Parameters{
    pub time_factor: PropertyLastValue<'static, f64>,
    fps: Property<'static, f32>,
    time_last_frame: Property<'static, f32>,
    time_last_frame_min: Property<'static, f32>,
    time_last_frame_max: Property<'static, f32>,
    time_last_frame_min_current: Option<f32>,
    time_last_frame_max_current: Option<f32>,
    time_last_second: Option<FloatDuration>,
    step: Property<'static, Step>,
    pub step_type: Property<'static, StepType>,
    pub fixed_step: Property<'static, u32>,
}

impl Bundle for Time{
    type Parameters = Self;

    fn parameters(&self) -> Option<&Self> {
        Some(self)
    }

    fn name(&self) -> &str{
        "time"
    }

    fn setup(self, world: &mut DeferredScene){
        #[cfg(not(feature="web"))]
        world.add_resource(Clock::new());
        #[cfg(feature="web")]
        world.add_resource(Clock::new_with_wall_time(FloatInstant::from_secs_f64(0.)));
        world.add_resource(FrameRateCounter::new(Duration::from_secs(2)));

        #[cfg(gui)]
        world.add_resource_thread_local(self.parameters());
    }
}

// #[system_thread_local(name = "update clock")]
// #[updates("Clock")]
// #[cfg_attr(not(feature="web"), updates("FrameCounter"))]
pub(crate) fn reset_clock(resources: ResourcesThreadLocal){
    let mut clock = resources.get_mut::<Clock>().unwrap();
    let mut step = monotonic_clock::FixedStep::new(FloatDuration::from_nanoseconds(0));
    #[cfg(feature="web")]
    let now = FloatInstant::from_secs_f64(0.);

    #[cfg(gui)]
    {
        let mut parameters = resources.get_mut::<Parameters>().unwrap();
        if let Some(factor) = parameters.time_factor.last_value() {
            clock.set_multiplier(*factor);
        }


        #[cfg(not(feature="web"))]
        clock.tick(&mut step);

        #[cfg(feature="web")]
        clock.tick_with_wall_time(&mut step, now);

        resources.get_mut::<FrameRateCounter>()
            .unwrap()
            .tick(clock.instant_at_frame_start());

        let fps = resources.get::<FrameRateCounter>().unwrap().fps() as f32;
        parameters.fps.set(fps);
        parameters.time_last_second = Some(clock.wall_time());
        let t_last_frame = clock.wall_time_delta().as_milliseconds() as f32;
        parameters.time_last_frame.set(t_last_frame);
        parameters.time_last_frame_min.set(t_last_frame);
        parameters.time_last_frame_max.set(t_last_frame);
        parameters.time_last_frame_min_current = Some(t_last_frame);
    }


    #[cfg(not(gui))]
    {
        #[cfg(not(feature="web"))]
        clock.tick(&mut step);

        #[cfg(feature="web")]
        clock.tick_with_wall_time(&mut step, now);

        resources.get_mut::<FrameRateCounter>()
            .unwrap()
            .tick(clock.instant_at_frame_start());
    }
}

// #[system_thread_local(name = "update clock")]
// #[updates("Clock")]
// #[cfg_attr(not(feature="web"), updates("FrameCounter"))]
pub(crate) fn update_clock(resources: ResourcesThreadLocal){
    let mut clock = resources.get_mut::<Clock>().unwrap();

    #[cfg(gui)]
    {
        let mut parameters = resources.get_mut::<Parameters>().unwrap();
        if let Some(factor) = parameters.time_factor.last_value() {
            clock.set_multiplier(*factor);
        }

        #[cfg(not(feature="web"))]
        {
            if let Step::Fixed(step) = *parameters.step.get() {
                let step = FloatDuration::from_milliseconds(step as u64);
                clock.tick(&mut monotonic_clock::FixedStep::new(step))
            }else{
                clock.tick(&mut monotonic_clock::VariableStep::new())
            }
        }

        resources.get_mut::<FrameRateCounter>()
            .unwrap()
            .tick(clock.instant_at_frame_start());


        let t_to_second = clock.wall_time() - *parameters.time_last_second.get_or_insert(clock.wall_time());
        let t_last_frame = clock.wall_time_delta().as_milliseconds() as f32;
        if t_to_second >= FloatDuration::from_seconds(1) {
            let t_last_frame_min = parameters.time_last_frame_min_current.unwrap();
            parameters.time_last_frame_min.set(t_last_frame_min);
            let t_last_frame_max = parameters.time_last_frame_max_current.unwrap();
            parameters.time_last_frame_max.set(t_last_frame_max);
            parameters.time_last_frame_min_current = Some(t_last_frame);
            parameters.time_last_frame_max_current = Some(t_last_frame);
            parameters.time_last_second = Some(clock.wall_time());
        }
        let t_last_frame_min = parameters.time_last_frame_min_current.get_or_insert(t_last_frame);
        *t_last_frame_min = t_last_frame_min.min(t_last_frame);
        let t_last_frame_max = parameters.time_last_frame_max_current.get_or_insert(t_last_frame);
        *t_last_frame_max = t_last_frame_max.max(t_last_frame);
        parameters.time_last_frame.set(t_last_frame);
        parameters.fps.set(resources.get::<FrameRateCounter>().unwrap().fps() as f32);
    }


    #[cfg(not(any(gui, feature="web")))]
    {
        clock.tick(&mut monotonic_clock::VariableStep::new());
        resources.get_mut::<FrameRateCounter>()
            .unwrap()
            .tick(clock.instant_at_frame_start());
    }
}

#[cfg(feature="web")]
pub(crate) fn update_clock_with_wall_time(resources: ResourcesThreadLocal, wall_time_secs: f64){
    let mut clock = resources.get_mut::<Clock>().unwrap();
    let now = FloatInstant::from_secs_f64(wall_time_secs);

    #[cfg(gui)]
    {
        let mut parameters = resources.get_mut::<Parameters>().unwrap();
        if let Some(factor) = parameters.time_factor.last_value() {
            clock.set_multiplier(*factor);
        }

        if let Step::Fixed(step) = *parameters.step.get() {
            let step = FloatDuration::from_milliseconds(step as u64);
            clock.tick_with_wall_time(&mut monotonic_clock::FixedStep::new(step), now)
        }else{
            clock.tick_with_wall_time(&mut monotonic_clock::VariableStep::new(), now)
        }

        resources.get_mut::<FrameRateCounter>()
            .unwrap()
            .tick(clock.instant_at_frame_start());

        parameters.fps.set(resources.get::<FrameRateCounter>().unwrap().fps() as f32);
        parameters.time_last_frame.set(clock.wall_time_delta().as_milliseconds() as f32);
    }

    #[cfg(not(gui))]
    {
        clock.tick_with_wall_time(&mut monotonic_clock::VariableStep::new(), now);
        resources.get_mut::<FrameRateCounter>()
            .unwrap()
            .tick(clock.instant_at_frame_start());
    }
}

pub enum Placement{
    TopRight,
    BottomRight,
    TopLeft,
    BottomLeft,
    Custom(Pnt2),
}

pub struct FpsRenderer{
    placement: Placement
}

impl FpsRenderer{
    pub fn new(placement: Placement) -> FpsRenderer{
        FpsRenderer{ placement }
    }
}

#[cfg(any(feature="desktop", feature="desktop_gles", feature="web"))]
#[system_thread_local(name = "draw fps")]
#[cfg_attr(gui, after(crate::gui::gui_renderer))]
#[needs(Window, FrameRateCounter)]
#[reads(gl::Renderer)]
impl SystemThreadLocal for FpsRenderer{
    fn run(&mut self, _entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
        let glin = resources.get::<gl::Renderer<'static>>().unwrap();
        let window = resources.as_trait::<dyn window::WindowExt>().unwrap();
        let viewport = window.viewport();
        let glin = glin.with_mvp(Mvp::ortho_top_left(window.viewport()));
        let pos = match self.placement {
            Placement::TopRight => pnt2(viewport.width as f32 - 60., 20.),
            Placement::BottomRight => pnt2(viewport.width as f32 - 60., viewport.height as f32 - 20.),
            Placement::TopLeft => pnt2(20., 20.),
            Placement::BottomLeft => pnt2(20., viewport.height as f32 - 20.),
            Placement::Custom(pos) => pos
        };

        if let Some(fps) = resources.get::<FrameRateCounter>().map(|counter| counter.fps()) {
            glin.draw_bitmap_string(&format!("{:#.02}", fps), &pos, &WHITE);
        }
    }
}