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