Skip to main content

mln_engine/render/
renderer.rs

1use std::sync::Arc;
2use std::time::Duration;
3
4use mln_gfx::gpu::{ColorAttachment, DepthStencilAttachment, Gpu, LoadOp, TargetFormats};
5use mln_gfx::rendering_stats::{RenderingStats, TerrainStats};
6use mln_gfx::shaders::bindings::PAINT_PARAMS_ID;
7use mln_gfx::{FrameImage, Handoff, Rgba, ScissorRect};
8use mln_style::color::Color;
9use mln_style::error::Error;
10use mln_style::time::Instant;
11
12use crate::camera::FrameProjection;
13use crate::draw::context::Context;
14use crate::exec::event_queue::Waker;
15use crate::exec::pool::Pool;
16use crate::layer::layer_drawing::{DrawGroups, DrawOrder};
17use crate::layers::custom::{CustomLayerFrame, end_hosts};
18use crate::render::clip_masks::ClipMasks;
19use crate::render::events::{RenderMode, RendererEvent, RendererEvents};
20use crate::render::frame::Frame;
21use crate::render::frame_projection;
22use crate::render::layer_composite::LayerComposite;
23use crate::render::orchestrator::RenderOrchestrator;
24use crate::render::paint_parameters::{OpenPass, PaintParameters};
25use crate::render::pass::RenderPass;
26use crate::render::static_data::RenderStaticData;
27use crate::render::tile_matrix::to_projection_ubo;
28use crate::render::update_parameters::UpdateParameters;
29use crate::text::GlyphCache;
30use crate::text::local_fonts::LocalGlyphs;
31use crate::worker::worker_codec::RemoteWorkers;
32use crate::{Registry, log_target};
33
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35enum RenderState {
36    Never,
37    Partial,
38    Fully,
39}
40
41/// What the last frame that [`Renderer::render`] drew spent on
42/// each of its steps, on the CPU, from its [update](Renderer::update) on.
43/// They follow each other, and together take nearly all of `update` and
44/// `render`.
45#[derive(Clone, Copy, Debug, Default, PartialEq)]
46pub struct RenderTimings {
47    /// The update up to symbol placement: the style's changes, the layers'
48    /// values, the sources' tiles and the layers' choice of them.
49    pub sources: Duration,
50    /// The rest of the update: placing symbols across tiles and updating
51    /// their buckets.
52    pub symbols: Duration,
53    /// Making the layers' draws from the tiles, with their uniforms.
54    pub layers: Duration,
55    /// Making the shaders when there are none, and uploading buffers and
56    /// textures.
57    pub upload: Duration,
58    /// Encoding the render passes and submitting them.
59    pub draw: Duration,
60}
61
62/// Draws a map's updates into the frames of one backend's [`Gpu`]: it keeps
63/// the map's sources, tiles and layers between frames, and the GPU objects
64/// they draw with.
65///
66/// The renderer holds no `Gpu`. Each call that makes, draws or frees its GPU
67/// objects takes the one it was made for, which its host lends it, as it
68/// does to the target that the renderer draws into. A frame runs in the
69/// host, with one `Gpu` lent to all of it:
70///
71/// ```ignore
72/// let frame = renderer.update(gpu, &update)?;
73/// let image = target.begin_frame(gpu)?;
74/// let drawn = renderer.render(gpu, &image, frame);
75/// let handoff = target.end_frame(gpu);
76/// renderer.finish_frame(gpu, drawn, handoff);
77/// ```
78///
79/// [`tear_down`](Self::tear_down) frees the renderer's GPU objects. A
80/// renderer dropped without it leaves them to the `Gpu`, which frees them
81/// when it drops, and its custom layers' hosts hear that their graphics
82/// objects are lost.
83pub struct Renderer {
84    orchestrator: RenderOrchestrator,
85    encoder: Encoder,
86    /// Where the renderer reports its events, once the host gives it one.
87    events: Option<RendererEvents>,
88}
89
90/// A frame that [`Renderer::update`] brought the renderer's state to, for
91/// [`Renderer::render`] to draw.
92#[must_use = "an updated frame is drawn"]
93pub struct UpdatedFrame {
94    frame: Frame,
95    parameters: Arc<UpdateParameters>,
96    updated: Instant,
97}
98
99/// A frame that [`Renderer::render`] drew, for
100/// [`Renderer::finish_frame`] once the target handed it off.
101#[must_use = "a drawn frame is finished once its target handed it off"]
102pub struct DrawnFrame {
103    /// Why the frame failed on the GPU, if it did.
104    error: Option<Error>,
105    mode: RenderMode,
106    needs_repaint: bool,
107    /// When the frame's placement wants the next frame, if it does.
108    repaint_at: Option<Instant>,
109    placement_changed: bool,
110    /// The `still_image_request_id` of a still image's frame, or 0.
111    still_image_request_id: u64,
112    /// The `update_id` of the update the frame drew.
113    update_id: u64,
114    started: Instant,
115    symbols_started: Instant,
116    updated: Instant,
117    layers_uploaded: Instant,
118    start_rendering: Instant,
119}
120
121/// What the renderer keeps for its frames' encodes: its GPU state, the
122/// shaders, the passes' masks and composite, and what the last frame drew.
123struct Encoder {
124    /// What the renderer keeps over the backend's `Gpu`, which the
125    /// tear-down destroys after what the other fields hold.
126    context: Context,
127    pixel_ratio: f32,
128    /// Reset in the tear-down, after the orchestrator.
129    static_data: RenderStaticData,
130    /// Kept across frames; dropped in the tear-down.
131    clip_masks: ClipMasks,
132    /// What layers drawn as a whole draw into and composite with, between
133    /// frames.
134    layer_composite: LayerComposite,
135    /// Whether the context's shaders and pipelines are of an earlier pixel
136    /// ratio, which the next update's render layers no
137    /// longer draw with.
138    shaders_replaced: bool,
139    render_state: RenderState,
140    /// Where the last frame drew the map.
141    frame_projection: Option<FrameProjection>,
142    timings: RenderTimings,
143}
144
145impl DrawnFrame {
146    /// Why the frame failed on the GPU, if it did. Its image then lacks what
147    /// failed, or holds nothing.
148    #[must_use]
149    pub fn error(&self) -> Option<&Error> {
150        self.error.as_ref()
151    }
152}
153
154impl Renderer {
155    /// A renderer with a glyph cache of its own, which runs its background
156    /// work on `pool` and draws `local_glyphs`. Its chooser of the device's
157    /// fonts runs there too, one choice at a time, never on the thread that
158    /// calls the renderer.
159    ///
160    /// `waker` runs, on any thread, when something the renderer waits for
161    /// arrives, such as a tile's data or a font engine that got ready: the
162    /// host asks the renderer's map for an update for it, as by pushing
163    /// [`RendererEvent::Invalidate`] to the queue the renderer reports to
164    /// ([`set_event_queue`](Self::set_event_queue)). It must not call the
165    /// renderer.
166    ///
167    /// The renderer draws with `gpu` and only with it: every later call
168    /// that takes a `Gpu` takes this one.
169    pub fn new(gpu: &dyn Gpu, pixel_ratio: f32, local_glyphs: LocalGlyphs, waker: Waker, pool: &Pool) -> Self {
170        Self::with_glyph_cache(gpu, pixel_ratio, local_glyphs, Arc::default(), waker, pool)
171    }
172
173    /// A renderer that uses `glyph_cache`: renderers given the same
174    /// `GlyphCache` share the glyphs they parse from glyph PBFs.
175    pub fn with_glyph_cache(
176        gpu: &dyn Gpu,
177        pixel_ratio: f32,
178        local_glyphs: LocalGlyphs,
179        glyph_cache: Arc<GlyphCache>,
180        waker: Waker,
181        pool: &Pool,
182    ) -> Self {
183        let engine = crate::text::font_face_engine::default_engine();
184        let registry = Registry::with_builtins();
185        Self::with_fonts(gpu, pixel_ratio, local_glyphs, glyph_cache, engine, registry, waker, pool)
186    }
187
188    /// A renderer that uses `glyph_cache`, loads the font files of a style's
189    /// font faces with `font_face_engine` instead of
190    /// `font_face_engine::default_engine()`, and draws the layer types of
191    /// `registry` instead of the built-in ones.
192    ///
193    /// The map that the renderer draws must have a registry filled by the
194    /// same calls: a layer whose type `registry` lacks isn't drawn.
195    #[expect(clippy::too_many_arguments, reason = "each argument is a part of the renderer that its host picks")]
196    pub fn with_fonts(
197        gpu: &dyn Gpu,
198        pixel_ratio: f32,
199        local_glyphs: LocalGlyphs,
200        glyph_cache: Arc<GlyphCache>,
201        font_face_engine: Arc<dyn crate::text::font_face_engine::FontFaceEngine>,
202        registry: Arc<Registry>,
203        waker: Waker,
204        pool: &Pool,
205    ) -> Self {
206        Renderer {
207            orchestrator: RenderOrchestrator::new(
208                true,
209                local_glyphs,
210                glyph_cache,
211                font_face_engine,
212                registry,
213                waker,
214                pool,
215            ),
216            encoder: Encoder {
217                context: Context::new(*gpu.caps(), pixel_ratio),
218                pixel_ratio,
219                static_data: RenderStaticData::default(),
220                clip_masks: ClipMasks::default(),
221                layer_composite: LayerComposite::default(),
222                shaders_replaced: false,
223                render_state: RenderState::Never,
224                frame_projection: None,
225                timings: RenderTimings::default(),
226            },
227            events: None,
228        }
229    }
230
231    /// Draws at `pixel_ratio` device pixels per logical pixel from the next
232    /// frame on, which should be the map's (`Map::set_pixel_ratio`). The
233    /// renderer makes its shaders and draws again, frees the ones they
234    /// replace, and keeps its tiles. The host sizes the backend's
235    /// framebuffer for the new ratio.
236    pub fn set_pixel_ratio(&mut self, pixel_ratio: f32) {
237        if pixel_ratio == self.encoder.pixel_ratio {
238            return;
239        }
240        // The shaders build the pixel ratio in on some backends, so a new
241        // ratio takes new shaders, and new draws that use them.
242        self.replace_shaders(pixel_ratio);
243    }
244
245    /// Compiles the shaders at `pixel_ratio` from the next update on. The render layers' draws go with
246    /// that update, which makes the layers again, and the old shaders after
247    /// it.
248    fn replace_shaders(&mut self, pixel_ratio: f32) {
249        let encoder = &mut self.encoder;
250        encoder.pixel_ratio = pixel_ratio;
251        encoder.context.set_program_parameters(pixel_ratio);
252        encoder.clip_masks = ClipMasks::default();
253        encoder.layer_composite = LayerComposite::default();
254        encoder.shaders_replaced = true;
255        self.orchestrator.release_shaders();
256    }
257
258    /// The device pixels per logical pixel the renderer draws at.
259    #[must_use]
260    pub fn pixel_ratio(&self) -> f32 {
261        self.encoder.pixel_ratio
262    }
263
264    /// Runs the tiles' jobs, and the raster tiles' workers, in
265    /// `workers` (by default on the renderer's pool). Set it before the
266    /// first render so that every tile uses it.
267    pub fn set_tile_workers(&mut self, workers: RemoteWorkers) {
268        self.orchestrator.set_tile_workers(workers);
269    }
270
271    /// Takes in what arrived for the tiles since the last frame (their data,
272    /// their jobs' replies, glyphs) and starts the jobs it makes ready. Each
273    /// frame does this first; a host that draws frames on a clock calls it
274    /// as soon as the renderer asks for an update, so that the tiles' work
275    /// doesn't wait for the next frame to start.
276    pub fn receive_tiles(&mut self) {
277        self.orchestrator.receive_tiles();
278        report(&mut self.orchestrator, self.events.as_ref());
279    }
280
281    /// Sets the queue the renderer pushes its events to: the map's, which
282    /// the map's frontend passes on.
283    pub fn set_event_queue(&mut self, events: Option<RendererEvents>) {
284        self.events = events;
285    }
286
287    /// Brings the renderer's state to `update_parameters`: its style,
288    /// sources, tiles, layers and placement. Returns the frame to draw,
289    /// which the host [renders](Self::render) into a frame of its target,
290    /// or `None` when there is nothing to draw: a still image that hasn't
291    /// loaded yet. Custom layers that the update removed or gave a new host
292    /// end on `gpu`.
293    pub fn update(&mut self, gpu: &mut dyn Gpu, update_parameters: &Arc<UpdateParameters>) -> Option<UpdatedFrame> {
294        let orchestrator = &mut self.orchestrator;
295        // Whether terrain draws depends on whether the backend has its shader.
296        orchestrator.terrain().make_shader(gpu, &mut self.encoder.context, update_parameters);
297        let frame = orchestrator.update(update_parameters);
298        report(orchestrator, self.events.as_ref());
299        let encoder = &mut self.encoder;
300        end_hosts(gpu, orchestrator.take_ended_hosts());
301        if std::mem::take(&mut encoder.shaders_replaced) {
302            encoder.context.release_shaders();
303        }
304        let frame = frame?;
305        Some(UpdatedFrame { frame, parameters: Arc::clone(update_parameters), updated: Instant::now() })
306    }
307
308    /// Draws `frame`, which the last [`update`](Self::update) returned, into
309    /// `image`, textures of `gpu` that the host's target began a frame with,
310    /// and submits the frame's passes. Returns the frame, which the host
311    /// ends on its target, whether or not it failed ([`DrawnFrame::error`]),
312    /// and then [finishes](Self::finish_frame).
313    pub fn render(&mut self, gpu: &mut dyn Gpu, image: &FrameImage, frame: UpdatedFrame) -> DrawnFrame {
314        self.encoder.encode(gpu, &mut self.orchestrator, self.events.as_ref(), image, frame)
315    }
316
317    /// Ends `frame`, which [`render`](Self::render) drew, once the host's
318    /// target handed it off as `handoff`: destroys what the frame replaced
319    /// and reports the frame with its rendering stats, and with its error
320    /// if it failed.
321    pub fn finish_frame(&mut self, gpu: &mut dyn Gpu, frame: DrawnFrame, handoff: Handoff) {
322        self.encoder.finish(gpu, self.events.as_ref(), frame, handoff);
323    }
324
325    /// The terrain of the frames it draws.
326    #[cfg(test)]
327    pub(crate) fn terrain(&mut self) -> &crate::render::terrain::RenderTerrain {
328        self.orchestrator.terrain()
329    }
330
331    /// Drops `value` on the renderer's workers instead of this
332    /// thread, for data that would take a frame long to free, such as the
333    /// sources of an earlier update. The renderer's drop waits for it.
334    pub fn drop_on_workers<T: Send + 'static>(&self, value: T) {
335        self.orchestrator.drop_on_workers(value);
336    }
337
338    /// What the last frame that [`render`](Self::render) drew
339    /// spent on each of its steps.
340    #[must_use]
341    pub fn render_timings(&self) -> RenderTimings {
342        self.encoder.timings
343    }
344
345    /// Where the last frame that [`render`](Self::render) drew put the map,
346    /// or `None` before the first.
347    #[must_use]
348    pub fn frame_projection(&self) -> Option<FrameProjection> {
349        self.encoder.frame_projection
350    }
351
352    /// The features drawn in `geometry`, a point or a polygon in screen
353    /// coordinates. `Err` for a malformed tile.
354    pub fn query_rendered_features(
355        &mut self,
356        geometry: &[crate::geo::ScreenCoordinate],
357        options: &crate::query::RenderedQueryOptions,
358    ) -> Result<Vec<crate::tile::feature::Feature>, Error> {
359        let features = self.orchestrator.query_rendered_features(geometry, options);
360        report(&mut self.orchestrator, self.events.as_ref());
361        features
362    }
363
364    pub fn query_rendered_features_at_point(
365        &mut self,
366        point: &crate::geo::ScreenCoordinate,
367        options: &crate::query::RenderedQueryOptions,
368    ) -> Result<Vec<crate::tile::feature::Feature>, Error> {
369        self.query_rendered_features(&[*point], options)
370    }
371
372    pub fn query_rendered_features_in_box(
373        &mut self,
374        min: &crate::geo::ScreenCoordinate,
375        max: &crate::geo::ScreenCoordinate,
376        options: &crate::query::RenderedQueryOptions,
377    ) -> Result<Vec<crate::tile::feature::Feature>, Error> {
378        use crate::geo::ScreenCoordinate;
379        self.query_rendered_features(
380            &[*min, ScreenCoordinate::new(max.x, min.y), *max, ScreenCoordinate::new(min.x, max.y), *min],
381            options,
382        )
383    }
384
385    pub fn query_source_features(
386        &mut self,
387        source_id: &str,
388        options: &crate::query::SourceQueryOptions,
389    ) -> Result<Vec<crate::tile::feature::Feature>, Error> {
390        let features = self.orchestrator.query_source_features(source_id, options);
391        report(&mut self.orchestrator, self.events.as_ref());
392        features
393    }
394
395    /// Queries a feature extension: for a GeoJSON source with `cluster` on,
396    /// the "supercluster" extension's "children", "leaves" or
397    /// "expansion-zoom" of a cluster feature (one with a `cluster_id`
398    /// property). Anything else is a null value. `Err` for a cluster ID the
399    /// source doesn't have.
400    pub fn query_feature_extensions(
401        &self,
402        source_id: &str,
403        feature: &crate::tile::feature::Feature,
404        extension: &str,
405        extension_field: &str,
406        args: Option<&feature::PropertyMap>,
407    ) -> Result<crate::query::FeatureExtensionValue, Error> {
408        self.orchestrator.query_feature_extensions(source_id, feature, extension, extension_field, args)
409    }
410
411    /// The data of the symbols the last placement placed, when
412    /// [`collect_placed_symbol_data`](Self::collect_placed_symbol_data)
413    /// turned their collection on.
414    #[must_use]
415    pub fn placed_symbols_data(&self) -> Vec<crate::placement::PlacedSymbolData> {
416        self.orchestrator.placed_symbols_data()
417    }
418
419    /// Logs every render source's tiles and the image manager's state.
420    pub fn dump_debug_logs(&self) {
421        self.orchestrator.dump_debug_logs();
422    }
423
424    /// Merges `state` into a feature's state.
425    ///
426    /// An update whose feature state for the source differs from the last
427    /// update's replaces the source's state with the update's, undoing what
428    /// this and [`remove_feature_state`](Self::remove_feature_state) did. A
429    /// renderer that a map drives takes its state from the map's
430    /// `set_feature_state`.
431    pub fn set_feature_state(
432        &mut self,
433        source_id: &str,
434        source_layer_id: Option<&str>,
435        feature_id: &str,
436        state: &mln_style::feature::FeatureState,
437    ) {
438        self.orchestrator.set_feature_state(source_id, source_layer_id, feature_id, state);
439    }
440
441    /// The state of a feature.
442    #[must_use]
443    pub fn feature_state(
444        &self,
445        source_id: &str,
446        source_layer_id: Option<&str>,
447        feature_id: &str,
448    ) -> mln_style::feature::FeatureState {
449        self.orchestrator.feature_state(source_id, source_layer_id, feature_id)
450    }
451
452    /// Removes a key of a feature's state, a feature's whole state, or a
453    /// source layer's. An update replaces the source's state as it does for
454    /// [`set_feature_state`](Self::set_feature_state).
455    pub fn remove_feature_state(
456        &mut self,
457        source_id: &str,
458        source_layer_id: Option<&str>,
459        feature_id: Option<&str>,
460        state_key: Option<&str>,
461    ) {
462        self.orchestrator.remove_feature_state(source_id, source_layer_id, feature_id, state_key);
463    }
464
465    pub fn collect_placed_symbol_data(&mut self, enable: bool) {
466        self.orchestrator.collect_placed_symbol_data(enable);
467    }
468
469    pub fn set_tile_cache_enabled(&mut self, enable: bool) {
470        self.orchestrator.set_tile_cache_enabled(enable);
471    }
472
473    /// Whether the renderer keeps tiles that left the view, to show them
474    /// again without loading them.
475    #[must_use]
476    pub fn tile_cache_enabled(&self) -> bool {
477        self.orchestrator.tile_cache_enabled()
478    }
479
480    /// Tells the hosts of the custom layers that the renderer's graphics
481    /// objects are lost, so that they forget theirs, and lets go of them.
482    /// Call it before the renderer goes when its device or target went first.
483    pub fn lose_custom_layers(&mut self) {
484        self.orchestrator.visit_render_layers(|layer| layer.lose_context());
485    }
486
487    /// Lets go of what the orchestrator caches, destroys what it and the
488    /// renderer released, and waits for `gpu`, so that its work finishes
489    /// before the app goes to the background.
490    pub fn reduce_memory_use(&mut self, gpu: &mut dyn Gpu) {
491        self.orchestrator.reduce_memory_use();
492        self.encoder.context.destroy_released(gpu);
493        if let Err(error) = gpu.flush(true) {
494            log::error!(target: log_target::RENDER, "Waiting for the GPU failed: {error}");
495        }
496        report(&mut self.orchestrator, self.events.as_ref());
497    }
498
499    /// The rendering stats, which count the renderer's resources until it
500    /// destroys them: a buffer or texture counts until the end of the frame
501    /// that follows its release, or until
502    /// [`reduce_memory_use`](Self::reduce_memory_use).
503    #[must_use]
504    pub fn rendering_stats(&self) -> RenderingStats {
505        self.encoder.context.stats()
506    }
507
508    /// Lets go of the map's data: its sources, tiles and layers, which the
509    /// next update loads again. The custom layers that go hear through
510    /// `gpu` that the renderer stopped.
511    pub fn clear_data(&mut self, gpu: &mut dyn Gpu) {
512        self.orchestrator.clear_data();
513        end_hosts(gpu, self.orchestrator.take_ended_hosts());
514        report(&mut self.orchestrator, self.events.as_ref());
515    }
516
517    /// Destroys the renderer's GPU objects on `gpu`, and tells its custom
518    /// layers' hosts that it stopped. Returns its rendering stats as it
519    /// leaves them, with all its resources released.
520    pub fn tear_down(self, gpu: &mut dyn Gpu) -> RenderingStats {
521        let Renderer { mut orchestrator, mut encoder, .. } = self;
522        // The layers' GPU objects go to the context's queue, and their
523        // custom layers' hosts to the ended ones.
524        orchestrator.leave_layers();
525        let ended = orchestrator.take_ended_hosts();
526        drop(orchestrator);
527        encoder.clip_masks = ClipMasks::default();
528        encoder.layer_composite = LayerComposite::default();
529        encoder.static_data = RenderStaticData::default();
530        encoder.context.tear_down(gpu);
531        end_hosts(gpu, ended);
532        encoder.context.stats()
533    }
534}
535
536impl Encoder {
537    /// The second phase of a frame: builds and refreshes the GPU objects of
538    /// the layers' draws of `frame` on `gpu`, draws them into `image` and
539    /// submits them. It reads the style, the sources, the tiles each layer
540    /// draws and the placement as the update left them, and changes only
541    /// what draws them on the GPU: the atlases' textures, the tiles'
542    /// buckets, which it uploads and binds to the atlases' textures, the
543    /// layers' drawing and the renderer's GPU state.
544    ///
545    /// It uploads the atlases and the tiles' buckets; then the draw update
546    /// makes the layers' draws of the frame, the draw upload uploads what
547    /// they bind, and the draw section encodes the passes and submits them.
548    fn encode(
549        &mut self,
550        gpu: &mut dyn Gpu,
551        orchestrator: &mut RenderOrchestrator,
552        events: Option<&RendererEvents>,
553        image: &FrameImage,
554        frame: UpdatedFrame,
555    ) -> DrawnFrame {
556        let UpdatedFrame { frame, parameters: update_parameters, updated } = frame;
557        let start = Instant::now();
558        {
559            let stats = self.context.rendering_stats();
560            stats.num_draw_calls = 0;
561            stats.terrain = TerrainStats::default();
562            stats.num_frames += 1;
563        }
564        let static_data = &self.static_data;
565
566        if self.render_state == RenderState::Never {
567            emit(events, RendererEvent::RenderMapStarted);
568        }
569        emit(events, RendererEvent::RenderFrameStarted);
570
571        let state = &frame.transform.view;
572        let renderable_size = image.size;
573        let frustum_offset = state.frustum_offset();
574        let pixel_ratio = f64::from(self.pixel_ratio);
575        let scissor_rect = ScissorRect {
576            x: (frustum_offset.left * pixel_ratio) as i32,
577            y: (frustum_offset.top * pixel_ratio) as i32,
578            width: renderable_size
579                .width
580                .wrapping_sub(((frustum_offset.left + frustum_offset.right) * pixel_ratio) as u32),
581            height: renderable_size
582                .height
583                .wrapping_sub(((frustum_offset.top + frustum_offset.bottom) * pixel_ratio) as u32),
584        };
585
586        let composites_with_frame_depth =
587            image.depth_stencil.is_some_and(|texture| gpu.attaches_with_any_color(texture));
588        let mut parameters = PaintParameters::new(
589            &mut self.context,
590            &mut self.clip_masks,
591            &mut self.layer_composite,
592            composites_with_frame_depth,
593            &frame,
594            static_data,
595            self.pixel_ratio,
596            renderable_size,
597            scissor_rect,
598        );
599
600        // - UPLOAD --------------------------------------------------------
601        // The atlases first, whose textures the tiles bind, then the tiles'
602        // buckets.
603        orchestrator.upload_atlases(gpu, parameters.context);
604        orchestrator.upload_sources(parameters.context);
605
606        // - DRAW UPDATE ---------------------------------------------------
607        // The layers' draws of the frame.
608        let uploaded = Instant::now();
609        orchestrator.update_layer_draws(gpu, &update_parameters, &mut parameters, &frame);
610        let layers_updated = Instant::now();
611
612        // What the frame's update and draw update replaced goes before the
613        // uploads make what replaces it.
614        parameters.context.destroy_released(gpu);
615
616        // - DRAW UPLOAD ---------------------------------------------------
617        orchestrator.upload_draws(gpu, parameters.context);
618        let draw_groups = DrawGroups::of(
619            |visit| orchestrator.visit_draw_groups(visit),
620            |tiles| parameters.stencil_clear_tiles(tiles),
621        );
622        parameters.stencil_clear.clone_from(&draw_groups.stencil_clear);
623        parameters.opaque_pass_cutoff = orchestrator.opaque_pass_cutoff();
624        let (proj_state, transform) = (parameters.view, parameters.transform_params);
625        parameters.clip_masks.update(gpu, parameters.context, proj_state.is_globe(), &draw_groups.clip_tiles, |tile| {
626            to_projection_ubo(&transform.projection_data_for_tile(tile, false))
627        });
628        orchestrator.terrain().upload_drapes(gpu, &mut parameters);
629        parameters.layer_composite.update(
630            gpu,
631            parameters.context,
632            image.size,
633            image.targets.color,
634            &draw_groups.composited,
635        );
636        let global_paint_params_ubo = parameters.global_paint_params(orchestrator.atlases().pattern.pixel_size());
637        parameters.context.write_global_uniform_buffer(gpu, PAINT_PARAMS_ID, &global_paint_params_ubo);
638        // What the uploads replaced goes before the passes make what
639        // replaces it, such as a draw's geometry.
640        parameters.context.destroy_released(gpu);
641        let layers_uploaded = Instant::now();
642
643        // - DRAW ----------------------------------------------------------
644        // The 3D layers draw into depth from 0 to the passes' depth range
645        // size, which the draw groups' count sets, and custom layers record
646        // their work with the projection that the frame's result reports.
647        let depth_range_size = draw_groups.depth_range_size();
648        let clip_depth = parameters.context.caps().clip_depth;
649        let frame_projection = frame_projection::compute(&frame.transform, depth_range_size, clip_depth, frame.terrain);
650        parameters.custom_layer_frame = Some(CustomLayerFrame {
651            view: state.map_view(pixel_ratio),
652            projection: frame_projection,
653            width: renderable_size.width,
654            height: renderable_size.height,
655        });
656        draw(orchestrator, gpu, &mut parameters, &frame, image, draw_groups.count, depth_range_size);
657        orchestrator.terrain().count(parameters.context);
658        let start_rendering = Instant::now();
659        let submitted = parameters.end_pass(gpu).and_then(|()| gpu.flush(false));
660        if let Err(error) = &submitted {
661            parameters.context.fail(format!("Submitting the frame failed: {error}"));
662        }
663        let error = parameters.context.device().take_failure().map(Error::native);
664        drop(parameters);
665        // A drape of a frame that failed may lack what failed: every drape
666        // draws again in the next frame.
667        if error.is_some() {
668            orchestrator.terrain().redraw_drapes();
669        }
670        if submitted.is_err() {
671            orchestrator.visit_render_layers(|layer| layer.prepare_again());
672        }
673
674        self.timings.layers = layers_updated - uploaded;
675        self.timings.upload = (uploaded - start) + (layers_uploaded - layers_updated);
676        self.frame_projection = Some(frame_projection);
677        DrawnFrame {
678            mode: if frame.loaded { RenderMode::Full } else { RenderMode::Partial },
679            error,
680            needs_repaint: frame.needs_repaint,
681            repaint_at: frame.repaint_at,
682            placement_changed: frame.placement_changed,
683            still_image_request_id: if update_parameters.still_image_request {
684                update_parameters.still_image_request_id
685            } else {
686                0
687            },
688            update_id: update_parameters.update_id,
689            started: frame.started,
690            symbols_started: frame.symbols_started,
691            updated,
692            layers_uploaded,
693            start_rendering,
694        }
695    }
696
697    /// The end of a frame that [`encode`](Self::encode) drew, once its
698    /// target handed it off as `handoff`: destroys what the uploads and the
699    /// passes replaced, and reports the frame with the rendering stats.
700    fn finish(&mut self, gpu: &mut dyn Gpu, events: Option<&RendererEvents>, frame: DrawnFrame, handoff: Handoff) {
701        let DrawnFrame {
702            error,
703            mode,
704            needs_repaint,
705            repaint_at,
706            placement_changed,
707            still_image_request_id,
708            update_id,
709            started,
710            symbols_started,
711            updated,
712            layers_uploaded,
713            start_rendering,
714        } = frame;
715        let submitted = Instant::now();
716        let context = &mut self.context;
717        {
718            let stats = context.rendering_stats();
719            // The frame read back counts as a framebuffer, as an offscreen
720            // texture does.
721            stats.num_frame_buffers = i32::from(handoff == Handoff::ReadBack);
722            stats.rendering_time = (submitted - start_rendering).as_secs_f64();
723        }
724        // What the uploads and the passes replaced.
725        context.destroy_released(gpu);
726        {
727            let stats = context.rendering_stats();
728            stats.encoding_time = started.elapsed().as_secs_f64() - stats.rendering_time;
729        }
730        let stats = Arc::new(context.stats());
731
732        self.timings.sources = symbols_started - started;
733        self.timings.symbols = updated - symbols_started;
734        self.timings.draw = submitted - layers_uploaded;
735
736        emit(
737            events,
738            RendererEvent::RenderFrameFinished {
739                mode,
740                needs_repaint,
741                repaint_at,
742                placement_changed,
743                still_image_request_id,
744                update_id,
745                stats,
746                error: error.map(Box::new),
747            },
748        );
749
750        if mode == RenderMode::Partial {
751            self.render_state = RenderState::Partial;
752        } else if self.render_state != RenderState::Fully {
753            self.render_state = RenderState::Fully;
754            emit(events, RendererEvent::RenderMapFinished);
755        }
756    }
757}
758
759/// The draw section of a frame's encode: encodes the passes of `frame` into
760/// `image` through `gpu`, which holds the frame's work until it is
761/// submitted, each pass drawing the `num_draw_groups` draw groups at depths
762/// below `depth_range_size`.
763fn draw(
764    orchestrator: &mut RenderOrchestrator,
765    gpu: &mut dyn Gpu,
766    parameters: &mut PaintParameters<'_>,
767    frame: &Frame,
768    image: &FrameImage,
769    num_draw_groups: usize,
770    depth_range_size: f32,
771) {
772    // Custom layers record their own work before the first pass.
773    for &index in frame.layers.keys() {
774        orchestrator.layer_mut(index as usize).prerender(gpu, parameters);
775    }
776
777    // The ground's depth, which the layers that stand on terrain hide
778    // behind, in a pass of its own.
779    parameters.pass = RenderPass::Translucent;
780    parameters.depth_range_size = depth_range_size;
781    orchestrator.terrain().render_ground(gpu, parameters);
782
783    // The 3D pass: the 3D layers draw bottom to top. No pass is open, so
784    // the draw groups draw nothing but into their own targets.
785    if frame.has_3d {
786        parameters.pass = RenderPass::Pass3D;
787        parameters.depth_range_size = depth_range_size;
788        parameters.current_layer = (num_draw_groups as u32).wrapping_sub(1);
789        orchestrator.render_draw_groups(gpu, parameters, DrawOrder::BottomUp);
790    }
791
792    // The layers' render targets, which the passes sample, and the
793    // terrain's drapes.
794    orchestrator.visit_render_layers(|layer| layer.render_targets(gpu, parameters));
795    orchestrator.terrain().render_drapes(gpu, parameters);
796
797    // The frame's pass, cleared to the backdrop, which shows where there are
798    // no tiles.
799    let Color { r, g, b, a, .. } = frame.background_color;
800    let color = Rgba::new(r, g, b, a);
801    let pass = OpenPass {
802        label: "main buffer",
803        color: Some(ColorAttachment {
804            texture: parameters.layer_composite.frame_texture().unwrap_or(image.color),
805            load: LoadOp::Clear(color),
806        }),
807        depth_stencil: image.depth_stencil.map(|texture| DepthStencilAttachment {
808            texture,
809            depth: LoadOp::Clear(1.0),
810            stencil: LoadOp::Clear(0),
811        }),
812        size: image.size,
813        targets: image.targets,
814    };
815    if let Err(error) = parameters.begin_pass(gpu, pass) {
816        parameters.context.fail(format!("Beginning the frame's pass failed: {error}"));
817    }
818
819    // The sky.
820    if let Some(sky) = orchestrator.sky() {
821        parameters.pass = RenderPass::Translucent;
822        parameters.depth_range_size = depth_range_size;
823        parameters.current_layer = num_draw_groups as u32 + 1;
824        sky.render(gpu, parameters);
825    }
826
827    // The opaque pass: front to back with the depth buffer, except on the
828    // globe, where 2D layers carry no depth and are painted bottom to top.
829    parameters.pass = RenderPass::Opaque;
830    parameters.depth_range_size = depth_range_size;
831    if frame.transform.view.is_globe() {
832        parameters.current_layer = (num_draw_groups as u32).wrapping_sub(1);
833        orchestrator.render_draw_groups(gpu, parameters, DrawOrder::BottomUp);
834    } else {
835        parameters.current_layer = 0;
836        orchestrator.render_draw_groups(gpu, parameters, DrawOrder::TopDown);
837    }
838
839    // The translucent pass. The planet goes into the depth buffer first, so
840    // 3D geometry behind the horizon stays hidden. Over terrain, each stack
841    // of draped layers draws its surface where its first layer draws, and
842    // the surface's depth goes first where a 3D layer draws before that.
843    parameters.pass = RenderPass::Translucent;
844    parameters.depth_range_size = depth_range_size;
845    orchestrator.globe_depth().render(gpu, parameters);
846    orchestrator.terrain().render_depth(gpu, parameters);
847    parameters.current_layer = (num_draw_groups as u32).wrapping_sub(1);
848    orchestrator.render_draw_groups(gpu, parameters, DrawOrder::BottomUp);
849
850    // The atmosphere.
851    if let Some(atmosphere) = orchestrator.atmosphere() {
852        parameters.pass = RenderPass::Translucent;
853        parameters.depth_range_size = depth_range_size;
854        parameters.current_layer = num_draw_groups as u32 + 1;
855        atmosphere.render(gpu, parameters);
856    }
857
858    // The frame, where it drew into the layer composite's texture, copied
859    // into the target.
860    let present = OpenPass {
861        label: "main buffer",
862        color: Some(ColorAttachment { texture: image.color, load: LoadOp::Clear(Rgba::new(0.0, 0.0, 0.0, 0.0)) }),
863        depth_stencil: None,
864        size: image.size,
865        targets: TargetFormats { color: image.targets.color, depth_stencil: None },
866    };
867    if let Err(error) = parameters.present_frame(gpu, present) {
868        parameters.context.fail(format!("Copying the frame into its target failed: {error}"));
869    }
870}
871
872/// Pushes what `orchestrator` reported since the last call to `events`, the
873/// renderer's event queue, or drops it when there is no queue.
874fn report(orchestrator: &mut RenderOrchestrator, events: Option<&RendererEvents>) {
875    for event in orchestrator.take_events() {
876        emit(events, event);
877    }
878}
879
880/// Pushes `event` to `events`, the renderer's event queue, if it has one.
881fn emit(events: Option<&RendererEvents>, event: RendererEvent) {
882    if let Some(events) = events {
883        events.push(event);
884    }
885}