mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! The schedule of placements: when the next may run, how far the fade of
//! the current one has come, and the engine's half of each placement.

use std::sync::Arc;
use std::time::Duration;

use mln_style::TransitionOptions;
use mln_style::constants::DEFAULT_TRANSITION_DURATION;
use mln_style::time::Instant;

use super::{CollisionIndex, PlacedSymbolData, TestedShape};
use crate::camera::View;
use crate::map::MapMode;
use crate::placement::Placed;
use crate::render::terrain::TerrainElevation;
use crate::render::update_parameters::UpdateParameters;

/// What of a placement's inputs the engine compares: the rest is each
/// participant's ([`Prepared::changed`](super::Prepared::changed)).
#[derive(Clone)]
pub(crate) struct PlacementInputs {
    mode: MapMode,
    view: View,
    transition_options: TransitionOptions,
    /// The map's [`fade_duration`](crate::map::MapOptions::fade_duration).
    fade_duration: Option<Duration>,
    /// Whether what shows fades, or shows at once.
    fades: bool,
    cross_source_collisions: bool,
    /// The ground the marks stand on, where terrain draws.
    ground: PlacedGround,
}

/// Inputs that would place the same. The fade only times placements.
impl PartialEq for PlacementInputs {
    fn eq(&self, other: &Self) -> bool {
        self.mode == other.mode
            && self.view == other.view
            && self.transition_options == other.transition_options
            && self.cross_source_collisions == other.cross_source_collisions
            && self.ground == other.ground
    }
}

/// The ground a placement's marks stand on: the renderer's ground of the
/// frame, which is a new one once it draws a different surface, so it
/// equals only itself.
#[derive(Clone, Default)]
struct PlacedGround(Option<Arc<TerrainElevation>>);

impl PartialEq for PlacedGround {
    fn eq(&self, other: &Self) -> bool {
        match (&self.0, &other.0) {
            (Some(a), Some(b)) => Arc::ptr_eq(a, b),
            (a, b) => a.is_none() && b.is_none(),
        }
    }
}

impl PlacementInputs {
    /// The inputs of placing at `update_parameters`, on `ground` where
    /// terrain draws.
    pub(crate) fn new(update_parameters: &UpdateParameters, ground: Option<&Arc<TerrainElevation>>) -> Self {
        PlacementInputs {
            mode: update_parameters.mode,
            view: update_parameters.view.clone(),
            transition_options: update_parameters.style.transition_options(),
            fade_duration: update_parameters.fade_duration,
            fades: update_parameters.fades,
            cross_source_collisions: update_parameters.cross_source_collisions,
            ground: PlacedGround(ground.cloned()),
        }
    }

    pub(crate) fn mode(&self) -> MapMode {
        self.mode
    }

    pub(crate) fn view(&self) -> &View {
        &self.view
    }

    pub(crate) fn ground(&self) -> Option<&TerrainElevation> {
        self.ground.0.as_deref()
    }
}

pub(crate) struct PlacementController {
    placement: PlacementState,
    commits: u64,
}

impl Default for PlacementController {
    fn default() -> Self {
        PlacementController::new()
    }
}

impl PlacementController {
    #[must_use]
    pub(crate) fn new() -> Self {
        PlacementController { placement: PlacementState::new_default(), commits: 0 }
    }

    /// Commits `placement`.
    pub(crate) fn set_placement(&mut self, placement: PlacementState) {
        self.placement = placement;
        self.commits += 1;
    }

    /// How many placements the controller has committed, each reset to the
    /// empty placement included.
    #[must_use]
    pub(crate) fn commits(&self) -> u64 {
        self.commits
    }

    /// Whether placing again from `inputs` would change the placement: they
    /// differ from the placement's own, or what it shows was still fading
    /// when it was made, which the first placement after the fade ends
    /// brings to its end. A participant says whether its own inputs
    /// changed.
    #[must_use]
    pub(crate) fn is_stale(&self, inputs: &PlacementInputs) -> bool {
        self.placement.inputs.as_ref() != Some(inputs) || !self.placement.settled
    }

    /// Takes the current placement, for the next one to place against,
    /// leaving the empty placement.
    pub(crate) fn take_placement(&mut self) -> PlacementState {
        std::mem::replace(&mut self.placement, PlacementState::new_default())
    }

    /// Commits the empty placement; returns whether a placement of anything
    /// was discarded.
    pub(crate) fn reset(&mut self) -> bool {
        let changed = self.placement.inputs.is_some();
        if changed {
            self.placement = PlacementState::new_default();
        }
        self.commits += 1;
        changed
    }

