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