mln_engine/layer/render_layer.rs
1// A render layer is the renderer's side of a style layer: its type's layer
2// (`Layer`), whose hooks see the frame's tiles and what they hold for
3// the type (`TileInput`), and what the engine keeps of it around them
4// (`Hosted`): its base, its values of its type, its value of each tile it
5// draws and its draws. `RenderLayer` is what the engine does with a render
6// layer of any type. The orchestrator owns the render layers, in the
7// style's order.
8
9use std::ops::Range;
10use std::sync::Arc;
11use std::time::Duration;
12
13use mln_gfx::gpu::Gpu;
14use mln_gfx::projection_variant::ProjectionVariant;
15use mln_style::color::Color;
16use mln_style::expression::Dependency;
17use mln_style::layer::{ErasedLayerStyle, LayerStyle, PaintSet, SourceKind, StyleLayerType};
18use mln_style::time::Instant;
19use mln_style::types::{LayerBlendType, VisibilityType};
20use mln_style::{PropertyEvaluationParameters, TransitionParameters};
21use smallvec::SmallVec;
22
23use crate::camera::View;
24use crate::draw::context::Context;
25use crate::draw::draws::{DrawOrder, Draws, Group, LayerFrame, LendAt, Lent};
26use crate::draw::resources::Resources;
27use crate::draw::store::Texture;
28use crate::geo::ScreenCoordinate;
29use crate::layer::bucket::ErasedBucket;
30use crate::layer::layer_drawing::{ChangedBuckets, TileMap};
31use crate::layer::layer_type::{ErasedEvaluatedLayer, EvaluatedLayer, entry};
32use crate::layer::tile_input::input::Find;
33use crate::layer::tile_input::{TileData, TileInput};
34use crate::query::feature_index::{Hit, QueryRegion};
35use crate::render::paint_parameters::PaintParameters;
36use crate::render::pass::RenderPass;
37use crate::render::shared_targets::SharedTargets;
38use crate::render::terrain::{SurfaceLight, TerrainElevation, TileGround};
39use crate::render::tile::{FoundTile, FrameTile, RenderTile, TILE_BOUNDS, TileContent, TileFade, TileStamp, overlaps};
40use crate::render::update_parameters::UpdateParameters;
41use crate::source::render_source::{RenderSource, TileOrder};
42use crate::tile::feature::Feature;
43use crate::tile::{OverscaledTileID, UnwrappedTileID};
44
45/// A layer's bucket in a layout, which the layers of its layout group
46/// share, with the layer's values it was laid out with, whichever the
47/// layer's type.
48#[derive(Clone, Copy)]
49pub(crate) struct ErasedLayerBucket<'a> {
50 pub(crate) bucket: &'a dyn ErasedBucket,
51 /// The index of the bucket among the layout's buckets.
52 pub(crate) bucket_index: usize,
53 /// The values of the layer that the bucket was laid out with.
54 pub(crate) layer: &'a dyn ErasedEvaluatedLayer,
55}
56
57/// A source's render tiles in a frame, with what each of them shows, and
58/// the tiles that the frame's updates of the layers found
59/// ([`LayerUpdateParameters::found`]), as the engine sees them.
60#[derive(Clone, Copy)]
61pub struct FrameSourceTiles<'a> {
62 tiles: &'a [RenderTile],
63 /// What each of `tiles` shows, at its index.
64 contents: &'a [Option<TileContent<'a>>],
65 found: &'a [FoundTile],
66}
67
68/// The tiles of a layer of the type `L` in a frame, each with what it shows
69/// the layer, which keeps up to 64 of them on the stack.
70pub(crate) type FrameTiles<'a, L> = SmallVec<[FrameTile<'a, L>; 64]>;
71
72impl<'a> FrameSourceTiles<'a> {
73 /// The render tiles `tiles`, which show `contents`, at their indexes,
74 /// and the tiles of them that the frame's layers found.
75 #[must_use]
76 pub(crate) fn new(
77 tiles: &'a [RenderTile],
78 contents: &'a [Option<TileContent<'a>>],
79 found: &'a [FoundTile],
80 ) -> Self {
81 FrameSourceTiles { tiles, contents, found }
82 }
83
84 /// What the tile at `index` shows.
85 pub(crate) fn content(self, index: usize) -> Option<TileContent<'a>> {
86 self.contents.get(index).copied().flatten()
87 }
88
89 /// The render tile at `index`.
90 pub(crate) fn tile(self, index: usize) -> Option<&'a RenderTile> {
91 self.tiles.get(index)
92 }
93
94 /// The tiles at the indexes of `order`, in that order, as the layer
95 /// `layer_id` of the type `T` sees them, each with what it shows the
96 /// layer, found by the layer's id. `found` keeps where.
97 fn find<L: Layer>(self, order: &[usize], layer_id: &str, found: &mut Vec<FoundTile>) -> FrameTiles<'a, L> {
98 let mut tiles = FrameTiles::new();
99 for &index in order {
100 let Some(tile) = self.tiles.get(index) else { continue };
101 let (frame_tile, view) = FrameTile::find(tile, self.content(index), layer_id);
102 tiles.push(frame_tile.with_fade(self.fade(tile, layer_id)));
103 found.push(FoundTile { tile: index, view });
104 }
105 tiles
106 }
107
108 /// The found tiles at `found`, a range of them.
109 pub(crate) fn found(self, found: Range<usize>) -> &'a [FoundTile] {
110 self.found.get(found).unwrap_or_default()
111 }
112
113 /// The tiles of `found`, as [`find`](Self::find) found them for the
114 /// layer `layer_id` of the type `T` in the same frame.
115 pub(crate) fn at<'f, L: Layer>(
116 self,
117 found: impl IntoIterator<Item = &'f FoundTile>,
118 layer_id: &str,
119 ) -> FrameTiles<'a, L> {
120 found
121 .into_iter()
122 .filter_map(|&FoundTile { tile, view }| {
123 let render_tile = self.tiles.get(tile);
124 debug_assert!(render_tile.is_some(), "a tile found past the frame's render tiles");
125 let render_tile = render_tile?;
126 let fade = self.fade(render_tile, layer_id);
127 Some(FrameTile::at(render_tile, self.content(tile), layer_id, view).with_fade(fade))
128 })
129 .collect()
130 }
131
132 /// How `tile` fades for the layer `layer_id` of the type `L`, with what
133 /// its parent holds for the layer.
134 fn fade<L: Layer>(self, tile: &RenderTile, layer_id: &str) -> Option<TileFade<'a, L>> {
135 let fade = tile.fade?;
136 let parent = fade.parent.and_then(|index| {
137 let parent = self.tiles.get(index)?;
138 let (parent_tile, _) = FrameTile::<L>::find(parent, self.content(index), layer_id);
139 Some((*parent.overscaled_tile_id(), parent_tile.data()?))
140 });
141 Some(TileFade::new(parent, fade.elapsed, fade.fade_in))
142 }
143
144 /// The tiles of the found tiles at `found`, as [`at`](Self::at) gives
145 /// them, that overlap `tile` (what they show covers part of it), each in
146 /// the world copy that does: on Mercator their own, so those of `tile`'s
147 /// copy; on the `globe`, which has no copies, whatever their copy, one by
148 /// `tile`'s. A drape of `tile` draws each in that copy
149 /// ([`FrameTile::draw_id`]).
150 pub(crate) fn overlapping<L: Layer>(
151 self,
152 found: Range<usize>,
153 layer_id: &str,
154 tile: UnwrappedTileID,
155 globe: bool,
156 ) -> FrameTiles<'a, L> {
157 let found = self.found(found);
158 self.overlaps(found, tile, globe)
159 .map(|(&FoundTile { tile: index, view }, render_tile, wrap)| {
160 FrameTile::at(render_tile, self.content(index), layer_id, view).in_copy(wrap)
161 })
162 .collect()
163 }
164
165 /// What a layer draws of the tiles that
166 /// [`overlapping`](Self::overlapping) gives, in its order, under the ids
167 /// it draws them in.
168 pub(crate) fn stamps(
169 self,
170 found: Range<usize>,
171 tile: UnwrappedTileID,
172 globe: bool,
173 ) -> impl Iterator<Item = TileStamp> {
174 let found = self.found(found);
175 self.overlaps(found, tile, globe).map(move |(&FoundTile { tile: index, view }, render_tile, wrap)| {
176 let stamp = self.content(index).zip(view).and_then(|(content, place)| content.stamp(place));
177 TileStamp {
178 tile: OverscaledTileID { wrap, ..*render_tile.overscaled_tile_id() },
179 bucket: stamp.map(|(bucket, _)| bucket),
180 generations: stamp.map_or([0, 0], |(_, generations)| generations),
181 }
182 })
183 }
184
185 /// The tiles of `found` that overlap `tile`, with their render tiles and
186 /// the world copies they overlap it in: on Mercator their own; on the
187 /// `globe`, any of `tile`'s and the copies either side, which an image
188 /// source's image that crosses the antimeridian reaches into.
189 pub(crate) fn overlaps<'f>(
190 self,
191 found: &'f [FoundTile],
192 tile: UnwrappedTileID,
193 globe: bool,
194 ) -> impl Iterator<Item = (&'f FoundTile, &'a RenderTile, i16)> {
195 let found = found.iter().filter_map(move |found| Some((found, self.tiles.get(found.tile)?)));
196 found.flat_map(move |(found, render_tile)| {
197 let bounds = self.content(found.tile).map_or(TILE_BOUNDS, TileContent::bounds);
198 let canonical = render_tile.id.canonical;
199 let wraps = if globe { tile.wrap - 1..=tile.wrap + 1 } else { render_tile.id.wrap..=render_tile.id.wrap };
200 wraps
201 .filter(move |&wrap| overlaps(&UnwrappedTileID::with_wrap(wrap, canonical), bounds, &tile))
202 .map(move |wrap| (found, render_tile, wrap))
203 })
204 }
205}
206
207/// What a layer reads in the frame's update, besides its tiles.
208pub struct LayerUpdateParameters<'a> {
209 /// The frame's camera.
210 pub view: &'a View,
211 /// The update the frame draws.
212 pub update_parameters: &'a UpdateParameters,
213 /// The layer's source, `None` for a layer without one or a source type
214 /// the renderer has no render source for.
215 pub(crate) source: Option<&'a dyn RenderSource>,
216 /// What each of the source's render tiles shows, at its index.
217 pub(crate) contents: &'a [Option<TileContent<'a>>],
218 /// The images of the style.
219 pub images: &'a crate::image::image_store::ImageStore,
220 /// The tiles of the frame's layers, as their updates find them, which
221 /// the update adds the layer's to: those the encode draws.
222 pub(crate) found: &'a mut Vec<FoundTile>,
223}
224
225impl<'a> LayerUpdateParameters<'a> {
226 /// The source's tiles, and their indexes in `order`; `None` for a layer
227 /// without a source or a source without tiles.
228 #[must_use]
229 pub(crate) fn tiles(&self, order: TileOrder) -> Option<(FrameSourceTiles<'a>, &'a [usize])> {
230 let source = self.source?;
231 Some((FrameSourceTiles::new(source.render_tiles(), self.contents, &[]), source.tile_order(order)?))
232 }
233}
234
235/// What every render layer has, whatever its type.
236pub struct RenderLayerBase {
237 pub(crate) evaluated_properties: Arc<dyn ErasedEvaluatedLayer>,
238 pub style: Arc<dyn ErasedLayerStyle>,
239
240 pub(crate) passes: RenderPass,
241 /// What the layer's last evaluation said of how it draws.
242 pub(crate) evaluation: Evaluation,
243 pub(crate) style_dependencies: Dependency,
244 /// Whether the frame draws the layer.
245 pub(crate) is_renderable: bool,
246
247 /// The projection variant this layer's draws are built with.
248 pub projection_variant: ProjectionVariant,
249
250 /// The shared target that the frame's draws of the layer draw into
251 /// instead of the map, if any.
252 pub(crate) route: Option<usize>,
253
254 /// Where the tiles the layer's update found are among the frame's
255 /// ([`LayerUpdateParameters::found`]).
256 found: Range<usize>,
257}
258
259impl RenderLayerBase {
260 /// The passes the layer draws in, as its last evaluation said.
261 #[must_use]
262 pub fn passes(&self) -> RenderPass {
263 self.passes
264 }
265
266 /// Where the tiles the layer's update found are among the frame's
267 /// ([`LayerUpdateParameters::found`]).
268 pub(crate) fn found(&self) -> Range<usize> {
269 self.found.clone()
270 }
271
272 pub(crate) fn set_found(&mut self, found: Range<usize>) {
273 self.found = found;
274 }
275
276 pub(crate) fn new(properties: Arc<dyn ErasedEvaluatedLayer>) -> Self {
277 let style = properties.shared_style();
278 RenderLayerBase {
279 evaluated_properties: properties,
280 style,
281 passes: RenderPass::NONE,
282 evaluation: Evaluation::NONE,
283 style_dependencies: Dependency::NONE,
284 is_renderable: false,
285 projection_variant: ProjectionVariant::Mercator,
286 route: None,
287 found: 0..0,
288 }
289 }
290}
291
292/// A layer's values of its style half `T`: its style, its paint values in
293/// transition, and their evaluation for the last frame.
294pub struct LayerValues<T: StyleLayerType> {
295 pub style: Arc<LayerStyle<T>>,
296 pub unevaluated: <T::PaintProperties as PaintSet>::Unevaluated,
297 pub evaluated: Arc<EvaluatedLayer<T>>,
298}
299
300impl<T: StyleLayerType> LayerValues<T> {
301 /// The values of the layer `style` of `layer_type`, before any
302 /// transition, and the base of a render layer that holds them.
303 pub(crate) fn new(
304 style: Arc<LayerStyle<T>>,
305 layer_type: &'static dyn crate::layer::layer_type::ErasedLayerType,
306 ) -> (RenderLayerBase, Self) {
307 let unevaluated = style.paint.untransitioned();
308 let evaluated = Arc::new(EvaluatedLayer::new(Arc::clone(&style), layer_type));
309 let mut base = RenderLayerBase::new(Arc::<EvaluatedLayer<T>>::clone(&evaluated));
310 base.style_dependencies = T::PaintProperties::dependencies(&unevaluated);
311 (base, LayerValues { style, unevaluated, evaluated })
312 }
313
314 /// The paint values evaluated for a frame, copying from the last
315 /// evaluation each value that can't have changed, with the frame's
316 /// cross-fade where the type `crossfades`, and no render passes yet.
317 pub(crate) fn evaluate(
318 &mut self,
319 parameters: &PropertyEvaluationParameters,
320 crossfades: bool,
321 ) -> EvaluatedLayer<T> {
322 let paint =
323 T::PaintProperties::evaluate_with_previous(&mut self.unevaluated, parameters, &self.evaluated.paint);
324 let layer_type = self.evaluated.layer_type;
325 let mut evaluated = EvaluatedLayer::with_paint(Arc::clone(&self.style), paint, layer_type);
326 if crossfades {
327 evaluated.crossfade = parameters.crossfade_parameters();
328 }
329 evaluated
330 }
331
332 /// Makes `evaluated` the layer's values, drawing in `base`'s passes.
333 pub(crate) fn set_evaluated(&mut self, base: &mut RenderLayerBase, mut evaluated: EvaluatedLayer<T>) {
334 evaluated.render_passes = base.passes.bits();
335 self.evaluated = Arc::new(evaluated);
336 base.evaluated_properties = Arc::<EvaluatedLayer<T>>::clone(&self.evaluated);
337 }
338}
339
340/// What a layer's evaluation says of how it draws with its values.
341#[derive(Clone, Copy, Debug, Default, PartialEq)]
342pub struct Evaluation {
343 /// Whether the layer draws anything.
344 pub draws: bool,
345 /// Whether the layer may draw in the opaque pass, which the frame draws
346 /// front to back before it blends the rest.
347 pub opaque: bool,
348 /// The one solid color the layer is, which the frame clears to instead
349 /// of drawing the layer when it is the style's bottom layer.
350 pub solid: Option<Color>,
351 /// Whether the layer draws a drape by the map's bearing: something of
352 /// it is anchored to the viewport.
353 pub drapes_by_bearing: bool,
354 /// Whether the layer draws a drape by the map's zoom beyond its evaluated
355 /// paint properties (e.g. screen-space line widths, patterns, or
356 /// translations).
357 pub drapes_by_zoom: bool,
358 /// Whether the layer animates continuously and needs another frame on
359 /// the next vsync (in continuous mode).
360 pub needs_repaint: bool,
361 /// When, without `needs_repaint`, the layer changes next on its own
362 /// (in continuous mode): the map schedules a repaint then.
363 pub repaint_at: Option<Instant>,
364 /// Whether the layer draws the shapes the frame's placement tested
365 /// ([`LayerFrame::collision_shapes`]): the placement records them
366 /// while a layer the frame draws reads them.
367 ///
368 /// [`LayerFrame::collision_shapes`]: crate::draw::draws::LayerFrame::collision_shapes
369 pub reads_collision_shapes: bool,
370}
371
372impl Evaluation {
373 /// The layer draws nothing.
374 pub const NONE: Evaluation = Evaluation {
375 draws: false,
376 opaque: false,
377 solid: None,
378 drapes_by_bearing: false,
379 drapes_by_zoom: false,
380 needs_repaint: false,
381 repaint_at: None,
382 reads_collision_shapes: false,
383 };
384 /// The layer draws, translucent.
385 pub const TRANSLUCENT: Evaluation = Evaluation { draws: true, drapes_by_zoom: true, ..Evaluation::NONE };
386 /// The layer draws, and may draw in the opaque pass.
387 pub const OPAQUE: Evaluation = Evaluation { opaque: true, ..Evaluation::TRANSLUCENT };
388
389 /// The passes a layer of this evaluation draws in.
390 pub(crate) fn passes(self) -> RenderPass {
391 match self {
392 Evaluation { draws: false, .. } => RenderPass::NONE,
393 Evaluation { opaque: true, .. } => RenderPass::OPAQUE | RenderPass::TRANSLUCENT,
394 Evaluation { opaque: false, .. } => RenderPass::TRANSLUCENT,
395 }
396 }
397}
398
399/// What a layer's [`Layer::evaluate`] reads and completes.
400pub struct EvaluateCx<'a, L: Layer> {
401 /// The layer's values before the evaluation: its style, its paint values
402 /// in transition and their last evaluation.
403 pub values: &'a LayerValues<L::Style>,
404 /// What the values were evaluated for.
405 pub parameters: &'a PropertyEvaluationParameters,
406 /// The new evaluation of the values, which becomes the layer's once the
407 /// hook returns.
408 pub evaluated: &'a mut EvaluatedLayer<L::Style>,
409}
410
411impl<L: Layer> EvaluateCx<'_, L> {
412 /// The frame's time, from the host's clock; `None` in still modes, which
413 /// have no clock and show transitions and animations as ended.
414 #[must_use]
415 pub fn time_point(&self) -> Option<Instant> {
416 self.parameters.now
417 }
418}
419
420/// How a layer type meets terrain.
421#[derive(Clone, Copy, Debug, PartialEq, Eq)]
422pub enum OnTerrain {
423 /// The layer draws flat, at sea level.
424 Flat,
425 /// The layer drapes over terrain: it draws flat into the terrain tiles'
426 /// textures (`RenderLayer::update_drape_draws`) rather than onto the
427 /// frame.
428 Drapes,
429 /// The layer stands on terrain: over terrain, its draws are of the
430 /// terrain variant ([`ProjectionVariant::stands`]), and their points
431 /// stand on the frame's ground, whose heights a program reads where it
432 /// declares [`GROUND_HEIGHT`](crate::draw::ground::GROUND_HEIGHT). One
433 /// that `hides_behind_ground` hides its points behind the ground in
434 /// front of them, which reads the ground's depth
435 /// ([`GROUND_DEPTH`](crate::draw::ground::GROUND_DEPTH)).
436 Stands { hides_behind_ground: bool },
437}
438
439impl OnTerrain {
440 /// Whether the layer drapes over terrain.
441 pub(crate) fn drapes(self) -> bool {
442 self == OnTerrain::Drapes
443 }
444
445 /// Whether the layer stands on terrain.
446 pub(crate) fn stands(self) -> bool {
447 matches!(self, OnTerrain::Stands { .. })
448 }
449
450 /// Whether the layer hides behind the ground in front of it.
451 pub(crate) fn hides_behind_ground(self) -> bool {
452 self == OnTerrain::Stands { hides_behind_ground: true }
453 }
454}
455
456/// What a layer's [`Layer::prepare`] reads and changes: its base and
457/// values, its values of the tiles it draws (`TileMap`), which the frame
458/// and its drapes share, by the tiles' own ids ([`FrameTile::id`]), and the
459/// frame it makes its draws for, the map's or a drape's.
460pub struct PrepareCx<'a, 'f, L: Layer> {
461 pub base: &'a RenderLayerBase,
462 pub values: &'a LayerValues<L::Style>,
463 pub tiles: &'a mut TileMap<L::Tile>,
464 /// For a layer that picks its tiles ([`Layer::PICKS_TILES`]),
465 /// those the frame draws, in id order: those it picked, or a drape's
466 /// tile. Empty for another layer.
467 pub picked: &'a [OverscaledTileID],
468 /// What the layer makes its meshes and targets with.
469 pub res: Resources<'a>,
470 pub frame: &'a LayerFrame<'f>,
471 /// The frame's shared targets, in the map's frame.
472 pub(crate) targets: Option<&'a mut SharedTargets>,
473}
474
475impl<L: Layer> PrepareCx<'_, '_, L> {
476 /// The texture of the frame's shared target `name`
477 /// ([`Router`](crate::layer::Router)), which the layer's
478 /// draws sample: its texel at `(x, y)` is what the layers routed into it
479 /// drew at the frame's device pixel `(x, y)`; the read orders the
480 /// target's pass before the layer's draws. A layer reads the targets only
481 /// in the map's frame, for its draws over the map: `None` in a drape,
482 /// and, with a warning, for a name that the frame has no target of.
483 pub fn read_target(&mut self, name: &str) -> Option<Texture> {
484 self.targets.as_deref_mut()?.read(&self.base.style.base().id, name)
485 }
486}
487
488/// What a layer's [`Layer::tile`] reads to make a tile's value.
489pub struct TileCx<'a, 'f, L: Layer> {
490 pub base: &'a RenderLayerBase,
491 pub values: &'a LayerValues<L::Style>,
492 /// What the layer makes its meshes and targets with.
493 pub res: Resources<'a>,
494 /// The frame the value is made in: the map's, or for a layer that
495 /// drapes, the drape's that first draws it, whose value every drape
496 /// the tile overlaps draws.
497 pub frame: &'a LayerFrame<'f>,
498}
499
500/// What a layer's [`Layer::update`] reads, besides its tiles.
501pub struct UpdateCx<'a, 'p, L: Layer> {
502 pub values: &'a LayerValues<L::Style>,
503 pub parameters: &'a mut LayerUpdateParameters<'p>,
504 picked: &'a mut Vec<OverscaledTileID>,
505}
506
507impl<L: Layer> UpdateCx<'_, '_, L> {
508 /// The deepest zoom the layer's source has tiles of; `None` for a layer
509 /// without a source or a source without tiles.
510 #[must_use]
511 pub fn source_max_zoom(&self) -> Option<u8> {
512 self.parameters.source.and_then(RenderSource::max_zoom)
513 }
514
515 /// Makes `tiles` those that a layer that picks its tiles
516 /// ([`Layer::PICKS_TILES`]) draws in the map's frame.
517 pub fn pick_tiles(&mut self, tiles: impl IntoIterator<Item = OverscaledTileID>) {
518 debug_assert!(L::PICKS_TILES, "a layer that doesn't pick its tiles picked some");
519 self.picked.clear();
520 self.picked.extend(tiles);
521 self.picked.sort();
522 self.picked.dedup();
523 }
524}
525
526/// A drape a layer draws in: its terrain tile, whether the frame is on the
527/// globe, and the tiles of every drape of the frame, in id order, which a
528/// layer that picks its tiles keeps values of.
529#[derive(Clone, Copy)]
530pub struct DrapeTile<'a> {
531 pub(crate) tile: OverscaledTileID,
532 pub(crate) globe: bool,
533 pub(crate) tiles: &'a [OverscaledTileID],
534}
535
536/// The draws a layer makes in a frame: the map's, which read the frame's
537/// shared targets, or a drape's, into the drape's draws of the layer.
538enum DrawsFor<'d> {
539 Map(&'d mut SharedTargets),
540 Drape(&'d mut Draws, &'d OverscaledTileID),
541}
542
543/// A layer type's render half: what it makes of its values, its tiles'
544/// data and the frame, whose hooks the engine calls on a render layer of the
545/// type (`Hosted`). The engine keeps the layer's base, its values of the
546/// layer type `Type`, its value of each tile it draws, a `Tile`, which the
547/// map's frame and every drape the tile overlaps draw, and its draws
548/// ([`Draws`]) in the frame and in each drape it draws in.
549pub trait Layer: Sized + 'static {
550 /// The type's style half: its name, its kind of source and its
551 /// properties.
552 type Style: StyleLayerType;
553
554 /// What the type's layers draw from: the features of a geometry
555 /// source's tiles, which a layout lays out into a bucket per tile
556 /// ([`Features`](crate::layer::tile_input::Features)), a raster or
557 /// raster-dem source's tiles, or none, for a type without a source
558 /// ([`NoTiles`](crate::layer::tile_input::NoTiles)). Of another kind of
559 /// source than the style half names, the registration doesn't compile.
560 type Input: TileInput<Self::Style>;
561
562 /// What the engine keeps of each tile the layer draws for it, from when
563 /// the layer makes it ([`tile`](Self::tile)) until what the tile shows
564 /// the layer changes.
565 type Tile: 'static;
566
567 /// The order the layer draws its source's tiles in.
568 const TILE_ORDER: TileOrder = TileOrder::ById;
569
570 /// How the layer meets terrain.
571 const TERRAIN: OnTerrain = OnTerrain::Flat;
572
573 /// Whether the layer draws 3D geometry, whose depth it writes in the
574 /// range of `PaintParameters::depth_mode_for_3d`. The layers above the
575 /// lowest such layer that draws draw without a depth test, and on the
576 /// globe the planet's depth hides its geometry behind the horizon.
577 const VOLUME: bool = false;
578
579 /// Whether the frame's draws of the layer can draw into a shared target
580 /// instead of the map
581 /// ([`Router`](crate::layer::Router)): not those of 3D geometry.
582 const ROUTES: bool = !Self::VOLUME;
583
584 /// Whether a layer of a type without a source draws tiles it picks in
585 /// its update ([`UpdateCx::pick_tiles`]), and in a drape the drape's
586 /// tile ([`PrepareCx::picked`]); one that picks none draws nothing. One
587 /// that doesn't pick draws without tiles.
588 const PICKS_TILES: bool = false;
589
590 /// Whether the layer's tile values hold nothing of its style's values,
591 /// so that they stay through a restyle.
592 const RESTYLE_KEEPS_TILES: bool = false;
593
594 /// Whether the type has cross-faded properties, whose evaluation takes
595 /// the frame's cross-fade.
596 const CROSSFADES: bool = false;
597
598 /// Whether the type's layers draw on the tiles that are fading out
599 /// while a placement fades their marks out.
600 const FADES_TILES: bool = false;
601
602 /// How long a tile that a layer of `values` draws takes to fade in once
603 /// it can draw, from the tile it replaces or from nothing, and a tile it
604 /// replaces takes to fade out (`FrameTile::fade`); zero for none, the
605 /// default. A source's tiles fade for the longest of its layers'.
606 fn tile_fade(_values: &EvaluatedLayer<Self::Style>) -> Duration {
607 Duration::ZERO
608 }
609
610 /// Whether the type's layers place their marks, with a participant in
611 /// placement ([`Placement`](crate::placement::Placement)) that registers
612 /// with the type
613 /// ([`add_placing_layer_type`](crate::RegistryBuilder::add_placing_layer_type)).
614 const PLACES: bool = false;
615
616 /// The layer of the values `values`, before they transition.
617 fn new(values: &LayerValues<Self::Style>) -> Self;
618
619 /// Called once the layer's paint values are evaluated for a frame,
620 /// before they become the layer's: the layer derives the values of
621 /// `cx.evaluated` that its type derives from others, remakes what it
622 /// makes of them, such as a color ramp, and says how it draws with them.
623 fn evaluate(&mut self, _cx: EvaluateCx<'_, Self>) -> Evaluation {
624 Evaluation::TRANSLUCENT
625 }
626
627 /// The light that the terrain's surface can shade the layer's drapes
628 /// with in `frame`, whose draws then put in them what it shades
629 /// ([`LayerFrame::drape_lit`]); `None` for a layer whose drapes hold its
630 /// colors.
631 fn surface_light(&mut self, _values: &LayerValues<Self::Style>, _frame: &LayerFrame<'_>) -> Option<SurfaceLight> {
632 None
633 }
634
635 /// Called in the frame's update of the layer with `tiles`, the frame's
636 /// tiles of its source in the order the layer draws them, each with
637 /// what it holds for the layer; none for a type without a source
638 /// ([`NoTiles`](crate::layer::tile_input::NoTiles)). The layer collects
639 /// here what the update needs of its tiles' data; a type that places
640 /// collects what it places in its participant instead
641 /// (`Placement::collect`). One
642 /// without a source that picks its tiles picks them here.
643 fn update(&mut self, _cx: UpdateCx<'_, '_, Self>, _tiles: &[FrameTile<'_, Self>]) {}
644
645 /// Whether `tile`, a tile's value the layer made, still draws the tile
646 /// with the layer's `values` of the frame. The engine retires a value
647 /// the layer doesn't keep before the layer makes the frame's draws.
648 fn keeps(&self, _values: &LayerValues<Self::Style>, _tile: &Self::Tile) -> bool {
649 true
650 }
651
652 /// The value of `tile`, which holds `data` for the layer, for a tile
653 /// the engine keeps no value of: none where the tile shows nothing to
654 /// draw. The engine keeps it until the tile shows the layer something
655 /// else (another bucket, or contents of another generation), leaves the
656 /// frame, or the layer's draws drop. The map's frame and every drape
657 /// the tile overlaps, in any world copy, draw the same value, so it
658 /// holds nothing of the frame or the copy it is first drawn in.
659 ///
660 /// `previous` is the tile's value before, if the engine retired it
661 /// rather than dropped it: when the tile came to show other contents or
662 /// another generation of them, the layer stopped keeping it
663 /// ([`keeps`](Self::keeps)), or its draws dropped for a restyle or the
664 /// frame's projection. A layer takes from it what it made of contents
665 /// that are still the tile's, such as a texture of the tile's image,
666 /// rather than making them again.
667 fn tile(
668 &mut self,
669 _cx: &mut TileCx<'_, '_, Self>,
670 _tile: FrameTile<'_, Self>,
671 _data: TileData<'_, Self>,
672 _previous: Option<Self::Tile>,
673 ) -> Option<Self::Tile> {
674 None
675 }
676
677 /// Makes the layer's draws of the frame, the map's or a drape's, in the
678 /// frame's encode, of a layer that draws in a pass and has tiles to draw,
679 /// once the engine made the values of the tiles that had none
680 /// ([`tile`](Self::tile)): from `tiles`, the frame's tiles of the layer,
681 /// in the order the update gave them, each with what it holds for the
682 /// layer, or in a drape those that overlap the drape's tile, each in the
683 /// world copy the drape draws it in ([`FrameTile::draw_id`]); none for a
684 /// type without a source, which draws the tiles it picked
685 /// ([`PrepareCx::picked`]). The layer pushes its draws, with the values
686 /// of their blocks, into `out`, which holds no draws yet, and copies
687 /// again into the tile values what changed of their buckets
688 /// (`TileMap::take_changes`), which every frame that draws them
689 /// then draws. The engine then writes, uploads and draws them, and draws
690 /// the masks of the layer's tiles where a draw clips.
691 fn prepare(&mut self, _cx: &mut PrepareCx<'_, '_, Self>, _tiles: &[FrameTile<'_, Self>], _out: &mut Draws) {}
692
693 /// Draws with the backend's commands that the frame lends the layer
694 /// `at` its time in the frame, where its draws asked for them
695 /// ([`Draws::lend`]): `lent`, which the layer may use only until this
696 /// returns. A frame without commands to lend, such as one outside a
697 /// pass at [`LendAt::Pass`], lends none.
698 ///
699 /// What the layer makes with the commands, the engine doesn't know of:
700 /// the layer frees it through work it queues for after the GPU
701 /// ([`Lent::after_gpu`]), at the latest as it drops, which is when it
702 /// leaves the renderer.
703 fn lend(&mut self, _at: LendAt, _lent: Lent<'_>) {}
704
705 /// How far outside a feature of `data`, a tile's bucket of the layer, a
706 /// query still hits it, from `layer`'s current values and the bucket's
707 /// statistics of them. The engine asks only a type whose input lays
708 /// out.
709 fn query_radius(_data: TileData<'_, Self>, _layer: &EvaluatedLayer<Self::Style>) -> f32 {
710 0.0
711 }
712
713 /// Whether a query hits the feature `feature` with `geometry`, with
714 /// `feature_state`: whether it intersects `region` of its tile as the
715 /// layer of `values` draws it at the view's zoom; a miss unless a layer
716 /// type overrides it. A type whose features stand at points and hide
717 /// behind the ground ([`OnTerrain::Stands`]) hits only those that show,
718 /// which [`QueryRegion::shows`] tells. A type that draws 3D geometry
719 /// ([`Layer::VOLUME`]) tells how far from the camera it hits
720 /// ([`Hit::At`]).
721 fn hit(
722 &self,
723 _values: &LayerValues<Self::Style>,
724 _region: &QueryRegion<'_>,
725 _feature: &dyn mln_style::feature::GeometryTileFeature,
726 _geometry: &mln_style::feature::GeometryCollection,
727 _feature_state: &mln_style::feature::FeatureState,
728 ) -> Hit {
729 Hit::Miss
730 }
731
732 /// Adds to `hits` the features that `query`'s geometry hits of what the
733 /// layer shows other than its tiles' features, such as a mark it places
734 /// itself, topmost first. As for tiles' features, a query answers for
735 /// the last update: the engine asks a layer that the update would draw,
736 /// with its view and values, which may come before a frame draws them,
737 /// so a layer answers from `query` rather than from what it kept from
738 /// drawing. The engine names the features' layer and source and keeps
739 /// those that the query's filter takes.
740 fn hit_frame(&self, _query: &FrameQuery<'_, Self>, _hits: &mut Vec<Feature>) {}
741}
742
743/// A rendered-feature query of a layer `L`, for what it shows other than
744/// its tiles' features, as of the last update ([`Layer::hit_frame`]).
745pub struct FrameQuery<'a, L: Layer> {
746 values: &'a LayerValues<L::Style>,
747 view: &'a View,
748 geometry: &'a [ScreenCoordinate],
749 ground: Option<&'a TerrainElevation>,
750}
751
752impl<'a, L: Layer> FrameQuery<'a, L> {
753 /// The layer's values of the last update.
754 #[must_use]
755 pub fn values(&self) -> &'a LayerValues<L::Style> {
756 self.values
757 }
758
759 /// The last update's camera and projection.
760 #[must_use]
761 pub fn view(&self) -> &'a View {
762 self.view
763 }
764
765 /// The query's geometry, in the view's logical pixels from its top left:
766 /// one point, or a closed ring.
767 #[must_use]
768 pub fn geometry(&self) -> &'a [ScreenCoordinate] {
769 self.geometry
770 }
771
772 /// Over terrain, the ground the frame drew under the points of `tile`,
773 /// for a layer that meets terrain ([`Layer::TERRAIN`]); `None` without
774 /// terrain or for a layer that draws flat.
775 #[must_use]
776 pub fn ground(&self, tile: UnwrappedTileID) -> Option<TileGround<'a>> {
777 self.ground.map(|ground| TileGround::new(ground, tile))
778 }
779}
780
781/// A render layer of a [`Layer`] `L`: the layer, and what the engine
782/// keeps of it, its base, its values, its tile values and its draws of the
783/// map's frame.
784pub(crate) struct Hosted<L: Layer> {
785 base: RenderLayerBase,
786 values: LayerValues<L::Style>,
787 tiles: TileMap<L::Tile>,
788 /// The tiles that a layer that picks its tiles picked in its update,
789 /// in id order, which it draws in the map's frame.
790 picked: Vec<OverscaledTileID>,
791 draws: Draws,
792 layer: L,
793}
794
795impl<L: Layer> Hosted<L> {
796 /// The render layer of the layer `style`, before its values transition.
797 pub(crate) fn new(style: Arc<LayerStyle<L::Style>>) -> Self {
798 let (base, values) = LayerValues::new(style, entry::<L>());
799 let layer = L::new(&values);
800 Hosted { base, values, tiles: TileMap::default(), picked: Vec::new(), draws: Draws::default(), layer }
801 }
802
803 /// [`new`](Self::new), boxed as a [`RenderLayer`].
804 pub(crate) fn boxed(style: Arc<LayerStyle<L::Style>>) -> Box<dyn RenderLayer> {
805 Box::new(Self::new(style))
806 }
807
808 /// The layer and its values, which benchmarks fill as the layer's
809 /// update would.
810 #[cfg(feature = "bench")]
811 pub(crate) fn layer_mut(&mut self) -> (&mut L, &LayerValues<L::Style>) {
812 (&mut self.layer, &self.values)
813 }
814
815 /// Makes `variant` the projection the layer draws in: where its draws
816 /// were of another, drops them and retires its tile values.
817 fn use_projection_variant(&mut self, variant: ProjectionVariant) {
818 if variant != self.base.projection_variant {
819 self.base.projection_variant = variant;
820 self.retire_draws();
821 }
822 }
823
824 /// Drops the frame's draws of the layer and retires its tile values,
825 /// which the next values of their tiles may take from: until the
826 /// layer's next draws are done, the draws keep what they kept for the
827 /// retired values' meshes. The tiles stay.
828 fn retire_draws(&mut self) {
829 self.tiles.retire();
830 self.draws.clear();
831 }
832
833 /// Readies the values of `tiles`, the tiles the layer draws, before the
834 /// layer makes its draws of them: retires each that was made from
835 /// something else than what its tile shows the layer, or that the layer
836 /// doesn't keep ([`Layer::keeps`]), and makes those the layer has
837 /// none of ([`Layer::tile`]), from their previous values. For a
838 /// layer that picks its tiles, retires those of its picked tiles that it
839 /// doesn't keep.
840 fn ready_tiles(
841 &mut self,
842 gpu: &mut dyn Gpu,
843 context: &mut Context,
844 frame: &LayerFrame<'_>,
845 tiles: &[FrameTile<'_, L>],
846 ) {
847 let Hosted { base, values, tiles: map, layer, .. } = self;
848 if !has_tiles::<L>() {
849 for (_, mut entry) in map.entries() {
850 if entry.value.as_ref().is_some_and(|value| !layer.keeps(values, value)) {
851 entry.retire();
852 }
853 }
854 return;
855 }
856 for &tile in tiles {
857 let Some(mut entry) = map.entry(&tile.id()) else { continue };
858 entry.show(tile.made_from());
859 if entry.value.as_ref().is_some_and(|value| !layer.keeps(values, value)) {
860 entry.retire();
861 }
862 if entry.value.is_none()
863 && let Some(data) = tile.data()
864 {
865 // A new value copies its bucket as it is.
866 entry.take_changes();
867 let previous = entry.take_previous();
868 let res = Resources::new(&mut *gpu, &mut *context);
869 *entry.value = layer.tile(&mut TileCx { base, values, res, frame }, tile, data, previous);
870 }
871 }
872 }
873
874 /// Makes the layer's draws of `into`'s frame, the map's or a drape's,
875 /// if it draws in a pass: starts them, readies its tile values of
876 /// `tiles` ([`ready_tiles`](Self::ready_tiles)), runs its
877 /// [`Layer::prepare`] and writes the buffers of the draws it made,
878 /// with the paint parameters of `parameters`' frame where it has its own
879 /// (a drape's), and the masks of `tiles` where a draw clips. One that
880 /// draws in no pass with its values of the frame draws nothing, and
881 /// keeps its tile values.
882 fn draw(
883 &mut self,
884 gpu: &mut dyn Gpu,
885 parameters: &mut PaintParameters<'_>,
886 tiles: &[FrameTile<'_, L>],
887 into: DrawsFor<'_>,
888 ) {
889 if self.values.evaluated.render_passes == RenderPass::NONE.bits() {
890 match into {
891 DrawsFor::Map(_) => self.draws.begin(),
892 DrawsFor::Drape(draws, _) => draws.begin(),
893 }
894 return;
895 }
896 let frame = parameters.frame();
897 self.ready_tiles(gpu, parameters.context, &frame, tiles);
898 let Hosted { base, values, tiles: map, picked, draws, layer } = self;
899 let (draws, picked, targets) = match into {
900 DrawsFor::Map(targets) => (draws, &picked[..], Some(targets)),
901 DrawsFor::Drape(draws, tile) => (draws, std::slice::from_ref(tile), None),
902 };
903 draws.begin();
904 let res = Resources::new(&mut *gpu, &mut *parameters.context);
905 layer.prepare(&mut PrepareCx { base, values, tiles: map, picked, res, frame: &frame, targets }, tiles, draws);
906 let paint_params = parameters.own_paint_params();
907 let clip_tiles = tiles.iter().map(|tile| tile.draw_id().to_unwrapped());
908 draws.finish(gpu, parameters.context, paint_params.as_ref(), clip_tiles);
909 }
910}
911
912/// Lends `layer` the backend's commands of `gpu` `at` its time in the frame
913/// of `parameters`, where the frame has them to lend: in a pass, the open
914/// one. A lend that fails fails the frame.
915fn lend<L: Layer>(layer: &mut L, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>, at: LendAt) {
916 let Some(projection) = parameters.lent_projection else { return };
917 let frame = parameters.frame();
918 let layer_depth = match at {
919 LendAt::BeforePasses => None,
920 LendAt::Pass if parameters.pass_target().is_some() => Some(f64::from(parameters.layer_depth())),
921 LendAt::Pass => return,
922 };
923 let after_gpu = parameters.context.after_gpu().handle();
924 let lent = gpu
925 .lend(&mut |raw| layer.lend(at, Lent { raw, frame: &frame, projection: &projection, layer_depth, after_gpu }));
926 if let Err(error) = lent {
927 parameters.context.fail(format!("Lending a layer the frame's commands failed: {error}"));
928 }
929}
930
931/// Whether layers of `L`'s type draw from their source's tiles: false for a
932/// type without a source.
933fn has_tiles<L: Layer>() -> bool {
934 <L::Input as Find<L::Style>>::KIND != SourceKind::None
935}
936
937/// What the engine does with a render layer, whatever its type: its base,
938/// its values, which this transitions without knowing their type, its tile
939/// values and its draws, which it writes, uploads and draws. It runs
940/// the layer's [`Layer`] hooks with what is common to every layer type
941/// around them.
942pub trait RenderLayer {
943 fn base(&self) -> &RenderLayerBase;
944
945 /// The layer's id.
946 fn id(&self) -> &str {
947 &self.base().style.base().id
948 }
949
950 /// The order the layer draws its source's tiles in.
951 fn tile_order(&self) -> TileOrder;
952
953 /// Makes `style`, the changed style of the layer (of the same id and
954 /// type), the layer's, drops the draws, which were built for the
955 /// previous style's values, with the tile values unless the layer keeps
956 /// them ([`Layer::RESTYLE_KEEPS_TILES`]), and begins transitions to
957 /// the new values. A style of another type leaves the layer's. The next
958 /// encode builds the draws again from the tiles' buckets.
959 fn restyle(&mut self, parameters: &TransitionParameters, style: &Arc<dyn ErasedLayerStyle>);
960
961 /// Begins transitions for the paint values that changed since the last
962 /// frame, to those of the layer's style.
963 fn transition(&mut self, parameters: &TransitionParameters);
964
965 /// Evaluates the layer's paint values for a frame of `parameters`,
966 /// which the layer completes ([`Layer::evaluate`]), and sets the
967 /// passes the layer draws in with them.
968 fn evaluate(&mut self, parameters: &PropertyEvaluationParameters);
969
970 /// Whether a paint value of the layer is still in transition.
971 fn has_transition(&self) -> bool;
972
973 /// Whether the layer has a pattern property and is in a cross-fade.
974 fn has_crossfade(&self) -> bool;
975
976 /// The frame's update of the layer: finds the tiles of `parameters`'
977 /// source the layer draws, which it adds to `parameters.found`, adds the
978 /// passes their buckets were laid out for to the layer's, runs the
979 /// layer's [`Layer::update`], and keeps entries for the tiles; or,
980 /// for a type without a source, runs its update without tiles.
981 fn update(&mut self, parameters: &mut LayerUpdateParameters<'_>);
982
983 /// The encode's update of the layer's draws: picks the shader variant
984 /// for the frame's projection, standing on the frame's ground where the
985 /// layer stands and the frame has one, dropping the draws and tile values
986 /// when it changed; drops them of a layer that has nothing to draw, and
987 /// otherwise starts its draws of the frame; for a layer that draws in a
988 /// pass, readies the tile values and runs the layer's
989 /// [`Layer::prepare`] with the tiles of its type that its update
990 /// found in `source`, or none for a type without a source, and writes
991 /// the buffers of its draws.
992 fn update_draws(
993 &mut self,
994 gpu: &mut dyn Gpu,
995 parameters: &mut PaintParameters<'_>,
996 source: Option<FrameSourceTiles<'_>>,
997 targets: &mut SharedTargets,
998 );
999
1000 /// How the layer meets terrain ([`Layer::TERRAIN`]).
1001 fn terrain(&self) -> OnTerrain;
1002
1003 /// Whether the layer draws 3D geometry ([`Layer::VOLUME`]).
1004 fn volume(&self) -> bool;
1005
1006 /// Whether the layer's draws can draw into a shared target
1007 /// ([`Layer::ROUTES`]).
1008 fn routes(&self) -> bool;
1009
1010 /// Makes `route` the shared target that the frame's draws of the layer
1011 /// draw into instead of the map, or with `None` the map.
1012 fn set_route(&mut self, route: Option<usize>);
1013
1014 /// Whether the layer's blend with its values of the frame reads what is
1015 /// drawn beneath it, which a shared target's pass can't give it.
1016 fn reads_backdrop(&self) -> bool;
1017
1018 /// Whether the layer blends with what is under it otherwise than by
1019 /// covering it, with its values of the frame: a layer blend
1020 /// ([`StyleLayerType::layer_blend`]) other than `normal`.
1021 fn blends(&self) -> bool;
1022
1023 /// The light the terrain's surface can shade the layer's drapes with
1024 /// ([`Layer::surface_light`]).
1025 fn surface_light(&mut self, parameters: &PaintParameters<'_>) -> Option<SurfaceLight>;
1026
1027 /// Where the tiles the layer's update found are among the frame's
1028 /// ([`LayerUpdateParameters::found`]); `None` for a type without a
1029 /// source.
1030 fn found(&self) -> Option<Range<usize>>;
1031
1032 /// The encode's update of the layer's draws into `drape`, `draws`, as
1033 /// [`update_draws`](Self::update_draws) makes the frame's, with the
1034 /// drape's `parameters`, from the tiles of `source` the layer's update
1035 /// found that overlap the drape's tile
1036 /// ([`FrameSourceTiles::overlapping`]), or from the drape's tile itself
1037 /// for a type without a source that picks its tiles, in the Mercator
1038 /// projection, a drape's. The drape draws the layer's tile values,
1039 /// which the frame's other drapes share: for a layer that picks its
1040 /// tiles, those of the tiles of every drape.
1041 fn update_drape_draws(
1042 &mut self,
1043 gpu: &mut dyn Gpu,
1044 parameters: &mut PaintParameters<'_>,
1045 source: Option<FrameSourceTiles<'_>>,
1046 drape: DrapeTile<'_>,
1047 draws: &mut Draws,
1048 );
1049
1050 /// Records that the buckets in `changed` changed, for the tiles whose
1051 /// values were made from them.
1052 fn mark_changed(&mut self, changed: &ChangedBuckets);
1053
1054 /// Moves the layer's value of each tile to the tile `wrap_delta` world
1055 /// copies east of it: the tiles are the same ones under new ids once the
1056 /// map's center has crossed the antimeridian, and their values stay
1057 /// rather than being made again.
1058 fn handle_wrap_jump(&mut self, wrap_delta: i16);
1059
1060 /// Includes the layer in the frame's drawing or excludes it. A layer
1061 /// excluded drops its draws and its tiles with their values, previous
1062 /// ones too: its updates don't run until it is included again, and they
1063 /// then rebuild everything from the source's tiles.
1064 fn set_renderable(&mut self, renderable: bool);
1065
1066 /// Drops the layer's tile values, previous ones too, and the frame's
1067 /// draws of the layer, which then let go of what they kept for the
1068 /// values' meshes. The tiles stay.
1069 fn remove_all_draws(&mut self);
1070
1071 /// Drops the map frame's draws of the layer, which a frame over terrain
1072 /// draws only in drapes; its tile values stay, for the drapes.
1073 fn remove_frame_draws(&mut self);
1074
1075 /// Visits the groups of the layer's draws of the frame that take a place
1076 /// in the layers' order and depth, in drawing order: none unless the
1077 /// frame draws the layer. They are the groups `upload` and `render`
1078 /// upload and draw.
1079 fn visit_draw_groups<'a>(&'a self, visit: &mut dyn FnMut(&'a Group));
1080
1081 /// Uploads the meshes of the layer's draws, before the frame draws them.
1082 fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context);
1083
1084 /// Draws the pass's draws of the layer's groups into the open pass of
1085 /// `gpu`, the context's, in `order`, each at its depth, and, in the
1086 /// translucent pass, lends the layer the pass after its main group where
1087 /// its draws asked for it ([`LendAt::Pass`]): the map's pass, or with
1088 /// `routed` the pass of the shared target the layer is routed into. In
1089 /// the other, the layer takes its depth and draws nothing.
1090 fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>, order: DrawOrder, routed: bool);
1091
1092 /// Before the frame's passes, outside any pass of `gpu`, the context's:
1093 /// draws into the targets of the layer's draws of the frame
1094 /// ([`Draws::target`]), and then lends the layer the frame's commands
1095 /// where its draws asked for them ([`LendAt::BeforePasses`]).
1096 fn before_passes(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>);
1097
1098 /// See [`Layer::hit`].
1099 fn hit(
1100 &self,
1101 region: &QueryRegion<'_>,
1102 feature: &dyn mln_style::feature::GeometryTileFeature,
1103 geometry: &mln_style::feature::GeometryCollection,
1104 feature_state: &mln_style::feature::FeatureState,
1105 ) -> Hit;
1106
1107 /// See [`Layer::hit_frame`]: what `geometry`, in `view`'s logical pixels,
1108 /// hits of what the layer shows, over `ground` where the map has
1109 /// terrain. Nothing for a layer the last update wouldn't draw.
1110 fn hit_frame(
1111 &self,
1112 view: &View,
1113 geometry: &[ScreenCoordinate],
1114 ground: Option<&TerrainElevation>,
1115 hits: &mut Vec<Feature>,
1116 );
1117
1118 /// Whether the layer draws in a pass and is visible.
1119 fn needs_rendering(&self) -> bool {
1120 self.base().passes != RenderPass::NONE && self.base().style.base().visibility != VisibilityType::None
1121 }
1122
1123 /// Whether the layer's last evaluation asked for another frame on the
1124 /// next vsync.
1125 fn needs_repaint(&self) -> bool {
1126 self.base().evaluation.needs_repaint
1127 }
1128
1129 /// When, without [`needs_repaint`](Self::needs_repaint), the layer's last
1130 /// evaluation said it changes next on its own.
1131 fn repaint_at(&self) -> Option<Instant> {
1132 self.base().evaluation.repaint_at
1133 }
1134
1135 /// Whether the layer draws at `zoom`. A minimum zoom of 0 is no
1136 /// minimum: the globe zooms below 0 toward the poles.
1137 fn supports_zoom(&self, zoom: f64) -> bool {
1138 let zoom_or_zero = if zoom < 0.0 { 0.0 } else { zoom };
1139 let style = self.base().style.base();
1140 style.min_zoom <= zoom_or_zero && zoom < style.max_zoom
1141 }
1142
1143 /// Whether the frame draws the layer.
1144 fn is_renderable(&self) -> bool {
1145 self.base().is_renderable
1146 }
1147
1148 /// What the layer's paint values depend on.
1149 fn style_dependencies(&self) -> Dependency {
1150 self.base().style_dependencies
1151 }
1152}
1153
1154impl<L: Layer> RenderLayer for Hosted<L> {
1155 fn base(&self) -> &RenderLayerBase {
1156 &self.base
1157 }
1158
1159 fn tile_order(&self) -> TileOrder {
1160 L::TILE_ORDER
1161 }
1162
1163 fn restyle(&mut self, parameters: &TransitionParameters, style: &Arc<dyn ErasedLayerStyle>) {
1164 if L::RESTYLE_KEEPS_TILES {
1165 self.draws.clear();
1166 } else {
1167 self.retire_draws();
1168 }
1169 if let Some(recovered) = LayerStyle::recover(style) {
1170 self.values.style = recovered;
1171 self.base.style = Arc::clone(style);
1172 }
1173 self.transition(parameters);
1174 }
1175
1176 fn transition(&mut self, parameters: &TransitionParameters) {
1177 let values = &mut self.values;
1178 let prior = std::mem::take(&mut values.unevaluated);
1179 values.unevaluated = values.style.paint.transitioned(parameters, prior);
1180 self.base.style_dependencies = <L::Style as StyleLayerType>::PaintProperties::dependencies(&values.unevaluated);
1181 }
1182
1183 fn evaluate(&mut self, parameters: &PropertyEvaluationParameters) {
1184 let mut evaluated = self.values.evaluate(parameters, L::CROSSFADES);
1185 let evaluation =
1186 self.layer.evaluate(EvaluateCx { values: &self.values, parameters, evaluated: &mut evaluated });
1187 self.base.passes = evaluation.passes();
1188 self.base.evaluation = evaluation;
1189 self.values.set_evaluated(&mut self.base, evaluated);
1190 }
1191
1192 fn has_transition(&self) -> bool {
1193 <L::Style as StyleLayerType>::PaintProperties::has_transition(&self.values.unevaluated)
1194 }
1195
1196 fn has_crossfade(&self) -> bool {
1197 L::CROSSFADES && self.values.evaluated.crossfade.t != 1.0
1198 }
1199
1200 fn update(&mut self, parameters: &mut LayerUpdateParameters<'_>) {
1201 let Hosted { base, values, tiles: map, picked, layer, .. } = self;
1202 if !has_tiles::<L>() {
1203 layer.update(UpdateCx { values, parameters, picked }, &[]);
1204 return;
1205 }
1206 let start = parameters.found.len();
1207 let tiles = match parameters.tiles(L::TILE_ORDER) {
1208 Some((tiles, order)) => tiles.find::<L>(order, &base.style.base().id, parameters.found),
1209 None => FrameTiles::new(),
1210 };
1211 base.found = start..parameters.found.len();
1212 for data in tiles.iter().filter_map(|tile| tile.data()) {
1213 base.passes |= <L::Input as Find<L::Style>>::passes(data);
1214 }
1215 layer.update(UpdateCx { values, parameters, picked }, &tiles);
1216 map.set_tiles(tiles.iter().map(|tile| tile.id()));
1217 }
1218
1219 fn update_draws(
1220 &mut self,
1221 gpu: &mut dyn Gpu,
1222 parameters: &mut PaintParameters<'_>,
1223 source: Option<FrameSourceTiles<'_>>,
1224 targets: &mut SharedTargets,
1225 ) {
1226 let stands = L::TERRAIN.stands() && parameters.ground.is_some();
1227 self.use_projection_variant(ProjectionVariant::new(parameters.view.is_globe(), stands));
1228 if !has_tiles::<L>() {
1229 // A layer that picks tiles draws those its update picked.
1230 if L::PICKS_TILES {
1231 self.tiles.set_tiles(self.picked.iter().copied());
1232 }
1233 if L::PICKS_TILES && self.tiles.is_empty() {
1234 self.remove_all_draws();
1235 } else {
1236 self.draw(gpu, parameters, &[], DrawsFor::Map(targets));
1237 }
1238 return;
1239 }
1240 match source.map(|source| (source, source.found(self.base.found.clone()))) {
1241 Some((source, found)) if !found.is_empty() => {
1242 let tiles = source.at::<L>(found, self.id());
1243 self.draw(gpu, parameters, &tiles, DrawsFor::Map(targets));
1244 }
1245 _ => self.remove_all_draws(),
1246 }
1247 }
1248
1249 fn terrain(&self) -> OnTerrain {
1250 L::TERRAIN
1251 }
1252
1253 fn volume(&self) -> bool {
1254 L::VOLUME
1255 }
1256
1257 fn routes(&self) -> bool {
1258 L::ROUTES
1259 }
1260
1261 fn set_route(&mut self, route: Option<usize>) {
1262 self.base.route = route;
1263 }
1264
1265 fn reads_backdrop(&self) -> bool {
1266 crate::render::layer_composite::reads_backdrop(L::Style::layer_blend(&self.values.evaluated.paint))
1267 }
1268
1269 fn blends(&self) -> bool {
1270 L::Style::layer_blend(&self.values.evaluated.paint) != LayerBlendType::Normal
1271 }
1272
1273 fn surface_light(&mut self, parameters: &PaintParameters<'_>) -> Option<SurfaceLight> {
1274 self.layer.surface_light(&self.values, ¶meters.frame())
1275 }
1276
1277 fn found(&self) -> Option<Range<usize>> {
1278 has_tiles::<L>().then(|| self.base.found.clone())
1279 }
1280
1281 fn update_drape_draws(
1282 &mut self,
1283 gpu: &mut dyn Gpu,
1284 parameters: &mut PaintParameters<'_>,
1285 source: Option<FrameSourceTiles<'_>>,
1286 drape: DrapeTile<'_>,
1287 draws: &mut Draws,
1288 ) {
1289 // Only a layer that drapes builds the code of its draws in a drape.
1290 if !L::TERRAIN.drapes() {
1291 debug_assert!(false, "a layer that doesn't drape in a drape");
1292 return;
1293 }
1294 // A drape is flat: the layer's draws are Mercator's.
1295 self.use_projection_variant(ProjectionVariant::Mercator);
1296 if !has_tiles::<L>() {
1297 if L::PICKS_TILES {
1298 self.tiles.set_tiles(drape.tiles.iter().copied());
1299 }
1300 self.draw(gpu, parameters, &[], DrawsFor::Drape(draws, &drape.tile));
1301 return;
1302 }
1303 let tiles = match source {
1304 Some(source) => {
1305 source.overlapping::<L>(self.base.found.clone(), self.id(), drape.tile.to_unwrapped(), drape.globe)
1306 }
1307 None => FrameTiles::new(),
1308 };
1309 if tiles.is_empty() {
1310 draws.clear();
1311 } else {
1312 self.draw(gpu, parameters, &tiles, DrawsFor::Drape(draws, &drape.tile));
1313 }
1314 }
1315
1316 fn mark_changed(&mut self, changed: &ChangedBuckets) {
1317 self.tiles.mark_changed(changed);
1318 }
1319
1320 fn handle_wrap_jump(&mut self, wrap_delta: i16) {
1321 self.tiles.shift_wraps(wrap_delta);
1322 }
1323
1324 fn set_renderable(&mut self, renderable: bool) {
1325 self.base.is_renderable = renderable;
1326 if !renderable {
1327 self.tiles.clear_tiles();
1328 self.draws.clear();
1329 }
1330 }
1331
1332 fn remove_all_draws(&mut self) {
1333 self.tiles.clear();
1334 self.draws.clear();
1335 }
1336
1337 fn remove_frame_draws(&mut self) {
1338 self.draws.clear();
1339 }
1340
1341 fn visit_draw_groups<'a>(&'a self, visit: &mut dyn FnMut(&'a Group)) {
1342 if self.base.is_renderable {
1343 self.draws.visit_groups(visit);
1344 }
1345 }
1346
1347 fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context) {
1348 if self.base.is_renderable {
1349 self.draws.upload(gpu, context);
1350 }
1351 }
1352
1353 fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>, order: DrawOrder, routed: bool) {
1354 let Hosted { base, draws, layer, .. } = self;
1355 if base.is_renderable && base.route.is_some() != routed {
1356 draws.skip(parameters, order);
1357 } else if base.is_renderable {
1358 let lends = draws.lends(LendAt::Pass) && parameters.pass == RenderPass::TRANSLUCENT;
1359 let mut lend_pass = |gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>| {
1360 lend(layer, gpu, parameters, LendAt::Pass);
1361 };
1362 draws.render(gpu, parameters, order, lends.then_some(&mut lend_pass));
1363 }
1364 }
1365
1366 fn before_passes(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
1367 if self.base.is_renderable {
1368 self.draws.render_targets(gpu, parameters);
1369 if self.draws.lends(LendAt::BeforePasses) {
1370 lend(&mut self.layer, gpu, parameters, LendAt::BeforePasses);
1371 }
1372 }
1373 }
1374
1375 fn hit(
1376 &self,
1377 region: &QueryRegion<'_>,
1378 feature: &dyn mln_style::feature::GeometryTileFeature,
1379 geometry: &mln_style::feature::GeometryCollection,
1380 feature_state: &mln_style::feature::FeatureState,
1381 ) -> Hit {
1382 self.layer.hit(&self.values, region, feature, geometry, feature_state)
1383 }
1384
1385 fn hit_frame(
1386 &self,
1387 view: &View,
1388 geometry: &[ScreenCoordinate],
1389 ground: Option<&TerrainElevation>,
1390 hits: &mut Vec<Feature>,
1391 ) {
1392 if self.base.is_renderable {
1393 let ground = ground.filter(|_| L::TERRAIN != OnTerrain::Flat);
1394 self.layer.hit_frame(&FrameQuery { values: &self.values, view, geometry, ground }, hits);
1395 }
1396 }
1397}