mln-rs-runtime 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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
//! The handle of a render session, and the state that its thread shares
//! with the handle.

mod acquired;
mod attach;
mod shared;

use std::sync::Arc;
use std::sync::atomic::Ordering;

use mln_engine::camera::LogicalExtent;
use mln_engine::exec::thread::Joined;
use mln_engine::query::{RenderedQueryOptions, SourceQueryOptions};
use mln_engine::tile::feature::Feature;
use mln_style::bitmap::PremultipliedImage;
use mln_style::error::Error;
use mln_style::size::Size;

pub use self::acquired::{AcquiredFrame, FrameView};
pub(crate) use self::attach::attach;
pub(crate) use self::shared::{Abandoner, Published, SessionId, SessionShared, WorkId};
use self::shared::{Pacing, check_usable, released, with_unlocked_wakes};
use super::driver::DriverWork;
use super::frame::{FrameDemand, FrameResult};
use super::query::RenderedQueryGeometry;
use super::target::{BorrowedRing, Driver, ExportKind, GpuSync, SentSurface, Surface, SyncKind, SyncKinds};
use super::worker::{self, Worker};
use crate::completion::Completion;
use crate::frame_pacer::FramePacer;
use crate::map::Applied;
use crate::runtime::Outbox;

/// Where a render session is in its life.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RenderSessionState {
    /// The session is starting: it builds its renderer and binds to its map.
    Attaching,
    Attached,
    /// A detach or release is on its way.
    Detaching,
    /// The session let go of its map and its graphics objects.
    Detached,
    /// The session couldn't build its renderer, or failed while it rendered,
    /// as when a panic in its work stopped it. Its snapshot says why.
    Failed,
    Abandoned,
}

/// The state of a render session at one moment.
#[derive(Clone, Debug, PartialEq)]
pub struct RenderSessionSnapshot {
    pub state: RenderSessionState,
    /// The target's logical size, and the map's pixel ratio.
    pub extent: LogicalExtent,
    /// Grows each time the target changes size or is replaced.
    pub generation: u64,
    /// Counts the frames that the session rendered.
    pub frame_generation: u64,
    /// Why the session failed.
    pub failure: Option<Error>,
    /// Whether the session is attached and has a target to render to. It is
    /// false from a [`release_target`](RenderSession::release_target) until
    /// a [`set_surface`](RenderSession::set_surface) gives it a new one.
    pub has_target: bool,
    /// How many of a borrowed ring's frames the host holds.
    pub acquired_frames: u32,
}

/// What a render session can do.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct RenderSessionCapabilities {
    pub driver: Driver,
    /// How many textures the session's texture ring has.
    pub texture_ring_depth: u32,
    /// Whether the host can take the frames it renders.
    pub frame_acquisition: bool,
    /// Whether [`RenderSession::read_texture`] can read its pixels.
    pub readback: bool,
    /// Whether it shows frames on a surface.
    pub presentation: bool,
    /// The kind of sync that a borrowed ring's frames carry.
    pub producer_sync_kind: Option<SyncKind>,
    /// The kinds of sync that [`AcquiredFrame::release`] takes.
    pub consumer_sync_kinds: SyncKinds,
    /// How an exported ring shares its images, for an exported ring.
    pub export_kind: Option<ExportKind>,
}

/// Sizes in pixels a target of `size` logical pixels at `scale_factor`, by
/// [`LogicalExtent::physical_size`].
pub(crate) fn physical_size(size: Size, scale_factor: f64) -> Result<Size, Error> {
    LogicalExtent::new(size, scale_factor)
        .physical_size()
        .ok_or_else(|| Error::invalid_argument(format!("{size:?} at scale factor {scale_factor} has no physical size")))
}