    #[must_use]
    pub(crate) fn placement(&self) -> &PlacementState {
        &self.placement
    }

    pub(crate) fn placement_mut(&mut self) -> &mut PlacementState {
        &mut self.placement
    }

    /// When the next placement from `inputs` may run: an update period at
    /// their zoom and fade duration, or `period_override` if it is shorter,
    /// after this one; `None` for at once, as where placements don't fade.
    #[must_use]
    pub(crate) fn next_placement_at(
        &self,
        inputs: &PlacementInputs,
        period_override: Option<Duration>,
    ) -> Option<Instant> {
        if !self.placement.transitions_enabled() {
            return None;
        }
        let update_period = self.placement.update_period(inputs.view.zoom() as f32, inputs.fade_duration);
        let update_period = period_override.map_or(update_period, |period| period.min(update_period));
        self.placement.commit_time?.checked_add(update_period)
    }

    /// Whether what shows still fades at `now`.
    #[must_use]
    pub(crate) fn has_transitions(&self, now: Option<Instant>) -> bool {
        self.placement.transitions_enabled() && self.placement.has_transitions(now)
    }
}

/// How long after `since` `now` is: zero if it is before, and
/// `Duration::MAX` without either time, as for a time long ago.
fn elapsed(now: Option<Instant>, since: Option<Instant>) -> Duration {
    match (now, since) {
        (Some(now), Some(since)) => now.saturating_duration_since(since),
        _ => Duration::MAX,
    }
}

/// The engine's half of a placement: its collision index, its records,
/// and its fade. Continuous mode fades from the placement before; static
/// and tile modes show what they place at once, and tile mode places across
/// its tile's borders.
pub(crate) struct PlacementState {
    /// What the placement places from; `None` for the empty placement.
    inputs: Option<PlacementInputs>,
    collision_index: CollisionIndex,

    transition_options: TransitionOptions,

    /// When what shows last began to fade; `None` for long ago.
    fade_start_time: Option<Instant>,
    /// The time of the update that placed; `None` for long ago.
    commit_time: Option<Instant>,
    placement_zoom: f32,
    prev_zoom_adjustment: f32,

    /// The placement this one replaces, which its commit reads and drops.
    prev_placement: Option<Box<PlacementState>>,
    /// The collision index of the placement this one replaced, which its
    /// commit no longer reads; the next placement reuses its grids.
    spare_collision_index: Option<CollisionIndex>,
    /// Everything that shows was at the end of its fade when the placement
    /// was made.
    settled: bool,

    /// What a tile-mode placement placed, while it collects it.
    records: Option<Vec<PlacedSymbolData>>,
    /// The shapes the placement tested, while it records them: the
    /// placement alone holds them while it places.
    tested: Option<Arc<Vec<TestedShape>>>,
}

impl PlacementState {
    /// The initial placement of a `PlacementController`.
    #[must_use]
    pub(crate) fn new_default() -> Self {
        PlacementState::new(None, CollisionIndex::new(&View::default(), MapMode::Static), None)
    }

    fn new(
        inputs: Option<PlacementInputs>,
        collision_index: CollisionIndex,
        prev_placement: Option<PlacementState>,
    ) -> Self {
        PlacementState {
            collision_index,
            transition_options: inputs.as_ref().map(|inputs| inputs.transition_options).unwrap_or_default(),
            fade_start_time: None,
            commit_time: None,
            placement_zoom: inputs.as_ref().map_or(0.0, |inputs| inputs.view.zoom() as f32),
            prev_zoom_adjustment: 0.0,
            prev_placement: prev_placement.map(Box::new),
            spare_collision_index: None,
            settled: false,
            records: None,
            tested: None,
            inputs,
        }
    }

    /// A new placement from `inputs`, at `time_point`, the frame's time. In
    /// continuous mode, `prev_placement` must be provided.
    pub(crate) fn create(
        inputs: PlacementInputs,
        time_point: Option<Instant>,
        prev_placement: Option<PlacementState>,
    ) -> PlacementState {
        let mut prev_placement = match inputs.mode {
            MapMode::Continuous => {
                debug_assert!(prev_placement.is_some());
                prev_placement
            }
            MapMode::Static | MapMode::Tile => None,
        };
        let spare_index = prev_placement.as_mut().and_then(|prev| prev.spare_collision_index.take());
        let collision_index = CollisionIndex::reusing(&inputs.view, inputs.mode, spare_index);
        PlacementState { commit_time: time_point, ..PlacementState::new(Some(inputs), collision_index, prev_placement) }
    }

