Skip to main content

mln_map/
map_impl.rs

1// Ports src/mln/map/map_impl.hpp and src/mln/map/map_impl.cpp.
2//
3// C++ `Map::Impl` is at once the TransformObserver, the style::Observer and
4// the RendererObserver, and holds references to the frontend and the
5// MapObserver. The port keeps it in an `Rc` so the renderer can observe it
6// through a `Weak` (C++: a raw pointer), with the mutable state in
7// `Cell`/`RefCell`s:
8// - The TransformObserver part only forwards to the MapObserver, so the
9//   Transform gets a small forwarding object (`MapTransformObserver`).
10// - The style::Observer part is `MapStyleObserver`, holding a `Weak` to the
11//   Impl. The style calls it while the Map hands out `&mut Style` (inside
12//   `load_json`, layer mutations, ...), when the Impl can't read the style.
13//   Those calls are queued and replayed, in order, as soon as the mutable
14//   borrow ends (`StyleMut` drop). Calls made while the style is not
15//   borrowed mutably are handled immediately, as in C++.
16
17use crate::map_observer::{CameraChangeMode, MapLoadError, MapObserver, RenderFrameStatus};
18use crate::map_options::MapOptions;
19use crate::transform::{Transform, TransformObserver};
20use mln_map_types::{CameraOptions, MapDebugOptions, MapMode, TileLodMode};
21use mln_renderer::{ExceptionPtr, RenderMode, RendererFrontend, RendererObserver, UpdateParameters};
22use mln_style::observer::{Observer as StyleObserver, SourceObserver};
23use mln_style::source::Source;
24use mln_style::sprite::Sprite;
25use mln_actor::{TaggedScheduler, scheduler};
26use mln_storage::FileSource;
27use mln_style::Style;
28use mln_util::chrono::{Clock, TimePoint};
29use mln_util::identity::SimpleIdentity;
30use mln_util::exception::{NotFoundException, StyleLoadException, StyleParseException};
31use std::cell::{Cell, RefCell, RefMut};
32use std::ops::{Deref, DerefMut};
33use std::rc::{Rc, Weak};
34use std::sync::Arc;
35
36/// `Map::StillImageCallback`: called with `None` on success, or the error.
37pub type StillImageCallback = Box<dyn FnOnce(Option<ExceptionPtr>)>;
38
39/// `StillImageRequest`.
40pub struct StillImageRequest {
41    pub callback: StillImageCallback,
42}
43
44/// The TransformObserver half of `Map::Impl`.
45struct MapTransformObserver {
46    observer: Rc<dyn MapObserver>,
47}
48
49impl TransformObserver for MapTransformObserver {
50    fn on_camera_will_change(&self, mode: CameraChangeMode) {
51        self.observer.on_camera_will_change(mode);
52    }
53    fn on_camera_is_changing(&self) {
54        self.observer.on_camera_is_changing();
55    }
56    fn on_camera_did_change(&self, mode: CameraChangeMode) {
57        self.observer.on_camera_did_change(mode);
58    }
59}
60
61/// A style::Observer call, queued while the style is borrowed mutably.
62enum StyleEvent {
63    SourceChanged,
64    Update,
65    StyleLoading,
66    StyleLoaded,
67    StyleError(ExceptionPtr),
68    ResourceError(ExceptionPtr),
69    SpriteLoaded,
70    SpriteError,
71    SpriteRequested,
72    /// Port-only: a `Style::loadURL` response is waiting (see
73    /// `Observer::on_style_response`).
74    StyleResponse,
75}
76
77/// The style::Observer half of `Map::Impl`.
78struct MapStyleObserver {
79    map: Weak<MapImpl>,
80}
81
82impl MapStyleObserver {
83    fn dispatch(&self, event: StyleEvent) {
84        if let Some(map) = self.map.upgrade() {
85            map.on_style_event(event);
86        }
87    }
88}
89
90impl SourceObserver for MapStyleObserver {
91    fn on_source_changed(&self, _source: &dyn Source) {
92        self.dispatch(StyleEvent::SourceChanged);
93    }
94}
95
96impl StyleObserver for MapStyleObserver {
97    fn on_style_loading(&self) {
98        self.dispatch(StyleEvent::StyleLoading);
99    }
100    fn on_style_loaded(&self) {
101        self.dispatch(StyleEvent::StyleLoaded);
102    }
103    fn on_update(&self) {
104        self.dispatch(StyleEvent::Update);
105    }
106    fn on_style_error(&self, error: ExceptionPtr) {
107        self.dispatch(StyleEvent::StyleError(error));
108    }
109    fn on_resource_error(&self, error: ExceptionPtr) {
110        self.dispatch(StyleEvent::ResourceError(error));
111    }
112    fn on_sprite_loaded(&self, _sprite: Option<&Sprite>) {
113        self.dispatch(StyleEvent::SpriteLoaded);
114    }
115    fn on_sprite_error(&self, _sprite: Option<&Sprite>, _error: ExceptionPtr) {
116        self.dispatch(StyleEvent::SpriteError);
117    }
118    fn on_sprite_requested(&self, _sprite: Option<&Sprite>) {
119        self.dispatch(StyleEvent::SpriteRequested);
120    }
121    fn on_style_response(&self) {
122        self.dispatch(StyleEvent::StyleResponse);
123    }
124}
125
126pub struct MapImpl {
127    pub(crate) observer: Rc<dyn MapObserver>,
128    pub(crate) renderer_frontend: Box<dyn RendererFrontend>,
129    // TODO(port): std::unique_ptr<util::ActionJournal> actionJournal.
130    pub(crate) transform: RefCell<Transform>,
131
132    pub(crate) mode: MapMode,
133    pub(crate) pixel_ratio: f32,
134    pub(crate) cross_source_collisions: bool,
135    pub(crate) fast_pfor_enabled: bool,
136    pub(crate) capture_rendered_features: bool,
137
138    pub(crate) debug_options: Cell<MapDebugOptions>,
139    // TODO(port): renderingStatsView, lastFrameStats, annotationManager.
140    pub(crate) style: RefCell<Style>,
141    pending_style_events: RefCell<Vec<StyleEvent>>,
142
143    pub(crate) camera_mutated: Cell<bool>,
144
145    pub(crate) prefetch_zoom_delta: Cell<u8>,
146
147    pub(crate) loading: Cell<bool>,
148    pub(crate) renderer_fully_loaded: Cell<bool>,
149    pub(crate) still_image_request: RefCell<Option<StillImageRequest>>,
150
151    pub(crate) tile_lod_min_radius: Cell<f64>,
152    pub(crate) tile_lod_scale: Cell<f64>,
153    pub(crate) tile_lod_pitch_threshold: Cell<f64>,
154    pub(crate) tile_lod_zoom_shift: Cell<f64>,
155    pub(crate) tile_lod_mode: Cell<TileLodMode>,
156
157    /// `std::shared_ptr<FileSource> fileSource`. Declared after `style`:
158    /// C++ destroys members in reverse order, so the style (and its sprite
159    /// requests) goes first.
160    pub(crate) file_source: Option<Arc<dyn FileSource>>,
161}
162
163impl MapImpl {
164    /// `Map::Impl(RendererFrontend&, MapObserver&, std::shared_ptr<FileSource>, const MapOptions&)`.
165    pub fn new(
166        frontend: Box<dyn RendererFrontend>,
167        observer: Rc<dyn MapObserver>,
168        file_source: Option<Arc<dyn FileSource>>,
169        map_options: &MapOptions,
170    ) -> Rc<MapImpl> {
171        let transform_observer: Rc<dyn TransformObserver> = Rc::new(MapTransformObserver {
172            observer: observer.clone(),
173        });
174        let pixel_ratio = map_options.pixel_ratio();
175        // TODO(port): `frontend_.getThreadPool()` (RendererFrontend has no
176        // thread pool yet); the background pool with a fresh tag instead.
177        let thread_pool = TaggedScheduler::new(scheduler::get_background(), SimpleIdentity::new());
178        let map = Rc::new(MapImpl {
179            observer,
180            renderer_frontend: frontend,
181            transform: RefCell::new(Transform::new(
182                transform_observer,
183                map_options.constrain_mode(),
184                map_options.viewport_mode(),
185            )),
186            mode: map_options.map_mode(),
187            pixel_ratio,
188            cross_source_collisions: map_options.cross_source_collisions(),
189            fast_pfor_enabled: map_options.fast_pfor_enabled(),
190            capture_rendered_features: map_options.rendered_feature_info(),
191            debug_options: Cell::new(MapDebugOptions::NO_DEBUG),
192            style: RefCell::new(Style::with_file_source(file_source.clone(), pixel_ratio, thread_pool)),
193            pending_style_events: RefCell::new(Vec::new()),
194            camera_mutated: Cell::new(false),
195            // util::DEFAULT_PREFETCH_ZOOM_DELTA
196            prefetch_zoom_delta: Cell::new(4),
197            loading: Cell::new(false),
198            // C++ leaves `rendererFullyLoaded` uninitialized until the first
199            // frame or style load.
200            renderer_fully_loaded: Cell::new(false),
201            still_image_request: RefCell::new(None),
202            tile_lod_min_radius: Cell::new(3.0),
203            tile_lod_scale: Cell::new(1.0),
204            tile_lod_pitch_threshold: Cell::new((60.0 / 180.0) * std::f64::consts::PI),
205            tile_lod_zoom_shift: Cell::new(0.0),
206            tile_lod_mode: Cell::new(TileLodMode::Default),
207            file_source,
208        });
209        map.transform
210            .borrow_mut()
211            .set_north_orientation(map_options.north_orientation());
212        let style_observer: Rc<dyn StyleObserver> = Rc::new(MapStyleObserver {
213            map: Rc::downgrade(&map),
214        });
215        map.style.borrow_mut().impl_.set_observer(Some(style_observer));
216        let weak: Weak<MapImpl> = Rc::downgrade(&map);
217        map.renderer_frontend.set_observer(weak);
218        // C++ throws from the constructor for an empty size; the Rust Map
219        // constructor is infallible (agreed interface), so this panics.
220        if let Err(e) = map.transform.borrow_mut().resize(map_options.size()) {
221            panic!("{e}");
222        }
223        map
224    }
225
226    // MARK: - style::Observer dispatch
227
228    fn on_style_event(&self, event: StyleEvent) {
229        if self.style.try_borrow().is_err() {
230            // The style is being mutated through a StyleMut; replay when it
231            // drops.
232            self.pending_style_events.borrow_mut().push(event);
233            return;
234        }
235        self.handle_style_event(event);
236    }
237
238    /// Replays the style::Observer calls queued while the style was
239    /// borrowed mutably.
240    pub(crate) fn process_pending_style_events(&self) {
241        loop {
242            let event = {
243                let mut pending = self.pending_style_events.borrow_mut();
244                if pending.is_empty() {
245                    break;
246                }
247                pending.remove(0)
248            };
249            self.handle_style_event(event);
250        }
251    }
252
253    fn handle_style_event(&self, event: StyleEvent) {
254        match event {
255            StyleEvent::SourceChanged => self.on_source_changed(),
256            StyleEvent::Update => self.on_update(),
257            StyleEvent::StyleLoading => self.on_style_loading(),
258            StyleEvent::StyleLoaded => self.on_style_loaded(),
259            StyleEvent::StyleError(error) => self.on_style_error(error),
260            StyleEvent::ResourceError(error) => RendererObserver::on_resource_error(self, error),
261            // TODO(port): MapObserver::onSpriteLoaded / onSpriteError /
262            // onSpriteRequested (and the action journal).
263            StyleEvent::SpriteLoaded | StyleEvent::SpriteError | StyleEvent::SpriteRequested => {}
264            // C++ parses inside the file source callback (the lambda in
265            // Style::Impl::loadURL); the observer calls the parse makes are
266            // queued while the style is borrowed and replayed here.
267            StyleEvent::StyleResponse => {
268                self.style.borrow_mut().impl_.process_style_responses();
269                self.process_pending_style_events();
270            }
271        }
272    }
273
274    // MARK: - Map::Impl StyleObserver
275
276    fn on_source_changed(&self) {
277        // TODO(port): observer.onSourceChanged(source).
278    }
279
280    pub fn on_update(&self) {
281        // Don't load/render anything in still mode until explicitly requested.
282        if self.mode != MapMode::Continuous && self.still_image_request.borrow().is_none() {
283            return;
284        }
285
286        let time_point = if self.mode == MapMode::Continuous {
287            Clock::now()
288        } else {
289            TimePoint::max()
290        };
291
292        self.transform.borrow_mut().update_transitions(time_point);
293
294        let params = {
295            let style = self.style.borrow();
296            let style_impl = &style.impl_;
297            UpdateParameters {
298                style_loaded: style_impl.is_loaded(),
299                mode: self.mode,
300                pixel_ratio: self.pixel_ratio,
301                debug_options: self.debug_options.get(),
302                time_point,
303                transform_state: self.transform.borrow().get_state().clone(),
304                glyph_url: style_impl.get_glyph_url().to_owned(),
305                font_faces: style_impl.get_font_faces(),
306                sprite_loaded: style_impl.are_sprites_loaded(),
307                transition_options: style_impl.get_transition_options(),
308                light: style_impl.get_light_impl(),
309                images: style_impl.get_image_impls(),
310                sources: style_impl.get_source_impls(),
311                layers: style_impl.get_layer_impls(),
312                global_state: Some(style_impl.get_global_state_shared()),
313                file_source: self.file_source.clone(),
314                prefetch_zoom_delta: self.prefetch_zoom_delta.get(),
315                still_image_request: self.still_image_request.borrow().is_some(),
316                cross_source_collisions: self.cross_source_collisions,
317                fast_pfor_enabled: self.fast_pfor_enabled,
318                capture_rendered_features: self.capture_rendered_features,
319                tile_lod_min_radius: self.tile_lod_min_radius.get(),
320                tile_lod_scale: self.tile_lod_scale.get(),
321                tile_lod_pitch_threshold: self.tile_lod_pitch_threshold.get(),
322                tile_lod_zoom_shift: self.tile_lod_zoom_shift.get(),
323                tile_lod_mode: self.tile_lod_mode.get(),
324            }
325        };
326
327        self.renderer_frontend.update(Arc::new(params));
328    }
329
330    pub fn on_style_loading(&self) {
331        self.loading.set(true);
332        self.renderer_fully_loaded.set(false);
333        self.observer.on_will_start_loading_map();
334    }
335
336    pub fn on_style_loaded(&self) {
337        if !self.camera_mutated.get() {
338            let camera = self.style.borrow().get_default_camera();
339            self.jump_to(&camera);
340        }
341        // TODO(port): if (LayerManager::annotationsEnabled)
342        // annotationManager.onStyleLoaded() (see DEVIATIONS.md).
343
344        self.observer.on_did_finish_loading_style();
345
346        // TODO(port): logStyleDependencies (debug builds only).
347    }
348
349    pub fn on_style_error(&self, error: ExceptionPtr) {
350        let type_ = if error.downcast_ref::<StyleParseException>().is_some() {
351            MapLoadError::StyleParseError
352        } else if error.downcast_ref::<StyleLoadException>().is_some() {
353            MapLoadError::StyleLoadError
354        } else if error.downcast_ref::<NotFoundException>().is_some() {
355            MapLoadError::NotFoundError
356        } else {
357            MapLoadError::UnknownError
358        };
359        let description = error.to_string();
360
361        self.observer.on_did_fail_loading_map(type_, &description);
362    }
363
364    // MARK: - Map
365
366    pub fn jump_to(&self, camera: &CameraOptions) {
367        self.camera_mutated.set(true);
368        self.transform.borrow_mut().jump_to(camera);
369        self.on_update();
370    }
371}
372
373impl Drop for MapImpl {
374    fn drop(&mut self) {
375        // Explicitly reset the RendererFrontend first to ensure it releases
376        // all shared resources (AnnotationManager).
377        self.renderer_frontend.reset();
378    }
379}
380
381// MARK: - Map::Impl RendererObserver
382
383impl RendererObserver for MapImpl {
384    fn on_invalidate(&self) {
385        self.on_update();
386    }
387
388    fn on_resource_error(&self, error: ExceptionPtr) {
389        if self.mode != MapMode::Continuous {
390            let request = self.still_image_request.borrow_mut().take();
391            if let Some(request) = request {
392                (request.callback)(Some(error));
393            }
394        }
395    }
396
397    fn on_will_start_rendering_frame(&self) {
398        if self.mode == MapMode::Continuous {
399            self.observer.on_will_start_rendering_frame();
400        }
401    }
402
403    fn on_did_finish_rendering_frame(&self, render_mode: RenderMode, needs_repaint: bool, placement_changed: bool) {
404        self.renderer_fully_loaded.set(render_mode == RenderMode::Full);
405
406        // TODO(port): renderingStatsView->update(*style, *stats).
407
408        if self.mode == MapMode::Continuous {
409            let frame_status = RenderFrameStatus {
410                mode: match render_mode {
411                    RenderMode::Partial => crate::map_observer::RenderMode::Partial,
412                    RenderMode::Full => crate::map_observer::RenderMode::Full,
413                },
414                needs_repaint,
415                placement_changed,
416            };
417            self.observer.on_did_finish_rendering_frame(&frame_status);
418
419            if needs_repaint || self.transform.borrow().in_transition() {
420                self.on_update();
421            } else if self.renderer_fully_loaded.get() {
422                self.observer.on_did_become_idle();
423            }
424        } else if self.still_image_request.borrow().is_some() && self.renderer_fully_loaded.get() {
425            let request = self.still_image_request.borrow_mut().take();
426            if let Some(request) = request {
427                (request.callback)(None);
428            }
429        }
430    }
431
432    fn on_will_start_rendering_map(&self) {
433        if self.mode == MapMode::Continuous {
434            self.observer.on_will_start_rendering_map();
435        }
436    }
437
438    fn on_did_finish_rendering_map(&self) {
439        if self.mode == MapMode::Continuous && self.loading.get() {
440            self.observer
441                .on_did_finish_rendering_map(crate::map_observer::RenderMode::Full);
442            if self.loading.get() {
443                self.loading.set(false);
444                self.observer.on_did_finish_loading_map();
445            }
446        }
447    }
448
449    fn on_style_image_missing(&self, id: &str, done: &mut dyn FnMut()) {
450        if self.style.borrow().get_image(id).is_none() {
451            self.observer.on_style_image_missing(id);
452        }
453
454        done();
455        self.on_update();
456    }
457
458    fn on_remove_unused_style_images(&self, unused_image_ids: &[String]) {
459        for unused_image_id in unused_image_ids {
460            if self.observer.on_can_remove_unused_style_image(unused_image_id) {
461                self.style.borrow_mut().remove_image(unused_image_id);
462                self.process_pending_style_events();
463            }
464        }
465    }
466
467    fn on_render_error(&self, error: ExceptionPtr) {
468        self.observer.on_render_error(error);
469    }
470}
471
472/// The `style::Style&` that `Map::getStyle()` returns, for mutation: derefs
473/// to `Style`; when it drops, the style::Observer calls the mutation made
474/// are delivered to the map (see the comment at the top of this file).
475pub struct StyleMut<'a> {
476    map: &'a MapImpl,
477    style: Option<RefMut<'a, Style>>,
478}
479
480impl<'a> StyleMut<'a> {
481    pub(crate) fn new(map: &'a MapImpl) -> Self {
482        StyleMut {
483            map,
484            style: Some(map.style.borrow_mut()),
485        }
486    }
487}
488
489impl Deref for StyleMut<'_> {
490    type Target = Style;
491    fn deref(&self) -> &Style {
492        self.style.as_ref().expect("style")
493    }
494}
495
496impl DerefMut for StyleMut<'_> {
497    fn deref_mut(&mut self) -> &mut Style {
498        self.style.as_mut().expect("style")
499    }
500}
501
502impl Drop for StyleMut<'_> {
503    fn drop(&mut self) {
504        drop(self.style.take());
505        self.map.process_pending_style_events();
506    }
507}