mln-rs-engine 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
// The orchestrator owns the render sources and the tile store their tiles
// are in, and turns what the store reports into the renderer's events.

mod draws;
mod query;
mod style;

use std::sync::Arc;
use std::time::Duration;

use mln_style::collections::VecSet;
use mln_style::diff::{StyleDiff, sources_by_id};
use mln_style::expression::GlobalStateMap;
use mln_style::hash::HashMap;
use mln_style::layer::SourceKind;
use mln_style::property::evaluation::ZoomHistory;
use mln_style::time::Instant;
use mln_style::{Source, Style};

use crate::camera::View;
use crate::draw::draws::SingleDraw;
use crate::exec::pool::{Pool, TaskGroup};
use crate::image::image_store::ImageStore;
use crate::layer::layer_drawing::ChangedBuckets;
use crate::layer::layer_type::ErasedEvaluatedLayer;
use crate::layer::render_layer::{FrameSourceTiles, RenderLayer};
use crate::placement::Placements;
use crate::render::events::RendererEvent;
use crate::render::frame::Frame;
use crate::render::globe::depth_pass::GlobeDepthPass;
use crate::render::shared_targets::{Routing, SharedTargets};
use crate::render::terrain::{DrapeStacks, RenderTerrain};
use crate::render::tile::{FoundTile, TileContent};
use crate::render::update_parameters::UpdateParameters;
use crate::source::render_source::RenderSource;
use crate::text::GlyphCache;
use crate::text::glyph_store::GlyphStore;
use crate::text::local_fonts::LocalGlyphs;
use crate::tile_store::inbox::Waker;
use crate::tile_store::source_tiles::SourceTiles;
use crate::tile_store::store::{StoreEvent, TileStore};
use crate::worker::tile_workers::PoolWorkers;
use crate::worker::worker_codec::RemoteWorkers;
use crate::{Registry, log_target};

/// The jobs in flight per thread of the pool.
const JOBS_PER_THREAD: usize = 2;

/// The jobs in flight on a pool without threads, whose host runs them
/// between its own work.
const JOBS_WITHOUT_THREADS: usize = 8;

pub(crate) struct RenderOrchestrator {
    registry: Arc<Registry>,
    /// What the orchestrator and its stores reported since the renderer
    /// last took them, oldest first.
    events: Vec<RendererEvent>,

    zoom_history: ZoomHistory,
    /// How long the last update cross-fades for.
    cross_fade_duration: Duration,
    /// The still image request the last update was for.
    still_image_request_id: u64,
    view: View,

    /// The sources' tiles, with the glyph and image stores their layouts
    /// resolve through and the atlas they pack them into.
    tile_store: TileStore,
    /// The tiles the frame's layers draw, as their updates found them, each
    /// layer's in a range of its own.
    found_tiles: Vec<FoundTile>,

    /// The version of the style the last update drew, or `None` before
    /// the first and after `clear_data`: no layers, sources or images.
    style: Option<Arc<Style>>,
    /// The style's sources in id order, the order of the per-source pass.
    sources_by_id: Vec<Source>,

    render_sources: HashMap<String, Box<dyn RenderSource>>,
    /// The render layers, in the style's order: a layer's index is its
    /// place in the drawing order. A layer whose type has no render layer
    /// has none.
    layers: Vec<Box<dyn RenderLayer>>,
    /// The index in `layers` of each render layer, by layer id.
    layer_indexes: HashMap<String, usize>,
    render_light: crate::render::light::RenderLight,
    render_sky: Option<crate::render::sky::RenderSky>,

    /// The placements of the layers that place, such as symbols.
    placements: Placements,
    background_layer_as_color: bool,
    /// The center's longitude at the last update, which tells a wrap jump.
    longitude: f32,
    tile_cache_enabled: bool,

    /// Whether the next update makes the render layers again, for new
    /// shaders.
    remake_render_layers: bool,
    filtered_layers_for_source: Vec<Arc<dyn ErasedEvaluatedLayer>>,

    thread_pool: TaskGroup,

    global_state: Option<Arc<GlobalStateMap>>,