    pub(crate) fn collision_index(&self) -> &CollisionIndex {
        &self.collision_index
    }

    /// The placement's index, and the ground its marks stand on, where
    /// terrain draws.
    pub(crate) fn index_and_ground(&mut self) -> (&mut CollisionIndex, Option<&TerrainElevation>) {
        (&mut self.collision_index, self.inputs.as_ref().and_then(PlacementInputs::ground))
    }

    /// The placement's index, its inputs, its records and the shapes it
    /// tested, while it places.
    pub(crate) fn placing(&mut self) -> Placing<'_> {
        Placing {
            index: &mut self.collision_index,
            inputs: self.inputs.as_ref(),
            records: self.records.as_mut(),
            tested: self.tested.as_mut().and_then(Arc::get_mut),
        }
    }

    /// How far the fade of the placement this one replaces had come at this
    /// one's commit: 1 for a still image's.
    pub(crate) fn commit_fade(&mut self) -> f32 {
        if self.mode() != MapMode::Continuous {
            return 1.0;
        }
        let Some(prev) = &self.prev_placement else {
            debug_assert!(false, "a continuous placement replaces one");
            return 1.0;
        };
        self.prev_zoom_adjustment = prev.zoom_adjustment(self.placement_zoom);
        prev.fade(self.commit_time)
    }

    /// Ends the commit of a placement that changed what shows as `placed`
    /// says: a continuous map's fade starts again where it changed.
    pub(crate) fn end_commit(&mut self, placed: Placed) {
        if self.mode() != MapMode::Continuous {
            self.fade_start_time = self.commit_time;
            return;
        }
        let Some(prev) = self.prev_placement.take() else {
            return;
        };
        self.fade_start_time = if placed.changed { self.commit_time } else { prev.fade_start_time };
        self.settled = placed.settled;
        self.spare_collision_index = Some(prev.collision_index);
    }

    fn mode(&self) -> MapMode {
        self.inputs.as_ref().map_or(MapMode::Continuous, |inputs| inputs.mode)
    }

    /// How far what shows has faded at `now`, from 0 to 1 and past it once
    /// it is done: always 1 where nothing fades.
    pub(crate) fn fade(&self, now: Option<Instant>) -> f32 {
        let duration = self.fade_duration();
        if self.transitions_enabled() && duration > Duration::ZERO {
            return elapsed(now, self.commit_time).div_duration_f32(duration) + self.prev_zoom_adjustment;
        }
        1.0
    }

    fn fade_duration(&self) -> Duration {
        match &self.inputs {
            Some(inputs) if !inputs.fades => Duration::ZERO,
            inputs => inputs
                .as_ref()
                .and_then(|inputs| inputs.fade_duration)
                .or(self.transition_options.duration)
                .unwrap_or(DEFAULT_TRANSITION_DURATION),
        }
    }

    /// How much quicker what shows fades, and placements run, while the map
    /// zooms out from the placement's zoom to `zoom`, where labels come to
    /// overlap quickly.
    fn zoom_adjustment(&self, zoom: f32) -> f32 {
        ((self.placement_zoom - zoom) / 1.5).max(0.0)
    }

    /// How long after this placement the next may run, at `zoom`, for the
    /// map's fade duration then.
    fn update_period(&self, zoom: f32, map_fade_duration: Option<Duration>) -> Duration {
        // The map's fade duration is the period. Without one, even with a
        // transition shorter than the default, placement waits for the
        // default before it runs again. Either is zero once the zoom
        // adjustment passes 1.
        let style_duration = self.transition_options.duration.unwrap_or(DEFAULT_TRANSITION_DURATION);
        let fade_duration = map_fade_duration.unwrap_or(style_duration.max(DEFAULT_TRANSITION_DURATION));
        fade_duration.mul_f64(f64::from(1.0 - self.zoom_adjustment(zoom)).max(0.0))
    }

    /// Whether what shows fades between placements: only in continuous
    /// mode, where the style enables placement transitions.
    fn transitions_enabled(&self) -> bool {
        self.mode() == MapMode::Continuous && self.transition_options.enable_placement_transitions
    }

    /// Whether what shows still fades at `now`.
    fn has_transitions(&self, now: Option<Instant>) -> bool {
        self.transitions_enabled() && elapsed(now, self.fade_start_time) < self.fade_duration()
    }

    /// Collects the records of what a tile-mode placement places, or not.
    pub(crate) fn collect_records(&mut self, enable: bool) {
        self.records = (enable && self.mode() == MapMode::Tile).then(Vec::new);
    }

    /// What a tile-mode placement placed, while it collected it.
    pub(crate) fn records(&self) -> &[PlacedSymbolData] {
        self.records.as_deref().unwrap_or_default()
    }

    /// Records the shapes the placement tests, or not.
    pub(crate) fn record_tested(&mut self, enable: bool) {
        self.tested = enable.then(Arc::default);
    }

    /// The shapes the placement tested, if it recorded them.
    pub(crate) fn tested(&self) -> Option<&Arc<Vec<TestedShape>>> {
        self.tested.as_ref()
    }
}