/// A render session: a renderer that draws a map into a target, on a thread
/// of its own or on the host's.
///
/// The host demands frames, which finish with [`FrameResult`]s that
/// [`drain_frame_results`](Self::drain_frame_results) takes. A demand shows
/// the map's commands sent before it, except the changes that an open
/// command group holds back. The session's work runs on its thread in the
/// order it was sent, and reports through a [`Completion`]. `Clone` is
/// another handle to the same session, and any thread may use one.
///
/// A session that attached with [`Driver::CallerThread`] runs its work only
/// when the host services its [`DriverWork`], which
/// [`take_driver_work`](Self::take_driver_work) hands out.
///
/// The session lives until [`detach`](Self::detach),
/// [`release`](Self::release), [`dispose`](Self::dispose) or
/// [`abandon`](Self::abandon), or until its last handle drops, and it holds
/// its map until then. A call that sends work to a session that no longer
/// takes it fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind), or
/// with the failure of a session that failed.
///
/// Unless the session was released or disposed, the last drop of its
/// handles, [`AcquiredFrame`]s and [`FrameView`]s waits for a core worker's
/// thread to end, once the session has let go of its graphics objects and
/// its map. A drop on a thread of the library, such as in a callback or a
/// wake that the library runs, doesn't wait: it leaves the session's thread
/// to end alone.
#[derive(Clone)]
pub struct RenderSession {
    handle: Arc<SessionHandle>,
}

/// Disposes of the session when the last handle drops.
struct SessionHandle {
    shared: Arc<SessionShared>,
    thread_end: ThreadEnd,
}

/// A core worker's thread, which the last of the host's handles, frames and
/// views of the session to drop waits for. A caller-driven session has no
/// thread, and in the browser the thread is the host's.
type ThreadEnd = Option<Arc<Joined>>;

impl Drop for SessionHandle {
    /// Disposes of the session, which ends its thread once the frames and
    /// views of it end too, then waits for the thread as `thread_end` drops,
    /// unless they hold it.
    fn drop(&mut self) {
        let _ = self.shared.dispose(None);
    }
}

impl std::fmt::Debug for RenderSession {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RenderSession").field("id", &self.shared().id).finish()
    }
}

impl PartialEq for RenderSession {
    fn eq(&self, other: &RenderSession) -> bool {
        Arc::ptr_eq(&self.handle, &other.handle)
    }
}

impl Eq for RenderSession {}

impl RenderSession {
    fn shared(&self) -> &Arc<SessionShared> {
        &self.handle.shared
    }