    globe_depth_pass: GlobeDepthPass,
    sky_pass: crate::render::sky_pass::SkyPass,
    terrain: RenderTerrain,
    /// The frame's stacks of draped layers, whose surfaces the translucent
    /// pass draws among the layers; none without terrain.
    stacks: DrapeStacks,
    /// The registry's routes of the version of the style the last update
    /// drew.
    routing: Routing,
    /// The shared targets, and the frame's routes and reads of them.
    shared: SharedTargets,

    /// Last, so that it drops after the fields above: the render sources'
    /// tiles free their data on the thread pool (`drop_on_workers`).
    _wait_for_thread_pool: WaitOnDrop,
}

impl RenderOrchestrator {
    /// An orchestrator whose background work runs in a group of its own on
    /// `pool`, which its drop waits for, and whose tiles and glyphs call
    /// `waker` for an update (see `Renderer::with_glyph_cache`).
    pub(crate) fn new(
        background_layer_as_color: bool,
        local_glyphs: LocalGlyphs,
        glyph_cache: Arc<GlyphCache>,
        font_face_engine: Arc<dyn crate::text::font_face_engine::FontFaceEngine>,
        registry: Arc<Registry>,
        waker: Waker,
        pool: &Pool,
    ) -> Self {
        let thread_pool = TaskGroup::new(pool);
        let glyph_store =
            GlyphStore::new(local_glyphs, glyph_cache, thread_pool.clone(), font_face_engine, Arc::clone(&waker));
        let jobs = match pool.threads() {
            0 => JOBS_WITHOUT_THREADS,
            threads => JOBS_PER_THREAD * threads,
        };
        let pool_workers = PoolWorkers::new(thread_pool.clone(), jobs);
        let tile_store =
            TileStore::new(Box::new(pool_workers), glyph_store, ImageStore::default(), thread_pool.clone(), waker);
        let placements = Placements::new(&registry);
        RenderOrchestrator {
            registry,
            events: Vec::new(),
            zoom_history: ZoomHistory::default(),
            cross_fade_duration: Duration::ZERO,
            still_image_request_id: 0,
            view: View::default(),
            tile_store,
            placements,
            found_tiles: Vec::new(),
            style: None,
            sources_by_id: Vec::new(),
            render_sources: HashMap::default(),
            layers: Vec::new(),
            layer_indexes: HashMap::default(),
            render_light: crate::render::light::RenderLight::new(Arc::default()),
            render_sky: None,
            background_layer_as_color,
            longitude: 0.0,
            tile_cache_enabled: true,
            remake_render_layers: false,
            filtered_layers_for_source: Vec::new(),
            _wait_for_thread_pool: WaitOnDrop(thread_pool.clone()),
            thread_pool,
            global_state: None,
            globe_depth_pass: GlobeDepthPass::default(),
            sky_pass: crate::render::sky_pass::SkyPass::default(),
            terrain: RenderTerrain::default(),
            stacks: DrapeStacks::default(),
            routing: Routing::default(),
            shared: SharedTargets::default(),
        }
    }

    /// Runs the tiles' jobs in `workers` (by default on the thread
    /// pool). The jobs in flight elsewhere run again there.
    pub(crate) fn set_tile_workers(&mut self, workers: RemoteWorkers) {
        self.tile_store.set_workers(Box::new(workers));
    }

    /// What the orchestrator and its stores reported since the last call,
    /// oldest first.
    pub(crate) fn take_events(&mut self) -> Vec<RendererEvent> {
        std::mem::take(&mut self.events)
    }

