Skip to main content

mln_engine/map/
map.rs

1// The map owns its style versions, its transform and its style loader. An
2// edit reacts in the call that makes it; the loader and the renderer report
3// through queues that the map drains in `process_events`.
4
5use std::rc::Rc;
6use std::sync::Arc;
7use std::time::Duration;
8
9use geo_types::Geometry;
10use glam::{DMat4, DVec3};
11use mln_style::conversion::Convertible;
12use mln_style::error::Error;
13use mln_style::geo::{LatLng, LatLngBounds, WrapMode};
14use mln_style::geometry::for_each_point;
15use mln_style::size::Size;
16use mln_style::source::convert_source;
17use mln_style::subdivision_granularity::SubdivisionGranularitySetting;
18use mln_style::time::Instant;
19use mln_style::types::{ProjectionDefinition, ProjectionType};
20use mln_style::{Edit, Source, Style, StyleRegistry};
21
22use crate::camera::transform::{CameraCommandId, CommandEnd, FrameClock, TerrainGround, Transform, TransformEvent};
23use crate::camera::{
24    AnimationOptions, BoundOptions, CameraDelta, CameraError, CameraLimits, CameraOptions, CameraUpdate, Elevation,
25    ProjectionMode, TransformState, VerticalPerspectiveProjection, Viewport,
26};
27use crate::exec::event_queue::{EventQueue, Waker};
28use crate::exec::pool::Pool;
29use crate::geo::{EdgeInsets, ScreenCoordinate};
30use crate::map::events::{MapEvent, RenderFrameStatus};
31use crate::map::feature_state::FeatureStateStore;
32use crate::map::options::{MapOptions, UnusedStyleImagePolicy};
33use crate::map::snapshot::{CameraBounds, FreeCamera, MapSnapshot, TileSettings};
34use crate::map::style_loader::{LoadEvent, StyleLoader};
35use crate::map::{MapMode, TerrainOptions};
36use crate::storage::FileSource;
37#[cfg(not(target_family = "wasm"))]
38use crate::storage::{Loader, ResourceOptions};
39use crate::text::glyph::{FontFace, FontFaces};
40use crate::tile_store::TileLodMode;
41use crate::{
42    Registry, RendererEvent, RendererEvents, RenderingStats, UpdateParameters, UpdateReader, UpdateSlot, log_target,
43};
44
45/// How many times the terrain may move the camera while a still image
46/// waits, before the map stops following it for that image: a camera whose
47/// ground changes with each move would otherwise never settle.
48const MAX_GROUND_MOVES_PER_STILL: u32 = 8;
49
50/// The camera options of `style`'s default camera, which the map jumps to
51/// once the style loads, unless a camera command came first.
52#[must_use]
53pub fn style_camera(style: &Style) -> CameraOptions {
54    let camera = style.get_default_camera();
55    CameraOptions {
56        center: camera.center,
57        center_altitude: camera.center_altitude,
58        zoom: camera.zoom,
59        bearing: camera.bearing,
60        pitch: camera.pitch,
61        roll: camera.roll,
62        ..CameraOptions::default()
63    }
64}
65
66/// How long a continuous map waits to draw again after the first of a run
67/// of frames that failed on the GPU, in case the failure passes.
68const RETRY_DELAY: Duration = Duration::from_millis(200);
69
70/// Where a still image that [`Map::render_still`] asked for stands.
71#[derive(Debug, PartialEq)]
72enum StillImage {
73    None,
74    /// Waits for a complete frame.
75    Pending,
76    /// Ended, until [`Map::take_still_image`] takes it.
77    Ended(Result<(), Error>),
78}
79
80/// A map: its style, its camera, and the updates it publishes for its
81/// renderer.
82///
83/// The map publishes its state for a renderer in an update slot, which a
84/// renderer reads through [`update_reader`](Self::update_reader) and
85/// reports back to through [`renderer_events`](Self::renderer_events).
86/// The style is an `Arc<Style>` version: [`edit_style`](Self::edit_style)
87/// makes the next one and publishes it at once. The style's loader and the
88/// renderer report to the map through queues, which the map handles only
89/// in [`process_events`](Self::process_events) (which
90/// [`drain_events`](Self::drain_events) calls): an owner calls it once per
91/// phase, before the commands that should see what was reported, such as a
92/// camera command that should land after the style's default camera. What
93/// the map reports to its owner waits in another queue, for `drain_events`.
94/// An owner sets a waker ([`set_waker`](Self::set_waker)) that schedules
95/// those calls on its thread.
96pub struct Map {
97    updates: UpdateSlot,
98    transform: Transform,
99
100    mode: MapMode,
101    pixel_ratio: f32,
102    cross_source_collisions: bool,
103    fast_pfor_enabled: bool,
104    unused_style_image_policy: UnusedStyleImagePolicy,
105    /// How the map draws its terrain.
106    terrain: TerrainOptions,
107    /// The ground of the terrain as the renderer last drew it, while
108    /// terrain draws. Each update carries it, and the renderer completes a
109    /// frame only of an update that carries its newest ground.
110    elevation: Option<Arc<dyn Elevation>>,
111    /// The terrain's moves of the camera while the still image waits.
112    ground_moves: u32,
113
114    /// The current version of the style.
115    style: Arc<Style>,
116    /// The faces that the map draws the style's text with: its
117    /// `font-faces`, then the fallback faces in effect when it parsed.
118    font_faces: Option<Arc<FontFaces>>,
119    /// Loads the style's document, its sprites and its sources'
120    /// descriptions.
121    loader: StyleLoader,
122    /// The state of the sources' features, which each update carries.
123    feature_state: FeatureStateStore,
124
125    camera_mutated: bool,
126    /// How the map picks the tiles to load, as its snapshot reports it.
127    tile: TileSettings,
128    loading: bool,
129    renderer_fully_loaded: bool,
130    /// When the last frame said the map changes next on its own, until an
131    /// update goes out.
132    repaint_at: Option<Instant>,
133    /// Whether the last frame of a continuous map failed on the GPU.
134    render_failing: bool,
135    /// A still image that [`Map::render_still`] asked for, until it ends.
136    still_image: StillImage,
137    /// Counts the still image requests, so the renderer can tell a new one.
138    still_image_request_id: u64,
139    /// The `update_id` of the last update the map made.
140    update_id: u64,
141
142    /// Grows with each change to the map's state.
143    generation: u64,
144
145    renderer_events: RendererEvents,
146    /// What the map reports to its owner.
147    events: EventQueue<MapEvent>,
148    /// The ends of the camera commands, for its owner.
149    command_ends: Vec<CommandEnd>,
150
151    /// Declared after `style`, so the style and its requests go first.
152    file_source: Option<Arc<dyn FileSource>>,
153    /// Where the map's background work runs.
154    pool: Pool,
155}
156
157impl Map {
158    /// A map with a [`Loader`] of its own for the default
159    /// `ResourceOptions`, whose background work runs on `pool`.
160    ///
161    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an empty `map_options.size`.
162    #[cfg(not(target_family = "wasm"))]
163    pub fn new(map_options: MapOptions, pool: &Pool) -> Result<Map, Error> {
164        Self::with_resource_options(map_options, &ResourceOptions::default(), pool)
165    }
166
167    /// A map with a [`Loader`] of its own for `resource_options`, on
168    /// `pool`.
169    #[cfg(not(target_family = "wasm"))]
170    pub fn with_resource_options(
171        map_options: MapOptions,
172        resource_options: &ResourceOptions,
173        pool: &Pool,
174    ) -> Result<Map, Error> {
175        let loader: Arc<dyn FileSource> = Arc::new(Loader::new(resource_options, pool));
176        Self::with_registry(loader, map_options, Arc::clone(Registry::with_builtins().style()), pool)
177    }
178
179    // gtests-core: the C++ tests' `MapAdapter` (test/include/mln/test/
180    // map_adapter.hpp): a map over a given file source.
181    /// A map whose resources come from `file_source`, on `pool`.
182    pub fn with_file_source(
183        file_source: Arc<dyn FileSource>,
184        map_options: MapOptions,
185        pool: &Pool,
186    ) -> Result<Map, Error> {
187        Self::with_registry(file_source, map_options, Arc::clone(Registry::with_builtins().style()), pool)
188    }
189
190    /// A map whose resources come from `file_source` and whose style parses
191    /// against `registry`, on `pool`. The other constructors
192    /// use the built-in registrations.
193    ///
194    /// The renderer that draws the map must be given a registry filled by
195    /// the same calls as `registry` ([`crate::Registry::style`]): it
196    /// finds a layer's type by name, and draws no layer whose type it lacks.
197    pub fn with_registry(
198        file_source: Arc<dyn FileSource>,
199        map_options: MapOptions,
200        registry: Arc<StyleRegistry>,
201        pool: &Pool,
202    ) -> Result<Map, Error> {
203        let events = EventQueue::new();
204        let renderer_events = RendererEvents::new();
205        let pixel_ratio = map_options.pixel_ratio;
206        let style = Arc::new(Style::new(registry));
207        let loader = StyleLoader::new(Some(Arc::clone(&file_source)), pool, pixel_ratio);
208        let mut transform = Transform::new(map_options.constrain_mode, map_options.viewport_mode);
209        transform.set_north_orientation(map_options.north_orientation);
210        transform.set_center_clamped_to_ground(map_options.center_clamped_to_ground);
211        let mut map = Map {
212            updates: UpdateSlot::new(),
213            transform,
214            mode: map_options.map_mode,
215            pixel_ratio,
216            cross_source_collisions: map_options.cross_source_collisions,
217            fast_pfor_enabled: map_options.fast_pfor_enabled,
218            unused_style_image_policy: map_options.unused_style_image_policy,
219            terrain: map_options.terrain,
220            elevation: None,
221            ground_moves: 0,
222            style,
223            font_faces: None,
224            loader,
225            feature_state: FeatureStateStore::default(),
226            camera_mutated: false,
227            tile: TileSettings {
228                // util::DEFAULT_PREFETCH_ZOOM_DELTA
229                prefetch_zoom_delta: 4,
230                lod_min_radius: 3.0,
231                lod_scale: 1.0,
232                lod_pitch_threshold: 60.0,
233                lod_zoom_shift: 0.0,
234                lod_mode: TileLodMode::Default,
235            },
236            loading: false,
237            renderer_fully_loaded: false,
238            repaint_at: None,
239            render_failing: false,
240            still_image: StillImage::None,
241            still_image_request_id: 0,
242            update_id: 0,
243            generation: 1,
244            renderer_events,
245            events,
246            command_ends: Vec::new(),
247            file_source: Some(file_source),
248            pool: pool.clone(),
249        };
250        map.share_projection_with_transform();
251        map.transform.resize(map_options.size)?;
252        Ok(map)
253    }
254
255    /// Where the map's background work runs.
256    #[must_use]
257    pub fn pool(&self) -> &Pool {
258        &self.pool
259    }
260
261    // MARK: - Renderer
262
263    /// A reader of the updates that the map publishes for its renderer.
264    #[must_use]
265    pub fn update_reader(&self) -> UpdateReader {
266        self.updates.reader()
267    }
268
269    /// The queue that the map's renderer reports its events to.
270    #[must_use]
271    pub fn renderer_events(&self) -> RendererEvents {
272        self.renderer_events.clone()
273    }
274
275    /// Holds the map's updates back from its renderer until the matching
276    /// [`end_command_group`](Self::end_command_group), so the changes in
277    /// between show in the same frame. Groups nest, and the changes show
278    /// when the outermost group ends.
279    pub fn begin_command_group(&mut self) {
280        self.updates.begin_group();
281    }
282
283    /// Ends the group that [`begin_command_group`](Self::begin_command_group)
284    /// began. Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
285    /// when no group is open.
286    pub fn end_command_group(&mut self) -> Result<(), Error> {
287        self.updates.end_group()
288    }
289
290    /// How many command groups are open.
291    #[must_use]
292    pub fn command_group_depth(&self) -> u32 {
293        self.updates.group_depth()
294    }
295
296    /// Holds the map's updates back from its renderer, as a command group
297    /// does, until [`release_updates`](Self::release_updates). The hold is
298    /// apart from the groups: it doesn't nest, and
299    /// [`command_group_depth`](Self::command_group_depth) doesn't count it.
300    pub fn hold_updates(&mut self) {
301        self.updates.hold();
302    }
303
304    /// Ends the hold that [`hold_updates`](Self::hold_updates) began. The
305    /// changes show unless a command group still holds them.
306    pub fn release_updates(&mut self) {
307        self.updates.release();
308    }
309
310    // MARK: - Events
311
312    /// Sets the waker that runs, on any thread, when the map has events to
313    /// handle or to drain. It must not call the map: it schedules a call of
314    /// [`drain_events`](Self::drain_events) or
315    /// [`process_events`](Self::process_events) on the map's thread, as by
316    /// posting to the owner's `Queue`.
317    pub fn set_waker(&mut self, waker: Option<Waker>) {
318        self.loader.set_waker(waker.clone());
319        self.renderer_events.set_waker(waker.clone());
320        self.events.set_waker(waker);
321    }
322
323    /// Whether the style or the renderer reported something that
324    /// [`process_events`](Self::process_events) hasn't handled. A report
325    /// counts once it is queued, though its waker may not have run yet.
326    #[must_use]
327    pub fn has_reports(&self) -> bool {
328        self.loader.has_replies() || !self.renderer_events.is_empty()
329    }
330
331    /// Sets a waker as [`set_waker`](Self::set_waker) does, that runs only
332    /// when the style or the renderer reports something for the map to
333    /// handle, which can come from any thread. The events that the map's own
334    /// calls report don't run it, for an owner that drains them after each
335    /// call.
336    pub fn set_reports_waker(&mut self, waker: Option<Waker>) {
337        self.loader.set_waker(waker.clone());
338        self.renderer_events.set_waker(waker);
339        self.events.set_waker(None);
340    }
341
342    /// Handles what the style and the renderer reported since the last
343    /// call: loads, frames, errors and missing images. The map's reactions,
344    /// such as an update for the renderer or a still image's callback, run
345    /// here, and its events wait for [`drain_events`](Self::drain_events).
346    pub fn process_events(&mut self) {
347        loop {
348            let replies = self.loader.take_replies();
349            let renderer_events = self.renderer_events.take();
350            if replies.is_empty() && renderer_events.is_empty() {
351                break;
352            }
353            for reply in replies {
354                let events = self.loader.on_reply(&self.style, reply);
355                self.handle_load_events(events);
356            }
357            for event in renderer_events {
358                self.handle_renderer_event(event);
359            }
360        }
361    }
362
363    /// Handles what the style and the renderer reported, as
364    /// [`process_events`](Self::process_events) does, and takes the map's
365    /// events, oldest first.
366    pub fn drain_events(&mut self) -> Vec<MapEvent> {
367        self.process_events();
368        self.forward_camera_events();
369        self.events.take()
370    }
371
372    fn emit(&mut self, event: MapEvent) {
373        self.forward_camera_events();
374        self.events.push(event);
375    }
376
377    /// Moves what the transform reported to the map's events, after the
378    /// events before it, and to its command ends.
379    fn forward_camera_events(&mut self) {
380        for event in self.transform.drain_events() {
381            match event {
382                TransformEvent::CameraWillChange(change) => self.events.push(MapEvent::CameraWillChange(change)),
383                TransformEvent::CameraIsChanging => self.events.push(MapEvent::CameraIsChanging),
384                TransformEvent::CameraDidChange(change) => self.events.push(MapEvent::CameraDidChange(change)),
385                TransformEvent::CommandEnded(end) => self.command_ends.push(end),
386            }
387        }
388    }
389
390    /// Drains the ends of the camera commands that ended since the last
391    /// call, oldest first: each command's end comes once, unless the map
392    /// drops while the command runs (see [`close_camera`](Self::close_camera)).
393    /// They come with the camera events of the same calls, which
394    /// [`drain_events`](Self::drain_events) takes. The map keeps its buffer
395    /// for the ends that come next.
396    pub fn drain_command_ends(&mut self) -> std::vec::Drain<'_, CommandEnd> {
397        self.forward_camera_events();
398        self.command_ends.drain(..)
399    }
400
401    /// Does what the loader's events ask, in their order.
402    fn handle_load_events(&mut self, events: Vec<LoadEvent>) {
403        for event in events {
404            match event {
405                LoadEvent::Loading => {
406                    self.changed();
407                    self.loading = true;
408                    self.renderer_fully_loaded = false;
409                    self.emit(MapEvent::LoadingStarted);
410                }
411                LoadEvent::Parsed(style, font_faces) => {
412                    self.style = Arc::new(style);
413                    self.font_faces = font_faces;
414                    self.watch_sources();
415                    // A style that loads takes every source's feature state
416                    // with it.
417                    self.feature_state.clear();
418                    self.share_projection_with_transform();
419                    self.on_update();
420                }
421                LoadEvent::Loaded => {
422                    self.changed();
423                    if !self.camera_mutated {
424                        let camera = style_camera(&self.style);
425                        self.jump_to(&camera);
426                    }
427                    self.emit(MapEvent::StyleLoaded);
428                }
429                LoadEvent::Failed(error) => self.emit(MapEvent::LoadingFailed(error)),
430                LoadEvent::ResourceError(error) => self.on_resource_error(error),
431                LoadEvent::SpriteRequested(sprite) => self.emit(MapEvent::SpriteRequested(sprite)),
432                LoadEvent::SpriteImages(sprite, images) => {
433                    // The update this publishes is for *-pattern properties.
434                    let _ = self.apply_loaded(Edit::AddImages(images));
435                    self.emit(MapEvent::SpriteLoaded(sprite));
436                }
437                LoadEvent::SpriteFailed(sprite, error) => {
438                    // Unblocks the tiles that wait for the sprite.
439                    self.on_update();
440                    self.emit(MapEvent::SpriteError(sprite, error));
441                }
442                LoadEvent::SourceDescribed { load, result: Err(error) } => {
443                    log::error!(target: log_target::STYLE, "Failed to load source {}: {error}", load.id);
444                    self.on_resource_error(error);
445                }
446                LoadEvent::SourceDescribed { load, result: Ok(description) } => {
447                    let previous = self.style.get_source(&load.id).cloned();
448                    let edit = Edit::SetSourceDescription {
449                        id: load.id.to_string(),
450                        instance: load.instance,
451                        load: load.load,
452                        result: Ok(description),
453                    };
454                    if !self.apply_loaded_changes(edit) {
455                        // The source is loaded now, which the update says.
456                        self.on_update();
457                    }
458                    if let (Some(previous), Some(source)) = (previous, self.style.get_source(&load.id))
459                        && source.metadata_changed_from(&previous)
460                    {
461                        self.emit(MapEvent::SourceChanged { source_id: load.id.to_string() });
462                        self.on_update();
463                    }
464                }
465            }
466        }
467    }
468
469    /// Loads the descriptions of the sources whose loads the loader hasn't
470    /// seen, and gives the style the ones their types know without a fetch,
471    /// before the version is published.
472    fn watch_sources(&mut self) {
473        let edits = self.loader.watch_sources(&self.style);
474        if edits.is_empty() {
475            return;
476        }
477        let style = Arc::make_mut(&mut self.style);
478        for edit in edits {
479            // A description that the loader found for the version can't fail.
480            let _ = style.apply(edit);
481        }
482    }
483
484    fn handle_renderer_event(&mut self, event: RendererEvent) {
485        let continuous = self.mode == MapMode::Continuous;
486        match event {
487            RendererEvent::Invalidate => self.on_update(),
488            RendererEvent::ResourceError(error) => self.on_resource_error(error),
489            RendererEvent::RenderFrameStarted => {
490                if continuous {
491                    self.emit(MapEvent::RenderFrameStarted);
492                }
493            }
494            RendererEvent::RenderFrameFinished {
495                mode,
496                needs_repaint,
497                repaint_at,
498                placement_changed,
499                still_image_request_id,
500                update_id,
501                stats,
502                error,
503            } => {
504                self.repaint_at = repaint_at.filter(|_| continuous && !needs_repaint);
505                match error {
506                    Some(error) => self.on_render_failure(*error, still_image_request_id),
507                    None => self.render_failing = false,
508                }
509                self.on_render_frame_finished(
510                    mode,
511                    needs_repaint,
512                    placement_changed,
513                    still_image_request_id,
514                    update_id,
515                    stats,
516                );
517            }
518            // The renderer completes a frame only of an update that carries
519            // its newest ground, so the map answers new ground with one,
520            // whether or not the camera moves onto it (`follow_terrain`).
521            // The renderer tells it again of ground that an update in flight
522            // already carries.
523            RendererEvent::TerrainElevation(elevation) => {
524                let held = match (&self.elevation, &elevation) {
525                    (Some(held), Some(told)) => Arc::ptr_eq(held, told),
526                    (held, told) => held.is_none() && told.is_none(),
527                };
528                if !held {
529                    self.elevation = elevation;
530                    self.on_update();
531                }
532            }
533            RendererEvent::RenderMapStarted => {
534                if continuous {
535                    self.emit(MapEvent::RenderMapStarted);
536                }
537            }
538            RendererEvent::RenderMapFinished => {
539                if continuous && self.loading {
540                    self.emit(MapEvent::RenderMapFinished(crate::RenderMode::Full));
541                    self.loading = false;
542                    self.emit(MapEvent::LoadingFinished);
543                }
544            }
545            RendererEvent::StyleImageMissing(id) => {
546                if self.style.get_image(&id).is_none() {
547                    self.emit(MapEvent::StyleImageMissing { id });
548                }
549                self.on_update();
550            }
551            RendererEvent::UnusedStyleImages(ids) => {
552                if self.unused_style_image_policy == UnusedStyleImagePolicy::Remove {
553                    for id in ids {
554                        if self.style.get_image(&id).is_some_and(|image| !image.keep_unused) {
555                            let _ = self.apply_loaded(Edit::RemoveImage(id));
556                        }
557                    }
558                }
559            }
560            RendererEvent::GlyphsRequested { font_stack, range } => {
561                self.emit(MapEvent::GlyphsRequested { font_stack, range });
562            }
563            RendererEvent::GlyphsLoaded { font_stack, range } => {
564                self.emit(MapEvent::GlyphsLoaded { font_stack, range });
565            }
566            RendererEvent::GlyphsError { font_stack, range, error } => {
567                self.emit(MapEvent::GlyphsError { font_stack, range, error });
568            }
569            RendererEvent::TileAction { op, id, source_id } => self.emit(MapEvent::TileAction { op, id, source_id }),
570        }
571    }
572
573    /// Reports a frame that failed on the GPU, and fails the still image it
574    /// was drawn for. A continuous map reports a run of failed frames once,
575    /// and draws again after [`RETRY_DELAY`] unless a frame comes sooner.
576    fn on_render_failure(&mut self, error: Error, still_image_request_id: u64) {
577        if self.mode == MapMode::Continuous {
578            if std::mem::replace(&mut self.render_failing, true) {
579                return;
580            }
581            self.repaint_at.get_or_insert(Instant::now() + RETRY_DELAY);
582        } else if still_image_request_id != 0 && still_image_request_id == self.still_image_request_id {
583            self.on_resource_error(error.clone());
584        }
585        self.emit(MapEvent::RenderError(error));
586    }
587
588    /// Fails the still image being rendered.
589    fn on_resource_error(&mut self, error: Error) {
590        if self.mode != MapMode::Continuous && self.still_image == StillImage::Pending {
591            self.still_image = StillImage::Ended(Err(error));
592        }
593    }
594
595    /// Handles the end of a frame. Only a `Full` frame completes a still
596    /// image; one whose camera hadn't stood on the terrain's newest ground
597    /// isn't `Full`. Only a `Full` frame of the map's last update leaves a
598    /// continuous map idle: the map may have made an update since the
599    /// renderer took the frame's, such as its answer to the new ground or to
600    /// a tile that the frame itself took in, and that update's frame is still
601    /// to come.
602    fn on_render_frame_finished(
603        &mut self,
604        mode: crate::RenderMode,
605        needs_repaint: bool,
606        placement_changed: bool,
607        still_image_request_id: u64,
608        update_id: u64,
609        stats: Arc<RenderingStats>,
610    ) {
611        let fully_loaded = mode == crate::RenderMode::Full;
612        if std::mem::replace(&mut self.renderer_fully_loaded, fully_loaded) != fully_loaded {
613            self.changed();
614        }
615
616        if self.mode == MapMode::Continuous {
617            self.emit(MapEvent::RenderFrameFinished(RenderFrameStatus {
618                mode,
619                needs_repaint: needs_repaint || self.repaint_at.is_some(),
620                placement_changed,
621                rendering_stats: stats,
622            }));
623
624            // A host on a frame clock has each frame sample the running
625            // animations (`sample_frame`), so a frame's report adds no update
626            // for them, which would only repeat the frame's camera.
627            let animating = self.transform.in_transition();
628            if needs_repaint || (animating && self.transform.frame_time().is_none()) {
629                self.on_update();
630            } else if !animating
631                && self.renderer_fully_loaded
632                && self.repaint_at.is_none()
633                && update_id == self.update_id
634            {
635                self.emit(MapEvent::Idle);
636            }
637        } else if self.renderer_fully_loaded
638            && still_image_request_id == self.still_image_request_id
639            && self.still_image == StillImage::Pending
640        {
641            self.still_image = StillImage::Ended(Ok(()));
642        }
643    }
644
645    /// Records a change to the map's state.
646    fn changed(&mut self) {
647        self.generation += 1;
648    }
649
650    /// Counts a change to state that the map's owner keeps for the map, such
651    /// as which of its events a runtime reports, in the map's
652    /// [`generation`](Self::generation).
653    pub fn record_change(&mut self) {
654        self.changed();
655    }
656
657    /// Publishes an update of the map's state for the renderer.
658    fn on_update(&mut self) {
659        // Each update request comes from a change, so the generation grows
660        // even in still mode, where no update goes out.
661        self.changed();
662
663        // Don't load/render anything in still mode until explicitly requested.
664        if self.mode != MapMode::Continuous && self.still_image != StillImage::Pending {
665            // The camera stands on the ground all the same.
666            self.follow_terrain();
667            return;
668        }
669
670        // Still modes have no clock: they show every transition as ended.
671        let time_point =
672            (self.mode == MapMode::Continuous).then(|| self.transform.frame_time().unwrap_or_else(Instant::now));
673        // An update once the time the map changes next came shows the map at
674        // that time, though the host's last frame came before it.
675        let time_point = match (time_point, self.repaint_at.take()) {
676            (Some(time), Some(at)) if Instant::now() >= at => Some(time.max(at)),
677            (time_point, _) => time_point,
678        };
679
680        // The frame's commands keep their eye above the newest ground.
681        let ground = self.terrain_ground();
682        self.transform.set_terrain(ground);
683        self.transform.update_transitions(time_point);
684        let projection = self.projection_at(self.transform.view().zoom());
685        self.transform.set_projection_definition(&projection);
686        self.follow_terrain();
687
688        self.update_id += 1;
689        let params = UpdateParameters {
690            style_loaded: self.style_loaded(),
691            mode: self.mode,
692            pixel_ratio: self.pixel_ratio,
693            time_point,
694            view: self.transform.state().view().clone(),
695            min_zoom: self.transform.state().min_zoom(),
696            max_zoom: self.transform.state().limits().max_zoom,
697            camera_moving: self.transform.is_camera_moving(),
698            style: Arc::clone(&self.style),
699            font_faces: self.font_faces.clone(),
700            sprite_loaded: self.loader.sprites_loaded(),
701            feature_states: self.feature_state.shared(),
702            file_source: self.file_source.clone(),
703            prefetch_zoom_delta: self.tile.prefetch_zoom_delta,
704            still_image_request: self.still_image == StillImage::Pending,
705            still_image_request_id: self.still_image_request_id,
706            update_id: self.update_id,
707            cross_source_collisions: self.cross_source_collisions,
708            fast_pfor_enabled: self.fast_pfor_enabled,
709            terrain: self.terrain,
710            elevation: self.elevation.clone(),
711            tile_lod_min_radius: self.tile.lod_min_radius,
712            tile_lod_scale: self.tile.lod_scale,
713            tile_lod_pitch_threshold: mln_style::math::deg2rad(self.tile.lod_pitch_threshold),
714            tile_lod_zoom_shift: self.tile.lod_zoom_shift,
715            tile_lod_mode: self.tile.lod_mode,
716            subdivision_granularity: if self.mode == MapMode::Tile {
717                SubdivisionGranularitySetting::none()
718            } else {
719                self.style.get_projection().get_subdivision_granularity()
720            },
721        };
722
723        self.updates.publish(Arc::new(params));
724        self.forward_camera_events();
725    }
726
727    pub fn jump_to(&mut self, camera: &CameraOptions) {
728        self.camera_mutated = true;
729        // The style's projection decides how the camera is constrained, so it
730        // has to be in place first.
731        let zoom = camera.zoom.unwrap_or_else(|| self.transform.view().zoom());
732        let projection = self.projection_at(zoom);
733        self.transform.set_projection_definition(&projection);
734        // So does the terrain, which applies only on Mercator.
735        let ground = self.terrain_ground();
736        self.transform.set_terrain(ground);
737        self.transform.jump_to(camera);
738        self.on_update();
739    }
740
741    /// The style's projection at the zoom; always Mercator in tile mode,
742    /// whose tiles are Mercator tiles.
743    fn projection_at(&self, zoom: f64) -> ProjectionDefinition {
744        if self.mode == MapMode::Tile {
745            return ProjectionDefinition::new(ProjectionType::Mercator);
746        }
747        self.style.get_projection().evaluate(zoom as f32)
748    }
749
750    /// Gives the transform the style's current projection, which constrains
751    /// the target of an animation it starts. The style reports each change
752    /// to its projection, and the map calls this then.
753    fn share_projection_with_transform(&mut self) {
754        let projection = (self.mode != MapMode::Tile).then(|| Arc::clone(self.style.get_projection()));
755        self.transform.set_projection_for_zoom(Some(Rc::new(move |zoom: f64| match &projection {
756            Some(projection) => projection.evaluate(zoom as f32),
757            None => ProjectionDefinition::new(ProjectionType::Mercator),
758        })));
759    }
760
761    // MARK: - Still images
762
763    /// Asks for a still image: the map's renderer draws frames until one
764    /// has everything loaded, and [`take_still_image`](Self::take_still_image)
765    /// then reports it. Fails with
766    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a continuous map
767    /// and while another still image is on its way, and with the style's
768    /// error when it failed to load.
769    pub fn render_still(&mut self) -> Result<(), Error> {
770        if self.mode != MapMode::Static && self.mode != MapMode::Tile {
771            return Err(Error::invalid_state("Map is not in static or tile image render modes"));
772        }
773        if self.still_image == StillImage::Pending {
774            return Err(Error::invalid_state("Map is currently rendering an image"));
775        }
776        if let Some(error) = self.loader.last_error() {
777            return Err(error.clone());
778        }
779        self.still_image = StillImage::Pending;
780        self.still_image_request_id += 1;
781        self.ground_moves = 0;
782        self.on_update();
783        Ok(())
784    }
785
786    /// How the still image that [`render_still`](Self::render_still) asked
787    /// for ended, once it has: `Ok` once a complete frame rendered, or why
788    /// the image failed. The map handles its renderer's reports in
789    /// [`process_events`](Self::process_events), so call that first.
790    pub fn take_still_image(&mut self) -> Option<Result<(), Error>> {
791        match std::mem::replace(&mut self.still_image, StillImage::None) {
792            StillImage::Ended(result) => Some(result),
793            other => {
794                self.still_image = other;
795                None
796            }
797        }
798    }
799
800    /// The still image request that waits for a frame, as the
801    /// `still_image_request_id` of the updates that ask for it, or `None`
802    /// once it ended.
803    #[must_use]
804    pub fn pending_still_image(&self) -> Option<u64> {
805        (self.still_image == StillImage::Pending).then_some(self.still_image_request_id)
806    }
807
808    /// Triggers a repaint.
809    pub fn trigger_repaint(&mut self) {
810        self.on_update();
811    }
812
813    /// When the map changes next on its own, though its last frame asked for
814    /// no other: the owner calls [`trigger_repaint`](Self::trigger_repaint)
815    /// then, by the frame clock. `None` once an update went out since.
816    #[must_use]
817    pub fn repaint_at(&self) -> Option<Instant> {
818        self.repaint_at
819    }
820
821    // MARK: - Feature state
822
823    /// Merges `state` into the state of the feature `feature_id` of the
824    /// source `source_id`, in its source layer `source_layer_id`: its keys
825    /// replace the same keys of the feature's state, and the other keys
826    /// stay. `None`, like the empty string, names no source layer.
827    ///
828    /// The map keeps the state until it is removed or a style loads, which
829    /// removes the state of every source, and sends it to the renderer with
830    /// its updates. Publishes an update when the state changes. Returns
831    /// whether it changed.
832    pub fn set_feature_state(
833        &mut self,
834        source_id: &str,
835        source_layer_id: Option<&str>,
836        feature_id: &str,
837        state: mln_style::feature::FeatureState,
838    ) -> bool {
839        let changed = self.feature_state.set(source_id, source_layer_id.unwrap_or(""), feature_id, state);
840        if changed {
841            self.on_update();
842        }
843        changed
844    }
845
846    /// The state of the feature `feature_id` of the source `source_id`, in
847    /// its source layer `source_layer_id`, empty when it has none.
848    #[must_use]
849    pub fn feature_state(
850        &self,
851        source_id: &str,
852        source_layer_id: Option<&str>,
853        feature_id: &str,
854    ) -> mln_style::feature::FeatureState {
855        self.feature_state.get(source_id, source_layer_id.unwrap_or(""), feature_id)
856    }
857
858    /// Removes the state of the feature `feature_id` of the source
859    /// `source_id`, in its source layer `source_layer_id`: only its key
860    /// `state_key` when there is one, and that of every feature in the
861    /// source layer without `feature_id`. Publishes an update when the state
862    /// changes. Returns whether it changed.
863    pub fn remove_feature_state(
864        &mut self,
865        source_id: &str,
866        source_layer_id: Option<&str>,
867        feature_id: Option<&str>,
868        state_key: Option<&str>,
869    ) -> bool {
870        let changed = self.feature_state.remove(source_id, source_layer_id.unwrap_or(""), feature_id, state_key);
871        if changed {
872            self.on_update();
873        }
874        changed
875    }
876
877    /// Removes the state of every feature of the source `source_id`, as when
878    /// the source leaves the style. Publishes an update when the state
879    /// changes. Returns whether it changed.
880    pub fn remove_source_feature_state(&mut self, source_id: &str) -> bool {
881        let changed = self.feature_state.remove_source(source_id);
882        if changed {
883            self.on_update();
884        }
885        changed
886    }
887
888    // MARK: - Style
889
890    /// The map's style.
891    #[must_use]
892    pub fn style(&self) -> &Arc<Style> {
893        &self.style
894    }
895
896    /// Edits the style: `edit` changes the next version of it, and the map
897    /// publishes that version for the renderer if anything changed. A
898    /// version that `edit` left as it was stays the same `Arc`, so it
899    /// publishes nothing. Returns what `edit` returns, and keeps what it
900    /// changed before it failed.
901    ///
902    /// Each source that the edit changed, rather than added or removed,
903    /// reports [`MapEvent::SourceChanged`].
904    pub fn edit_style<R, E>(&mut self, edit: impl FnOnce(&mut Style) -> Result<R, E>) -> Result<R, E> {
905        let before = Arc::clone(&self.style);
906        let result = edit(Arc::make_mut(&mut self.style));
907        let changed_sources = changed_sources(&before, &self.style);
908        if self.react_to_change(before) {
909            // A revalidated document no longer replaces the edited style.
910            self.loader.edited();
911        }
912        for source_id in changed_sources {
913            self.emit(MapEvent::SourceChanged { source_id });
914        }
915        result
916    }
917
918    /// As [`edit_style`](Self::edit_style), but fails with
919    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) ("style is not
920    /// loaded") until a style document parsed, and from the start of each
921    /// [`load_style_url`](Self::load_style_url) until its document parses:
922    /// the parse replaces the whole style, so an edit made before it would
923    /// be lost.
924    pub fn edit_loaded_style<R>(&mut self, edit: impl FnOnce(&mut Style) -> Result<R, Error>) -> Result<R, Error> {
925        if !self.loader.document_loaded() {
926            return Err(Error::invalid_state("style is not loaded"));
927        }
928        self.edit_style(edit)
929    }
930
931    /// Whether a style document parsed, and no
932    /// [`load_style_url`](Self::load_style_url) began since.
933    #[must_use]
934    pub fn style_document_loaded(&self) -> bool {
935        self.loader.document_loaded()
936    }
937
938    /// Makes an edit that the map itself causes, such as a sprite's images,
939    /// which doesn't count as an edit of the loaded document.
940    pub(crate) fn apply_loaded(&mut self, edit: Edit) -> Result<(), Error> {
941        let before = Arc::clone(&self.style);
942        let result = Arc::make_mut(&mut self.style).apply(edit);
943        self.react_to_change(before);
944        result
945    }
946
947    /// As [`apply_loaded`](Self::apply_loaded), for an edit that can't fail.
948    /// Returns whether it changed the style.
949    fn apply_loaded_changes(&mut self, edit: Edit) -> bool {
950        let before = Arc::clone(&self.style);
951        let _ = Arc::make_mut(&mut self.style).apply(edit);
952        self.react_to_change(before)
953    }
954
955    /// Reacts to the change from `before` to the current version: keeps
956    /// `before` when nothing changed, and otherwise starts the loads of new
957    /// sources, shares a new projection with the transform and publishes an
958    /// update. Returns whether anything changed.
959    fn react_to_change(&mut self, before: Arc<Style>) -> bool {
960        if before.is_same_version(&self.style) {
961            self.style = before;
962            return false;
963        }
964        if !Arc::ptr_eq(before.get_sources(), self.style.get_sources()) {
965            self.watch_sources();
966        }
967        if !Arc::ptr_eq(before.get_projection(), self.style.get_projection()) {
968            self.share_projection_with_transform();
969        }
970        self.on_update();
971        true
972    }
973
974    // MARK: - Sources
975
976    /// Adds `source` to the style, last, and starts loading its description.
977    /// Fails with [`ErrorKind::AlreadyExists`](mln_style::error::ErrorKind) if the
978    /// style has a source with its id, and with `InvalidArgument` if a layer
979    /// that names its id can't draw a source of its kind.
980    pub fn add_source(&mut self, source: Source) -> Result<(), Error> {
981        self.edit_style(|style| style.apply(Edit::AddSource(source)))
982    }
983
984    /// Adds the [source](https://maplibre.org/maplibre-style-spec/sources/)
985    /// that `json` describes, with the ID `id`.
986    ///
987    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) while the
988    /// style isn't loaded, with `AlreadyExists` if the style has a source
989    /// named `id`, and with `InvalidArgument` if `json` isn't a valid source
990    /// or a layer that names `id` can't draw it.
991    pub fn add_source_json(&mut self, id: &str, json: &str) -> Result<(), Error> {
992        if !self.loader.document_loaded() {
993            return Err(Error::invalid_state("style is not loaded"));
994        }
995        if self.style.get_source(id).is_some() {
996            return Err(Error::already_exists(format!("source \"{id}\" already exists")));
997        }
998        let value: serde_json::Value = serde_json::from_str(json)
999            .map_err(|error| Error::invalid_argument(format!("style source \"{id}\" is not valid JSON: {error}")))?;
1000        let mut error = mln_style::conversion::Error::default();
1001        let registry = Arc::clone(self.style.registry());
1002        let Some(source) = convert_source(&Convertible::from(&value), &mut error, id, &registry) else {
1003            return Err(Error::invalid_argument(format!("style source \"{id}\": {}", error.message)));
1004        };
1005        self.add_source(source)
1006    }
1007
1008    /// Removes the source `id` from the style and gives it back, unless a
1009    /// layer uses it, which logs a warning.
1010    pub fn remove_source(&mut self, id: &str) -> Option<Source> {
1011        if self.style.get_layers().any(|layer| layer.get_source_id() == id) {
1012            log::warn!(target: log_target::GENERAL, "Source '{id}' is in use, cannot remove");
1013            return None;
1014        }
1015        let source = self.style.get_source(id)?.clone();
1016        self.edit_style(|style| style.apply(Edit::RemoveSource(id.to_owned()))).ok()?;
1017        Some(source)
1018    }
1019
1020    /// The style's source `id`.
1021    #[must_use]
1022    pub fn source(&self, id: &str) -> Option<&Source> {
1023        self.style.get_source(id)
1024    }
1025
1026    /// The style's sources, in the order they were added.
1027    pub fn sources(&self) -> impl Iterator<Item = &Source> {
1028        self.style.get_sources().iter()
1029    }
1030
1031    /// Loads the style document `json`, which replaces the style, and
1032    /// cancels a URL load. A document that doesn't parse leaves the style
1033    /// as it was and reports [`MapEvent::LoadingFailed`].
1034    pub fn load_style_json(&mut self, json: &str) {
1035        let events = self.loader.load_json(self.style.registry(), json);
1036        self.handle_load_events(events);
1037    }
1038
1039    /// Fetches the style document at `url`, which replaces the style when it
1040    /// arrives and parses. The style stays meanwhile, but isn't loaded.
1041    pub fn load_style_url(&mut self, url: &str) {
1042        let events = self.loader.load_url(url);
1043        self.handle_load_events(events);
1044    }
1045
1046    /// The URL of the style document, or `None` for a style loaded from
1047    /// JSON or none at all.
1048    #[must_use]
1049    pub fn style_url(&self) -> Option<&str> {
1050        self.loader.url()
1051    }
1052
1053    /// Sets the font faces that every font stack falls back to, for the
1054    /// style documents that load after this call. They shape the text that
1055    /// glyph PBFs can't shape, or all the text of a style without glyph
1056    /// PBFs, and draw the glyphs that come from local fonts (`LocalGlyphs`)
1057    /// before the device's fonts do.
1058    ///
1059    /// `json` is an array of font files, each an object with a `url` and an
1060    /// optional `unicode-range`, as in a font face of a style's `font-faces`.
1061    /// It fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) if
1062    /// `json` isn't such an array. Without a font-face shaper, the map ignores
1063    /// them, as it ignores a style's `font-faces`.
1064    pub fn set_fallback_font_faces(&mut self, json: &str) -> Result<(), Error> {
1065        let faces = mln_style::parse_fallback_font_faces(json)?;
1066        self.set_fallback_font_face_list(faces.iter().map(FontFace::from).collect());
1067        Ok(())
1068    }
1069
1070    /// [`set_fallback_font_faces`](Self::set_fallback_font_faces) with faces
1071    /// an app has made, such as `FontFace::fallback(url, ranges).with_data(bytes)`
1072    /// for a font file it holds in memory, or `FontFace::system`, for the
1073    /// device's fonts that the renderer's `LocalGlyphs::chooser` chooses.
1074    pub fn set_fallback_font_face_list(&mut self, faces: FontFaces) {
1075        self.loader.set_fallback_font_faces(Some(Arc::new(faces)));
1076    }
1077
1078    /// The last error of a sprite or a source of the style since its load
1079    /// began, which fails still images.
1080    #[must_use]
1081    pub fn last_style_error(&self) -> Option<&Error> {
1082        self.loader.last_error()
1083    }
1084
1085    #[cfg(test)]
1086    pub(crate) fn style_loader(&self) -> &StyleLoader {
1087        &self.loader
1088    }
1089
1090    /// Whether the style document parsed, and its sprites and sources
1091    /// loaded.
1092    pub(crate) fn style_loaded(&self) -> bool {
1093        self.loader.document_loaded() && self.loader.sprites_loaded() && self.loader.sources_loaded(&self.style)
1094    }
1095
1096    // MARK: - Transitions
1097
1098    pub fn cancel_transitions(&mut self) {
1099        self.transform.cancel_transitions();
1100        self.on_update();
1101    }
1102
1103    /// Cancels the commands whose [`AnimationOptions::transition_id`] equals
1104    /// `transition_id`, and leaves the others running. Requests an update only
1105    /// when a command ended.
1106    pub fn cancel_transitions_with_id(&mut self, transition_id: u64) {
1107        let ended = self.transform.cancel_transitions_with_id(transition_id);
1108        if ended {
1109            self.on_update();
1110        }
1111    }
1112
1113    /// Moves the camera relative to where it is, as a gesture does
1114    /// (the C API's `mln_map_apply_camera_delta`): a pan, a zoom,
1115    /// turn and tilt around an anchor, a gesture phase, and the momentum a
1116    /// gesture's end continues with. See [`CameraDelta`]. Returns the
1117    /// command, whose end [`drain_command_ends`](Self::drain_command_ends)
1118    /// reports.
1119    pub fn apply_camera_delta(&mut self, delta: &CameraDelta) -> Result<CameraCommandId, CameraError> {
1120        let command = self.transform.apply_camera_delta(delta)?;
1121        self.camera_mutated = true;
1122        self.on_update();
1123        Ok(command)
1124    }
1125
1126    /// Moves the camera to absolute values, by a jump, an ease or a flight,
1127    /// as a command or as part of a gesture (the C API's
1128    /// `mln_map_update_camera`). See [`CameraUpdate`]. Returns the command,
1129    /// whose end [`drain_command_ends`](Self::drain_command_ends) reports.
1130    pub fn update_camera(&mut self, update: &CameraUpdate) -> CameraCommandId {
1131        self.camera_mutated = true;
1132        let command = self.transform.update_camera(update);
1133        self.on_update();
1134        command
1135    }
1136
1137    /// Ends the running camera commands as closed, as when the map closes,
1138    /// which [`drain_command_ends`](Self::drain_command_ends) reports. An
1139    /// owner that waits for the commands' ends calls it before it drops the
1140    /// map.
1141    pub fn close_camera(&mut self) {
1142        self.transform.close();
1143        self.forward_camera_events();
1144    }
1145
1146    /// Sets whether drags and zooms on the globe turn the bearing
1147    /// ([`Viewport::globe_free_bearing`]), as
1148    /// [`set_viewport`](Self::set_viewport) does.
1149    pub fn set_globe_free_bearing(&mut self, free_bearing: bool) {
1150        if free_bearing != self.transform.is_globe_free_bearing() {
1151            self.transform.set_globe_free_bearing(free_bearing);
1152            self.changed();
1153        }
1154    }
1155
1156    /// Samples the camera's animations at the host's frame time, from now on,
1157    /// and starts new ones from it: call it at the start of each frame with
1158    /// `Instant::now()`, before rendering. One older than
1159    /// [`STALE_FRAME_TIME`](crate::camera::transform::STALE_FRAME_TIME) counts as
1160    /// unset, so commands made while the host isn't drawing start now. If an
1161    /// animation runs, the map updates for this frame at once. `None` goes
1162    /// back to sampling at `Instant::now()` whenever the map updates. Still
1163    /// images ignore it. See
1164    /// [`Transform::set_frame_time`](crate::camera::transform::Transform::set_frame_time).
1165    pub fn set_frame_time(&mut self, time: Option<Instant>) {
1166        self.transform.set_frame_time(time);
1167        self.sample_frame();
1168    }
1169
1170    /// The clock that [`set_frame_time`](Self::set_frame_time) sets, for a
1171    /// host that sets it from the thread that draws, without updating the
1172    /// map. It then calls [`sample_frame`](Self::sample_frame) for each frame
1173    /// that an animation runs in.
1174    #[must_use]
1175    pub fn frame_clock(&self) -> FrameClock {
1176        self.transform.frame_clock()
1177    }
1178
1179    /// Updates the map for a frame at the frame clock's time, if an
1180    /// animation runs.
1181    pub fn sample_frame(&mut self) {
1182        if self.transform.in_transition() {
1183            self.on_update();
1184        }
1185    }
1186
1187    // MARK: - Camera
1188
1189    // query: the render-test runner's tile mode uses it.
1190    /// The bounds of the area the map shows from `camera`.
1191    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a camera whose
1192    /// corners have no `LatLng`.
1193    ///
1194    /// Over terrain, the area is where the view meets the plane through the
1195    /// camera's center, as [`camera_for_lat_lngs`](Self::camera_for_lat_lngs)
1196    /// fits it.
1197    pub fn lat_lng_bounds_for_camera(&self, camera: &CameraOptions) -> Result<LatLngBounds, Error> {
1198        let shallow = self.fitting_transform(camera);
1199        let size = shallow.state().view().size();
1200
1201        if shallow.state().view().is_globe() {
1202            return globe_bounds(&shallow);
1203        }
1204        Ok(LatLngBounds::hull(
1205            shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(0.0, 0.0), WrapMode::Wrapped)?,
1206            shallow.screen_coordinate_to_lat_lng(
1207                &ScreenCoordinate::new(f64::from(size.width), f64::from(size.height)),
1208                WrapMode::Wrapped,
1209            )?,
1210        ))
1211    }
1212
1213    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a NaN or infinite
1214    /// point.
1215    pub fn move_by(&mut self, point: &ScreenCoordinate, animation: &AnimationOptions) -> Result<(), Error> {
1216        self.camera_mutated = true;
1217        self.transform.move_by(point, animation)?;
1218        self.on_update();
1219        Ok(())
1220    }
1221
1222    // gtests-core: cameraForLatLngBounds, cameraForLatLngs,
1223    // latLngBoundsForCameraUnwrapped (test/map/map.test.cpp).
1224    /// The camera that fits `bounds` in the view, inset by `padding`, at
1225    /// `bearing` and `pitch` (the current ones for `None`). Fails with
1226    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a center that has no
1227    /// `LatLng` (padding that pushes it to infinity).
1228    pub fn camera_for_lat_lng_bounds(
1229        &self,
1230        bounds: &LatLngBounds,
1231        padding: &EdgeInsets,
1232        bearing: Option<f64>,
1233        pitch: Option<f64>,
1234    ) -> Result<CameraOptions, Error> {
1235        self.camera_for_lat_lngs(
1236            &[bounds.northwest(), bounds.southwest(), bounds.southeast(), bounds.northeast()],
1237            padding,
1238            bearing,
1239            pitch,
1240        )
1241    }
1242
1243    /// The camera that fits every point of `lat_lngs` in the view, inset by
1244    /// `padding`, at `bearing` and `pitch` (the current ones for `None`).
1245    /// Fails as [`camera_for_lat_lng_bounds`](Self::camera_for_lat_lng_bounds)
1246    /// does.
1247    ///
1248    /// On the flat map the points stand at sea level, and the center keeps
1249    /// its altitude. Over terrain, where the center will stand isn't known
1250    /// until the ground there draws, so the points fit as if they stood as
1251    /// high as the center: the camera shows them inside the padding at that
1252    /// height, whatever altitude it comes to. Points on higher ground can
1253    /// show past the padding, and those on lower ground inside it.
1254    pub fn camera_for_lat_lngs(
1255        &self,
1256        lat_lngs: &[LatLng],
1257        padding: &EdgeInsets,
1258        bearing: Option<f64>,
1259        pitch: Option<f64>,
1260    ) -> Result<CameraOptions, Error> {
1261        let transform = self.fitting_transform(&CameraOptions { bearing, pitch, ..Default::default() });
1262        if bearing.is_none() && pitch.is_none() {
1263            return camera_for_lat_lngs(lat_lngs, &transform, padding);
1264        }
1265
1266        Ok(CameraOptions {
1267            bearing: Some(mln_style::math::rad2deg(-transform.view().angle())),
1268            pitch: Some(mln_style::math::rad2deg(transform.view().pitch())),
1269            ..camera_for_lat_lngs(lat_lngs, &transform, padding)?
1270        })
1271    }
1272
1273    /// The camera that fits every point of `geometry` (x longitude, y
1274    /// latitude), as [`camera_for_lat_lngs`](Self::camera_for_lat_lngs) fits
1275    /// them. Fails as that does, and with
1276    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a point with no
1277    /// `LatLng` (an infinite or NaN coordinate, or a latitude beyond ±90°).
1278    pub fn camera_for_geometry(
1279        &self,
1280        geometry: &Geometry<f64>,
1281        padding: &EdgeInsets,
1282        bearing: Option<f64>,
1283        pitch: Option<f64>,
1284    ) -> Result<CameraOptions, Error> {
1285        let mut points = Vec::new();
1286        for_each_point(geometry, &mut |point| points.push(*point));
1287        let lat_lngs = points.iter().map(|point| LatLng::new(point.y, point.x)).collect::<Result<Vec<_>, _>>()?;
1288        self.camera_for_lat_lngs(&lat_lngs, padding, bearing, pitch)
1289    }
1290
1291    /// The bounds of the area the map shows from `camera`, with the corners
1292    /// unwrapped toward the center, so that the bounds can cross the
1293    /// antimeridian. Fails as
1294    /// [`lat_lng_bounds_for_camera`](Self::lat_lng_bounds_for_camera) does.
1295    pub fn lat_lng_bounds_for_camera_unwrapped(&self, camera: &CameraOptions) -> Result<LatLngBounds, Error> {
1296        let shallow = self.fitting_transform(camera);
1297        let size = shallow.state().view().size();
1298
1299        if shallow.state().view().is_globe() {
1300            return globe_bounds(&shallow);
1301        }
1302        let width = f64::from(size.width);
1303        let height = f64::from(size.height);
1304        let mut nw = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(0.0, 0.0), WrapMode::Wrapped)?;
1305        let mut se = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(width, height), WrapMode::Wrapped)?;
1306        let mut ne = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(width, 0.0), WrapMode::Wrapped)?;
1307        let mut sw = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(0.0, height), WrapMode::Wrapped)?;
1308        let center = shallow
1309            .screen_coordinate_to_lat_lng(&ScreenCoordinate::new(width / 2.0, height / 2.0), WrapMode::Wrapped)?;
1310        nw.unwrap_for_shortest_path(&center);
1311        se.unwrap_for_shortest_path(&center);
1312        ne.unwrap_for_shortest_path(&center);
1313        sw.unwrap_for_shortest_path(&center);
1314        let mut bounds = LatLngBounds::hull(nw, se);
1315        bounds.extend(&ne);
1316        bounds.extend(&sw);
1317        bounds.extend(&center);
1318        Ok(bounds)
1319    }
1320
1321    /// A copy of the map's transform moved by `camera`, without the map's
1322    /// terrain, to fit cameras and find what they show. Over terrain its
1323    /// center stands at sea level, whatever its altitude: a view is the same
1324    /// raised by any height but for where the ground meets it, so sea-level
1325    /// conversions then meet the plane through the center.
1326    fn fitting_transform(&self, camera: &CameraOptions) -> Transform {
1327        let mut transform = Transform::from_state(self.transform.state().clone());
1328        let center_altitude = if self.terrain_applies() { Some(0.0) } else { camera.center_altitude };
1329        let camera = CameraOptions { center_altitude, ..*camera };
1330        if camera != CameraOptions::default() {
1331            transform.jump_to(&camera);
1332        }
1333        transform
1334    }
1335
1336    // MARK: - Bounds
1337
1338    pub fn set_bounds(&mut self, options: &BoundOptions) -> Result<(), Error> {
1339        let current = *self.transform.state().limits();
1340        let limits = CameraLimits {
1341            bounds: options.bounds.unwrap_or(current.bounds),
1342            min_zoom: options.min_zoom.unwrap_or(current.min_zoom),
1343            max_zoom: options.max_zoom.unwrap_or(current.max_zoom),
1344            min_pitch: options.min_pitch.map_or(current.min_pitch, mln_style::math::deg2rad),
1345            max_pitch: options.max_pitch.map_or(current.max_pitch, mln_style::math::deg2rad),
1346        };
1347        self.transform.set_limits(limits)?;
1348        if *options != BoundOptions::default() {
1349            self.changed();
1350        }
1351
1352        // The camera moves inside the limits that changed.
1353        let state = self.transform.state();
1354        let view = state.view();
1355        let limits = *state.limits();
1356        let mut camera_options = CameraOptions::default();
1357        let mut change_camera = options.bounds.is_some();
1358        if options.min_zoom.is_some() {
1359            // On the globe the lowest zoom falls with latitude; on Mercator it
1360            // is the minimum.
1361            let latitude_term =
1362                state.min_zoom_at_latitude(view.center(WrapMode::Unwrapped).latitude()) - state.min_zoom();
1363            let min_zoom = limits.min_zoom + latitude_term;
1364            if view.zoom() < min_zoom {
1365                change_camera = true;
1366                camera_options.zoom = Some(min_zoom);
1367            }
1368        }
1369        if options.max_zoom.is_some() && view.zoom() > limits.max_zoom {
1370            change_camera = true;
1371            camera_options.zoom = Some(limits.max_zoom);
1372        }
1373        if options.max_pitch.is_some() && view.pitch() > limits.max_pitch {
1374            change_camera = true;
1375            camera_options.pitch = Some(mln_style::math::rad2deg(limits.max_pitch));
1376        }
1377        if options.min_pitch.is_some() && view.pitch() < limits.min_pitch {
1378            change_camera = true;
1379            camera_options.pitch = Some(mln_style::math::rad2deg(limits.min_pitch));
1380        }
1381
1382        if change_camera {
1383            self.jump_to(&camera_options);
1384        }
1385        Ok(())
1386    }
1387
1388    // MARK: - Map options
1389
1390    /// Sets how the map orients and constrains its view, every setting at
1391    /// once.
1392    pub fn set_viewport(&mut self, viewport: &Viewport) {
1393        let state = self.transform.state();
1394        let (orientation, constrain_mode, viewport_mode, frustum_offset) = (
1395            state.view().north_orientation(),
1396            state.constrain_mode(),
1397            state.view().viewport_mode(),
1398            state.view().frustum_offset(),
1399        );
1400        if viewport.north_orientation != orientation {
1401            self.transform.set_north_orientation(viewport.north_orientation);
1402        }
1403        if viewport.constrain_mode != constrain_mode {
1404            self.transform.set_constrain_mode(viewport.constrain_mode);
1405        }
1406        if viewport.viewport_mode != viewport_mode {
1407            self.transform.set_viewport_mode(viewport.viewport_mode);
1408        }
1409        if viewport.frustum_offset != frustum_offset {
1410            self.transform.set_frustum_offset(&viewport.frustum_offset);
1411        }
1412        if viewport.center_clamped_to_ground != self.center_clamped_to_ground() {
1413            self.transform.set_center_clamped_to_ground(viewport.center_clamped_to_ground);
1414        }
1415        if viewport.globe_free_bearing != self.transform.is_globe_free_bearing() {
1416            self.transform.set_globe_free_bearing(viewport.globe_free_bearing);
1417        }
1418        self.on_update();
1419    }
1420
1421    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an empty size.
1422    pub fn set_size(&mut self, size: Size) -> Result<(), Error> {
1423        self.transform.resize(size)?;
1424        self.on_update();
1425        Ok(())
1426    }
1427
1428    /// Sets the map's pixel ratio: device pixels per logical pixel. The
1429    /// renderer draws the next frame at the new ratio and lays the loaded
1430    /// tiles out again without loading them, and the style loads its sprites
1431    /// again where the ratio picks their other resolution.
1432    ///
1433    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
1434    /// ratio that isn't finite and positive.
1435    pub fn set_pixel_ratio(&mut self, pixel_ratio: f32) -> Result<(), Error> {
1436        if !pixel_ratio.is_finite() || pixel_ratio <= 0.0 {
1437            return Err(Error::invalid_argument(format!("pixel ratio {pixel_ratio} isn't finite and positive")));
1438        }
1439        if pixel_ratio == self.pixel_ratio {
1440            return Ok(());
1441        }
1442        self.pixel_ratio = pixel_ratio;
1443        let events = self.loader.set_pixel_ratio(pixel_ratio);
1444        self.handle_load_events(events);
1445        self.on_update();
1446        Ok(())
1447    }
1448
1449    // MARK: - Projection mode
1450
1451    pub fn set_projection_mode(&mut self, options: &ProjectionMode) {
1452        self.transform.set_projection_mode(options);
1453        self.on_update();
1454    }
1455
1456    // MARK: - Transform
1457
1458    /// The camera, the viewport and the limits the camera moves within.
1459    #[must_use]
1460    pub fn transform_state(&self) -> &TransformState {
1461        self.transform.state()
1462    }
1463
1464    // MARK: - Tile settings
1465
1466    /// Sets how the map picks the tiles to load, every setting at once, in
1467    /// the units that its snapshot reports them. Publishes an update when
1468    /// they change.
1469    pub fn set_tile_settings(&mut self, tile: &TileSettings) {
1470        if self.tile != *tile {
1471            self.tile = *tile;
1472            self.on_update();
1473        }
1474    }
1475
1476    // gtests-core: projection and prefetch zoom delta (test/map, test/api).
1477    // MARK: - Projection
1478
1479    /// The screen point of `lat_lng`, in the copy of the world nearest the
1480    /// camera's center, standing on the ground the map draws: over terrain,
1481    /// at the height the renderer drew the ground at there ([`Self::ground`]),
1482    /// or at the center's altitude where it drew none; on the flat map, at
1483    /// sea level. A location that nearer ground hides still has the point
1484    /// where its ground draws.
1485    #[must_use]
1486    pub fn pixel_for_lat_lng(&self, lat_lng: &LatLng) -> ScreenCoordinate {
1487        crate::camera::map_projection::pixel_for_lat_lng(self.transform.view(), self.ground().as_deref(), lat_lng)
1488    }
1489
1490    /// The location that `pixel` shows on the ground the map draws: over
1491    /// terrain, where its line of sight first meets the ground the renderer
1492    /// drew ([`Self::ground`]), or, where it meets none, as in the sky, the
1493    /// plane at the center's altitude; on the flat map, sea level.
1494    /// [`pixel_for_lat_lng`](Self::pixel_for_lat_lng) takes the location
1495    /// back to the pixel, but above the horizon of the plane, which the line
1496    /// of sight doesn't meet. Fails with
1497    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a NaN or
1498    /// infinite pixel.
1499    pub fn lat_lng_for_pixel(&self, pixel: &ScreenCoordinate, wrap_mode: WrapMode) -> Result<LatLng, Error> {
1500        crate::camera::map_projection::lat_lng_for_pixel(
1501            self.transform.view(),
1502            self.ground().as_deref(),
1503            pixel,
1504            wrap_mode,
1505        )
1506    }
1507
1508    /// Whether the globe hides a location from the camera; a Mercator map
1509    /// hides nothing.
1510    #[cfg(test)]
1511    pub(crate) fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
1512        self.transform.is_location_occluded(lat_lng)
1513    }
1514
1515    /// [`lat_lng_for_pixel`](Self::lat_lng_for_pixel) of each pixel. Fails
1516    /// as that does for any of them.
1517    pub fn lat_lngs_for_pixels(
1518        &self,
1519        screen_coords: &[ScreenCoordinate],
1520        wrap_mode: WrapMode,
1521    ) -> Result<Vec<LatLng>, Error> {
1522        let ground = self.ground();
1523        let view = self.transform.view();
1524        screen_coords
1525            .iter()
1526            .map(|pixel| crate::camera::map_projection::lat_lng_for_pixel(view, ground.as_deref(), pixel, wrap_mode))
1527            .collect()
1528    }
1529
1530    /// Places the camera by its position and orientation, and cancels the
1531    /// running camera commands. A NaN position, or a NaN or zero-length
1532    /// orientation, is ignored; the position's height is clamped to the zoom
1533    /// range.
1534    pub fn set_free_camera_options(&mut self, camera: &crate::camera::FreeCameraOptions) {
1535        self.transform.set_free_camera_options(camera);
1536        self.camera_mutated = true;
1537        self.on_update();
1538    }
1539
1540    // MARK: - Terrain
1541
1542    /// Sets whether the center stands on the terrain, at its height under
1543    /// the center ([`Viewport::center_clamped_to_ground`]), as
1544    /// [`set_viewport`](Self::set_viewport) does. Turning it on stands a
1545    /// camera at rest on the ground at once, without camera events; turning
1546    /// it off leaves the altitude where it is.
1547    pub fn set_center_clamped_to_ground(&mut self, clamped: bool) {
1548        if self.center_clamped_to_ground() != clamped {
1549            self.transform.set_center_clamped_to_ground(clamped);
1550            self.on_update();
1551        }
1552    }
1553
1554    /// Whether the center stands on the terrain.
1555    #[must_use]
1556    pub fn center_clamped_to_ground(&self) -> bool {
1557        self.transform.view().center_clamped_to_ground()
1558    }
1559
1560    /// Hands the transform the terrain the camera stands on
1561    /// ([`Self::terrain_ground`]), and moves the camera onto it
1562    /// ([`Transform::follow_terrain`]).
1563    ///
1564    /// The moves report no camera change. A still image stops following the
1565    /// terrain after [`MAX_GROUND_MOVES_PER_STILL`] of them, though it still
1566    /// goes back to the flat map, and its updates still carry the newest
1567    /// ground, so its frame draws.
1568    fn follow_terrain(&mut self) {
1569        let ground = self.terrain_ground();
1570        let grounded = ground.as_ref().is_some_and(|ground| ground.elevation.is_some());
1571        self.transform.set_terrain(ground);
1572        let still = self.mode != MapMode::Continuous && self.still_image == StillImage::Pending;
1573        if still && grounded && self.ground_moves >= MAX_GROUND_MOVES_PER_STILL {
1574            return;
1575        }
1576        if self.transform.follow_terrain() && still && grounded {
1577            self.ground_moves += 1;
1578            if self.ground_moves == MAX_GROUND_MOVES_PER_STILL {
1579                log::warn!(
1580                    target: log_target::RENDER,
1581                    "The camera didn't settle on the terrain: the still image shows it where it last moved"
1582                );
1583            }
1584        }
1585    }
1586
1587    /// The terrain the camera stands on: the ground the renderer last drew,
1588    /// while the style has terrain outside tile mode, on every projection;
1589    /// else none, which turns the camera's rules over terrain off.
1590    fn terrain_ground(&mut self) -> Option<TerrainGround> {
1591        // The renderer tells of the ground only after it draws an update
1592        // without it, so the map, which owns the style, lets go first.
1593        if self.style.get_terrain().is_none() {
1594            self.elevation = None;
1595        }
1596        self.terrain_applies()
1597            .then(|| TerrainGround { elevation: self.elevation.clone(), clamped: self.center_clamped_to_ground() })
1598    }
1599
1600    /// Whether the style's terrain applies: it has terrain, outside tile
1601    /// mode, on every projection.
1602    fn terrain_applies(&self) -> bool {
1603        self.style.get_terrain().is_some() && self.mode != MapMode::Tile
1604    }
1605
1606    /// The ground of the style's terrain as the renderer last drew it, which
1607    /// the camera stands on and the map's conversions meet
1608    /// ([`pixel_for_lat_lng`](Self::pixel_for_lat_lng)). `None` while the
1609    /// map draws flat: without terrain, in tile mode, and until the renderer
1610    /// draws the terrain.
1611    #[must_use]
1612    pub fn ground(&self) -> Option<Arc<dyn Elevation>> {
1613        self.elevation.clone().filter(|_| self.terrain_applies())
1614    }
1615
1616    /// Grows with each change to the map's state: each call that changes it,
1617    /// and each change that loading, rendering and animations make.
1618    #[must_use]
1619    pub fn generation(&self) -> u64 {
1620        self.generation
1621    }
1622
1623    /// Counts the updates that the map has published for its renderer.
1624    /// An update that a command group holds back counts when it shows.
1625    #[must_use]
1626    pub fn update_generation(&self) -> u64 {
1627        self.updates.generation()
1628    }
1629
1630    /// The generation of the update that shows the map's changes so far:
1631    /// [`update_generation`](Self::update_generation), or while a command
1632    /// group holds an update back, the one that the outermost group's end
1633    /// shows.
1634    #[must_use]
1635    pub fn pending_update_generation(&self) -> u64 {
1636        self.updates.pending_generation()
1637    }
1638
1639    /// Copies the map's state.
1640    #[must_use]
1641    pub fn snapshot(&self) -> MapSnapshot {
1642        let transform = &self.transform;
1643        let state = transform.state();
1644        let bounds = state.limits().bounds;
1645        let free_camera = state.view().free_camera_options();
1646        MapSnapshot {
1647            generation: self.generation,
1648            update_generation: self.updates.generation(),
1649            fully_loaded: self.is_fully_loaded(),
1650            gesture_in_progress: transform.is_gesture_in_progress(),
1651            transition_in_progress: transform.in_transition(),
1652            tile: self.tile,
1653            bounds: CameraBounds {
1654                bounds: (bounds != LatLngBounds::infinite()).then_some(bounds),
1655                min_zoom: state.min_zoom(),
1656                max_zoom: state.limits().max_zoom,
1657                min_pitch: mln_style::math::rad2deg(state.limits().min_pitch),
1658                max_pitch: mln_style::math::rad2deg(state.limits().max_pitch),
1659            },
1660            free_camera: FreeCamera {
1661                position: free_camera.position.unwrap_or_default(),
1662                orientation: free_camera.orientation.unwrap_or_default(),
1663            },
1664            view: state.view().map_view(f64::from(self.pixel_ratio)),
1665            globe_rendering: state.view().is_globe(),
1666        }
1667    }
1668
1669    fn is_fully_loaded(&self) -> bool {
1670        self.style_loaded() && self.renderer_fully_loaded
1671    }
1672
1673    /// Logs the style's sources and their state.
1674    pub fn dump_debug_logs(&self) {
1675        let rule = "-".repeat(80);
1676        log::info!(target: log_target::GENERAL, "{rule}");
1677        log::info!(target: log_target::GENERAL, "styleURL: {}", self.loader.url().unwrap_or_default());
1678        for source in self.style.get_sources().iter() {
1679            log::info!(target: log_target::GENERAL, "Source::id: {}", source.id());
1680            log::info!(
1681                target: log_target::GENERAL,
1682                "Source::loaded: {}",
1683                i32::from(self.loader.source_loaded(source.id()))
1684            );
1685        }
1686        log::info!(target: log_target::GENERAL, "{rule}");
1687    }
1688}
1689
1690/// The ids of the sources that are in both `before` and `after`, as the same
1691/// instance, and changed from one to the other, in `after`'s order.
1692fn changed_sources(before: &Style, after: &Style) -> Vec<String> {
1693    let (old, new) = (before.get_sources(), after.get_sources());
1694    if Arc::ptr_eq(old, new) {
1695        return Vec::new();
1696    }
1697    new.iter()
1698        .filter(|source| {
1699            old.get(source.id()).is_some_and(|old| old.instance() == source.instance() && !Source::ptr_eq(old, source))
1700        })
1701        .map(|source| source.id().to_owned())
1702        .collect()
1703}
1704
1705// gtests-core: the free function `cameraForLatLngs(latLngs, transform,
1706// padding)` of map.cpp (Map::cameraForLatLngs and MapProjection use it).
1707pub(crate) fn camera_for_lat_lngs(
1708    lat_lngs: &[LatLng],
1709    transform: &Transform,
1710    padding: &EdgeInsets,
1711) -> Result<CameraOptions, Error> {
1712    if lat_lngs.is_empty() {
1713        return Ok(CameraOptions::default());
1714    }
1715    if transform.state().view().is_globe() {
1716        camera_for_lat_lngs_on_globe(lat_lngs, transform, padding)
1717    } else {
1718        camera_for_lat_lngs_on_screen(lat_lngs, transform, padding)
1719    }
1720}
1721
1722/// Fails as `Map::camera_for_lat_lngs` does.
1723fn camera_for_lat_lngs_on_screen(
1724    lat_lngs: &[LatLng],
1725    transform: &Transform,
1726    padding: &EdgeInsets,
1727) -> Result<CameraOptions, Error> {
1728    let size = transform.state().view().size();
1729    // Calculate the bounds of the possibly rotated shape with respect to the viewport.
1730    let mut ne_pixel = ScreenCoordinate::new(f64::NEG_INFINITY, f64::NEG_INFINITY);
1731    let mut sw_pixel = ScreenCoordinate::new(f64::INFINITY, f64::INFINITY);
1732    for lat_lng in lat_lngs {
1733        let pixel = transform.lat_lng_to_screen_coordinate(lat_lng);
1734        // std::min / std::max
1735        sw_pixel.x = if pixel.x < sw_pixel.x { pixel.x } else { sw_pixel.x };
1736        ne_pixel.x = if ne_pixel.x < pixel.x { pixel.x } else { ne_pixel.x };
1737        sw_pixel.y = if pixel.y < sw_pixel.y { pixel.y } else { sw_pixel.y };
1738        ne_pixel.y = if ne_pixel.y < pixel.y { pixel.y } else { ne_pixel.y };
1739    }
1740    let width = ne_pixel.x - sw_pixel.x;
1741    let height = ne_pixel.y - sw_pixel.y;
1742
1743    // Calculate the zoom level.
1744    let mut min_scale = f64::INFINITY;
1745    if width > 0.0 || height > 0.0 {
1746        let mut scale_x = f64::from(size.width) / width;
1747        let mut scale_y = f64::from(size.height) / height;
1748        scale_x -= (padding.left() + padding.right()) / width;
1749        scale_y -= (padding.top() + padding.bottom()) / height;
1750        min_scale = mln_style::math::fmin(scale_x, scale_y);
1751    }
1752
1753    let mut zoom = transform.view().zoom();
1754    if min_scale > 0.0 {
1755        zoom = mln_style::math::clamp_f64(
1756            zoom + min_scale.log2(),
1757            transform.state().min_zoom(),
1758            transform.state().limits().max_zoom,
1759        );
1760    } else {
1761        log::error!(
1762            target: log_target::GENERAL,
1763            "Unable to calculate appropriate zoom level for bounds. Vertical or horizontal padding is greater than \
1764             map's height or width."
1765        );
1766    }
1767
1768    // Calculate the center point of a virtual bounds that is extended in all directions by padding.
1769    let center_pixel =
1770        ScreenCoordinate::new(f64::midpoint(ne_pixel.x, sw_pixel.x), f64::midpoint(ne_pixel.y, sw_pixel.y));
1771
1772    Ok(CameraOptions {
1773        center: Some(transform.screen_coordinate_to_lat_lng(&center_pixel, WrapMode::Wrapped)?),
1774        padding: Some(*padding),
1775        zoom: Some(zoom),
1776        ..Default::default()
1777    })
1778}
1779
1780/// GL JS `solveVectorScale`: how much to scale the globe for a surface point
1781/// to land on `target` along one clip axis, or nothing when the equation
1782/// degenerates. Zooming out also moves the camera along `to_center`, so the
1783/// point solved for is `vector * t + to_center * (1 - t)`.
1784fn globe_scale_for_clip_target(
1785    vector: DVec3,
1786    to_center: DVec3,
1787    projection: &DMat4,
1788    x_axis: bool,
1789    target: f64,
1790) -> Option<f64> {
1791    // The rows of the clip axis and of w.
1792    let column = projection.row(usize::from(!x_axis));
1793    let column_z = projection.row(3);
1794
1795    let vector_dot = vector.dot(column.truncate());
1796    let vector_dot_z = vector.dot(column_z.truncate());
1797    let to_center_dot = to_center.dot(column.truncate());
1798    let to_center_dot_z = to_center.dot(column_z.truncate());
1799
1800    if to_center_dot + target * vector_dot_z == vector_dot + target * to_center_dot_z
1801        || column_z[3] * (vector_dot - to_center_dot)
1802            + column[3] * (to_center_dot_z - vector_dot_z)
1803            + vector_dot * to_center_dot_z
1804            == to_center_dot * vector_dot_z
1805    {
1806        return None;
1807    }
1808    Some(
1809        (to_center_dot + column[3] - target * to_center_dot_z - target * column_z[3])
1810            / (to_center_dot - vector_dot - target * to_center_dot_z + target * vector_dot_z),
1811    )
1812}
1813
1814fn keep_smallest_scale(smallest: &mut f64, candidate: Option<f64>) {
1815    if let Some(candidate) = candidate
1816        && candidate >= 0.0
1817        && candidate < *smallest
1818    {
1819        *smallest = candidate;
1820    }
1821}
1822
1823/// GL JS `VerticalPerspectiveCameraHelper.cameraForBoxAndBearing`: fit the
1824/// flat world first, then scale the globe until every corner and edge
1825/// midpoint of the bounds is inside the padded viewport, with no pitch.
1826/// Fails as `Map::camera_for_lat_lngs` does.
1827fn camera_for_lat_lngs_on_globe(
1828    lat_lngs: &[LatLng],
1829    transform: &Transform,
1830    padding: &EdgeInsets,
1831) -> Result<CameraOptions, Error> {
1832    let mut flat = Transform::from_state(transform.state().clone());
1833    flat.set_projection_definition(&ProjectionDefinition::new(ProjectionType::Mercator));
1834    flat.jump_to(&CameraOptions { pitch: Some(0.0), roll: Some(0.0), ..Default::default() });
1835    let fit = camera_for_lat_lngs_on_screen(lat_lngs, &flat, padding)?;
1836    let (Some(fit_center), Some(fit_zoom)) = (fit.center, fit.zoom) else {
1837        return Ok(fit);
1838    };
1839
1840    // Solve with the padding the returned camera is shown with.
1841    let mut globe = Transform::from_state(transform.state().clone());
1842    globe.jump_to(&CameraOptions {
1843        center: Some(fit_center),
1844        zoom: Some(fit_zoom),
1845        padding: Some(*padding),
1846        pitch: Some(0.0),
1847        roll: Some(0.0),
1848        ..Default::default()
1849    });
1850    let state = globe.state();
1851    let matrix = state.view().globe_view_projection_matrix();
1852    let size = state.view().size();
1853    let width = f64::from(size.width);
1854    let height = f64::from(size.height);
1855    let left = padding.left() / width * 2.0 - 1.0;
1856    let right = (width - padding.right()) / width * 2.0 - 1.0;
1857    let top = padding.top() / height * -2.0 + 1.0;
1858    let bottom = (height - padding.bottom()) / height * -2.0 + 1.0;
1859
1860    let mut bounds = LatLngBounds::empty();
1861    for lat_lng in lat_lngs {
1862        bounds.extend(lat_lng);
1863    }
1864    let west = bounds.west();
1865    let east = bounds.east();
1866    let north = bounds.north();
1867    let south = bounds.south();
1868    let mid_longitude = west + VerticalPerspectiveProjection::difference_of_angles_degrees(west, east) * 0.5;
1869    let mid_latitude = north + VerticalPerspectiveProjection::difference_of_angles_degrees(north, south) * 0.5;
1870    let samples = [
1871        LatLng::new(north, west)?,
1872        LatLng::new(north, east)?,
1873        LatLng::new(south, west)?,
1874        LatLng::new(south, east)?,
1875        LatLng::new(mid_latitude, east)?,
1876        LatLng::new(mid_latitude, west)?,
1877        LatLng::new(north, mid_longitude)?,
1878        LatLng::new(south, mid_longitude)?,
1879    ];
1880    let to_center = VerticalPerspectiveProjection::surface_vector(&fit_center);
1881
1882    let mut smallest = f64::INFINITY;
1883    for sample in &samples {
1884        let vector = VerticalPerspectiveProjection::surface_vector(sample);
1885        if left < 0.0 {
1886            keep_smallest_scale(&mut smallest, globe_scale_for_clip_target(vector, to_center, &matrix, true, left));
1887        }
1888        if right > 0.0 {
1889            keep_smallest_scale(&mut smallest, globe_scale_for_clip_target(vector, to_center, &matrix, true, right));
1890        }
1891        if top > 0.0 {
1892            keep_smallest_scale(&mut smallest, globe_scale_for_clip_target(vector, to_center, &matrix, false, top));
1893        }
1894        if bottom < 0.0 {
1895            keep_smallest_scale(&mut smallest, globe_scale_for_clip_target(vector, to_center, &matrix, false, bottom));
1896        }
1897    }
1898    if !smallest.is_finite() || smallest == 0.0 {
1899        log::warn!(target: log_target::GENERAL, "Unable to fit the bounds on the globe; keeping the flat fit.");
1900        return Ok(fit);
1901    }
1902    Ok(CameraOptions {
1903        zoom: Some(f64::min(globe.view().zoom() + crate::camera::scale_zoom(smallest), state.limits().max_zoom)),
1904        ..fit
1905    })
1906}
1907
1908/// GL JS's globe bounds: the farthest of eight edge points on each side of
1909/// the center, where points off the planet fall on its horizon, widened to
1910/// every longitude when a pole is on screen.
1911/// Fails as `Map::lat_lng_bounds_for_camera` does.
1912fn globe_bounds(transform: &Transform) -> Result<LatLngBounds, Error> {
1913    let width = f64::from(transform.state().view().size().width);
1914    let height = f64::from(transform.state().view().size().height);
1915    let center = transform.view().center(WrapMode::Wrapped);
1916    let mut west = 0.0;
1917    let mut east = 0.0;
1918    let mut south = 0.0;
1919    let mut north = 0.0;
1920    for point in [
1921        ScreenCoordinate::new(0.0, 0.0),
1922        ScreenCoordinate::new(width / 2.0, 0.0),
1923        ScreenCoordinate::new(width, 0.0),
1924        ScreenCoordinate::new(width, height / 2.0),
1925        ScreenCoordinate::new(width, height),
1926        ScreenCoordinate::new(width / 2.0, height),
1927        ScreenCoordinate::new(0.0, height),
1928        ScreenCoordinate::new(0.0, height / 2.0),
1929    ] {
1930        let lat_lng = transform.screen_coordinate_to_lat_lng(&point, WrapMode::Wrapped)?;
1931        let longitude =
1932            VerticalPerspectiveProjection::difference_of_angles_degrees(center.longitude(), lat_lng.longitude());
1933        let latitude =
1934            VerticalPerspectiveProjection::difference_of_angles_degrees(center.latitude(), lat_lng.latitude());
1935        west = f64::min(west, longitude);
1936        east = f64::max(east, longitude);
1937        south = f64::min(south, latitude);
1938        north = f64::max(north, latitude);
1939    }
1940    west += center.longitude();
1941    east += center.longitude();
1942    south += center.latitude();
1943    north += center.latitude();
1944
1945    let on_screen = |pole: &LatLng| {
1946        // In front of the camera and inside its depth range, as GL JS's
1947        // isSurfacePointOnScreen asks.
1948        let (_, clip) =
1949            VerticalPerspectiveProjection::lat_lng_to_screen_coordinate(transform.state().view(), pole, 0.0);
1950        if clip[3] <= 0.0 || (clip[2] / clip[3]).abs() >= 1.0 {
1951            return false;
1952        }
1953        let point = transform.lat_lng_to_screen_coordinate(pole);
1954        !transform.state().view().is_location_occluded(pole)
1955            && point.x > 0.0
1956            && point.x < width
1957            && point.y > 0.0
1958            && point.y < height
1959    };
1960    if on_screen(&LatLng::new(90.0, 0.0)?) {
1961        north = 90.0;
1962        west = -180.0;
1963        east = 180.0;
1964    }
1965    if on_screen(&LatLng::new(-90.0, 0.0)?) {
1966        south = -90.0;
1967        west = -180.0;
1968        east = 180.0;
1969    }
1970    Ok(LatLngBounds::hull(LatLng::new(south, west)?, LatLng::new(north, east)?))
1971}