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