    /// The first phase of a frame: brings the orchestrator to
    /// `update_parameters` and returns the frame for the encode, or `None`
    /// for a still image that hasn't loaded yet, which isn't drawn.
    ///
    /// It applies what changed in the style since the version the last
    /// update drew, evaluates the layers, updates the sources' tiles and
    /// their feature state, chooses the layers the frame draws and gives
    /// them their tiles, places the symbols and brings the symbol buckets
    /// to the placement. The encode then changes none of this: it changes
    /// only what draws it on the GPU, uploading the tiles' atlas and
    /// buckets and making the layers' draws.
    pub(crate) fn update(&mut self, update_parameters: &Arc<UpdateParameters>) -> Option<Frame> {
        let mut frame =
            Frame::new(&update_parameters.view, update_parameters.camera_moving, update_parameters.time_point);
        let mut clock = self.advance_clock(update_parameters);
        let style = &update_parameters.style;

        self.tile_store.glyphs().set_url(style.glyph_url());
        self.tile_store.glyphs().set_font_faces(update_parameters.font_faces.clone());
        self.tile_store.set_file_source(update_parameters.file_source.clone());

        // What arrived for the tiles before the sources update, so that a
        // tile laid out since the last update renders in this one.
        self.receive_tiles();

        self.update_light_and_sky(style, &clock);
        frame.light = self.render_light.evaluated().clone();
        frame.sky = self.render_sky.as_ref().map(|render_sky| render_sky.evaluated().clone());

        // The previous sources may hold the last references to replaced
        // data, such as a GeoJSON source's index, which can take
        // milliseconds to free. The workers drop them once this update has
        // moved the render sources and their tiles to the new ones. Declared
        // before the diff, which holds previous sources too, so that it
        // drops after the diff. The previous version itself drops here, on
        // the render thread, with its layers and images.
        let previous_sources = self.style.as_ref().map(|previous| previous.sources());
        let sources_changed = previous_sources.is_none_or(|previous| !Arc::ptr_eq(previous, style.sources()));
        let _previous_sources = previous_sources
            .filter(|_| sources_changed)
            .map(|previous| DropOnWorkers::new(Arc::clone(previous), self.thread_pool.clone()));
        let StyleDiff { layers: layer_changes, sources: source_diff, images: image_diff } =
            StyleDiff::between(self.style.as_deref(), style);
        if sources_changed {
            self.sources_by_id = sources_by_id(style.sources());
        }
        let style_changed = self.style.as_ref().is_none_or(|previous| !Arc::ptr_eq(previous, style));
        self.style = Some(Arc::clone(style));
        let layers = Arc::clone(style.layer_list());

        self.apply_image_diff(&image_diff, update_parameters.sprite_loaded);
        // The drapes' keys don't tell what the style's images draw.
        if !(image_diff.added.is_empty() && image_diff.removed.is_empty() && image_diff.changed.is_empty()) {
            self.terrain.redraw_drapes();
        }

        let render_layers_remade = self.apply_layer_changes(&layer_changes, &layers, &clock);
        let routers = self.registry.routers();
        if !routers.is_empty() && (style_changed || render_layers_remade) {
            self.routing = Routing::of(routers, style, &self.layer_indexes);
            // The frame's draws route only while the routing has routes.
            if self.routing.is_empty() {
                for layer in &mut self.layers {
                    layer.set_route(None);
                }
            }
        }
        let constants_mask_changed = self.evaluate_layers(&layer_changes, render_layers_remade, &mut clock);
        self.apply_source_diff(&source_diff, update_parameters);

        // A still image fails at the first resource error, and nothing
        // requests a failed resource again on its own: each new still image
        // retries them instead of waiting on them or rendering without them.
        if !clock.continuous
            && update_parameters.still_image_request
            && update_parameters.still_image_request_id != self.still_image_request_id
        {
            self.still_image_request_id = update_parameters.still_image_request_id;
            // A tile laid out without the glyphs of a failed range lays out
            // again, which requests the range again.
            self.tile_store.retry_failed();
        }
        self.view = update_parameters.view.clone();

        // The terrain's cover is made of its DEM's, which the DEM's origin
        // makes of its source as the style has it now.
        let style = &update_parameters.style;
        if let Some(terrain) = style.terrain()
            && let Some(style_source) = style.source(&terrain.source)
            && let Some(source) = self.render_sources.get_mut(&terrain.source)
        {
            source.update_origin(&mut self.tile_store, style_source, update_parameters);
        }
        let (store, render_sources) = (&self.tile_store, &self.render_sources);
        let dem = |id: &str| store.source(render_sources.get(id)?.tiles()?);
        frame.terrain = self.terrain.update(update_parameters, dem).is_some();
        let will_render = self.update_sources(
            update_parameters,
            &layers,
            &layer_changes,
            &constants_mask_changed,
            &clock,
            &mut frame,
        );
        let (store, render_sources) = (&self.tile_store, &self.render_sources);
        let dem = |id: &str| store.source(render_sources.get(id)?.tiles()?);
        let grounded = self.terrain.bind(dem, update_parameters, &mut self.events);

        #[cfg(feature = "bench")]
        crate::bench::observe_cover(&self.view, &self.tile_store);

        // A synchronous source's tile laid out by its answer isn't in this
        // update's render tiles yet: the next update has it.
        let answered = self.tile_store.drive();
        self.forward_store_events();
        if answered {
            self.events.push(RendererEvent::Invalidate);
        }

        // The sources' tiles are in other world copies once the center has
        // crossed the antimeridian (`SourceTiles::handle_wrap_jump`), and
        // the layers' draws go with them.
        let longitude = update_parameters.view.world_copy_longitude() as f32;
        let wrap_delta = ((longitude - self.longitude) / 360.0).round() as i16;
        self.longitude = longitude;
        if wrap_delta != 0 {
            self.terrain.handle_wrap_jump();
        }
        for (layer, will_render) in self.layers.iter_mut().zip(will_render) {
            if wrap_delta != 0 {
                layer.handle_wrap_jump(wrap_delta);
            }
            if layer.is_renderable() != will_render {
                layer.set_renderable(will_render);
            }
        }

        // A frame whose camera would move on the terrain's current ground
        // isn't complete: the map answers the new ground with an update, and
        // a still image draws only the frame of an update that stands on it.
        frame.loaded = update_parameters.style_loaded && !answered && grounded && self.is_loaded();
        if !clock.continuous && !frame.loaded {
            return None;
        }

        // The buckets whose vertex data the frame's feature state and symbol
        // placement change, which the draws that copied it copy again.
        let mut changed_buckets = ChangedBuckets::default();
        self.update_render_tiles(&frame, &mut changed_buckets);
        self.update_layer_tiles(update_parameters, &frame);

        frame.symbols_started = Instant::now();
        let placed = self.place(update_parameters, &mut frame);

        if !frame.needs_repaint && frame.loaded {
            // Ask the app to remove the unused images it added once the map
            // is fully loaded and there are no ongoing transitions.
            if self.tile_store.images().exceeds_cache_size_limit() {
                let used = self.tile_store.images_used();
                self.tile_store.images_mut().reduce_memory_use(&used);
                self.events.extend(self.tile_store.take_resource_events());
            }
        }

        // The buckets of the layers that place, and of those that draw
        // buckets other layers place, follow the placement.
        self.placements.update(
            &frame.transform.view,
            update_parameters.mode,
            placed,
            &mut self.tile_store,
            &mut changed_buckets,
        );
        if !changed_buckets.is_empty() {
            for layer in &mut self.layers {
                layer.mark_changed(&changed_buckets);
            }
            self.terrain.mark_changed(&changed_buckets);
        }

        Some(frame)
    }

