Skip to main content

mln_engine/source/
mod.rs

1//! The source type contract: what a crate implements to add a source type
2//! whose sources the renderer draws. `mln_builtins` implements it for the
3//! style specification's source types.
4//!
5//! A source type has two halves, which
6//! [`RegistryBuilder::add_source_type::<T>()`](crate::RegistryBuilder::add_source_type)
7//! registers together. It fails for a name that another type took, and for
8//! a type whose halves name different kinds of data.
9//!
10//! - **The style half**, a marker type that implements `mln_style`'s
11//!   [`StyleSourceType`]: the type's name and its kind of data
12//!   ([`SourceTypeInfo`](mln_style::source::SourceTypeInfo)), and the options
13//!   it reads from style JSON. It may be another crate's, as the
14//!   specification's types are `mln_style`'s, so that a tool that only
15//!   parses styles needs no engine.
16//! - **The engine half**, [`SourceType`], whose [`Style`](SourceType::Style)
17//!   names the style half: how the map loads what the style doesn't hold
18//!   itself, such as a TileJSON or GeoJSON data, into the source's
19//!   description, what a source reports about itself and offline downloads
20//!   fetch, and what it supplies the renderer.
21//!
22//! # What a source type writes
23//!
24//! 1. How its description loads, if it has one: [`SourceType::load`] says
25//!    what loads for a source's options, which the map's loader fetches and
26//!    hands to [`SourceType::describe`] or [`SourceType::describe_image`].
27//!    The style holds the description without knowing its type, in the
28//!    source's [`SourceData::description`]; the type reads it back with
29//!    [`SourceData::description`]`::<Self::Description>()`.
30//! 2. Its kind of data, the [`Data`](SourceType::Data) that its sources
31//!    supply: tiles of [geometry](GeometryTiles), which the engine lays out
32//!    into the buckets of the layers that draw them, or of
33//!    [raster images](RasterTiles) or [raster-dem elevations](DemTiles),
34//!    which it decodes. A new kind of data is a change to the engine, not a
35//!    source type.
36//! 3. Its [supply](SourceType::supply), made once as a source joins the
37//!    renderer's style: tiles that a [`DataOrigin`] loads
38//!    ([`Supply::tiles`]), or, for raster data, one image at four
39//!    coordinates that the engine reads from each version of the source
40//!    ([`Supply::image`]), as the image source type supplies.
41//! 4. Its origin. [`DataOrigin::update`] takes in the source as the style
42//!    has it and returns what its tiles [`Cover`]. [`DataOrigin::start`]
43//!    starts each new tile and returns the origin's state of it, its
44//!    [`Tile`](DataOrigin::Tile), which the engine keeps with the tile and
45//!    drops as the tile goes, which lets go of what it holds. Through the
46//!    tile's [`LoadContext`] the origin [begins a load](LoadContext::begin_load),
47//!    whose [`Replier`] sends what the load gets back from any thread to
48//!    [`DataOrigin::receive`], and [delivers](LoadContext::deliver) what it
49//!    brought: an [item](TileKind::Item) of the source's kind, nothing for an
50//!    empty tile, or [missing](LoadContext::missing) for a tile the source
51//!    doesn't have. An origin that loads cheaply first, or retries, or keeps
52//!    what it loaded fresh, also writes
53//!    [`set_necessity`](DataOrigin::set_necessity),
54//!    [`retry`](DataOrigin::retry) and [`failed`](DataOrigin::failed), as the
55//!    tileset's does.
56//!
57//! # When the hooks run
58//!
59//! The engine runs [`SourceType::supply`] and every hook of the origin one
60//! at a time on the renderer's thread, never one from within another, so an
61//! origin and its tiles' states needn't be `Send`. In each of the
62//! renderer's updates, it first hands each tile the replies that arrived
63//! for its latest load ([`receive`](DataOrigin::receive)), then, per
64//! source, runs [`update`](DataOrigin::update) with the source as the style
65//! has it, the same version until the style changes it, so the origin tells
66//! a new version from the last it took in and then clears or loads its
67//! tiles again ([`OriginUpdate`]). With the cover `update` returns, the
68//! engine works out the view's tiles: it [starts](DataOrigin::start) those
69//! it makes, and sets the [necessity](DataOrigin::set_necessity) of each it
70//! keeps, as it first keeps it in the update and as it lets it go into its
71//! cache. The engine runs [`retry`](DataOrigin::retry) on each required
72//! tile of the cover before each still image, and
73//! [`failed`](DataOrigin::failed) when what a tile took in fails to lay out
74//! or decode.
75//!
76//! A load's work runs wherever the origin puts it: on the renderer's pool
77//! ([`OriginUpdate::pool`]), which runs on the renderer's thread in the
78//! browser, on a file source's threads, or in a host's callback. Its
79//! [`Replier`] and its replies are `Send`, and a replier sends as many
80//! replies as its load has. What the tiles take in lays out or decodes on
81//! the tile workers, through the worker codec where they run apart, or, for
82//! geometry of a source that updates synchronously, lays out in the update
83//! that delivers it; an origin's own types and values never cross the
84//! codec.
85//!
86//! # What the engine owns
87//!
88//! The engine owns how MapLibre loads tiles; the origin owns where their
89//! data comes from. The engine decides which tiles the view needs, in which
90//! order their requests start ([`LoadContext::order`]), and which it keeps
91//! in its cache and evicts: a tile with nothing to show whose origin said
92//! its load [failed and waits for a retry](LoadContext::fail_retrying)
93//! isn't loading, so the cache lets go of it, and a cached tile whose data
94//! its origin said may no longer be shown ([`TileTimes::usable_until`])
95//! goes rather than come back. While a tile has nothing to show, it draws
96//! the tile's children or parent that can draw; it makes a missing parent
97//! only once the tile has loaded, or has
98//! [tried](LoadContext::tried_optional) what it can while optional, so a
99//! parent never loads for a tile that loads at once. It makes a tile in a
100//! new world copy show the same tile's contents in another, which
101//! [`WorldCopy::take_into`] makes the new tile's answer, and hands a reply to
102//! the origin only while its load is the tile's latest. It lays out and
103//! decodes what tiles take in, knows when a tile has done what it can, and
104//! starts a failed tile over when its retry loads anew. How data is
105//! requested, cached, revalidated, kept fresh and retried is the origin's.
106//!
107//! # Necessity
108//!
109//! A tile is required while the view needs it, and optional while it is
110//! only a fallback or a prefetch the view can do without, or waits in the
111//! cache. Necessity is a hint: an origin with a cheap way to get data, such
112//! as a cache, may try only that while the tile is optional, and say when
113//! it did ([`LoadContext::tried_optional`]), so that the engine makes and
114//! loads a parent to stand in; it asks for more as the tile becomes
115//! required, and stops as it becomes optional, as the tileset's origin does
116//! with its network requests. An origin without one loads every tile as it
117//! starts and ignores necessity: a parent draws for its loading tiles only
118//! if the cover already has it.
119
120use std::marker::PhantomData;
121use std::sync::Arc;
122
123use mln_style::Source;
124use mln_style::bitmap::PremultipliedImage;
125use mln_style::crs::WorldMapping;
126use mln_style::error::Error;
127use mln_style::geo::{LatLng, LatLngBounds};
128use mln_style::range::Range;
129use mln_style::source::{SourceData, StyleSourceType};
130use mln_style::tileset::{RasterEncoding, Tileset};
131
132use crate::exec::pool::Pool;
133use crate::map::MapMode;
134use crate::query::FeatureExtensionValue;
135use crate::source::erased::{ErasedOrigin, UpdateParts, typed};
136use crate::storage::resource::RequestOrder;
137use crate::storage::{Data, FileSource};
138use crate::tile::{OverscaledTileID, TileData};
139use crate::tile_store::inbox::{InboxSender, TileEvent};
140pub use crate::tile_store::loading::TileTimes;
141pub use crate::tile_store::tile::{TileNecessity, TileOperation};
142use crate::tile_store::tile_mut::{CopyAnswer, TileMut};
143use crate::worker::job::TileKey;
144
145pub mod dynamic;
146pub(crate) mod erased;
147mod loading;
148pub(crate) mod render_image_source;
149pub(crate) mod render_source;
150pub(crate) mod render_tile_source;
151pub(crate) mod source_state;
152#[cfg(test)]
153mod tests;
154
155pub use loading::{Described, Fetch, Load, OfflineResources, Respond, SourceSummary};
156
157/// The options of a source of the type `T`.
158pub type OptionsOf<T> = <<T as SourceType>::Style as StyleSourceType>::Options;
159
160/// A source type's engine half: how its sources load, what they report and
161/// what they supply the renderer.
162///
163/// The hooks that take a source's data take it as the style has it, a
164/// [`SourceData`] of the style half.
165pub trait SourceType: Send + Sync + 'static {
166    /// The style half: the type's name, its kind of data and its options.
167    type Style: StyleSourceType;
168
169    /// The kind of data its sources supply: the kind its style half's
170    /// [`layer_kind`](mln_style::source::SourceTypeInfo::layer_kind) names,
171    /// or the type doesn't register.
172    type Data: TileKind;
173
174    /// What loading a source finds: a tileset, GeoJSON data, an image. The
175    /// style holds it in [`SourceData::description`].
176    type Description: Send + Sync + 'static;
177
178    /// Whether [`describe`](Self::describe) runs on the thread pool rather
179    /// than on the map's thread, for work such as indexing GeoJSON.
180    const DESCRIBES_IN_BACKGROUND: bool = false;
181
182    /// Whether a description depends on the map's world square, as GeoJSON
183    /// tiled there does: the map then describes the source again when the
184    /// style's projection changes the world.
185    const DESCRIBES_IN_WORLD: bool = false;
186
187    /// How `source`'s description loads for its current options. The map
188    /// asks again whenever [`SourceData::load`] grows.
189    fn load(_source: &SourceData<Self::Style>) -> Load<Self::Description> {
190        Load::Done
191    }
192
193    /// Turns `data`, the fetched resource of a [`Fetch::Source`], into the
194    /// description of a source of `options` on a map whose lng/lat maps to
195    /// its world square as `world` maps it, and answers through `respond`,
196    /// at once or later. `data` is `None` for a response without content,
197    /// and for a [`Load::Describe`], which describes the options alone.
198    fn describe(
199        _options: &OptionsOf<Self>,
200        _world: &WorldMapping,
201        _data: Option<Data>,
202        respond: Respond<Described<Self::Description>>,
203    ) {
204        respond(Err(Error::failed(format!("a {} source fetches nothing", Self::Style::INFO.name))));
205    }
206
207    /// Turns `image`, the decoded image of a [`Fetch::Image`], into the
208    /// description of a source of `options`.
209    fn describe_image(_options: &OptionsOf<Self>, _image: PremultipliedImage) -> Described<Self::Description> {
210        Err(Error::failed(format!("a {} source fetches no image", Self::Style::INFO.name)))
211    }
212
213    /// Whether `new`, a loaded description that replaces `old`, changes what
214    /// the source says about itself, such as a tileset's tiles and
215    /// attribution, which the map reports as a change of the source.
216    #[must_use]
217    fn metadata_changed(_old: Option<&Self::Description>, _new: Option<&Self::Description>) -> bool {
218        false
219    }
220
221    /// The source's attribution, as its style or its description gives it.
222    fn attribution(_source: &SourceData<Self::Style>) -> Option<String> {
223        None
224    }
225
226    /// What the source reports about itself.
227    fn summary(_source: &SourceData<Self::Style>) -> SourceSummary {
228        SourceSummary::default()
229    }
230
231    /// What an offline download fetches for the source.
232    fn offline(_source: &SourceData<Self::Style>) -> OfflineResources {
233        OfflineResources::None
234    }
235
236    /// The tileset that an offline download takes the source's tiles from,
237    /// once the TileJSON that [`OfflineResources::TileJson`] named arrived.
238    ///
239    /// # Errors
240    ///
241    /// When `tilejson` doesn't give the source a tileset.
242    fn offline_tileset(_source: &SourceData<Self::Style>, _tilejson: &[u8]) -> Result<Tileset, String> {
243        Err(format!("a {} source has no TileJSON", Self::Style::INFO.name))
244    }
245
246    /// What `source`, a source of the type, supplies the renderer, which
247    /// makes it once, as the source joins the renderer's style. A source
248    /// that later takes its place with the same id and type, as a style
249    /// reload makes, keeps the supply: its origin takes the new source in
250    /// [`DataOrigin::update`], and an image's `ImageOf` reads it.
251    fn supply(source: &Source) -> Supply<Self::Data>;
252
253    /// The `field` of the extension `extension` of `feature`, a feature
254    /// that a query found in a tile of `source`, with `args`: such as a
255    /// GeoJSON cluster's leaves. A null value for an extension the type
256    /// doesn't have.
257    ///
258    /// # Errors
259    ///
260    /// When the source can't answer, such as for a cluster it doesn't have.
261    fn query_feature_extension(
262        _source: &Source,
263        _feature: &crate::tile::feature::Feature,
264        _extension: &str,
265        _field: &str,
266        _args: Option<&mln_style::feature::PropertyMap>,
267    ) -> Result<FeatureExtensionValue, Error> {
268        Ok(FeatureExtensionValue::default())
269    }
270}
271
272/// What a source supplies the renderer: tiles of the kind `K`, which a data
273/// origin loads, or one image at four coordinates.
274pub struct Supply<K>(pub(crate) Supplied, PhantomData<fn() -> K>);
275
276pub(crate) enum Supplied {
277    Tiles(Box<dyn ErasedOrigin>),
278    Image(ImageOf),
279}
280
281/// The image of a source, if it is one of the type's.
282pub(crate) type ImageOf = fn(&Source) -> Option<SourceImage>;
283
284impl<K: TileKind> Supply<K> {
285    /// Tiles whose data comes from `origin`.
286    #[must_use]
287    pub fn tiles<O: DataOrigin<Data = K>>(origin: O) -> Self {
288        Supply(Supplied::Tiles(Box::new(origin)), PhantomData)
289    }
290}
291
292impl Supply<RasterTiles> {
293    /// One image, which `image_of` reads from each version of the source.
294    #[must_use]
295    pub fn image(image_of: ImageOf) -> Self {
296        Supply(Supplied::Image(image_of), PhantomData)
297    }
298}
299
300/// A kind of tile data, and what a tile's load delivers of it, its
301/// [`Item`](Self::Item). The kinds are the engine's: [`GeometryTiles`],
302/// [`RasterTiles`] and [`DemTiles`].
303#[expect(private_bounds, reason = "the engine's kinds are the only ones: `kind::Deliver` seals the trait")]
304pub trait TileKind: kind::Deliver + 'static {
305    /// What a load delivers to a tile of the kind.
306    type Item;
307}
308
309/// The tiles of a geometry source, whose features the engine lays out into
310/// the buckets of the layers that draw them. A load delivers a tile's
311/// [`TileData`].
312pub enum GeometryTiles {}
313
314impl TileKind for GeometryTiles {
315    type Item = TileData;
316}
317
318/// The tiles of a raster source. A load delivers a tile's encoded image,
319/// which the engine decodes. A layer type that draws raster images draws
320/// them, or the one image of an image source ([`Supply::image`]), as its
321/// input.
322pub enum RasterTiles {}
323
324impl TileKind for RasterTiles {
325    type Item = Data;
326}
327
328/// The tiles of a raster-dem source. A load delivers a tile's encoded image,
329/// which the engine decodes with the elevation encoding its origin set
330/// ([`OriginUpdate::set_encoding`]). A layer type that draws elevations
331/// draws them as its input.
332pub enum DemTiles {}
333
334impl TileKind for DemTiles {
335    type Item = Data;
336}
337
338pub(crate) mod kind {
339    use mln_style::layer::SourceKind;
340
341    use super::{DemTiles, GeometryTiles, RasterTiles, TileKind};
342    use crate::tile_store::tile_mut::TileMut;
343
344    /// The engine's side of a [`TileKind`]: the kind of source it is, and
345    /// how a tile takes in its items. It seals [`TileKind`].
346    pub(crate) trait Deliver {
347        const KIND: SourceKind;
348
349        /// Gives `tile` what a load delivered: `None` for an empty tile.
350        fn deliver(tile: &mut TileMut<'_>, item: Option<<Self as TileKind>::Item>)
351        where
352            Self: TileKind;
353    }
354
355    impl Deliver for GeometryTiles {
356        const KIND: SourceKind = SourceKind::Geometry;
357
358        fn deliver(tile: &mut TileMut<'_>, item: Option<<Self as TileKind>::Item>) {
359            tile.take_data(item, false);
360        }
361    }
362
363    impl Deliver for RasterTiles {
364        const KIND: SourceKind = SourceKind::Raster;
365
366        fn deliver(tile: &mut TileMut<'_>, item: Option<<Self as TileKind>::Item>) {
367            tile.take_image(item, false);
368        }
369    }
370
371    impl Deliver for DemTiles {
372        const KIND: SourceKind = SourceKind::RasterDem;
373
374        fn deliver(tile: &mut TileMut<'_>, item: Option<<Self as TileKind>::Item>) {
375            tile.take_image(item, false);
376        }
377    }
378}
379
380/// An image at coordinates: what an image source shows.
381#[derive(Clone, Debug)]
382pub struct SourceImage {
383    /// The image, `None` until it arrives or for a source without one. The
384    /// renderer uploads it again when it's another allocation.
385    pub image: Option<Arc<PremultipliedImage>>,
386    /// The image's corners: top left, top right, bottom right, bottom left.
387    pub coordinates: [LatLng; 4],
388}
389
390/// What a source's tiles cover, and how the views they draw choose them:
391/// their size in pixels, the zoom levels that have tiles of their own,
392/// beyond which they are drawn scaled up, the bounds outside which there
393/// are none, and how a view picks and lays out its tiles.
394#[derive(Clone, Copy, Debug, PartialEq)]
395pub struct Cover {
396    /// The size of the tiles, in pixels.
397    pub tile_size: u16,
398    /// The zoom levels that have tiles of their own.
399    pub zoom_range: Range<u8>,
400    /// The bounds outside which there are no tiles.
401    pub bounds: Option<LatLngBounds>,
402    /// Whether the tiles that cover a view are of the zoom level nearest the
403    /// view's, as for raster tiles, rather than the level below it. A
404    /// render in tile mode then draws every tile of the cover, not only
405    /// the first.
406    pub round_zoom: bool,
407    /// Whether a view past the highest zoom level that has tiles asks for
408    /// overscaled tiles of its own zoom, rather than drawing that level's
409    /// tiles larger.
410    pub overscale: bool,
411    /// Whether, in continuous mode, the map first loads tiles a few zoom
412    /// levels below the view's, and keeps the globe's lowest level loaded,
413    /// so that something shows while the view's tiles load.
414    pub prefetch: bool,
415    /// Whether the tiles' geometry lays out in the update that delivers it,
416    /// on the renderer's thread, rather than on the tile workers.
417    pub synchronous: bool,
418}
419
420/// Where a source's tiles get their data: what each tile has of the
421/// source's data, and how it loads.
422///
423/// The tile hooks ([`start`](Self::start), [`receive`](Self::receive),
424/// [`set_necessity`](Self::set_necessity), [`retry`](Self::retry) and
425/// [`failed`](Self::failed)) get the tile's [`LoadContext`], and all but
426/// `start` the origin's state of the tile. The engine calls none of the
427/// hooks from within another.
428pub trait DataOrigin: 'static {
429    /// The kind of data its tiles take in.
430    type Data: TileKind;
431
432    /// What the origin keeps of each tile. The engine drops it as the tile
433    /// goes, which lets go of what it holds, such as a request or a
434    /// subscription.
435    type Tile: 'static;
436
437    /// What a tile's load gets back, which [`receive`](Self::receive)
438    /// takes in.
439    type Reply: Send + 'static;
440
441    /// Takes in the source as the style has it now, before the cover's
442    /// update, in each of the renderer's updates: the same version until the
443    /// style changes it, so the origin tells a new version from the last it
444    /// took in, and then clears or loads the tiles again as the source's
445    /// rules say. Returns what the tiles cover, or `None` while the source
446    /// has nothing to make tiles from, in which case the engine leaves its
447    /// tiles as they are and makes no new ones.
448    fn update(&mut self, update: &mut OriginUpdate<'_, Self>) -> Option<Cover>;
449
450    /// Starts a new tile and returns the origin's state of it. The tile
451    /// starts optional; the cover sets how much it needs it
452    /// ([`set_necessity`](Self::set_necessity)) as it retains it, after
453    /// this. On a flat map, `copy` is the same tile in another world copy,
454    /// whose contents the new tile already shows, and
455    /// [`copy.take_into(cx)`](WorldCopy::take_into) settles the tile on them, as its
456    /// load's answer. Otherwise the origin delivers the tile's data at once,
457    /// starts a load, or waits until the tile is needed.
458    fn start(&mut self, cx: &mut LoadContext<'_, '_, Self>, copy: Option<WorldCopy<'_, Self::Tile>>) -> Self::Tile;
459
460    /// Takes in `reply`, which came for the tile's latest load.
461    fn receive(&mut self, tile: &mut Self::Tile, reply: Self::Reply, cx: &mut LoadContext<'_, '_, Self>);
462
463    /// The engine set how much the tile is needed, to
464    /// [`cx.necessity()`](LoadContext::necessity) from `previous`, which may
465    /// be the same: as each update's cover retains the tile, and as it
466    /// becomes optional.
467    fn set_necessity(&mut self, _tile: &mut Self::Tile, _previous: TileNecessity, _cx: &mut LoadContext<'_, '_, Self>) {
468    }
469
470    /// The engine retries the required tile's failed loads, before each
471    /// still image: it calls this for each required tile of the cover,
472    /// failed or not, and the origin retries what of it failed. A tile that
473    /// this begins a load of, or gives new data, loads anew; one that it
474    /// leaves as it was stays as it was.
475    fn retry(&mut self, _tile: &mut Self::Tile, _cx: &mut LoadContext<'_, '_, Self>) {}
476
477    /// The engine couldn't lay out or decode what the tile last took in, and
478    /// reported the error; the tile keeps what it shows. Not called for the
479    /// origin's own [`LoadContext::fail`] or
480    /// [`fail_retrying`](LoadContext::fail_retrying).
481    fn failed(&mut self, _tile: &mut Self::Tile, _cx: &mut LoadContext<'_, '_, Self>) {}
482}
483
484/// What the map says of its tiles, which an origin reads as it updates
485/// ([`OriginUpdate::map`]).
486#[derive(Clone)]
487pub struct MapSettings {
488    /// Whether the map draws continuously or still images, which a tile
489    /// shows only once it has done what it can.
490    pub mode: MapMode,
491    /// The map's pixel ratio, which a raster tile's resource may ask for.
492    pub pixel_ratio: f32,
493    /// How the map's lng/lat maps to its world square, whose grid the tiles
494    /// are in: Mercator's, also on the globe, or a registered projection's.
495    /// A tile's resource asks for the tile's `{bbox}` in units of its tile
496    /// matrix set.
497    pub world: WorldMapping,
498    /// The map's highest zoom level.
499    pub max_zoom: f64,
500    /// Where the map's resources load from, if anywhere.
501    pub file_source: Option<Arc<dyn FileSource>>,
502}
503
504impl std::fmt::Debug for MapSettings {
505    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
506        f.debug_struct("MapSettings")
507            .field("mode", &self.mode)
508            .field("pixel_ratio", &self.pixel_ratio)
509            .field("world", &self.world)
510            .field("max_zoom", &self.max_zoom)
511            .field("file_source", &self.file_source.as_ref().map(|_| format_args!("..")))
512            .finish()
513    }
514}
515
516/// A [`DataOrigin`]'s update: the source as the style has it, what the map
517/// says of its tiles, and the tiles, which the origin can clear or load
518/// again.
519pub struct OriginUpdate<'a, O: ?Sized> {
520    pub(crate) parts: UpdateParts<'a>,
521    pub(crate) origin: PhantomData<fn(&mut O)>,
522}
523
524impl<'a, O: ?Sized> OriginUpdate<'a, O> {
525    /// This update as one of the origin `P`'s, for an origin that runs its
526    /// hooks through a non-generic core, such as one type that several
527    /// generic origins share: what the update does to the tiles doesn't
528    /// depend on the origin's type.
529    pub fn cast<P: ?Sized>(&mut self) -> OriginUpdate<'_, P> {
530        let parts = &mut self.parts;
531        OriginUpdate {
532            parts: UpdateParts {
533                source: parts.source,
534                tiles: &mut *parts.tiles,
535                ctx: &mut *parts.ctx,
536                map: parts.map,
537                needs_relayout: parts.needs_relayout,
538            },
539            origin: PhantomData,
540        }
541    }
542
543    /// The source as the style has it now.
544    #[must_use]
545    pub fn source(&self) -> &'a Source {
546        self.parts.source
547    }
548
549    /// What the map says of its tiles.
550    #[must_use]
551    pub fn map(&self) -> &MapSettings {
552        self.parts.map
553    }
554
555    /// The renderer's thread pool.
556    #[must_use]
557    pub fn pool(&self) -> &Pool {
558        self.parts.ctx.pool.pool()
559    }
560
561    /// Whether the source's tiles lay out again.
562    #[must_use]
563    pub fn needs_relayout(&self) -> bool {
564        self.parts.needs_relayout
565    }
566
567    /// Lets go of every tile. The origin's state of each drops, with no
568    /// [`set_necessity`](DataOrigin::set_necessity) before.
569    pub fn clear_tiles(&mut self) {
570        self.parts.tiles.clear_all(self.parts.ctx);
571    }
572
573    /// Lets go of the cached tiles, those the view no longer needs. The
574    /// origin's state of each drops, with no
575    /// [`set_necessity`](DataOrigin::set_necessity) before, even for a tile
576    /// that was still loading.
577    pub fn clear_cache(&mut self) {
578        self.parts.tiles.reduce_memory_use(self.parts.ctx);
579    }
580}
581
582impl<O: DataOrigin> OriginUpdate<'_, O> {
583    /// Changes each tile of the cover, not of the cache, that `filter`
584    /// picks, through `f`, which gets the origin's state of it.
585    pub fn update_tiles(
586        &mut self,
587        filter: impl Fn(&OverscaledTileID) -> bool,
588        mut f: impl FnMut(&mut O::Tile, &mut LoadContext<'_, '_, O>),
589    ) {
590        self.parts.tiles.update_each(
591            self.parts.ctx,
592            |slot| !slot.place().is_cached() && filter(&slot.tile.id),
593            |tile| {
594                tile.with_state(|state, tile| {
595                    if let Some(state) = typed::<O>(state) {
596                        f(state, &mut LoadContext::new(tile));
597                    }
598                });
599            },
600        );
601    }
602}
603
604impl<O: DataOrigin<Data = DemTiles>> OriginUpdate<'_, O> {
605    /// Sets how the source's pixels encode elevations: the tiles made from
606    /// now on decode with it, and the terrain's surface reads them with it.
607    /// Mapbox's until an origin sets another.
608    pub fn set_encoding(&mut self, encoding: RasterEncoding) {
609        self.parts.tiles.info.dem_encoding = encoding;
610    }
611}
612
613/// A tile, as a [`DataOrigin`]'s hook sees it: what the engine knows of it,
614/// and what the origin can do to it.
615pub struct LoadContext<'a, 't, O: ?Sized> {
616    tile: &'a mut TileMut<'t>,
617    origin: PhantomData<fn(&O)>,
618}
619
620impl<'a, 't, O: ?Sized> LoadContext<'a, 't, O> {
621    pub(crate) fn new(tile: &'a mut TileMut<'t>) -> Self {
622        LoadContext { tile, origin: PhantomData }
623    }
624
625    /// This context as one of the origin `P`'s, for an origin that runs its
626    /// hooks through a non-generic core, as [`OriginUpdate::cast`]. The core
627    /// begins loads and delivers through
628    /// [`begin_load_of`](Self::begin_load_of) and
629    /// [`deliver_of`](Self::deliver_of), which name the reply and the kind
630    /// of data that the origin's own [`begin_load`](Self::begin_load) and
631    /// [`deliver`](Self::deliver) would.
632    pub fn cast<P: ?Sized>(&mut self) -> LoadContext<'_, 't, P> {
633        LoadContext { tile: &mut *self.tile, origin: PhantomData }
634    }
635
636    /// The tile's id, with its world copy and the zoom it draws at.
637    #[must_use]
638    pub fn id(&self) -> &OverscaledTileID {
639        &self.tile.tile().id
640    }
641
642    /// How much the view needs the tile now: a hint, which an origin
643    /// without a cheaper way to get data ignores.
644    #[must_use]
645    pub fn necessity(&self) -> TileNecessity {
646        self.tile.tile().load.necessity
647    }
648
649    /// When the tile's requests start among those that wait for a
650    /// connection, which the engine keeps up to date: for the tile's
651    /// resources.
652    #[must_use]
653    pub fn order(&self) -> RequestOrder {
654        self.tile.tile().load.order.clone()
655    }
656
657    /// Sets when the tile's data was modified, when it expires, and until
658    /// when it may be shown, which the engine's cache keeps to.
659    pub fn set_times(&mut self, times: TileTimes) {
660        self.tile.tile_mut().load.times = times;
661    }
662
663    /// Whether the tile can draw, if only some of its layers.
664    #[must_use]
665    pub fn is_renderable(&self) -> bool {
666        self.tile.tile().is_renderable()
667    }
668
669    /// [`begin_load`](Self::begin_load) of a load whose replies are `R`,
670    /// which must be the [`Reply`](DataOrigin::Reply) of the tile's origin:
671    /// the origin gets no other replies.
672    pub fn begin_load_of<R>(&mut self) -> Replier<R> {
673        let load = self.tile.next();
674        let tile = self.tile.tile_mut();
675        tile.load.current = Some(load);
676        tile.load.failed = false;
677        let tile = self.tile.key();
678        Replier { inbox: self.tile.store().inbox.clone(), tile, load, reply: PhantomData }
679    }
680
681    /// [`deliver`](Self::deliver) for tiles of the kind `K`, which must be
682    /// the [`Data`](DataOrigin::Data) of the tile's origin.
683    pub fn deliver_of<K: TileKind>(&mut self, item: Option<K::Item>) {
684        self.tile.tile_mut().load.failed = false;
685        K::deliver(self.tile, item);
686    }
687
688    /// A load found that the source has no tile here: a tile of another
689    /// zoom level draws in its place.
690    pub fn missing(&mut self) {
691        self.tile.tile_mut().load.failed = false;
692        self.tile.take_missing();
693    }
694
695    /// The tile couldn't load: it keeps what it shows, and the engine
696    /// reports `error`.
697    pub fn fail(&mut self, error: Error) {
698        self.tile.fail(error);
699    }
700
701    /// The tile's load failed, and waits to be tried again, as a network
702    /// request that stays open while its file source backs off: as
703    /// [`fail`](Self::fail), and until the origin begins a load or gives the
704    /// tile anything ([`begin_load`](Self::begin_load),
705    /// [`deliver`](Self::deliver), [`missing`](Self::missing),
706    /// [`keep_data`](Self::keep_data) or [`WorldCopy::take_into`]), the tile
707    /// counts as failed rather than loading: out of the view, one with
708    /// nothing to show goes rather than wait in the cache for the retry, and
709    /// is made anew if the view comes back.
710    pub fn fail_retrying(&mut self, error: Error) {
711        self.tile.tile_mut().load.failed = true;
712        self.tile.fail(error);
713    }
714
715    /// A load found the tile's data unchanged: the tile has done what it
716    /// can, unless work on its data is under way, which settles it as it
717    /// ends.
718    pub fn keep_data(&mut self) {
719        self.tile.tile_mut().load.failed = false;
720        self.tile.keep_data();
721    }
722
723    /// The tile has done what it can while optional, such as looking in a
724    /// cache. From then on, while it has nothing to show, the engine makes
725    /// its parent if the cover lacks one, and loads it to stand in; for a
726    /// tile that hasn't said so, only a parent the cover has stands in.
727    pub fn tried_optional(&mut self) {
728        self.tile.tile_mut().load.tried_optional = true;
729    }
730
731    /// Reports what the tile's load did: requested from the cache or the
732    /// network, or loaded from either. The engine reports the rest of a
733    /// tile's operations itself.
734    pub fn report(&mut self, op: TileOperation) {
735        debug_assert!(
736            matches!(
737                op,
738                TileOperation::RequestedFromCache
739                    | TileOperation::RequestedFromNetwork
740                    | TileOperation::LoadFromCache
741                    | TileOperation::LoadFromNetwork
742            ),
743            "an origin reports its loads' requests and answers, not {op:?}"
744        );
745        self.tile.action(op);
746    }
747
748    /// The tile changed: the renderer needs a frame.
749    pub fn changed(&mut self) {
750        self.tile.store_mut().changed();
751    }
752}
753
754impl<O: DataOrigin + ?Sized> LoadContext<'_, '_, O> {
755    /// Starts a load, the tile's latest from now on, whose replies the
756    /// returned replier sends. Replies to the loads before go nowhere. A
757    /// load stays the latest until the next one begins, so an origin that
758    /// stops a load's work ignores the replies it sent before it stopped.
759    pub fn begin_load(&mut self) -> Replier<O::Reply> {
760        self.begin_load_of()
761    }
762
763    /// Gives the tile what a load brought, which it lays out or decodes:
764    /// `None` for an empty tile, which shows nothing.
765    pub fn deliver(&mut self, item: Option<<O::Data as TileKind>::Item>) {
766        self.deliver_of::<O::Data>(item);
767    }
768}
769
770impl<O: DataOrigin<Data = GeometryTiles> + ?Sized> LoadContext<'_, '_, O> {
771    /// Drops the tile's data and style, so that it lays out anew once it
772    /// has both again.
773    pub fn reset(&mut self) {
774        self.tile.reset();
775    }
776}
777
778/// The same tile in another world copy, from whose contents a new tile
779/// starts ([`DataOrigin::start`]): the origin's state of it, and what
780/// taking it settles the new tile on.
781pub struct WorldCopy<'a, T> {
782    pub(crate) state: &'a T,
783    pub(crate) answer: Option<CopyAnswer>,
784}
785
786impl<'a, T> WorldCopy<'a, T> {
787    /// The origin's state of the copy.
788    #[must_use]
789    pub fn state(&self) -> &'a T {
790        self.state
791    }
792
793    /// Settles the new tile on the copy's contents, which it shows, as its
794    /// load's answer: a geometry tile lays out the copy's data for itself,
795    /// and a raster or raster-dem tile keeps what it shows. Returns false,
796    /// and changes nothing, if the copy has no data to give, as one whose
797    /// decode is still pending. It takes a context of any origin's, as a
798    /// non-generic core has ([`LoadContext::cast`]).
799    pub fn take_into<O: ?Sized>(self, cx: &mut LoadContext<'_, '_, O>) -> bool {
800        let Some(answer) = self.answer else {
801            return false;
802        };
803        cx.tile.take_copy(answer);
804        true
805    }
806}
807
808/// Sends the replies of one of a tile's loads to the tile, from any thread.
809pub struct Replier<R> {
810    inbox: InboxSender,
811    tile: TileKey,
812    load: u64,
813    reply: PhantomData<fn(R)>,
814}
815
816impl<R> Clone for Replier<R> {
817    fn clone(&self) -> Self {
818        Replier { inbox: self.inbox.clone(), tile: self.tile, load: self.load, reply: PhantomData }
819    }
820}
821
822impl<R: Send + 'static> Replier<R> {
823    /// Sends `reply`, which the tile takes in at the renderer's next update
824    /// if the load is still its latest.
825    pub fn send(&self, reply: R) {
826        self.inbox.send(TileEvent::Load { tile: self.tile, load: self.load, reply: Box::new(reply) });
827    }
828}