Skip to main content

mln_runtime/render/
session.rs

1//! The handle of a render session, and the state that its thread shares
2//! with the handle.
3
4use std::any::Any;
5use std::cell::RefCell;
6use std::collections::BTreeMap;
7use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
8use std::sync::{Arc, OnceLock, Weak};
9use std::thread::ThreadId;
10use std::time::Duration;
11
12use mln_engine::camera::LogicalExtent;
13use mln_engine::exec::thread::Joined;
14use mln_engine::query::{RenderedQueryOptions, SourceQueryOptions};
15use mln_engine::tile::feature::Feature;
16use mln_style::bitmap::PremultipliedImage;
17use mln_style::error::Error;
18use mln_style::size::Size;
19use parking_lot::Mutex;
20
21use super::driver::DriverWork;
22use super::frame::{FrameDemand, FrameResult};
23use super::query::RenderedQueryGeometry;
24use super::target::{
25    AttachOptions, BorrowedRing, ConsumerSync, Device, DeviceLease, Driver, ExportKind, FrameTexture, GpuSync,
26    RenderTarget, SentSurface, Surface, SyncKind, SyncKinds, Wake,
27};
28use super::worker::{self, Init, SessionQueue, TargetInit, Worker};
29use crate::completion::{Completion, Home, Resolver};
30use crate::frame_pacer::{FramePacer, RefreshWaiter};
31use crate::log_target;
32use crate::map::{Applied, Map};
33use crate::runtime::Outbox;
34
35/// The ID of a render session, unique in the process.
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37pub(crate) struct SessionId(u64);
38
39/// Where a render session is in its life.
40#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
41pub enum RenderSessionState {
42    /// The session is starting: it builds its renderer and binds to its map.
43    Attaching,
44    Attached,
45    /// A detach or release is on its way.
46    Detaching,
47    /// The session let go of its map and its graphics objects.
48    Detached,
49    /// The session couldn't build its renderer, or failed while it rendered,
50    /// as when a panic in its work stopped it. Its snapshot says why.
51    Failed,
52    Abandoned,
53}
54
55/// The state of a render session at one moment.
56#[derive(Clone, Debug, PartialEq)]
57pub struct RenderSessionSnapshot {
58    pub state: RenderSessionState,
59    /// The target's logical size, and the map's pixel ratio.
60    pub extent: LogicalExtent,
61    /// Grows each time the target changes size or is replaced.
62    pub generation: u64,
63    /// Counts the frames that the session rendered.
64    pub frame_generation: u64,
65    /// Why the session failed.
66    pub failure: Option<Error>,
67    /// Whether the session is attached and has a target to render to. It is
68    /// false from a [`release_target`](RenderSession::release_target) until
69    /// a [`set_surface`](RenderSession::set_surface) gives it a new one.
70    pub has_target: bool,
71    /// How many of a borrowed ring's frames the host holds.
72    pub acquired_frames: u32,
73}
74
75/// What a render session can do.
76#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
77pub struct RenderSessionCapabilities {
78    pub driver: Driver,
79    /// How many textures the session's texture ring has.
80    pub texture_ring_depth: u32,
81    /// Whether the host can take the frames it renders.
82    pub frame_acquisition: bool,
83    /// Whether [`RenderSession::read_texture`] can read its pixels.
84    pub readback: bool,
85    /// Whether it shows frames on a surface.
86    pub presentation: bool,
87    /// The kind of sync that a borrowed ring's frames carry.
88    pub producer_sync_kind: Option<SyncKind>,
89    /// The kinds of sync that [`AcquiredFrame::release`] takes.
90    pub consumer_sync_kinds: SyncKinds,
91    /// How an exported ring shares its images, for an exported ring.
92    pub export_kind: Option<ExportKind>,
93}
94
95/// A frame of a borrowed ring that the session published, and what the
96/// host waits for before it reads it.
97#[derive(Clone, Debug)]
98pub(crate) struct Published {
99    pub(crate) result: FrameResult,
100    pub(crate) sync: GpuSync,
101    pub(crate) texture: Option<FrameTexture>,
102}
103
104/// One texture of a borrowed ring.
105#[derive(Clone, Debug, Default)]
106pub(crate) struct RingSlot {
107    /// The newest frame rendered into the texture, which the host hasn't
108    /// acquired.
109    pub(crate) frame: Option<Published>,
110    pub(crate) acquired: bool,
111    pub(crate) rendering: bool,
112    /// The host's GPU may still read the texture, so the session renders
113    /// into it no more, even when a new ring has it again, until a release
114    /// of the ring.
115    pub(crate) quarantined: bool,
116    /// The host holds an exported ring's image from before a resize, which
117    /// gave the slot a new one that never reached the host: giving the old
118    /// one up quarantines nothing.
119    pub(crate) retired: bool,
120}
121
122impl RingSlot {
123    pub(crate) fn busy(&self) -> bool {
124        self.acquired || self.rendering || self.quarantined
125    }
126}
127
128/// Work sent to a session's thread, whose completion an abandon can fail at
129/// once instead of waiting for the thread to run it.
130pub(crate) trait PendingWork: Any + Send {
131    fn fail(self: Box<Self>, error: Error);
132}
133
134impl<T: Send + 'static> PendingWork for Resolver<T> {
135    fn fail(self: Box<Self>, error: Error) {
136        (*self).resolve(Err(error));
137    }
138}
139
140/// The ID of a piece of work that waits for a session's thread.
141#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
142pub(crate) struct WorkId(u64);
143
144/// The state that a session's handle and its thread share.
145pub(crate) struct SessionState {
146    pub(crate) lifecycle: RenderSessionState,
147    pub(crate) released: bool,
148    pub(crate) size: Size,
149    /// The scale factor that the target has, as `size` does.
150    pub(crate) scale_factor: f64,
151    /// The scale factor of the last resize sent, which a later resize that
152    /// names none keeps.
153    pub(crate) sent_scale_factor: f64,
154    pub(crate) generation: u64,
155    pub(crate) frame_generation: u64,
156    pub(crate) failure: Option<Error>,
157    /// Whether the session has a target to render to: false from a release
158    /// of its target until it gets a new one.
159    pub(crate) has_target: bool,
160    /// The frame results that wait for a drain.
161    pub(crate) results: Vec<FrameResult>,
162    /// Whether the frame wake ran since the last drain.
163    pub(crate) frame_woken: bool,
164    /// Whether the redraw wake may run: from the last demand until it runs.
165    /// Once it ran, the map has something new to draw that no demand has
166    /// answered.
167    pub(crate) redraw_armed: bool,
168    /// The frame pacer that takes the redraw wake's place, while one paces
169    /// the session.
170    pacing: Option<Pacing>,
171    /// The attach's completion, until the map binds the session.
172    pub(crate) attach: Option<Resolver<()>>,
173    /// The completions of the detaches on their way.
174    pub(crate) detach_waiters: Vec<Resolver<()>>,
175    /// The completions of the releases on their way.
176    pub(crate) release_waiters: Vec<Resolver<()>>,
177    /// The completions of the work that waits for the session's thread.
178    pending: BTreeMap<WorkId, Box<dyn PendingWork>>,
179    next_work: u64,
180    /// The session's map, until the session lets go of it.
181    pub(crate) map: Option<Map>,
182    /// What the session's thread builds the renderer from, until it does:
183    /// an [`Init`]. It is boxed as `Any` so that the state names no
184    /// graphics types, whose auto traits are deep to prove for every type
185    /// that holds a map handle.
186    pub(crate) init: Option<Box<dyn Any + Send>>,
187    /// Counts the resizes sent, which run on the map's thread before they
188    /// reach the session's.
189    pub(crate) resizes_sent: u64,
190    /// How many graphics objects the session's thread holds.
191    pub(crate) graphics_objects: u32,
192    /// Whether the session's thread keeps its graphics objects until the
193    /// process exits, instead of freeing them, when the session ends.
194    pub(crate) keep_graphics: bool,
195    /// Whether an abandon keeps the graphics objects on any thread, as
196    /// `Device::abandon_keeps_graphics` says of the session's device.
197    pub(crate) abandon_keeps_graphics: bool,
198    /// The slots of a borrowed ring, and none for another target.
199    pub(crate) ring: Vec<RingSlot>,
200    /// How many of the ring's frames the host holds.
201    pub(crate) acquired_frames: u32,
202    /// The ring replacements and releases on their way: no frame is
203    /// acquired until they ran, since the frames published before one name
204    /// textures it replaces or lets go of.
205    pub(crate) pending_retargets: u32,
206    /// How many views are open on the session's acquired frames.
207    pub(crate) views: u32,
208    /// Whether the session's thread keeps graphics objects that the open
209    /// views name, which it lets go of once the last view ends.
210    pub(crate) viewed_teardown: bool,
211}
212
213impl SessionState {
214    /// Keeps `resolver` until the session's thread takes it.
215    fn register<T: Send + 'static>(&mut self, resolver: Resolver<T>) -> WorkId {
216        self.next_work += 1;
217        let id = WorkId(self.next_work);
218        self.pending.insert(id, Box::new(resolver));
219        id
220    }
221
222    /// What an end of the session completes, once the state is unlocked.
223    pub(crate) fn take_waiters(&mut self) -> Waiters {
224        Waiters {
225            attach: self.attach.take(),
226            pending: std::mem::take(&mut self.pending).into_values().collect(),
227            detaches: std::mem::take(&mut self.detach_waiters),
228            releases: std::mem::take(&mut self.release_waiters),
229        }
230    }
231}
232
233/// The completions that wait for a session when it ends.
234pub(crate) struct Waiters {
235    attach: Option<Resolver<()>>,
236    pending: Vec<Box<dyn PendingWork>>,
237    detaches: Vec<Resolver<()>>,
238    releases: Vec<Resolver<()>>,
239}
240
241impl Waiters {
242    /// Completes the releases, and the detaches with `detached`. The attach
243    /// and the work that never ran fail with `lost`.
244    pub(crate) fn settle(self, detached: &Result<(), Error>, lost: impl Fn() -> Error) {
245        if let Some(attach) = self.attach {
246            attach.resolve(Err(lost()));
247        }
248        for work in self.pending {
249            work.fail(lost());
250        }
251        for waiter in self.detaches {
252            waiter.resolve(detached.clone());
253        }
254        for waiter in self.releases {
255            waiter.resolve(Ok(()));
256        }
257    }
258}
259
260/// Who abandons a session.
261#[derive(Clone, Copy, PartialEq, Eq)]
262pub(crate) enum Abandoner {
263    /// The host, through the handle.
264    Host,
265    /// The library, for a session that the host released, or stopped
266    /// servicing.
267    Library,
268}
269
270/// A session's frame pacer, and what waits for its refreshes.
271struct Pacing {
272    pacer: Arc<FramePacer>,
273    /// The session, as the pacer calls it back. Each pacing has its own, so
274    /// a refresh that an earlier pacing asked for demands nothing.
275    waiter: Arc<dyn RefreshWaiter>,
276}
277
278impl Pacing {
279    fn new(pacer: Arc<FramePacer>, session: Weak<SessionShared>) -> Self {
280        Self { pacer, waiter: Arc::new(PacedSession(session)) }
281    }
282
283    /// What asks the pacer for a refresh, in place of the redraw wake.
284    fn request(&self) -> Wake {
285        let (pacer, waiter) = (Arc::clone(&self.pacer), Arc::clone(&self.waiter));
286        Arc::new(move || pacer.request(&waiter))
287    }
288}
289
290/// A paced session, as its pacer holds it while it waits for a refresh.
291struct PacedSession(Weak<SessionShared>);
292
293impl RefreshWaiter for PacedSession {
294    fn refresh(&self, _time: Duration) {
295        if let Some(shared) = self.0.upgrade() {
296            shared.demand_paced(self);
297        }
298    }
299}
300
301pub(crate) struct SessionShared {
302    pub(crate) id: SessionId,
303    pub(crate) driver: Driver,
304    /// The work of the thread that runs the session.
305    pub(crate) queue: SessionQueue,
306    /// The thread that runs the session's work, once it is known: a core
307    /// worker's from the attach, and a caller thread's from when the host
308    /// takes the driver work.
309    pub(crate) thread: Arc<OnceLock<ThreadId>>,
310    /// The thread of the map's runtime, which runs the map's side of the
311    /// session's work.
312    runtime_thread: ThreadId,
313    pub(crate) state: Mutex<SessionState>,
314    /// Held while the session's thread runs a task, so an abandon waits for
315    /// the graphics work in progress.
316    pub(crate) gate: Mutex<()>,
317    /// The session's lease on the host's device, which an abandon revokes,
318    /// since graphics objects that it keeps hold the device.
319    lease: DeviceLease,
320    /// Held while [`RenderSession::send_then`] sends a command and attaches
321    /// its callback, and while an attach hands its completion out, which the
322    /// session's thread waits for before it delivers results.
323    sending: Mutex<()>,
324    /// Whether the session's thread is inside a driver call: a core worker
325    /// running a task and delivering what it sent the host, or a service of
326    /// a caller-driven session.
327    pub(crate) in_call: AtomicBool,
328    pub(crate) frame_wake: Option<Wake>,
329    pub(crate) redraw_wake: Option<Wake>,
330    capabilities: RenderSessionCapabilities,
331    driver_work_taken: AtomicBool,
332    /// Whether the driver-work wake may run: from the start of the last
333    /// service until it runs.
334    pub(crate) driver_armed: Arc<AtomicBool>,
335    /// The first of the map's commands that the session's work waits for,
336    /// or `u64::MAX` for none: the map tells the session's thread when it
337    /// ran a command only from that one on, so a command that no work waits
338    /// for wakes no caller's driver.
339    pub(crate) awaited_command: Arc<AtomicU64>,
340    /// In the browser, whether a caller-driven session waits for the device
341    /// that it asked the browser's WebGPU for: its services build nothing
342    /// until the device is there, and the driver-work wake runs then.
343    pub(crate) preparing: AtomicBool,
344}
345
346impl SessionShared {
347    /// A completion that the session's thread resolves.
348    fn completion<T: Send + 'static>(&self) -> (Completion<T>, Resolver<T>) {
349        Completion::at(Home::Later(Arc::clone(&self.thread), self.runtime_thread))
350    }
351
352    /// The completion of the work `id`, unless an end of the session
353    /// completed it first.
354    pub(crate) fn take_work<T: Send + 'static>(&self, id: WorkId) -> Option<Resolver<T>> {
355        let work: Box<dyn Any + Send> = self.state.lock().pending.remove(&id)?;
356        work.downcast::<Resolver<T>>().ok().map(|resolver| *resolver)
357    }
358
359    pub(crate) fn is_released(&self) -> bool {
360        self.state.lock().released
361    }
362
363    /// The redraw wake that tells the host the map has something new to
364    /// draw, unless the host was told since its last demand, or the session
365    /// has no target. The host isn't told again until its next demand.
366    pub(crate) fn take_redraw_wake(&self) -> Option<Wake> {
367        let mut state = self.state.lock();
368        let wake = state.redraw_armed && state.has_target && state.lifecycle == RenderSessionState::Attached;
369        state.redraw_armed &= !wake;
370        if !wake {
371            return None;
372        }
373        match &state.pacing {
374            Some(pacing) => Some(pacing.request()),
375            None => self.redraw_wake.clone(),
376        }
377    }
378
379    /// Sends `demand` to the session's thread. The state is locked.
380    fn demand_locked(&self, state: &mut SessionState, demand: FrameDemand) -> Result<(), Error> {
381        check_usable(state)?;
382        if !state.ring.is_empty() && state.ring.iter().all(|slot| slot.quarantined) {
383            return Err(Error::invalid_state(
384                "every texture of the ring is quarantined: give the session new textures",
385            ));
386        }
387        let (sequence, sample) = state.map.as_ref().map_or((0, 0), |map| (map.sent_sequence(), map.frame_demanded()));
388        state.redraw_armed = true;
389        worker::post(&self.queue, move |worker, outbox| worker.demand(demand, sequence, sample, outbox));
390        Ok(())
391    }
392
393    /// Demands the frame that the map has to draw at `waiter`'s refresh,
394    /// unless a demand came first or `waiter`'s pacing ended.
395    fn demand_paced(&self, waiter: &PacedSession) {
396        with_unlocked_wakes(|| {
397            let mut state = self.state.lock();
398            let current = state
399                .pacing
400                .as_ref()
401                .is_some_and(|pacing| core::ptr::addr_eq(Arc::as_ptr(&pacing.waiter), core::ptr::from_ref(waiter)));
402            if current && !state.redraw_armed {
403                // A session that failed or ended since it asked takes no demand.
404                let _ = self.demand_locked(&mut state, FrameDemand::new(super::DemandMode::IfChanged, 0));
405            }
406        });
407    }
408
409    /// Starts a detach on the session's thread, after the work sent before.
410    /// The state is locked, and the session usable or failed.
411    fn start_detach(&self, state: &mut SessionState) {
412        state.lifecycle = RenderSessionState::Detaching;
413        worker::post(&self.queue, Worker::detach);
414    }
415
416    /// Releases the session without waiting: it detaches, unless it is
417    /// detached or abandoned already, and every call on it fails after. A
418    /// caller-driven session that isn't attached, or whose map was released,
419    /// is abandoned instead, so the release doesn't wait for the host to
420    /// service it.
421    fn dispose(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
422        with_unlocked_wakes(|| self.dispose_locked(done))
423    }
424
425    /// Releases the session without waiting and without graphics calls past
426    /// the one in progress: a session that hasn't ended is abandoned, and
427    /// keeps its graphics objects until the process exits.
428    fn dispose_keeping_graphics(&self) -> Result<(), Error> {
429        with_unlocked_wakes(|| {
430            {
431                let mut state = self.state.lock();
432                if state.released {
433                    return Err(released());
434                }
435                state.released = true;
436                state.pacing = None;
437                state.keep_graphics = true;
438                if matches!(state.lifecycle, RenderSessionState::Detached | RenderSessionState::Abandoned) {
439                    return Ok(());
440                }
441            }
442            if self.abandon_locked(Abandoner::Library, true).is_err() {
443                // Only the session's own work could hold the gate here: the
444                // session detaches after it, keeping its graphics objects.
445                let mut state = self.state.lock();
446                if !matches!(
447                    state.lifecycle,
448                    RenderSessionState::Detaching | RenderSessionState::Detached | RenderSessionState::Abandoned
449                ) {
450                    self.start_detach(&mut state);
451                }
452            }
453            Ok(())
454        })
455    }
456
457    fn dispose_locked(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
458        let mut state = self.state.lock();
459        if state.released {
460            return Err(released());
461        }
462        state.released = true;
463        state.pacing = None;
464        // A released map waits for no service of its session's detach.
465        let map_released = state.map.as_ref().is_some_and(Map::is_released);
466        match state.lifecycle {
467            RenderSessionState::Detached | RenderSessionState::Abandoned => {
468                drop(state);
469                if let Some(done) = done {
470                    done.resolve(Ok(()));
471                }
472                return Ok(());
473            }
474            RenderSessionState::Detaching => {}
475            RenderSessionState::Attaching | RenderSessionState::Failed if self.driver == Driver::CallerThread => {
476                state.release_waiters.extend(done);
477                drop(state);
478                self.abandon_or_detach();
479                return Ok(());
480            }
481            RenderSessionState::Attached if self.driver == Driver::CallerThread && map_released => {
482                state.release_waiters.extend(done);
483                drop(state);
484                self.abandon_or_detach();
485                return Ok(());
486            }
487            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Failed => {
488                self.start_detach(&mut state);
489            }
490        }
491        state.release_waiters.extend(done);
492        Ok(())
493    }
494
495    /// Abandons the released session, or detaches it when its own work
496    /// holds the gate, which only it could here.
497    fn abandon_or_detach(&self) {
498        if self.abandon(Abandoner::Library).is_err() {
499            let mut state = self.state.lock();
500            if state.lifecycle != RenderSessionState::Abandoned {
501                self.start_detach(&mut state);
502            }
503        }
504    }
505
506    /// Stops the session at once, as [`RenderSession::abandon`] documents,
507    /// and returns how many graphics objects it keeps. The library may
508    /// abandon a released session too.
509    pub(crate) fn abandon(&self, by: Abandoner) -> Result<u32, Error> {
510        with_unlocked_wakes(|| self.abandon_locked(by, false))
511    }
512
513    /// Waits for a [`RenderSession::send_then`] in progress to attach its
514    /// callback. The session's thread calls it before it delivers what it
515    /// sent the host, so that a command's result reaches the callback there,
516    /// inside the driver call.
517    pub(crate) fn wait_for_senders(&self) {
518        drop(self.sending.lock());
519    }
520
521    /// Takes the sending lock, which the session's thread waits for before
522    /// it delivers results, unless this thread holds it already: a send
523    /// inside another, such as from a completion that a release settles at
524    /// once on this thread, is delivered after the outer one too.
525    fn hold_sending(&self) -> Option<Sending<'_>> {
526        if SENDING.with(|sending| sending.borrow().contains(&self.id)) {
527            return None;
528        }
529        let guard = self.sending.lock();
530        SENDING.with(|sending| sending.borrow_mut().push(self.id));
531        Some(Sending { id: self.id, _guard: guard })
532    }
533
534    /// Marks the session's thread as inside a driver call until the guard
535    /// drops.
536    pub(crate) fn enter_call(&self) -> InCall<'_> {
537        InCall { shared: self, previous: self.in_call.swap(true, Ordering::SeqCst) }
538    }
539
540    /// Abandons the session, which keeps its graphics objects until the
541    /// process exits if `keep_graphics`, and returns how many it keeps.
542    ///
543    /// A driver call can't be waited for on its own thread, where the
544    /// session's callbacks run inside it, and a host's service on another
545    /// thread is the host's to end, so either is busy. A core worker's call
546    /// on another thread is waited for. A caller-driven session that is
547    /// abandoned off its thread keeps its graphics objects, which only its
548    /// thread may free: once this returns, the host may destroy what they
549    /// were made on.
550    fn abandon_locked(&self, by: Abandoner, keep_graphics: bool) -> Result<u32, Error> {
551        let on_driver = self.thread.get() == Some(&std::thread::current().id());
552        if self.in_call.load(Ordering::SeqCst) {
553            if on_driver {
554                return Err(Error::busy("the render session's driver call is running on this thread"));
555            }
556            if self.driver == Driver::CallerThread && by == Abandoner::Host {
557                return Err(Error::busy("the render session's driver work is running on another thread"));
558            }
559        }
560        let off_thread = self.driver == Driver::CallerThread && !on_driver;
561        let gate = if on_driver {
562            self.gate.try_lock().ok_or_else(|| Error::busy("the render session is rendering on this thread"))?
563        } else {
564            self.gate.lock()
565        };
566        let (waiters, map, kept) = {
567            let mut state = self.state.lock();
568            if by == Abandoner::Host && state.released {
569                return Err(released());
570            }
571            match state.lifecycle {
572                RenderSessionState::Attaching
573                | RenderSessionState::Attached
574                | RenderSessionState::Detaching
575                | RenderSessionState::Failed => {}
576                RenderSessionState::Detached | RenderSessionState::Abandoned => {
577                    return Err(Error::invalid_state("the render session was detached or abandoned"));
578                }
579            }
580            // The views keep the frames' sync objects in place, which the
581            // abandon would let go of. A library's abandon, of a session
582            // that the host released, keeps them until the views end.
583            if by == Abandoner::Host && state.views != 0 {
584                return Err(Error::busy("a view is open on one of the render session's acquired frames"));
585            }
586            state.lifecycle = RenderSessionState::Abandoned;
587            state.keep_graphics |= keep_graphics || off_thread || state.abandon_keeps_graphics;
588            let kept = if state.keep_graphics { state.graphics_objects } else { 0 };
589            (state.take_waiters(), state.map.take(), kept)
590        };
591        match &map {
592            // The map unbinds the session before another can attach.
593            Some(map) => {
594                map.unbind_session_then(self.id, self.queue.clone(), Worker::finish);
595                map.release_session_claim(self.id);
596            }
597            None => worker::post(&self.queue, Worker::finish),
598        }
599        // A core worker lets go of its graphics objects at its next task,
600        // which runs before this returns: the host may destroy what they were
601        // made on once it does.
602        // In the browser the session's queue runs on this thread, which runs
603        // that task here instead, unless it is inside the session's work.
604        #[cfg(target_family = "wasm")]
605        let run_now = self.driver == Driver::CoreWorker
606            && !self.in_call.load(Ordering::SeqCst)
607            && !SENDING.with(|sending| sending.borrow().contains(&self.id));
608        let torn_down = (self.driver == Driver::CoreWorker && !on_driver).then(|| {
609            let (sender, receiver) = std::sync::mpsc::sync_channel::<()>(1);
610            worker::post(&self.queue, move |_, _| {
611                let _ = sender.send(());
612            });
613            receiver
614        });
615        drop(gate);
616        if let Some(receiver) = torn_down {
617            // A worker that ended drops the task, and the sender with it.
618            let _ = receiver.recv();
619        }
620        #[cfg(target_family = "wasm")]
621        if run_now {
622            worker::post(&self.queue, |_, _| {});
623            crate::web::run_session_now(self.id);
624        }
625        // Off the session's thread, the session makes no more graphics
626        // calls: a core worker tore down above, and a caller-driven session
627        // keeps its graphics objects. On it, the teardown that follows
628        // still needs the device.
629        if !on_driver {
630            self.lease.revoke();
631        }
632        if kept != 0 {
633            let reason = if keep_graphics {
634                "it was abandoned without graphics calls"
635            } else if off_thread {
636                "only the thread that services it may free them"
637            } else {
638                "only a detach frees OpenGL and WebGPU objects"
639            };
640            log::warn!(
641                target: log_target::RENDER,
642                "An abandoned render session keeps {kept} graphics objects until the process exits: {reason}"
643            );
644        }
645        let lost = || Error::target_lost("the render session was abandoned");
646        waiters.settle(&Err(lost()), lost);
647        drop(map);
648        Ok(kept)
649    }
650}
651
652/// Marks a session's thread as inside a driver call, as
653/// [`SessionShared::enter_call`] does.
654pub(crate) struct InCall<'a> {
655    shared: &'a SessionShared,
656    previous: bool,
657}
658
659impl Drop for InCall<'_> {
660    fn drop(&mut self) {
661        self.shared.in_call.store(self.previous, Ordering::SeqCst);
662    }
663}
664
665fn released() -> Error {
666    Error::invalid_state("the render session was released")
667}
668
669/// Fails unless the session takes work: it is attaching or attached, and
670/// not released.
671fn check_usable(state: &SessionState) -> Result<(), Error> {
672    if state.released {
673        return Err(released());
674    }
675    match state.lifecycle {
676        RenderSessionState::Attaching | RenderSessionState::Attached => Ok(()),
677        RenderSessionState::Failed => {
678            Err(state.failure.clone().unwrap_or_else(|| Error::native("the render session failed")))
679        }
680        RenderSessionState::Detaching | RenderSessionState::Detached | RenderSessionState::Abandoned => {
681            Err(Error::invalid_state("the render session is not attached: it was detached or abandoned"))
682        }
683    }
684}
685
686thread_local! {
687    /// The driver wakes that this thread's posts asked for during a handle
688    /// call, which may hold the session's locks.
689    static DEFERRED_WAKES: RefCell<Option<Vec<Wake>>> = const { RefCell::new(None) };
690    /// The sessions whose sending lock this thread holds.
691    static SENDING: RefCell<Vec<SessionId>> = const { RefCell::new(Vec::new()) };
692}
693
694/// A session's sending lock, which [`SessionShared::hold_sending`] took.
695struct Sending<'a> {
696    id: SessionId,
697    _guard: parking_lot::MutexGuard<'a, ()>,
698}
699
700impl Drop for Sending<'_> {
701    fn drop(&mut self) {
702        SENDING.with(|sending| sending.borrow_mut().retain(|id| *id != self.id));
703    }
704}
705
706/// Runs `call`, which may post to a session's queue with the session's locks
707/// held, then the driver wakes that its posts asked for, with nothing locked.
708fn with_unlocked_wakes<R>(call: impl FnOnce() -> R) -> R {
709    let outer = DEFERRED_WAKES.with(|deferred| deferred.borrow_mut().replace(Vec::new()));
710    let result = call();
711    let wakes = DEFERRED_WAKES.with(|deferred| {
712        let mut deferred = deferred.borrow_mut();
713        let wakes = deferred.take().unwrap_or_default();
714        match outer {
715            // The outer call runs them.
716            Some(mut outer) => {
717                outer.extend(wakes);
718                *deferred = Some(outer);
719                Vec::new()
720            }
721            None => wakes,
722        }
723    });
724    for wake in wakes {
725        wake();
726    }
727    result
728}
729
730/// Runs `wake` now, or once the handle call on this thread returns.
731fn wake_unlocked(wake: &Wake) {
732    let deferred = DEFERRED_WAKES.with(|deferred| match deferred.borrow_mut().as_mut() {
733        Some(wakes) => {
734            wakes.push(Arc::clone(wake));
735            true
736        }
737        None => false,
738    });
739    if !deferred {
740        wake();
741    }
742}
743
744/// Sizes in pixels a target of `size` logical pixels at `pixel_ratio`.
745pub(crate) fn physical_size(size: Size, pixel_ratio: f32) -> Size {
746    Size::new((size.width as f32 * pixel_ratio) as u32, (size.height as f32 * pixel_ratio) as u32)
747}
748
749/// A render session: a renderer that draws a map into a target, on a thread
750/// of its own or on the host's.
751///
752/// The host demands frames, which finish with [`FrameResult`]s that
753/// [`drain_frame_results`](Self::drain_frame_results) takes. A demand shows
754/// the map's commands sent before it, except the changes that an open
755/// command group holds back. The session's work runs on its thread in the
756/// order it was sent, and reports through a [`Completion`]. `Clone` is
757/// another handle to the same session, and any thread may use one.
758///
759/// A session that attached with [`Driver::CallerThread`] runs its work only
760/// when the host services its [`DriverWork`], which
761/// [`take_driver_work`](Self::take_driver_work) hands out.
762///
763/// The session lives until [`detach`](Self::detach),
764/// [`release`](Self::release), [`dispose`](Self::dispose) or
765/// [`abandon`](Self::abandon), or until its last handle drops, and it holds
766/// its map until then. A call that sends work to a session that no longer
767/// takes it fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind), or
768/// with the failure of a session that failed.
769///
770/// Unless the session was released or disposed, the last drop of its
771/// handles, [`AcquiredFrame`]s and [`FrameView`]s waits for a core worker's
772/// thread to end, once the session has let go of its graphics objects and
773/// its map. A drop on a thread of the library, such as in a callback or a
774/// wake that the library runs, doesn't wait: it leaves the session's thread
775/// to end alone.
776#[derive(Clone)]
777pub struct RenderSession {
778    handle: Arc<SessionHandle>,
779}
780
781/// Disposes of the session when the last handle drops.
782struct SessionHandle {
783    shared: Arc<SessionShared>,
784    thread_end: ThreadEnd,
785}
786
787/// A core worker's thread, which the last of the host's handles, frames and
788/// views of the session to drop waits for. A caller-driven session has no
789/// thread, and in the browser the thread is the host's.
790type ThreadEnd = Option<Arc<Joined>>;
791
792impl Drop for SessionHandle {
793    /// Disposes of the session, which ends its thread once the frames and
794    /// views of it end too, then waits for the thread as `thread_end` drops,
795    /// unless they hold it.
796    fn drop(&mut self) {
797        let _ = self.shared.dispose(None);
798    }
799}
800
801impl std::fmt::Debug for RenderSession {
802    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
803        f.debug_struct("RenderSession").field("id", &self.shared().id).finish()
804    }
805}
806
807impl PartialEq for RenderSession {
808    fn eq(&self, other: &RenderSession) -> bool {
809        Arc::ptr_eq(&self.handle, &other.handle)
810    }
811}
812
813impl Eq for RenderSession {}
814
815/// Attaches a session to `map`, as [`Map::attach`] documents, and runs `then`
816/// with the session and the attach's completion before the session's thread
817/// may deliver that, as [`Map::attach_then`] documents.
818pub(crate) fn attach<R>(
819    map: &Map,
820    target: RenderTarget,
821    options: AttachOptions,
822    then: impl FnOnce(&RenderSession, Completion<()>) -> R,
823) -> Result<R, Error> {
824    // The wakes that the attach runs, such as a caller-driven session's
825    // driver-work wake, wait for the release of the session's sending lock,
826    // so a host's wake that services the session can't wait for it.
827    with_unlocked_wakes(|| attach_unlocked(map, target, options, then))
828}
829
830fn attach_unlocked<R>(
831    map: &Map,
832    target: RenderTarget,
833    options: AttachOptions,
834    then: impl FnOnce(&RenderSession, Completion<()>) -> R,
835) -> Result<R, Error> {
836    static NEXT_ID: AtomicU64 = AtomicU64::new(1);
837    let id = SessionId(NEXT_ID.fetch_add(1, Ordering::Relaxed));
838    let mut ring = None;
839    let mut export_kind = None;
840    let (size, target) = match target {
841        RenderTarget::Offscreen { size, device } => (size, TargetInit::Offscreen(device)),
842        RenderTarget::Surface { size, surface, device } => {
843            if device.is_none() && !surface.needs_no_device() {
844                return Err(Error::invalid_argument("a surface that the host made needs the host's device"));
845            }
846            surface.check_area()?;
847            surface.check_pixel_format(device.as_ref())?;
848            (size, TargetInit::Surface { surface: SentSurface::new(surface, id), device })
849        }
850        RenderTarget::Borrowed { size, ring: borrowed, device } => {
851            let (producer, consumer) = device.borrowed_sync_kinds(&borrowed)?;
852            let picked = options.producer_sync_kinds.pick(producer).ok_or_else(|| {
853                Error::unsupported("render target supports none of the requested producer sync kinds")
854            })?;
855            if borrowed.depth() == 0 || borrowed.physical_size().is_empty() {
856                return Err(Error::invalid_argument("a borrowed ring needs textures of a size"));
857            }
858            ring = Some((borrowed.depth(), picked, consumer));
859            (size, TargetInit::Borrowed { ring: borrowed, device, producer: picked })
860        }
861        RenderTarget::Exported { size, ring: exported, device } => {
862            if exported.depth == 0 {
863                return Err(Error::invalid_argument("an exported ring needs at least one image"));
864            }
865            if exported.kinds.is_empty() {
866                return Err(Error::invalid_argument("an exported ring needs a kind of image to share"));
867            }
868            if size.is_empty() {
869                return Err(Error::invalid_argument("the target's size must not be empty"));
870            }
871            let device = match device {
872                Some(device) => device,
873                None => Device::for_exported_ring(&exported)?,
874            };
875            let (kind, producer, consumer) = device.export_plan(&exported)?;
876            let picked = options.producer_sync_kinds.pick(producer).ok_or_else(|| {
877                Error::unsupported("render target supports none of the requested producer sync kinds")
878            })?;
879            ring = Some((exported.depth, picked, consumer));
880            export_kind = Some(kind);
881            (size, TargetInit::Exported { ring: exported, device, kind, producer: picked })
882        }
883    };
884    if size.is_empty() {
885        return Err(Error::invalid_argument("the target's size must not be empty"));
886    }
887    let (target, lease) = target.lease();
888    let presentation = matches!(target, TargetInit::Surface { .. });
889    let queue = SessionQueue::default();
890    let driver_armed = Arc::new(AtomicBool::new(true));
891    if options.driver == Driver::CallerThread
892        && let Some(wake) = options.driver_work_wake
893    {
894        let armed = Arc::clone(&driver_armed);
895        queue.set_waker(Some(Arc::new(move || {
896            if armed.swap(false, Ordering::SeqCst) {
897                wake_unlocked(&wake);
898            }
899        })));
900    }
901    let scale_factor = map.scale_factor();
902    let shared = Arc::new(SessionShared {
903        id,
904        driver: options.driver,
905        queue: queue.clone(),
906        thread: Arc::default(),
907        runtime_thread: map.runtime_thread(),
908        state: Mutex::new(SessionState {
909            lifecycle: RenderSessionState::Attaching,
910            released: false,
911            size,
912            scale_factor,
913            sent_scale_factor: scale_factor,
914            generation: 1,
915            frame_generation: 0,
916            failure: None,
917            has_target: true,
918            results: Vec::new(),
919            frame_woken: false,
920            redraw_armed: true,
921            pacing: None,
922            attach: None,
923            detach_waiters: Vec::new(),
924            release_waiters: Vec::new(),
925            pending: BTreeMap::new(),
926            next_work: 0,
927            map: Some(map.clone()),
928            init: Some(Box::new(Init {
929                target,
930                size,
931                scale_factor,
932                glyph_cache: map.glyph_cache(),
933                font_face_engine: map.font_face_engine(),
934                registry: Arc::clone(map.registry()),
935                tile_cache_enabled: map.tile_cache_enabled(),
936                tile_worker_instances: map.tile_worker_instances(),
937                local_glyphs: map.local_glyphs(),
938                failure: None,
939                pool: map.pool(),
940            })),
941            resizes_sent: 0,
942            graphics_objects: 0,
943            keep_graphics: false,
944            abandon_keeps_graphics: false,
945            ring: vec![RingSlot::default(); ring.map_or(0, |(depth, _, _)| depth)],
946            acquired_frames: 0,
947            pending_retargets: 0,
948            views: 0,
949            viewed_teardown: false,
950        }),
951        gate: Mutex::new(()),
952        lease,
953        frame_wake: options.frame_wake,
954        redraw_wake: options.redraw_wake,
955        capabilities: RenderSessionCapabilities {
956            driver: options.driver,
957            texture_ring_depth: ring.map_or(1, |(depth, _, _)| depth as u32),
958            frame_acquisition: ring.is_some(),
959            readback: !presentation && ring.is_none(),
960            presentation,
961            producer_sync_kind: ring.map(|(_, producer, _)| producer),
962            consumer_sync_kinds: ring.map_or(SyncKinds::NONE, |(_, _, consumer)| consumer),
963            export_kind,
964        },
965        driver_work_taken: AtomicBool::new(false),
966        driver_armed,
967        awaited_command: Arc::new(AtomicU64::new(u64::MAX)),
968        preparing: AtomicBool::new(false),
969        in_call: AtomicBool::new(false),
970        sending: Mutex::new(()),
971    });
972    let (completion, resolver) = shared.completion();
973    shared.state.lock().attach = Some(resolver);
974    // Held until `then` returns: the session's thread delivers the attach's
975    // result after, inside its driver call.
976    let sending = Arc::clone(&shared);
977    let held = sending.hold_sending();
978    map.claim_session(id, Arc::downgrade(&shared))?;
979    let mut thread_end = None;
980    if options.driver == Driver::CoreWorker {
981        match start_thread(Arc::clone(&shared)) {
982            Ok((thread, end)) => {
983                let _ = shared.thread.set(thread);
984                thread_end = end.map(Arc::new);
985            }
986            Err(error) => {
987                map.release_session_claim(id);
988                return Err(error);
989            }
990        }
991    }
992    let session = RenderSession { handle: Arc::new(SessionHandle { shared, thread_end }) };
993    if let Err(error) = map.bind_session(id, queue, Arc::clone(&session.shared().awaited_command), size) {
994        // The map was released meanwhile: the session lets go of it. Its
995        // drop waits for its thread, which waits for the sending lock.
996        drop(held);
997        drop(session);
998        return Err(error);
999    }
1000    if options.driver == Driver::CallerThread {
1001        #[cfg(target_family = "wasm")]
1002        prepare_caller_driven(session.shared());
1003        // The first service builds the renderer, which is work that is ready
1004        // now: this wakes the host, unless the map's first update, posted
1005        // from the runtime's thread, woke it already.
1006        session.shared().queue.wake();
1007    }
1008    let attached = then(&session, completion);
1009    // Before the session, whose drop may wait for its thread, which waits
1010    // for the sending lock.
1011    drop(held);
1012    Ok(attached)
1013}
1014
1015/// Starts a core worker's thread, which builds the session's renderer, then
1016/// runs the session's queue until the session ends.
1017#[cfg(not(target_family = "wasm"))]
1018fn start_thread(shared: Arc<SessionShared>) -> Result<(ThreadId, Option<Joined>), Error> {
1019    let thread = mln_engine::exec::thread::spawn("RenderSession", move || {
1020        let queue = shared.queue.clone();
1021        let mut worker = None;
1022        worker::build(&shared, &mut worker, &mut None);
1023        // The worker holds the session from here on.
1024        drop(shared);
1025        queue.run(&mut worker);
1026        // The session's work that comes from now on drops at once, so tasks
1027        // that hold the queue can't keep it alive.
1028        queue.close();
1029        drop(worker);
1030    })
1031    .map_err(|error| Error::native(format!("can't start the render session's thread: {error}")))?;
1032    let thread_id = thread.thread().id();
1033    // The thread ends by itself once the session ends.
1034    Ok((thread_id, Some(Joined::new(thread))))
1035}
1036
1037/// Runs a core worker on this thread, the browser's one, in the instance's
1038/// pump: it builds the session's renderer once its device is ready, which
1039/// may take the browser's WebGPU a while, then runs the session's queue until
1040/// the session ends.
1041#[cfg(target_family = "wasm")]
1042#[expect(clippy::unnecessary_wraps, reason = "the threads of other builds can fail to start")]
1043fn start_thread(shared: Arc<SessionShared>) -> Result<(ThreadId, Option<Joined>), Error> {
1044    let prepared = worker::prepare(&shared);
1045    wasm_bindgen_futures::spawn_local(async move {
1046        prepared.await;
1047        let queue = shared.queue.clone();
1048        let mut worker = None;
1049        worker::build(&shared, &mut worker, &mut None);
1050        let id = shared.id;
1051        // The worker holds the session from here on.
1052        drop(shared);
1053        let worker = RefCell::new(worker);
1054        crate::web::drive_session(id, queue.clone(), move || {
1055            queue.run_once(&mut worker.borrow_mut());
1056            if queue.is_stopped() {
1057                queue.close();
1058                drop(worker.borrow_mut().take());
1059            }
1060        });
1061    });
1062    Ok((std::thread::current().id(), None))
1063}
1064
1065/// In the browser, asks for the device that a caller-driven session's build
1066/// needs, as a core worker does before it builds, and wakes the host to
1067/// service the session once the device is there.
1068#[cfg(target_family = "wasm")]
1069fn prepare_caller_driven(shared: &Arc<SessionShared>) {
1070    shared.preparing.store(true, Ordering::SeqCst);
1071    let prepared = worker::prepare(shared);
1072    let shared = Arc::downgrade(shared);
1073    wasm_bindgen_futures::spawn_local(async move {
1074        prepared.await;
1075        if let Some(shared) = shared.upgrade() {
1076            shared.preparing.store(false, Ordering::SeqCst);
1077            shared.queue.wake();
1078        }
1079    });
1080}
1081
1082impl RenderSession {
1083    fn shared(&self) -> &Arc<SessionShared> {
1084        &self.handle.shared
1085    }
1086
1087    /// Sends a command with `send`, such as [`barrier`](Self::barrier), and
1088    /// calls `callback` once with its result, where the session delivers
1089    /// it: on the session's thread, inside its driver call, even when the
1090    /// command runs before `send` returns. A [`Completion::on_complete`]
1091    /// after the command returned would run at once on this thread instead.
1092    /// The callback doesn't run when `send` fails.
1093    ///
1094    /// Fails as `send` does.
1095    pub fn send_then<T: Send + 'static>(
1096        &self,
1097        send: impl FnOnce(&RenderSession) -> Result<Completion<T>, Error>,
1098        callback: impl FnOnce(Result<T, Error>) + Send + 'static,
1099    ) -> Result<(), Error> {
1100        // The wakes that the command runs wait for the lock's release, so a
1101        // host's wake that services the session can't wait for it.
1102        with_unlocked_wakes(|| {
1103            let ready = {
1104                let _sending = self.shared().hold_sending();
1105                send(self)?.on_complete_unless_ready(callback)
1106            };
1107            // A result that came without the session's thread, such as a
1108            // command dropped unrun, goes to the callback here.
1109            if let Some((callback, result)) = ready {
1110                callback(result);
1111            }
1112            Ok(())
1113        })
1114    }
1115
1116    /// Sends `task` to the session's thread, after the work sent before,
1117    /// resizes included, and completes with its result. A session that lost
1118    /// its graphics objects before the task runs completes it with
1119    /// [`ErrorKind::TargetLost`](mln_style::error::ErrorKind).
1120    pub(crate) fn operation<T: Send + 'static>(
1121        &self,
1122        task: impl FnOnce(&mut Worker, &mut Outbox) -> Result<T, Error> + Send + 'static,
1123    ) -> Result<Completion<T>, Error> {
1124        let shared = self.shared();
1125        with_unlocked_wakes(|| {
1126            let mut state = shared.state.lock();
1127            check_usable(&state)?;
1128            let (completion, resolver) = shared.completion();
1129            let work = state.register(resolver);
1130            let resizes = state.resizes_sent;
1131            worker::post(&shared.queue, move |worker, outbox| {
1132                let task: worker::Task = Box::new(move |worker, outbox| {
1133                    let Some(resolver) = worker.take_work(work) else { return };
1134                    let result = task(worker, outbox);
1135                    outbox.resolve(resolver, result);
1136                });
1137                worker.after_earlier_work(resizes, task, outbox);
1138            });
1139            drop(state);
1140            Ok(completion)
1141        })
1142    }
1143
1144    /// Hands out the work of a [`Driver::CallerThread`] session, for the
1145    /// calling thread to run: the session's graphics work runs only in its
1146    /// [`service`](DriverWork::service), and on no other thread.
1147    ///
1148    /// Take it once, on the host's graphics thread, from the attach on: the
1149    /// attach itself completes in a service. It stays available after a
1150    /// release, which the host services to its end.
1151    ///
1152    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
1153    /// session on a core worker, and with
1154    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once it was taken.
1155    pub fn take_driver_work(&self) -> Result<DriverWork, Error> {
1156        let shared = self.shared();
1157        if shared.driver != Driver::CallerThread {
1158            return Err(Error::unsupported("the render session runs on a core worker"));
1159        }
1160        if shared.driver_work_taken.swap(true, Ordering::SeqCst) {
1161            return Err(Error::invalid_state("the render session's driver work was taken already"));
1162        }
1163        let _ = shared.thread.set(std::thread::current().id());
1164        Ok(DriverWork::new(Arc::clone(shared)))
1165    }
1166
1167    /// What the session can do. Fails with
1168    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once it is released.
1169    pub fn capabilities(&self) -> Result<RenderSessionCapabilities, Error> {
1170        let state = self.shared().state.lock();
1171        if state.released {
1172            return Err(released());
1173        }
1174        Ok(self.shared().capabilities)
1175    }
1176
1177    /// The session's state now. Fails with
1178    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once it is released.
1179    pub fn snapshot(&self) -> Result<RenderSessionSnapshot, Error> {
1180        let state = self.shared().state.lock();
1181        if state.released {
1182            return Err(released());
1183        }
1184        Ok(RenderSessionSnapshot {
1185            state: state.lifecycle,
1186            extent: LogicalExtent { size: state.size, scale_factor: state.scale_factor },
1187            generation: state.generation,
1188            frame_generation: state.frame_generation,
1189            failure: state.failure.clone(),
1190            has_target: state.lifecycle == RenderSessionState::Attached && state.has_target,
1191            acquired_frames: state.acquired_frames,
1192        })
1193    }
1194
1195    /// Takes the newest frame that a borrowed ring rendered, if one waits:
1196    /// the older frames that the host didn't acquire are dropped, and the
1197    /// session may render into their textures again. While the host holds a
1198    /// frame in every texture, demands wait for a release.
1199    ///
1200    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
1201    /// session without a ring, and as a call that sends work does once the
1202    /// session no longer takes work.
1203    pub fn acquire_frame(&self) -> Result<Option<AcquiredFrame>, Error> {
1204        let shared = self.shared();
1205        let mut state = shared.state.lock();
1206        check_usable(&state)?;
1207        if !shared.capabilities.frame_acquisition {
1208            return Err(Error::unsupported("render session does not expose acquired texture frames"));
1209        }
1210        if state.pending_retargets != 0 {
1211            return Ok(None);
1212        }
1213        let newest = state
1214            .ring
1215            .iter()
1216            .enumerate()
1217            .filter(|(_, slot)| !slot.acquired && slot.frame.is_some())
1218            .max_by_key(|(_, slot)| slot.frame.as_ref().map_or(0, |frame| frame.result.frame_generation))
1219            .map(|(index, _)| index);
1220        let Some(index) = newest else { return Ok(None) };
1221        for (other, slot) in state.ring.iter_mut().enumerate() {
1222            if other != index && !slot.acquired {
1223                slot.frame = None;
1224            }
1225        }
1226        let slot = &mut state.ring[index];
1227        let Some(frame) = slot.frame.take() else { return Ok(None) };
1228        slot.acquired = true;
1229        state.acquired_frames += 1;
1230        Ok(Some(AcquiredFrame {
1231            shared: Arc::clone(shared),
1232            thread_end: self.handle.thread_end.clone(),
1233            slot: index,
1234            frame,
1235            done: false,
1236        }))
1237    }
1238
1239    /// Gives a borrowed ring new textures, of `size` logical pixels: as many
1240    /// as it has, of its format. The completion reports the map's change and
1241    /// the sync after which the host may use the old textures that the new
1242    /// ring doesn't have, as [`release_target`](Self::release_target) says.
1243    ///
1244    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
1245    /// session without a borrowed ring, with
1246    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for another number
1247    /// of textures, and with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
1248    /// while the host holds one of the ring's frames. Completes with
1249    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for textures of
1250    /// another format or kind.
1251    pub fn set_ring(&self, size: Size, ring: BorrowedRing) -> Result<Completion<(Applied, GpuSync)>, Error> {
1252        let shared = Arc::clone(self.shared());
1253        {
1254            let mut state = shared.state.lock();
1255            check_usable(&state)?;
1256            if shared.capabilities.readback {
1257                return Err(Error::unsupported("an offscreen session keeps its target"));
1258            }
1259            if !shared.capabilities.frame_acquisition {
1260                return Err(Error::unsupported("a surface session takes no caller-owned texture"));
1261            }
1262            if shared.capabilities.export_kind.is_some() {
1263                return Err(Error::unsupported("an exported ring resizes instead of taking new textures"));
1264            }
1265            if state.acquired_frames != 0 {
1266                return Err(Error::invalid_state("cannot replace the render target while a texture frame is acquired"));
1267            }
1268            if ring.depth() != state.ring.len() {
1269                return Err(Error::invalid_argument(
1270                    "texture_count must equal the ring depth the session attached with",
1271                ));
1272            }
1273            state.pending_retargets += 1;
1274        }
1275        let guard = RetargetGuard(Arc::clone(&shared));
1276        // The guard goes with the closure, whether the closure runs or the
1277        // resize drops it.
1278        self.resize_then(size, None, move |worker, size, scale_factor, applied, outbox| {
1279            let _guard = guard;
1280            Ok((applied, worker.set_ring(size, scale_factor, &ring, outbox)?))
1281        })
1282    }
1283
1284    /// Asks the session to render a frame, which shows the map commands sent
1285    /// before the call, except the changes that an open command group holds
1286    /// back, and the map's animations as they are at the call: demand each
1287    /// frame at the display's pace. A demand sent while the session attaches
1288    /// waits for it.
1289    ///
1290    /// Every demand finishes with one [`FrameResult`] that carries its token.
1291    /// A demand that isn't [`DemandMode::Force`](super::DemandMode::Force)
1292    /// replaces the demands with the same mode still on their way, which
1293    /// finish as [`FrameDisposition::Superseded`](super::FrameDisposition).
1294    /// While the session has no target, or a surface has no texture to
1295    /// render into, a demand finishes as
1296    /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition).
1297    pub fn demand_frame(&self, demand: FrameDemand) -> Result<(), Error> {
1298        let shared = self.shared();
1299        with_unlocked_wakes(|| shared.demand_locked(&mut shared.state.lock(), demand))
1300    }
1301
1302    /// Paces the session's frames with `pacer`, or with none, stops. At the
1303    /// first refresh that the pacer allows after the map has something new to
1304    /// draw, it demands a frame in
1305    /// [`DemandMode::IfChanged`](super::DemandMode::IfChanged) with token 0,
1306    /// unless a demand came first. One pacer can pace many sessions.
1307    ///
1308    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a
1309    /// session with a redraw wake.
1310    pub fn set_frame_pacer(&self, pacer: Option<Arc<FramePacer>>) -> Result<(), Error> {
1311        let shared = self.shared();
1312        let request = {
1313            let mut state = shared.state.lock();
1314            check_usable(&state)?;
1315            if shared.redraw_wake.is_some() {
1316                return Err(Error::invalid_state("a render session with a redraw wake takes no frame pacer"));
1317            }
1318            let same = match (&state.pacing, &pacer) {
1319                (Some(pacing), Some(pacer)) => Arc::ptr_eq(&pacing.pacer, pacer),
1320                (None, None) => true,
1321                _ => false,
1322            };
1323            if same {
1324                return Ok(());
1325            }
1326            state.pacing = pacer.map(|pacer| Pacing::new(pacer, Arc::downgrade(shared)));
1327            state.pacing.as_ref().filter(|_| !state.redraw_armed).map(Pacing::request)
1328        };
1329        if let Some(request) = request {
1330            request();
1331        }
1332        Ok(())
1333    }
1334
1335    /// Takes the frame results that wait, oldest first. Fails with
1336    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once the session is
1337    /// released.
1338    pub fn drain_frame_results(&self) -> Result<Vec<FrameResult>, Error> {
1339        let mut state = self.shared().state.lock();
1340        if state.released {
1341            return Err(released());
1342        }
1343        state.frame_woken = false;
1344        Ok(std::mem::take(&mut state.results))
1345    }
1346
1347    /// Resizes the target, and the map with it, to `extent`'s size in
1348    /// logical pixels, and sets the map's scale factor to `extent`'s, such
1349    /// as when a window moves to a display of another density. The map keeps
1350    /// its tiles, and the renderer draws the next frame at the new scale
1351    /// factor. A later demand shows the new extent, and one sent before
1352    /// shows the old. An exported ring gets images of the new size, and the
1353    /// frames that the host holds keep theirs until it gives them back.
1354    ///
1355    /// Fails first as a call that sends work does once the session no
1356    /// longer takes work. Then fails with
1357    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a borrowed ring,
1358    /// which [`set_ring`](Self::set_ring) resizes, and with
1359    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an empty size,
1360    /// or a scale factor that isn't finite and positive.
1361    pub fn resize(&self, extent: LogicalExtent) -> Result<Completion<Applied>, Error> {
1362        check_usable(&self.shared().state.lock())?;
1363        let capabilities = self.shared().capabilities;
1364        if capabilities.frame_acquisition && capabilities.export_kind.is_none() {
1365            return Err(Error::unsupported("a borrowed ring is sized by its owner: give it new textures instead"));
1366        }
1367        let LogicalExtent { size, scale_factor } = extent;
1368        if !scale_factor.is_finite() || scale_factor <= 0.0 {
1369            return Err(Error::invalid_argument(format!("scale factor {scale_factor} isn't finite and positive")));
1370        }
1371        self.resize_then(size, Some(scale_factor), |worker, size, scale_factor, applied, outbox| {
1372            worker.resize(size, scale_factor, outbox).map(|()| applied)
1373        })
1374    }
1375
1376    /// Sends a map command that resizes the map to `size`, at
1377    /// `scale_factor` or the session's when that is `None`, then runs
1378    /// `change` on the session's thread with the map's change, which resizes
1379    /// or replaces the target, and completes with its result.
1380    fn resize_then<T: Send + 'static>(
1381        &self,
1382        size: Size,
1383        scale_factor: Option<f64>,
1384        change: impl FnOnce(&mut Worker, Size, f64, Applied, &mut Outbox) -> Result<T, Error> + Send + 'static,
1385    ) -> Result<Completion<T>, Error> {
1386        if size.is_empty() {
1387            return Err(Error::invalid_argument("the target's size must not be empty"));
1388        }
1389        let shared = self.shared();
1390        with_unlocked_wakes(|| {
1391            let mut state = shared.state.lock();
1392            check_usable(&state)?;
1393            let map = state.map.clone().ok_or_else(|| Error::invalid_state("the render session has no map"))?;
1394            let scale_factor = scale_factor.unwrap_or(state.sent_scale_factor);
1395            state.sent_scale_factor = scale_factor;
1396            let (completion, resolver) = shared.completion();
1397            let work = state.register(resolver);
1398            // The work sent after waits for the resize to land, which it
1399            // does even when the map drops it.
1400            state.resizes_sent += 1;
1401            let landing = worker::ResizeLanding::new(shared.queue.clone());
1402            let sent =
1403                map.resize_for_session(size, scale_factor, shared.queue.clone(), move |worker, result, outbox| {
1404                    if let Some(resolver) = worker.take_work::<T>(work) {
1405                        let result = result.and_then(|applied| change(worker, size, scale_factor, applied, outbox));
1406                        outbox.resolve(resolver, result);
1407                    }
1408                    landing.land(worker, outbox);
1409                });
1410            if let Err(error) = sent {
1411                state.pending.remove(&work);
1412                return Err(error);
1413            }
1414            drop(state);
1415            Ok(completion)
1416        })
1417    }
1418
1419    /// Lets go of a surface session's surface, and keeps the rest of the
1420    /// session, such as when the platform takes the window away. The demands
1421    /// on their way, and later ones until
1422    /// [`set_surface`](Self::set_surface) gives the session a surface again,
1423    /// finish as [`FrameDisposition::TargetNotReady`](super::FrameDisposition).
1424    /// Once the release completes, the session no longer uses the surface or
1425    /// the window it was made from. For a ring, it completes with a sync of
1426    /// the session's producer kind, after which the host may use or destroy
1427    /// the textures: the session's GPU work on them, and its waits for the
1428    /// consumer syncs that they were given back with, end there. The session
1429    /// keeps the objects that the sync names until its next release or
1430    /// replacement of the target completes, or it ends. It keeps nothing of
1431    /// the released textures: one that a later ring has again starts fresh,
1432    /// even one that the host gave up.
1433    ///
1434    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for an
1435    /// offscreen session or an exported ring, whose targets are their own.
1436    /// Completes with [`ErrorKind::Native`](mln_style::error::ErrorKind) when a ring
1437    /// can't submit its work on the textures, which it keeps then.
1438    pub fn release_target(&self) -> Result<Completion<Option<GpuSync>>, Error> {
1439        if self.shared().capabilities.export_kind.is_some() {
1440            return Err(Error::unsupported("an exported ring keeps its images until the session ends"));
1441        }
1442        let shared = Arc::clone(self.shared());
1443        let capabilities = shared.capabilities;
1444        if !capabilities.presentation && !capabilities.frame_acquisition {
1445            check_usable(&shared.state.lock())?;
1446            return Err(Error::unsupported("an offscreen session keeps its target"));
1447        }
1448        let guard = {
1449            let mut state = shared.state.lock();
1450            check_usable(&state)?;
1451            if state.acquired_frames != 0 {
1452                return Err(Error::invalid_state("release every acquired frame before the target"));
1453            }
1454            // No frame is acquired until the release runs: its textures go
1455            // with it.
1456            capabilities.frame_acquisition.then(|| {
1457                state.pending_retargets += 1;
1458                RetargetGuard(Arc::clone(&shared))
1459            })
1460        };
1461        self.operation(move |worker, outbox| {
1462            let _guard = guard;
1463            worker.release_target(outbox)
1464        })
1465    }
1466
1467    /// Gives a surface session a new surface of `size` logical pixels, after
1468    /// [`release_target`](Self::release_target), or in place of the one it
1469    /// has, and resizes the map to it. Once the completion reports success,
1470    /// the session no longer uses the old surface. The session presents to
1471    /// it on its device: a window becomes a surface of the device's backend,
1472    /// and a `Surface::wgpu` must come from the instance of a WebGPU
1473    /// device. Where the backend made for the old surface can't present to
1474    /// the new one, as OpenGL ES's context can't to another window, the
1475    /// session makes its backend and renderer again.
1476    ///
1477    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an
1478    /// empty size, with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for
1479    /// an offscreen session, and with
1480    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a window that is
1481    /// minimized or has no client area. Completes with
1482    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when the session's
1483    /// device can't present to the surface in the format that the session
1484    /// renders in: attach a new session instead. Completes with
1485    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the window had no
1486    /// area to present to by then. The session then keeps the surface it had,
1487    /// at the new size.
1488    pub fn set_surface(&self, size: Size, surface: Surface) -> Result<Completion<Applied>, Error> {
1489        check_usable(&self.shared().state.lock())?;
1490        let capabilities = self.shared().capabilities;
1491        if capabilities.frame_acquisition {
1492            return Err(Error::unsupported("a borrowed texture session takes no native surface"));
1493        }
1494        if !capabilities.presentation {
1495            return Err(Error::unsupported("an offscreen session keeps its target"));
1496        }
1497        surface.check_area()?;
1498        let surface = SentSurface::new(surface, self.shared().id);
1499        self.resize_then(size, None, move |worker, size, scale_factor, applied, outbox| {
1500            worker.set_surface(size, scale_factor, surface.receive()?, outbox).map(|()| applied)
1501        })
1502    }
1503
1504    /// Ends the frame demands on their way, including those that wait for a
1505    /// map update and the demand of a still image, which finish as
1506    /// [`FrameDisposition::NoUpdate`](super::FrameDisposition), and completes
1507    /// once the work sent before it has run. A still image that still waits
1508    /// gets a new demand once the barrier ran.
1509    pub fn barrier(&self) -> Result<Completion<()>, Error> {
1510        self.operation(|worker, outbox| {
1511            worker.barrier(outbox);
1512            Ok(())
1513        })
1514    }
1515
1516    /// Frees memory that the renderer can rebuild, such as caches.
1517    pub fn reduce_memory_use(&self) -> Result<Completion<()>, Error> {
1518        self.operation(|worker, _| worker.reduce_memory_use())
1519    }
1520
1521    /// Clears what the renderer holds, such as loaded tiles, so that the
1522    /// next frame loads and draws the map again.
1523    pub fn clear_data(&self) -> Result<Completion<()>, Error> {
1524        self.operation(Worker::clear_data)
1525    }
1526
1527    /// Logs the renderer's sources and tiles.
1528    pub fn dump_debug_logs(&self) -> Result<Completion<()>, Error> {
1529        self.operation(|worker, _| worker.dump_debug_logs())
1530    }
1531
1532    /// The pixels of the last frame that an offscreen session rendered:
1533    /// premultiplied RGBA, in rows from top to bottom, at the target's size
1534    /// in pixels.
1535    ///
1536    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
1537    /// surface session. Completes with
1538    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the session
1539    /// hasn't rendered a frame since it attached or resized.
1540    pub fn read_texture(&self) -> Result<Completion<PremultipliedImage>, Error> {
1541        check_usable(&self.shared().state.lock())?;
1542        if !self.shared().capabilities.readback {
1543            return Err(Error::unsupported("a surface session can't read its frames back"));
1544        }
1545        self.operation(|worker, _| worker.read_texture())
1546    }
1547
1548    /// The features that the session drew in an area of the screen, in its
1549    /// last frame. A feature that several layers draw appears once for each.
1550    /// The topmost layer's features come first, and the bottom layer's last.
1551    /// A box covers only its part inside the target, so one past every edge
1552    /// covers the whole target.
1553    ///
1554    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
1555    /// point that isn't finite or a line string without points.
1556    pub fn query_rendered_features(
1557        &self,
1558        geometry: RenderedQueryGeometry,
1559        options: RenderedQueryOptions,
1560    ) -> Result<Completion<Vec<Feature>>, Error> {
1561        geometry.points()?;
1562        self.operation(move |worker, _| match geometry.within(worker.size()).map(|geometry| geometry.points()) {
1563            Some(points) => worker.renderer()?.query_rendered_features(&points?, &options),
1564            None => Ok(Vec::new()),
1565        })
1566    }
1567
1568    /// The features of the source `source_id` in the tiles that it loaded
1569    /// for the current view. A source loads tiles only while a visible layer
1570    /// uses it.
1571    ///
1572    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an
1573    /// empty `source_id`.
1574    pub fn query_source_features(
1575        &self,
1576        source_id: impl Into<String>,
1577        options: SourceQueryOptions,
1578    ) -> Result<Completion<Vec<Feature>>, Error> {
1579        let source_id = source_id_of(source_id)?;
1580        self.operation(move |worker, _| worker.renderer()?.query_source_features(&source_id, &options))
1581    }
1582
1583    /// The clusters and points that a cluster of a clustered GeoJSON source
1584    /// splits into at the next zoom level. `cluster_id` is a cluster
1585    /// feature's `cluster_id` property.
1586    ///
1587    /// The query reads the source as the session's most recent render
1588    /// attempt had it. A cluster ID belongs to one version of the source's
1589    /// data, so query the features again after the data changes.
1590    ///
1591    /// Completes with [`ErrorKind::NotFound`](mln_style::error::ErrorKind) when that
1592    /// render had no source `source_id`, or the source has no cluster
1593    /// `cluster_id`, and with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind)
1594    /// when the source isn't a clustered GeoJSON source.
1595    pub fn cluster_children(
1596        &self,
1597        source_id: impl Into<String>,
1598        cluster_id: u32,
1599    ) -> Result<Completion<Vec<mln_style::feature::Feature<f64>>>, Error> {
1600        let source_id = source_id_of(source_id)?;
1601        self.operation(move |worker, _| worker.cluster(&source_id, cluster_id, |_, children| Ok(children)))
1602    }
1603
1604    /// The points in a cluster of a clustered GeoJSON source: it skips the
1605    /// first `offset`, then holds up to `limit`. It fails as
1606    /// [`cluster_children`](Self::cluster_children) does.
1607    pub fn cluster_leaves(
1608        &self,
1609        source_id: impl Into<String>,
1610        cluster_id: u32,
1611        limit: u32,
1612        offset: u32,
1613    ) -> Result<Completion<Vec<mln_style::feature::Feature<f64>>>, Error> {
1614        let source_id = source_id_of(source_id)?;
1615        self.operation(move |worker, _| {
1616            worker.cluster(&source_id, cluster_id, |index, _| index.get_leaves(cluster_id, limit, offset))
1617        })
1618    }
1619
1620    /// The zoom level at which a cluster of a clustered GeoJSON source splits
1621    /// into two or more clusters or points. It fails as
1622    /// [`cluster_children`](Self::cluster_children) does.
1623    pub fn cluster_expansion_zoom(
1624        &self,
1625        source_id: impl Into<String>,
1626        cluster_id: u32,
1627    ) -> Result<Completion<u8>, Error> {
1628        let source_id = source_id_of(source_id)?;
1629        self.operation(move |worker, _| {
1630            worker.cluster(&source_id, cluster_id, |index, _| index.get_cluster_expansion_zoom(cluster_id))
1631        })
1632    }
1633
1634    /// Detaches the session from its map and frees its graphics objects. The
1635    /// demands on their way finish as
1636    /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition). Once
1637    /// the detach completes, another session can attach to the map.
1638    pub fn detach(&self) -> Result<Completion<()>, Error> {
1639        let shared = self.shared();
1640        with_unlocked_wakes(|| {
1641            let mut state = shared.state.lock();
1642            if !matches!(state.lifecycle, RenderSessionState::Failed) {
1643                check_usable(&state)?;
1644            } else if state.released {
1645                return Err(released());
1646            }
1647            if state.acquired_frames != 0 {
1648                return Err(Error::invalid_state("release every acquired frame before the session detaches"));
1649            }
1650            let (completion, resolver) = shared.completion();
1651            state.detach_waiters.push(resolver);
1652            shared.start_detach(&mut state);
1653            Ok(completion)
1654        })
1655    }
1656
1657    /// Stops the session at once, without its pending graphics work: that
1658    /// work completes with [`ErrorKind::TargetLost`](mln_style::error::ErrorKind)
1659    /// before this returns, and the demands on their way finish as
1660    /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition). Once it
1661    /// returns, the session renders no more, and another session can attach
1662    /// to the map. Release the session afterward.
1663    ///
1664    /// Returns how many graphics objects the session keeps until the
1665    /// process exits. A caller-driven session abandoned on the thread that
1666    /// services it lets go of them there, at its next service or when its
1667    /// [`DriverWork`] drops, and keeps none. Abandoned on another thread, it
1668    /// keeps them, since only that thread may free them, and logs a warning.
1669    ///
1670    /// It waits for a core worker's driver call on another thread, such as a
1671    /// frame that it renders. Fails with
1672    /// [`ErrorKind::Busy`](mln_style::error::ErrorKind) inside a driver call on the
1673    /// session's own thread, such as from a completion that the session
1674    /// delivers, and while a caller-driven session's service runs on another
1675    /// thread. Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
1676    /// once the session is detached, abandoned or released.
1677    pub fn abandon(&self) -> Result<u32, Error> {
1678        self.shared().abandon(Abandoner::Host)
1679    }
1680
1681    /// Abandons the session as [`abandon`](Self::abandon) does, but makes no
1682    /// graphics call: the session keeps its graphics objects until the
1683    /// process exits. Returns how many it keeps, such as its renderer and
1684    /// the backend it draws with.
1685    ///
1686    /// This is for a host whose shutdown may already have destroyed the
1687    /// graphics objects behind the session.
1688    pub fn abandon_keeping_graphics(&self) -> Result<u32, Error> {
1689        with_unlocked_wakes(|| self.shared().abandon_locked(Abandoner::Host, true))
1690    }
1691
1692    /// Releases the session, detaching it first when it is attached. The
1693    /// completion reports when the session has let go of its map and its
1694    /// graphics objects, and nothing waits for its thread to end after
1695    /// that. Every call on the session fails with
1696    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) after.
1697    ///
1698    /// A caller-driven session detaches at the host's next service, so keep
1699    /// servicing it until the release completes. One that isn't attached,
1700    /// such as while it attaches or after it failed, is abandoned instead,
1701    /// and so is one whose map is released before that service.
1702    pub fn release(&self) -> Result<Completion<()>, Error> {
1703        {
1704            let state = self.shared().state.lock();
1705            let live = matches!(state.lifecycle, RenderSessionState::Attaching | RenderSessionState::Attached);
1706            if live && !state.released && state.acquired_frames != 0 {
1707                return Err(Error::invalid_state("release every acquired frame before the session is released"));
1708            }
1709        }
1710        let (completion, resolver) = self.shared().completion();
1711        self.shared().dispose(Some(resolver))?;
1712        self.detach_thread();
1713        Ok(completion)
1714    }
1715
1716    /// Releases the session in any state, without waiting, and nothing waits
1717    /// for its thread to end. Dropping the last handle does the same, then
1718    /// waits for the thread.
1719    pub fn dispose(&self) -> Result<(), Error> {
1720        self.shared().dispose(None)?;
1721        self.detach_thread();
1722        Ok(())
1723    }
1724
1725    /// Releases the session in any state, without waiting and without a
1726    /// graphics call past the one in progress. A session that hasn't ended
1727    /// is abandoned, keeping its graphics objects until the process exits,
1728    /// as [`abandon_keeping_graphics`](Self::abandon_keeping_graphics) does.
1729    /// Nothing waits for its thread to end.
1730    pub fn dispose_keeping_graphics(&self) -> Result<(), Error> {
1731        self.shared().dispose_keeping_graphics()?;
1732        self.detach_thread();
1733        Ok(())
1734    }
1735
1736    /// Leaves a core worker's thread to end alone, for a release or
1737    /// disposal, which don't wait for it.
1738    fn detach_thread(&self) {
1739        if let Some(thread) = &self.handle.thread_end {
1740            thread.detach();
1741        }
1742    }
1743}
1744
1745/// Counts a ring replacement or release on its way until it runs, or never
1746/// will.
1747struct RetargetGuard(Arc<SessionShared>);
1748
1749impl Drop for RetargetGuard {
1750    fn drop(&mut self) {
1751        let mut state = self.0.state.lock();
1752        state.pending_retargets = state.pending_retargets.saturating_sub(1);
1753    }
1754}
1755
1756/// A frame of a borrowed ring that the host acquired, until it gives it
1757/// back. Dropping it gives it back as [`release`](Self::release) with
1758/// [`SyncKind::CpuComplete`] does.
1759pub struct AcquiredFrame {
1760    shared: Arc<SessionShared>,
1761    /// Dropped after the frame is given back.
1762    thread_end: ThreadEnd,
1763    slot: usize,
1764    frame: Published,
1765    done: bool,
1766}
1767
1768impl std::fmt::Debug for AcquiredFrame {
1769    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1770        f.debug_struct("AcquiredFrame").field("slot", &self.slot).field("frame", &self.frame).finish_non_exhaustive()
1771    }
1772}
1773
1774impl AcquiredFrame {
1775    /// The index of the frame's texture in the ring.
1776    #[must_use]
1777    pub fn slot(&self) -> usize {
1778        self.slot
1779    }
1780
1781    /// The result of the demand that rendered the frame.
1782    #[must_use]
1783    pub fn result(&self) -> &FrameResult {
1784        &self.frame.result
1785    }
1786
1787    /// What to wait for before reading the frame's texture. The object it
1788    /// names is the session's, and stays valid until the frame is given
1789    /// back.
1790    #[must_use]
1791    pub fn producer_sync(&self) -> GpuSync {
1792        self.frame.sync
1793    }
1794
1795    /// The host's texture that holds the frame.
1796    #[must_use]
1797    pub fn texture(&self) -> Option<&FrameTexture> {
1798        self.frame.texture.as_ref()
1799    }
1800
1801    /// Whether [`release`](Self::release) takes a sync of `kind`.
1802    #[must_use]
1803    pub fn accepts(&self, kind: SyncKind) -> bool {
1804        self.shared.capabilities.consumer_sync_kinds.contains(kind)
1805    }
1806
1807    /// Opens a view of the frame, which keeps the frame's texture and sync
1808    /// objects in place until the view drops: an
1809    /// [`abandon`](RenderSession::abandon) fails while one is open, and a
1810    /// dispose of the session keeps them until the last view ends. Keep the
1811    /// frame until its views end.
1812    ///
1813    /// Fails with [`ErrorKind::TargetLost`](mln_style::error::ErrorKind) once the
1814    /// session can no longer render.
1815    pub fn view(&self) -> Result<FrameView, Error> {
1816        let mut state = self.shared.state.lock();
1817        if !matches!(
1818            state.lifecycle,
1819            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
1820        ) {
1821            return Err(Error::target_lost("the render session failed, or was detached, abandoned, or disposed"));
1822        }
1823        state.views += 1;
1824        Ok(FrameView { shared: Arc::clone(&self.shared), _thread_end: self.thread_end.clone() })
1825    }
1826
1827    /// Whether the session can still render: the frame's objects stay valid
1828    /// until it ends.
1829    #[must_use]
1830    pub fn session_live(&self) -> bool {
1831        matches!(
1832            self.shared.state.lock().lifecycle,
1833            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
1834        )
1835    }
1836
1837    /// Gives the frame back once the host's reads of its texture reach
1838    /// `consumer`: the session waits for it before it renders into the
1839    /// texture again, and takes the sync file or GL fence that it names.
1840    ///
1841    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind), handing
1842    /// back the frame and `consumer`, for a kind that the session's
1843    /// [`consumer_sync_kinds`](RenderSessionCapabilities::consumer_sync_kinds)
1844    /// lacks.
1845    #[expect(
1846        clippy::result_large_err,
1847        reason = "the error hands back the frame and the consumer's sync, so that the caller can release it another way"
1848    )]
1849    pub fn release(mut self, consumer: ConsumerSync) -> Result<(), (AcquiredFrame, ConsumerSync, Error)> {
1850        if !self.shared.capabilities.consumer_sync_kinds.contains(consumer.sync.kind) {
1851            return Err((self, consumer, Error::unsupported("render backend does not support this gpu sync kind")));
1852        }
1853        self.done = true;
1854        give_back(&self.shared, self.slot, Some(consumer));
1855        Ok(())
1856    }
1857
1858    /// Gives the frame up without saying when the host's reads end: the
1859    /// session never renders into its texture again, even when
1860    /// [`set_ring`](RenderSession::set_ring) gives the ring the texture
1861    /// again, until a [`release_target`](RenderSession::release_target) of
1862    /// the ring.
1863    pub fn discard(mut self) {
1864        self.done = true;
1865        give_back(&self.shared, self.slot, None);
1866    }
1867}
1868
1869/// A view of an acquired frame, which [`AcquiredFrame::view`] opens, until
1870/// it drops.
1871pub struct FrameView {
1872    shared: Arc<SessionShared>,
1873    /// Dropped after the view ends.
1874    _thread_end: ThreadEnd,
1875}
1876
1877impl std::fmt::Debug for FrameView {
1878    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1879        f.debug_struct("FrameView").finish_non_exhaustive()
1880    }
1881}
1882
1883impl Drop for FrameView {
1884    fn drop(&mut self) {
1885        let release = {
1886            let mut state = self.shared.state.lock();
1887            state.views = state.views.saturating_sub(1);
1888            state.views == 0 && std::mem::take(&mut state.viewed_teardown)
1889        };
1890        if release {
1891            worker::post(&self.shared.queue, |worker, _| worker.release_viewed());
1892        }
1893    }
1894}
1895
1896impl Drop for AcquiredFrame {
1897    fn drop(&mut self) {
1898        if !self.done {
1899            give_back(&self.shared, self.slot, Some(ConsumerSync::of(GpuSync::of(SyncKind::CpuComplete))));
1900        }
1901    }
1902}
1903
1904/// Gives the ring's `slot` back to the session, with the host's `consumer`
1905/// sync, or discarded without one.
1906fn give_back(shared: &Arc<SessionShared>, slot: usize, consumer: Option<ConsumerSync>) {
1907    with_unlocked_wakes(|| {
1908        let mut state = shared.state.lock();
1909        state.acquired_frames = state.acquired_frames.saturating_sub(1);
1910        let live = matches!(
1911            state.lifecycle,
1912            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
1913        );
1914        if !live {
1915            if let Some(entry) = state.ring.get_mut(slot) {
1916                entry.acquired = false;
1917                // The host's GPU may still read a texture whose wait never
1918                // ran.
1919                entry.quarantined |=
1920                    consumer.as_ref().is_none_or(|consumer| consumer.sync.kind != SyncKind::CpuComplete);
1921            }
1922            // A sync file that no backend waits on closes with `consumer`.
1923            return;
1924        }
1925        if let Some(sync) = consumer {
1926            worker::post(&shared.queue, move |worker, outbox| worker.release_slot(slot, sync, outbox));
1927        } else {
1928            if let Some(entry) = state.ring.get_mut(slot) {
1929                entry.acquired = false;
1930                entry.quarantined = !entry.retired;
1931                entry.retired = false;
1932            }
1933            worker::post(&shared.queue, move |worker, outbox| worker.discard_slot(slot, outbox));
1934        }
1935    });
1936}
1937
1938fn source_id_of(source_id: impl Into<String>) -> Result<String, Error> {
1939    let source_id = source_id.into();
1940    if source_id.is_empty() {
1941        return Err(Error::invalid_argument("the source ID must not be empty"));
1942    }
1943    Ok(source_id)
1944}
1945
1946// Handles cross threads; the renderer never leaves its own.
1947const _: () = {
1948    const fn assert_send_sync<T: Send + Sync>() {}
1949    assert_send_sync::<RenderSession>();
1950};