    pub(crate) fn clear_data(&mut self) {
        // The next update finds every layer, source and image added. The
        // global state, light and sky stay, so the next update doesn't
        // transition them again.
        self.style = None;
        self.sources_by_id.clear();
        self.routing = Routing::default();

        self.render_sources.clear();
        self.tile_store.clear();
        self.leave_layers();
        self.layer_indexes.clear();

        self.placements.forget_buckets();

        self.tile_store.images_mut().clear();
        self.tile_store.glyphs().evict(&VecSet::new());
        self.terrain.clear_data(&mut self.events);
    }

    /// Drops what holds the renderer's shaders: the sky and globe depth
    /// passes and the terrain's draws now, and the render layers in the next
    /// update, which makes them again. The draws made after that use the
    /// shaders the renderer has then. The sources keep their tiles, and the
    /// tiles their layout.
    pub(crate) fn release_shaders(&mut self) {
        self.remake_render_layers = true;
        self.sky_pass = crate::render::sky_pass::SkyPass::default();
        self.globe_depth_pass = GlobeDepthPass::default();
        self.terrain.release_shaders();
    }

    /// Drops every render layer, and the shared targets.
    pub(crate) fn leave_layers(&mut self) {
        self.layers.clear();
        self.shared.lose();
    }

    /// Takes in what arrived for the tiles, and starts the jobs that it
    /// makes ready.
    pub(crate) fn receive_tiles(&mut self) {
        self.tile_store.receive();
        self.tile_store.drive();
        self.forward_store_events();
    }