/// What a placement changes while it places ([`PlacementState::placing`]).
pub(crate) struct Placing<'a> {
    pub(crate) index: &'a mut CollisionIndex,
    pub(crate) inputs: Option<&'a PlacementInputs>,
    pub(crate) records: Option<&'a mut Vec<PlacedSymbolData>>,
    pub(crate) tested: Option<&'a mut Vec<TestedShape>>,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn inputs() -> PlacementInputs {
        PlacementInputs {
            mode: MapMode::Continuous,
            view: View::default(),
            transition_options: TransitionOptions::default(),
            fade_duration: None,
            fades: true,
            cross_source_collisions: true,
            ground: PlacedGround::default(),
        }
    }

    /// The placement from `inputs` at `time`, after `controller`'s, which
    /// changed what shows and is settled as `placed` says.
    fn place(controller: &mut PlacementController, time: Instant, placed: Placed) {
        let prev = controller.take_placement();
        let mut placement = PlacementState::create(inputs(), Some(time), Some(prev));
        placement.commit_fade();
        placement.end_commit(placed);
        controller.set_placement(placement);
    }

    /// The map's fade duration times the fade and the next placement,
    /// apart from the style's transition, down to none. Before the map
    /// fades, what shows shows at once, on the same schedule.
    #[test]
    fn the_maps_fade_duration_times_the_fade_and_the_next_placement() {
        let start = crate::tests::start_time();
        let fade_at_50ms = |fade_duration, fades| {
            let mut controller = PlacementController::new();
            let prev = controller.take_placement();
            let inputs = PlacementInputs { fade_duration, fades, ..inputs() };
            let mut placement = PlacementState::create(inputs.clone(), Some(start), Some(prev));
            placement.commit_fade();
            placement.end_commit(Placed { changed: true, settled: false });
            controller.set_placement(placement);
            let period = controller.next_placement_at(&inputs, None).map(|at| at - start);
            // A shorter period overrides it; a longer one doesn't.
            let sooner = controller.next_placement_at(&inputs, Some(Duration::from_millis(30))).map(|at| at - start);
            assert_eq!(sooner, period.map(|period| period.min(Duration::from_millis(30))));
            (period, controller.placement().fade(Some(start + Duration::from_millis(50))))
        };
        let (period, fade) = fade_at_50ms(None, true);
        assert_eq!(period, Some(DEFAULT_TRANSITION_DURATION));
        assert!((fade - 1.0 / 6.0).abs() < 1e-6, "{fade}");
        let ms = Duration::from_millis;
        assert_eq!(fade_at_50ms(Some(ms(100)), true), (Some(ms(100)), 0.5));
        assert_eq!(fade_at_50ms(Some(Duration::ZERO), true), (Some(Duration::ZERO), 1.0));
        assert_eq!(fade_at_50ms(Some(ms(100)), false), (Some(ms(100)), 1.0));
        assert_eq!(fade_at_50ms(None, false), (Some(DEFAULT_TRANSITION_DURATION), 1.0));
    }

    #[test]
    fn a_placement_is_stale_until_one_after_its_fade() {
        let mut controller = PlacementController::new();
        assert!(controller.is_stale(&inputs()), "the empty placement");
        let start = crate::tests::start_time();
        let fading = Placed { changed: true, settled: false };
        place(&mut controller, start, fading);
        assert!(controller.is_stale(&inputs()), "fading in");
        assert!(controller.has_transitions(Some(start + Duration::from_millis(100))));
        place(&mut controller, start + Duration::from_secs(1), Placed::default());
        assert!(!controller.is_stale(&inputs()), "faded in");
        assert!(!controller.has_transitions(Some(start + Duration::from_secs(2))), "the fade started before");
        assert!(controller.reset());
        assert!(controller.is_stale(&inputs()), "the empty placement again");
    }
}