    /// Sends a command with `send`, such as [`barrier`](Self::barrier), and
    /// calls `callback` once with its result, where the session delivers
    /// it: on the session's thread, inside its driver call, even when the
    /// command runs before `send` returns. A [`Completion::on_complete`]
    /// after the command returned would run at once on this thread instead.
    /// The callback doesn't run when `send` fails.
    ///
    /// Fails as `send` does.
    pub fn send_then<T: Send + 'static>(
        &self,
        send: impl FnOnce(&RenderSession) -> Result<Completion<T>, Error>,
        callback: impl FnOnce(Result<T, Error>) + Send + 'static,
    ) -> Result<(), Error> {
        // The wakes that the command runs wait for the lock's release, so a
        // host's wake that services the session can't wait for it.
        with_unlocked_wakes(|| {
            let ready = {
                let _sending = self.shared().hold_sending();
                send(self)?.on_complete_unless_ready(callback)
            };
            // A result that came without the session's thread, such as a
            // command dropped unrun, goes to the callback here.
            if let Some((callback, result)) = ready {
                callback(result);
            }
            Ok(())
        })
    }

    /// Sends `task` to the session's thread, after the work sent before,
    /// resizes included, and completes with its result. A session that lost
    /// its graphics objects before the task runs completes it with
    /// [`ErrorKind::TargetLost`](mln_style::error::ErrorKind).
    pub(crate) fn operation<T: Send + 'static>(
        &self,
        task: impl FnOnce(&mut Worker, &mut Outbox) -> Result<T, Error> + Send + 'static,
    ) -> Result<Completion<T>, Error> {
        let shared = self.shared();
        with_unlocked_wakes(|| {
            let mut state = shared.state.lock();
            check_usable(&state)?;
            let (completion, resolver) = shared.completion();
            let work = state.register(resolver);
            let resizes = state.resizes_sent;
            worker::post(&shared.queue, move |worker, outbox| {
                let task: worker::Task = Box::new(move |worker, outbox| {
                    let Some(resolver) = worker.take_work(work) else { return };
                    let result = task(worker, outbox);
                    outbox.resolve(resolver, result);
                });
                worker.after_earlier_work(resizes, task, outbox);
            });
            drop(state);
            Ok(completion)
        })
    }

    /// Hands out the work of a [`Driver::CallerThread`] session, for the
    /// calling thread to run: the session's graphics work runs only in its
    /// [`service`](DriverWork::service), and on no other thread.
    ///
    /// Take it once, on the host's graphics thread, from the attach on: the
    /// attach itself completes in a service. It stays available after a
    /// release, which the host services to its end.
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
    /// session on a core worker, and with
    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once it was taken.
    pub fn take_driver_work(&self) -> Result<DriverWork, Error> {
        let shared = self.shared();
        if shared.driver != Driver::CallerThread {
            return Err(Error::unsupported("the render session runs on a core worker"));
        }
        if shared.driver_work_taken.swap(true, Ordering::SeqCst) {
            return Err(Error::invalid_state("the render session's driver work was taken already"));
        }
        let _ = shared.thread.set(std::thread::current().id());
        Ok(DriverWork::new(Arc::clone(shared)))
    }

    /// What the session can do. Fails with
    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once it is released.
    pub fn capabilities(&self) -> Result<RenderSessionCapabilities, Error> {
        let state = self.shared().state.lock();
        if state.released {
            return Err(released());
        }
        Ok(self.shared().capabilities)
    }

    /// The session's state now. Fails with
    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once it is released.
    pub fn snapshot(&self) -> Result<RenderSessionSnapshot, Error> {
        let state = self.shared().state.lock();
        if state.released {
            return Err(released());
        }
        Ok(RenderSessionSnapshot {
            state: state.lifecycle,
            extent: LogicalExtent { size: state.size, scale_factor: state.scale_factor },
            generation: state.generation,
            frame_generation: state.frame_generation,
            failure: state.failure.clone(),
            has_target: state.lifecycle == RenderSessionState::Attached && state.has_target,
            acquired_frames: state.acquired_frames,
        })
    }

    /// Takes the newest frame that a borrowed ring rendered, if one waits:
    /// the older frames that the host didn't acquire are dropped, and the
    /// session may render into their textures again. While the host holds a
    /// frame in every texture, demands wait for a release.
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
    /// session without a ring, and as a call that sends work does once the
    /// session no longer takes work.
    pub fn acquire_frame(&self) -> Result<Option<AcquiredFrame>, Error> {
        let shared = self.shared();
        let mut state = shared.state.lock();
        check_usable(&state)?;
        if !shared.capabilities.frame_acquisition {
            return Err(Error::unsupported("render session does not expose acquired texture frames"));
        }
        if state.pending_retargets != 0 {
            return Ok(None);
        }
        let newest = state
            .ring
            .iter()
            .enumerate()
            .filter(|(_, slot)| !slot.acquired && slot.frame.is_some())
            .max_by_key(|(_, slot)| slot.frame.as_ref().map_or(0, |frame| frame.result.frame_generation))
            .map(|(index, _)| index);
        let Some(index) = newest else { return Ok(None) };
        for (other, slot) in state.ring.iter_mut().enumerate() {
            if other != index && !slot.acquired {
                slot.frame = None;
            }
        }
        let slot = &mut state.ring[index];
        let Some(frame) = slot.frame.take() else { return Ok(None) };
        slot.acquired = true;
        state.acquired_frames += 1;
        Ok(Some(AcquiredFrame {
            shared: Arc::clone(shared),
            thread_end: self.handle.thread_end.clone(),
            slot: index,
            frame,
            done: false,
        }))
    }

    /// Gives a borrowed ring new textures, of `size` logical pixels: as many
    /// as it has, of its format. The completion reports the map's change and
    /// the sync after which the host may use the old textures that the new
    /// ring doesn't have, as [`release_target`](Self::release_target) says.
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
    /// session without a borrowed ring, with
    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for another number
    /// of textures, and with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
    /// while the host holds one of the ring's frames. Completes with
    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for textures of
    /// another format or kind.
    pub fn set_ring(&self, size: Size, ring: BorrowedRing) -> Result<Completion<(Applied, GpuSync)>, Error> {
        let shared = Arc::clone(self.shared());
        {
            let mut state = shared.state.lock();
            check_usable(&state)?;
            if shared.capabilities.readback {
                return Err(Error::unsupported("an offscreen session keeps its target"));
            }
            if !shared.capabilities.frame_acquisition {
                return Err(Error::unsupported("a surface session takes no caller-owned texture"));
            }
            if shared.capabilities.export_kind.is_some() {
                return Err(Error::unsupported("an exported ring resizes instead of taking new textures"));
            }
            if state.acquired_frames != 0 {
                return Err(Error::invalid_state("cannot replace the render target while a texture frame is acquired"));
            }
            if ring.depth() != state.ring.len() {
                return Err(Error::invalid_argument(
                    "texture_count must equal the ring depth the session attached with",
                ));
            }
            state.pending_retargets += 1;
        }
        let guard = RetargetGuard(Arc::clone(&shared));
        // The guard goes with the closure, whether the closure runs or the
        // resize drops it.
        self.resize_then(size, None, move |worker, size, scale_factor, applied, outbox| {
            let _guard = guard;
            Ok((applied, worker.set_ring(size, scale_factor, &ring, outbox)?))
        })
    }

    /// Asks the session to render a frame, which shows the map commands sent
    /// before the call, except the changes that an open command group holds
    /// back, and the map's animations as they are at the call: demand each
    /// frame at the display's pace. A demand sent while the session attaches
    /// waits for it.
    ///
    /// Every demand finishes with one [`FrameResult`] that carries its token.
    /// A demand that isn't [`DemandMode::Force`](super::DemandMode::Force)
    /// replaces the demands with the same mode still on their way, which
    /// finish as [`FrameDisposition::Superseded`](super::FrameDisposition).
    /// While the session has no target, or a surface has no texture to
    /// render into, a demand finishes as
    /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition).
    pub fn demand_frame(&self, demand: FrameDemand) -> Result<(), Error> {
        let shared = self.shared();
        with_unlocked_wakes(|| shared.demand_locked(&mut shared.state.lock(), demand))
    }

    /// Paces the session's frames with `pacer`, or with none, stops. At the
    /// first refresh that the pacer allows after the map has something new to
    /// draw, it demands a frame in
    /// [`DemandMode::IfChanged`](super::DemandMode::IfChanged) with token 0,
    /// unless a demand came first. One pacer can pace many sessions.
    ///
    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a
    /// session with a redraw wake.
    pub fn set_frame_pacer(&self, pacer: Option<Arc<FramePacer>>) -> Result<(), Error> {
        let shared = self.shared();
        let request = {
            let mut state = shared.state.lock();
            check_usable(&state)?;
            if shared.redraw_wake.is_some() {
                return Err(Error::invalid_state("a render session with a redraw wake takes no frame pacer"));
            }
            let same = match (&state.pacing, &pacer) {
                (Some(pacing), Some(pacer)) => Arc::ptr_eq(&pacing.pacer, pacer),
                (None, None) => true,
                _ => false,
            };
            if same {
                return Ok(());
            }
            state.pacing = pacer.map(|pacer| Pacing::new(pacer, Arc::downgrade(shared)));
            state.pacing.as_ref().filter(|_| !state.redraw_armed).map(Pacing::request)
        };
        if let Some(request) = request {
            request();
        }
        Ok(())
    }

    /// Takes the frame results that wait, oldest first. Fails with
    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once the session is
    /// released.
    pub fn drain_frame_results(&self) -> Result<Vec<FrameResult>, Error> {
        let mut state = self.shared().state.lock();
        if state.released {
            return Err(released());
        }
        state.frame_woken = false;
        Ok(std::mem::take(&mut state.results))
    }

    /// Resizes the target, and the map with it, to `extent`'s size in
    /// logical pixels, and sets the map's scale factor to `extent`'s, such
    /// as when a window moves to a display of another density. The map keeps
    /// its tiles, and the renderer draws the next frame at the new scale
    /// factor. A later demand shows the new extent, and one sent before
    /// shows the old. An exported ring gets images of the new size, and the
    /// frames that the host holds keep theirs until it gives them back.
    ///
    /// Fails first as a call that sends work does once the session no
    /// longer takes work. Then fails with
    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a borrowed ring,
    /// which [`set_ring`](Self::set_ring) resizes, and with
    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an empty size,
    /// or a scale factor that isn't finite and positive.
    pub fn resize(&self, extent: LogicalExtent) -> Result<Completion<Applied>, Error> {
        check_usable(&self.shared().state.lock())?;
        let capabilities = self.shared().capabilities;
        if capabilities.frame_acquisition && capabilities.export_kind.is_none() {
            return Err(Error::unsupported("a borrowed ring is sized by its owner: give it new textures instead"));
        }
        let LogicalExtent { size, scale_factor } = extent;
        if !scale_factor.is_finite() || scale_factor <= 0.0 {
            return Err(Error::invalid_argument(format!("scale factor {scale_factor} isn't finite and positive")));
        }
        self.resize_then(size, Some(scale_factor), |worker, size, scale_factor, applied, outbox| {
            worker.resize(size, scale_factor, outbox).map(|()| applied)
        })
    }

    /// Sends a map command that resizes the map to `size`, at
    /// `scale_factor` or the session's when that is `None`, then runs
    /// `change` on the session's thread with the map's change, which resizes
    /// or replaces the target, and completes with its result.
    fn resize_then<T: Send + 'static>(
        &self,
        size: Size,
        scale_factor: Option<f64>,
        change: impl FnOnce(&mut Worker, Size, f64, Applied, &mut Outbox) -> Result<T, Error> + Send + 'static,
    ) -> Result<Completion<T>, Error> {
        if size.is_empty() {
            return Err(Error::invalid_argument("the target's size must not be empty"));
        }
        let shared = self.shared();
        with_unlocked_wakes(|| {
            let mut state = shared.state.lock();
            check_usable(&state)?;
            let map = state.map.clone().ok_or_else(|| Error::invalid_state("the render session has no map"))?;
            let scale_factor = scale_factor.unwrap_or(state.sent_scale_factor);
            state.sent_scale_factor = scale_factor;
            let (completion, resolver) = shared.completion();
            let work = state.register(resolver);
            // The work sent after waits for the resize to land, which it
            // does even when the map drops it.
            state.resizes_sent += 1;
            let landing = worker::ResizeLanding::new(shared.queue.clone());
            let sent =
                map.resize_for_session(size, scale_factor, shared.queue.clone(), move |worker, result, outbox| {
                    if let Some(resolver) = worker.take_work::<T>(work) {
                        let result = result.and_then(|applied| change(worker, size, scale_factor, applied, outbox));
                        outbox.resolve(resolver, result);
                    }
                    landing.land(worker, outbox);
                });
            if let Err(error) = sent {
                state.pending.remove(&work);
                return Err(error);
            }
            drop(state);
            Ok(completion)
        })
    }

    /// Lets go of a surface session's surface, and keeps the rest of the
    /// session, such as when the platform takes the window away. The demands
    /// on their way, and later ones until
    /// [`set_surface`](Self::set_surface) gives the session a surface again,
    /// finish as [`FrameDisposition::TargetNotReady`](super::FrameDisposition).
    /// Once the release completes, the session no longer uses the surface or
    /// the window it was made from. For a ring, it completes with a sync of
    /// the session's producer kind, after which the host may use or destroy
    /// the textures: the session's GPU work on them, and its waits for the
    /// consumer syncs that they were given back with, end there. The session
    /// keeps the objects that the sync names until its next release or
    /// replacement of the target completes, or it ends. It keeps nothing of
    /// the released textures: one that a later ring has again starts fresh,
    /// even one that the host gave up.
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for an
    /// offscreen session or an exported ring, whose targets are their own.
    /// Completes with [`ErrorKind::Failed`](mln_style::error::ErrorKind) when a ring
    /// can't submit its work on the textures, which it keeps then.
    pub fn release_target(&self) -> Result<Completion<Option<GpuSync>>, Error> {
        if self.shared().capabilities.export_kind.is_some() {
            return Err(Error::unsupported("an exported ring keeps its images until the session ends"));
        }
        let shared = Arc::clone(self.shared());
        let capabilities = shared.capabilities;
        if !capabilities.presentation && !capabilities.frame_acquisition {
            check_usable(&shared.state.lock())?;
            return Err(Error::unsupported("an offscreen session keeps its target"));
        }
        let guard = {
            let mut state = shared.state.lock();
            check_usable(&state)?;
            if state.acquired_frames != 0 {
                return Err(Error::invalid_state("release every acquired frame before the target"));
            }
            // No frame is acquired until the release runs: its textures go
            // with it.
            capabilities.frame_acquisition.then(|| {
                state.pending_retargets += 1;
                RetargetGuard(Arc::clone(&shared))
            })
        };
        self.operation(move |worker, outbox| {
            let _guard = guard;
            worker.release_target(outbox)
        })
    }

    /// Gives a surface session a new surface of `size` logical pixels, after
    /// [`release_target`](Self::release_target), or in place of the one it
    /// has, and resizes the map to it. Once the completion reports success,
    /// the session no longer uses the old surface. The session presents to
    /// it on its device: a window becomes a surface of the device's backend,
    /// and a `Surface::wgpu` must come from the instance of a WebGPU
    /// device. Where the backend made for the old surface can't present to
    /// the new one, as OpenGL ES's context can't to another window, the
    /// session makes its backend and renderer again.
    ///
    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an
    /// empty size, with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for
    /// an offscreen session, and with
    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a window that is
    /// minimized or has no client area. Completes with
    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when the session's
    /// device can't present to the surface in the format that the session
    /// renders in: attach a new session instead. Completes with
    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the window had no
    /// area to present to by then. The session then keeps the surface it had,
    /// at the new size.
    pub fn set_surface(&self, size: Size, surface: Surface) -> Result<Completion<Applied>, Error> {
        check_usable(&self.shared().state.lock())?;
        let capabilities = self.shared().capabilities;
        if capabilities.frame_acquisition {
            return Err(Error::unsupported("a borrowed texture session takes no native surface"));
        }
        if !capabilities.presentation {
            return Err(Error::unsupported("an offscreen session keeps its target"));
        }
        surface.check_area()?;
        let surface = SentSurface::new(surface, self.shared().id);
        self.resize_then(size, None, move |worker, size, scale_factor, applied, outbox| {
            worker.set_surface(size, scale_factor, surface.receive()?, outbox).map(|()| applied)
        })
    }

    /// Ends the frame demands on their way, including those that wait for a
    /// map update and the demand of a still image, which finish as
    /// [`FrameDisposition::NoUpdate`](super::FrameDisposition), and completes
    /// once the work sent before it has run. A still image that still waits
    /// gets a new demand once the barrier ran.
    pub fn barrier(&self) -> Result<Completion<()>, Error> {
        self.operation(|worker, outbox| {
            worker.barrier(outbox);
            Ok(())
        })
    }

    /// Frees memory that the renderer can rebuild, such as caches.
    pub fn reduce_memory_use(&self) -> Result<Completion<()>, Error> {
        self.operation(|worker, _| worker.reduce_memory_use())
    }

    /// Clears what the renderer holds, such as loaded tiles, so that the
    /// next frame loads and draws the map again.
    pub fn clear_data(&self) -> Result<Completion<()>, Error> {
        self.operation(Worker::clear_data)
    }

    /// Logs the renderer's sources and tiles.
    pub fn dump_debug_logs(&self) -> Result<Completion<()>, Error> {
        self.operation(|worker, _| worker.dump_debug_logs())
    }

    /// The pixels of the last frame that an offscreen session rendered:
    /// premultiplied RGBA, in rows from top to bottom, at the target's size
    /// in pixels.
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
    /// surface session. Completes with
    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the session
    /// hasn't rendered a frame since it attached or resized.
    pub fn read_texture(&self) -> Result<Completion<PremultipliedImage>, Error> {
        check_usable(&self.shared().state.lock())?;
        if !self.shared().capabilities.readback {
            return Err(Error::unsupported("a surface session can't read its frames back"));
        }
        self.operation(|worker, _| worker.read_texture())
    }

    /// The features that the session drew in an area of the screen, in its
    /// last frame. A feature that several layers draw appears once for each.
    /// The topmost layer's features come first, and the bottom layer's last.
    /// A box covers only its part inside the target, so one past every edge
    /// covers the whole target.
    ///
    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
    /// point that isn't finite or a line string without points.
    pub fn query_rendered_features(
        &self,
        geometry: RenderedQueryGeometry,
        options: RenderedQueryOptions,
    ) -> Result<Completion<Vec<Feature>>, Error> {
        geometry.points()?;
        self.operation(move |worker, _| match geometry.within(worker.size()).map(|geometry| geometry.points()) {
            Some(points) => worker.renderer()?.query_rendered_features(&points?, &options),
            None => Ok(Vec::new()),
        })
    }

    /// The features of the source `source_id` in the tiles that it loaded
    /// for the current view. A source loads tiles only while a visible layer
    /// uses it.
    ///
    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an
    /// empty `source_id`.
    pub fn query_source_features(
        &self,
        source_id: impl Into<String>,
        options: SourceQueryOptions,
    ) -> Result<Completion<Vec<Feature>>, Error> {
        let source_id = source_id_of(source_id)?;
        self.operation(move |worker, _| worker.renderer()?.query_source_features(&source_id, &options))
    }

    /// The clusters and points that a cluster of a clustered GeoJSON source
    /// splits into at the next zoom level. `cluster_id` is a cluster
    /// feature's `cluster_id` property.
    ///
    /// The query reads the source as the session's most recent render
    /// attempt had it. A cluster ID belongs to one version of the source's
    /// data, so query the features again after the data changes.
    ///
    /// Completes with [`ErrorKind::NotFound`](mln_style::error::ErrorKind) when that
    /// render had no source `source_id`, or the source has no cluster
    /// `cluster_id`, and with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind)
    /// when the source isn't a clustered GeoJSON source.
    pub fn cluster_children(
        &self,
        source_id: impl Into<String>,
        cluster_id: u32,
    ) -> Result<Completion<Vec<mln_style::feature::Feature<f64>>>, Error> {
        let source_id = source_id_of(source_id)?;
        self.operation(move |worker, _| worker.cluster(&source_id, cluster_id, |_, children| Ok(children)))
    }

    /// The points in a cluster of a clustered GeoJSON source: it skips the
    /// first `offset`, then holds up to `limit`. It fails as
    /// [`cluster_children`](Self::cluster_children) does.
    pub fn cluster_leaves(
        &self,
        source_id: impl Into<String>,
        cluster_id: u32,
        limit: u32,
        offset: u32,
    ) -> Result<Completion<Vec<mln_style::feature::Feature<f64>>>, Error> {
        let source_id = source_id_of(source_id)?;
        self.operation(move |worker, _| {
            worker.cluster(&source_id, cluster_id, |index, _| index.leaves(cluster_id, limit, offset))
        })
    }

    /// The zoom level at which a cluster of a clustered GeoJSON source splits
    /// into two or more clusters or points. It fails as
    /// [`cluster_children`](Self::cluster_children) does.
    pub fn cluster_expansion_zoom(
        &self,
        source_id: impl Into<String>,
        cluster_id: u32,
    ) -> Result<Completion<u8>, Error> {
        let source_id = source_id_of(source_id)?;
        self.operation(move |worker, _| {
            worker.cluster(&source_id, cluster_id, |index, _| index.cluster_expansion_zoom(cluster_id))
        })
    }

    /// Detaches the session from its map and frees its graphics objects. The
    /// demands on their way finish as
    /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition). Once
    /// the detach completes, another session can attach to the map.
    pub fn detach(&self) -> Result<Completion<()>, Error> {
        let shared = self.shared();
        with_unlocked_wakes(|| {
            let mut state = shared.state.lock();
            if !matches!(state.lifecycle, RenderSessionState::Failed) {
                check_usable(&state)?;
            } else if state.released {
                return Err(released());
            }
            if state.acquired_frames != 0 {
                return Err(Error::invalid_state("release every acquired frame before the session detaches"));
            }
            let (completion, resolver) = shared.completion();
            state.detach_waiters.push(resolver);
            shared.start_detach(&mut state);
            Ok(completion)
        })
    }

    /// Stops the session at once, without its pending graphics work: that
    /// work completes with [`ErrorKind::TargetLost`](mln_style::error::ErrorKind)
    /// before this returns, and the demands on their way finish as
    /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition). Once it
    /// returns, the session renders no more, and another session can attach
    /// to the map. Release the session afterward.
    ///
    /// Returns how many graphics objects the session keeps until the
    /// process exits. A caller-driven session abandoned on the thread that
    /// services it lets go of them there, at its next service or when its
    /// [`DriverWork`] drops, and keeps none. Abandoned on another thread, it
    /// keeps them, since only that thread may free them, and logs a warning.
    ///
    /// It waits for a core worker's driver call on another thread, such as a
    /// frame that it renders. Fails with
    /// [`ErrorKind::Busy`](mln_style::error::ErrorKind) inside a driver call on the
    /// session's own thread, such as from a completion that the session
    /// delivers, and while a caller-driven session's service runs on another
    /// thread. Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
    /// once the session is detached, abandoned or released.
    pub fn abandon(&self) -> Result<u32, Error> {
        self.shared().abandon(Abandoner::Host)
    }

    /// Abandons the session as [`abandon`](Self::abandon) does, but makes no
    /// graphics call: the session keeps its graphics objects until the
    /// process exits. Returns how many it keeps, such as its renderer and
    /// the backend it draws with.
    ///
    /// This is for a host whose shutdown may already have destroyed the
    /// graphics objects behind the session.
    pub fn abandon_keeping_graphics(&self) -> Result<u32, Error> {
        with_unlocked_wakes(|| self.shared().abandon_locked(Abandoner::Host, true))
    }

    /// Releases the session, detaching it first when it is attached. The
    /// completion reports when the session has let go of its map and its
    /// graphics objects, and nothing waits for its thread to end after
    /// that. Every call on the session fails with
    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) after.
    ///
    /// A caller-driven session detaches at the host's next service, so keep
    /// servicing it until the release completes. One that isn't attached,
    /// such as while it attaches or after it failed, is abandoned instead,
    /// and so is one whose map is released before that service.
    pub fn release(&self) -> Result<Completion<()>, Error> {
        {
            let state = self.shared().state.lock();
            let live = matches!(state.lifecycle, RenderSessionState::Attaching | RenderSessionState::Attached);
            if live && !state.released && state.acquired_frames != 0 {
                return Err(Error::invalid_state("release every acquired frame before the session is released"));
            }
        }
        let (completion, resolver) = self.shared().completion();
        self.shared().dispose(Some(resolver))?;
        self.detach_thread();
        Ok(completion)
    }

    /// Releases the session in any state, without waiting, and nothing waits
    /// for its thread to end. Dropping the last handle does the same, then
    /// waits for the thread.
    pub fn dispose(&self) -> Result<(), Error> {
        self.shared().dispose(None)?;
        self.detach_thread();
        Ok(())
    }

    /// Releases the session in any state, without waiting and without a
    /// graphics call past the one in progress. A session that hasn't ended
    /// is abandoned, keeping its graphics objects until the process exits,
    /// as [`abandon_keeping_graphics`](Self::abandon_keeping_graphics) does.
    /// Nothing waits for its thread to end.
    pub fn dispose_keeping_graphics(&self) -> Result<(), Error> {
        self.shared().dispose_keeping_graphics()?;
        self.detach_thread();
        Ok(())
    }

    /// Leaves a core worker's thread to end alone, for a release or
    /// disposal, which don't wait for it.
    fn detach_thread(&self) {
        if let Some(thread) = &self.handle.thread_end {
            thread.detach();
        }
    }
}

/// Counts a host's frame demand until the session evaluates or ends it, or
/// drops it unrun.
pub(crate) struct DemandGuard(Arc<SessionShared>);

impl Drop for DemandGuard {
    fn drop(&mut self) {
        let mut state = self.0.state.lock();
        state.pending_demands = state.pending_demands.saturating_sub(1);
    }
}

/// Counts a ring replacement or release on its way until it runs, or never
/// will.
struct RetargetGuard(Arc<SessionShared>);

impl Drop for RetargetGuard {
    fn drop(&mut self) {
        let mut state = self.0.state.lock();
        state.pending_retargets = state.pending_retargets.saturating_sub(1);
    }
}

fn source_id_of(source_id: impl Into<String>) -> Result<String, Error> {
    let source_id = source_id.into();
    if source_id.is_empty() {
        return Err(Error::invalid_argument("the source ID must not be empty"));
    }
    Ok(source_id)
}

// Handles cross threads; the renderer never leaves its own.
const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<RenderSession>();
};