    /// Turns what the tile store and its image and glyph stores reported
    /// into the renderer's events.
    fn forward_store_events(&mut self) {
        self.events.extend(self.tile_store.take_resource_events());
        for event in self.tile_store.take_events() {
            match event {
                StoreEvent::Changed => self.events.push(RendererEvent::Invalidate),
                StoreEvent::Error { source, tile, error } => {
                    tracing::error!(
                        target: log_target::STYLE,
                        tile = %tile,
                        source_id = %source,
                        error = %error,
                        "Failed to load a tile"
                    );
                    self.events.push(RendererEvent::ResourceError(error));
                    // A failed tile is done loading, and its parents or
                    // children may stand in for it, as when it changes: a
                    // continuous map needs a frame to see that, or it never
                    // reports that it finished loading. The error goes
                    // first, so the still image it fails isn't rendered
                    // again.
                    self.events.push(RendererEvent::Invalidate);
                }
                StoreEvent::Action { op, tile, source } => {
                    self.events.push(RendererEvent::TileAction { op, id: tile, source_id: source });
                }
            }
        }
    }

    /// The tiles of source `id`, if it has any.
    fn source_tiles(&self, id: &str) -> Option<&SourceTiles> {
        self.tile_store.source(self.render_sources.get(id)?.tiles()?)
    }

    fn source_tiles_mut(&mut self, id: &str) -> Option<&mut SourceTiles> {
        let key = self.render_sources.get(id)?.tiles()?;
        Some(self.tile_store.source_mut(key)?.0)
    }

    /// The sky, which draws before the layers, if the frame draws it.
    pub(crate) fn sky(&mut self) -> Option<&mut SingleDraw> {
        self.sky_pass.sky()
    }

    /// The globe's atmosphere, which draws after the layers, if the frame
    /// draws it.
    pub(crate) fn atmosphere(&mut self) -> Option<&mut SingleDraw> {
        self.sky_pass.atmosphere()
    }

    /// The pass that draws the planet's depth.
    pub(crate) fn globe_depth(&mut self) -> &mut GlobeDepthPass {
        &mut self.globe_depth_pass
    }

    /// The terrain, whose drapes draw before the frame's pass.
    pub(crate) fn terrain(&mut self) -> &mut RenderTerrain {
        &mut self.terrain
    }

    pub(crate) fn dump_debug_logs(&self) {
        for source in self.render_sources.values() {
            source.dump_debug_logs();
        }
        self.tile_store.dump_debug_logs();
    }

    pub(crate) fn set_feature_state(
        &mut self,
        source_id: &str,
        source_layer_id: Option<&str>,
        feature_id: &str,
        state: &mln_style::feature::FeatureState,
    ) {
        if let Some(source) = self.source_tiles_mut(source_id) {
            source.info.feature_state.update_state(source_layer_id, feature_id, state);
        }
    }

    pub(crate) fn feature_state(
        &self,
        source_id: &str,
        source_layer_id: Option<&str>,
        feature_id: &str,
    ) -> mln_style::feature::FeatureState {
        match self.source_tiles(source_id) {
            Some(source) => source.info.feature_state.state(source_layer_id, feature_id),
            None => mln_style::feature::FeatureState::default(),
        }
    }

    pub(crate) fn remove_feature_state(
        &mut self,
        source_id: &str,
        source_layer_id: Option<&str>,
        feature_id: Option<&str>,
        state_key: Option<&str>,
    ) {
        if let Some(source) = self.source_tiles_mut(source_id) {
            source.info.feature_state.remove_state(source_layer_id, feature_id, state_key);
        }
    }

    pub(crate) fn collect_placed_symbol_data(&mut self, enable: bool) {
        self.placements.collect_placed_symbol_data(enable);
    }

    pub(crate) fn set_tile_cache_enabled(&mut self, enable: bool) {
        self.tile_cache_enabled = enable;
        self.tile_store.set_cache_enabled(enable);
    }

    pub(crate) fn reduce_memory_use(&mut self) {
        self.filtered_layers_for_source.shrink_to_fit();
        self.tile_store.reduce_memory_use();
        let used = self.tile_store.images_used();
        self.tile_store.images_mut().reduce_memory_use(&used);
        self.events.extend(self.tile_store.take_resource_events());
        self.events.push(RendererEvent::Invalidate);
    }

    pub(crate) fn tile_cache_enabled(&self) -> bool {
        self.tile_cache_enabled
    }

    /// Drops `value` on the renderer's workers instead of this thread. The
    /// orchestrator's drop waits for it.
    pub(crate) fn drop_on_workers<T: Send + 'static>(&self, value: T) {
        drop_on_workers(&self.thread_pool, value);
    }
}

/// What the render tiles of a source show, at their indexes, for the layers
/// of a phase of the frame, which go through their sources in runs.
#[derive(Default)]
struct SourceContents<'a> {
    source: Option<&'a str>,
    contents: Vec<Option<TileContent<'a>>>,
}

impl<'a> SourceContents<'a> {
    /// What the render tiles of `source`, an id and its render source,
    /// show, from `store`; none for no source.
    fn of(
        &mut self,
        source: Option<(&'a str, &'a dyn RenderSource)>,
        store: &'a TileStore,
    ) -> &[Option<TileContent<'a>>] {
        let Some((id, source)) = source else {
            return &[];
        };
        if self.source != Some(id) {
            self.source = Some(id);
            self.contents.clear();
            source.tile_contents(store, &mut self.contents);
        }
        &self.contents
    }
}

/// The id of `layer`'s source, `None` for a layer type without one.
fn layer_source_id(layer: &dyn RenderLayer) -> Option<&str> {
    let style = &layer.base().style;
    (style.info().source != SourceKind::None).then(|| style.base().source.as_str())
}

/// What `layer`, a layer of the frame, draws from its source among
/// `render_sources`: the source's render tiles with what `contents` finds
/// they show in `tile_store`, among which it draws those of `found` its
/// update found.
fn layer_source<'a, 'c>(
    layer: &dyn RenderLayer,
    render_sources: &'a HashMap<String, Box<dyn RenderSource>>,
    tile_store: &'a TileStore,
    found: &'a [FoundTile],
    contents: &'c mut SourceContents<'a>,
) -> Option<FrameSourceTiles<'c>> {
    let source = layer_source_id(layer).and_then(|id| render_sources.get_key_value(id));
    let (id, source) = source.map(|(id, source)| (id.as_str(), &**source))?;
    Some(FrameSourceTiles::new(source.render_tiles(), contents.of(Some((id, source)), tile_store), found))
}

/// Drops `value` on `thread_pool`, the orchestrator's workers, instead of
/// this thread. The orchestrator's drop waits for it.
pub(crate) fn drop_on_workers<T: Send + 'static>(thread_pool: &TaskGroup, value: T) {
    thread_pool.spawn(move || drop(value));
}

/// A value that [`RenderOrchestrator::drop_on_workers`] drops once this
/// drops.
struct DropOnWorkers<T: Send + 'static> {
    value: Option<T>,
    thread_pool: TaskGroup,
}

impl<T: Send + 'static> DropOnWorkers<T> {
    fn new(value: T, thread_pool: TaskGroup) -> Self {
        DropOnWorkers { value: Some(value), thread_pool }
    }
}

impl<T: Send + 'static> Drop for DropOnWorkers<T> {
    fn drop(&mut self) {
        if let Some(value) = self.value.take() {
            drop_on_workers(&self.thread_pool, value);
        }
    }
}

/// Waits for its thread pool's tasks when it drops.
struct WaitOnDrop(TaskGroup);

impl Drop for WaitOnDrop {
    fn drop(&mut self) {
        self.0.wait();
    }
}

impl Drop for RenderOrchestrator {
    fn drop(&mut self) {
        // The render sources and their tiles go before the wait, since
        // their data drops on the thread pool.
        self.render_sources.clear();
        self.tile_store.clear();
        self.thread_pool.wait();
    }
}