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            tracing::warn!(
641                target: log_target::RENDER,
642                count = kept,
643                reason,
644                "An abandoned render session keeps graphics objects until the process exits"
645            );
646        }
647        let lost = || Error::target_lost("the render session was abandoned");
648        waiters.settle(&Err(lost()), lost);
649        drop(map);
650        Ok(kept)
651    }
652}
653
654/// Marks a session's thread as inside a driver call, as
655/// [`SessionShared::enter_call`] does.
656pub(crate) struct InCall<'a> {
657    shared: &'a SessionShared,
658    previous: bool,
659}
660
661impl Drop for InCall<'_> {
662    fn drop(&mut self) {
663        self.shared.in_call.store(self.previous, Ordering::SeqCst);
664    }
665}
666
667fn released() -> Error {
668    Error::invalid_state("the render session was released")
669}
670
671/// Fails unless the session takes work: it is attaching or attached, and
672/// not released.
673fn check_usable(state: &SessionState) -> Result<(), Error> {
674    if state.released {
675        return Err(released());
676    }
677    match state.lifecycle {
678        RenderSessionState::Attaching | RenderSessionState::Attached => Ok(()),
679        RenderSessionState::Failed => {
680            Err(state.failure.clone().unwrap_or_else(|| Error::failed("the render session failed")))
681        }
682        RenderSessionState::Detaching | RenderSessionState::Detached | RenderSessionState::Abandoned => {
683            Err(Error::invalid_state("the render session is not attached: it was detached or abandoned"))
684        }
685    }
686}
687
688thread_local! {
689    /// The driver wakes that this thread's posts asked for during a handle
690    /// call, which may hold the session's locks.
691    static DEFERRED_WAKES: RefCell<Option<Vec<Wake>>> = const { RefCell::new(None) };
692    /// The sessions whose sending lock this thread holds.
693    static SENDING: RefCell<Vec<SessionId>> = const { RefCell::new(Vec::new()) };
694}
695
696/// A session's sending lock, which [`SessionShared::hold_sending`] took.
697struct Sending<'a> {
698    id: SessionId,
699    _guard: parking_lot::MutexGuard<'a, ()>,
700}
701
702impl Drop for Sending<'_> {
703    fn drop(&mut self) {
704        SENDING.with(|sending| sending.borrow_mut().retain(|id| *id != self.id));
705    }
706}
707
708/// Runs `call`, which may post to a session's queue with the session's locks
709/// held, then the driver wakes that its posts asked for, with nothing locked.
710fn with_unlocked_wakes<R>(call: impl FnOnce() -> R) -> R {
711    let outer = DEFERRED_WAKES.with(|deferred| deferred.borrow_mut().replace(Vec::new()));
712    let result = call();
713    let wakes = DEFERRED_WAKES.with(|deferred| {
714        let mut deferred = deferred.borrow_mut();
715        let wakes = deferred.take().unwrap_or_default();
716        match outer {
717            // The outer call runs them.
718            Some(mut outer) => {
719                outer.extend(wakes);
720                *deferred = Some(outer);
721                Vec::new()
722            }
723            None => wakes,
724        }
725    });
726    for wake in wakes {
727        wake();
728    }
729    result
730}
731
732/// Runs `wake` now, or once the handle call on this thread returns.
733fn wake_unlocked(wake: &Wake) {
734    let deferred = DEFERRED_WAKES.with(|deferred| match deferred.borrow_mut().as_mut() {
735        Some(wakes) => {
736            wakes.push(Arc::clone(wake));
737            true
738        }
739        None => false,
740    });
741    if !deferred {
742        wake();
743    }
744}
745
746/// Sizes in pixels a target of `size` logical pixels at `scale_factor`, by
747/// [`LogicalExtent::physical_size`].
748pub(crate) fn physical_size(size: Size, scale_factor: f64) -> Result<Size, Error> {
749    LogicalExtent::new(size, scale_factor)
750        .physical_size()
751        .ok_or_else(|| Error::invalid_argument(format!("{size:?} at scale factor {scale_factor} has no physical size")))
752}
753
754/// A render session: a renderer that draws a map into a target, on a thread
755/// of its own or on the host's.
756///
757/// The host demands frames, which finish with [`FrameResult`]s that
758/// [`drain_frame_results`](Self::drain_frame_results) takes. A demand shows
759/// the map's commands sent before it, except the changes that an open
760/// command group holds back. The session's work runs on its thread in the
761/// order it was sent, and reports through a [`Completion`]. `Clone` is
762/// another handle to the same session, and any thread may use one.
763///
764/// A session that attached with [`Driver::CallerThread`] runs its work only
765/// when the host services its [`DriverWork`], which
766/// [`take_driver_work`](Self::take_driver_work) hands out.
767///
768/// The session lives until [`detach`](Self::detach),
769/// [`release`](Self::release), [`dispose`](Self::dispose) or
770/// [`abandon`](Self::abandon), or until its last handle drops, and it holds
771/// its map until then. A call that sends work to a session that no longer
772/// takes it fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind), or
773/// with the failure of a session that failed.
774///
775/// Unless the session was released or disposed, the last drop of its
776/// handles, [`AcquiredFrame`]s and [`FrameView`]s waits for a core worker's
777/// thread to end, once the session has let go of its graphics objects and
778/// its map. A drop on a thread of the library, such as in a callback or a
779/// wake that the library runs, doesn't wait: it leaves the session's thread
780/// to end alone.
781#[derive(Clone)]
782pub struct RenderSession {
783    handle: Arc<SessionHandle>,
784}
785
786/// Disposes of the session when the last handle drops.
787struct SessionHandle {
788    shared: Arc<SessionShared>,
789    thread_end: ThreadEnd,
790}
791
792/// A core worker's thread, which the last of the host's handles, frames and
793/// views of the session to drop waits for. A caller-driven session has no
794/// thread, and in the browser the thread is the host's.
795type ThreadEnd = Option<Arc<Joined>>;
796
797impl Drop for SessionHandle {
798    /// Disposes of the session, which ends its thread once the frames and
799    /// views of it end too, then waits for the thread as `thread_end` drops,
800    /// unless they hold it.
801    fn drop(&mut self) {
802        let _ = self.shared.dispose(None);
803    }
804}
805
806impl std::fmt::Debug for RenderSession {
807    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
808        f.debug_struct("RenderSession").field("id", &self.shared().id).finish()
809    }
810}
811
812impl PartialEq for RenderSession {
813    fn eq(&self, other: &RenderSession) -> bool {
814        Arc::ptr_eq(&self.handle, &other.handle)
815    }
816}
817
818impl Eq for RenderSession {}
819
820/// Attaches a session to `map`, as [`Map::attach`] documents, and runs `then`
821/// with the session and the attach's completion before the session's thread
822/// may deliver that, as [`Map::attach_then`] documents.
823pub(crate) fn attach<R>(
824    map: &Map,
825    target: RenderTarget,
826    options: AttachOptions,
827    then: impl FnOnce(&RenderSession, Completion<()>) -> R,
828) -> Result<R, Error> {
829    // The wakes that the attach runs, such as a caller-driven session's
830    // driver-work wake, wait for the release of the session's sending lock,
831    // so a host's wake that services the session can't wait for it.
832    with_unlocked_wakes(|| attach_unlocked(map, target, options, then))
833}
834
835fn attach_unlocked<R>(
836    map: &Map,
837    target: RenderTarget,
838    options: AttachOptions,
839    then: impl FnOnce(&RenderSession, Completion<()>) -> R,
840) -> Result<R, Error> {
841    static NEXT_ID: AtomicU64 = AtomicU64::new(1);
842    let id = SessionId(NEXT_ID.fetch_add(1, Ordering::Relaxed));
843    let mut ring = None;
844    let mut export_kind = None;
845    let (size, target) = match target {
846        RenderTarget::Offscreen { size, device } => (size, TargetInit::Offscreen(device)),
847        RenderTarget::Surface { size, surface, device } => {
848            if device.is_none() && !surface.needs_no_device() {
849                return Err(Error::invalid_argument("a surface that the host made needs the host's device"));
850            }
851            surface.check_area()?;
852            surface.check_pixel_format(device.as_ref())?;
853            (size, TargetInit::Surface { surface: SentSurface::new(surface, id), device })
854        }
855        RenderTarget::Borrowed { size, ring: borrowed, device } => {
856            let (producer, consumer) = device.borrowed_sync_kinds(&borrowed)?;
857            let picked = options.producer_sync_kinds.pick(producer).ok_or_else(|| {
858                Error::unsupported("render target supports none of the requested producer sync kinds")
859            })?;
860            if borrowed.depth() == 0 || borrowed.physical_size().is_empty() {
861                return Err(Error::invalid_argument("a borrowed ring needs textures of a size"));
862            }
863            ring = Some((borrowed.depth(), picked, consumer));
864            (size, TargetInit::Borrowed { ring: borrowed, device, producer: picked })
865        }
866        RenderTarget::Exported { size, ring: exported, device } => {
867            if exported.depth == 0 {
868                return Err(Error::invalid_argument("an exported ring needs at least one image"));
869            }
870            if exported.kinds.is_empty() {
871                return Err(Error::invalid_argument("an exported ring needs a kind of image to share"));
872            }
873            if size.is_empty() {
874                return Err(Error::invalid_argument("the target's size must not be empty"));
875            }
876            let device = match device {
877                Some(device) => device,
878                None => Device::for_exported_ring(&exported)?,
879            };
880            let (kind, producer, consumer) = device.export_plan(&exported)?;
881            let picked = options.producer_sync_kinds.pick(producer).ok_or_else(|| {
882                Error::unsupported("render target supports none of the requested producer sync kinds")
883            })?;
884            ring = Some((exported.depth, picked, consumer));
885            export_kind = Some(kind);
886            (size, TargetInit::Exported { ring: exported, device, kind, producer: picked })
887        }
888    };
889    if size.is_empty() {
890        return Err(Error::invalid_argument("the target's size must not be empty"));
891    }
892    let (target, lease) = target.lease();
893    let presentation = matches!(target, TargetInit::Surface { .. });
894    let queue = SessionQueue::default();
895    let driver_armed = Arc::new(AtomicBool::new(true));
896    if options.driver == Driver::CallerThread
897        && let Some(wake) = options.driver_work_wake
898    {
899        let armed = Arc::clone(&driver_armed);
900        queue.set_waker(Some(Arc::new(move || {
901            if armed.swap(false, Ordering::SeqCst) {
902                wake_unlocked(&wake);
903            }
904        })));
905    }
906    let scale_factor = map.scale_factor();
907    let shared = Arc::new(SessionShared {
908        id,
909        driver: options.driver,
910        queue: queue.clone(),
911        thread: Arc::default(),
912        runtime_thread: map.runtime_thread(),
913        state: Mutex::new(SessionState {
914            lifecycle: RenderSessionState::Attaching,
915            released: false,
916            size,
917            scale_factor,
918            sent_scale_factor: scale_factor,
919            generation: 1,
920            frame_generation: 0,
921            failure: None,
922            has_target: true,
923            results: Vec::new(),
924            frame_woken: false,
925            redraw_armed: true,
926            pacing: None,
927            attach: None,
928            detach_waiters: Vec::new(),
929            release_waiters: Vec::new(),
930            pending: BTreeMap::new(),
931            next_work: 0,
932            map: Some(map.clone()),
933            init: Some(Box::new(Init {
934                target,
935                size,
936                scale_factor,
937                glyph_cache: map.glyph_cache(),
938                font_face_engine: map.font_face_engine(),
939                registry: Arc::clone(map.registry()),
940                tile_cache_enabled: map.tile_cache_enabled(),
941                tile_worker_instances: map.tile_worker_instances(),
942                local_glyphs: map.local_glyphs(),
943                failure: None,
944                pool: map.pool(),
945            })),
946            resizes_sent: 0,
947            graphics_objects: 0,
948            keep_graphics: false,
949            abandon_keeps_graphics: false,
950            ring: vec![RingSlot::default(); ring.map_or(0, |(depth, _, _)| depth)],
951            acquired_frames: 0,
952            pending_retargets: 0,
953            views: 0,
954            viewed_teardown: false,
955        }),
956        gate: Mutex::new(()),
957        lease,
958        frame_wake: options.frame_wake,
959        redraw_wake: options.redraw_wake,
960        capabilities: RenderSessionCapabilities {
961            driver: options.driver,
962            texture_ring_depth: ring.map_or(1, |(depth, _, _)| depth as u32),
963            frame_acquisition: ring.is_some(),
964            readback: !presentation && ring.is_none(),
965            presentation,
966            producer_sync_kind: ring.map(|(_, producer, _)| producer),
967            consumer_sync_kinds: ring.map_or(SyncKinds::NONE, |(_, _, consumer)| consumer),
968            export_kind,
969        },
970        driver_work_taken: AtomicBool::new(false),
971        driver_armed,
972        awaited_command: Arc::new(AtomicU64::new(u64::MAX)),
973        preparing: AtomicBool::new(false),
974        in_call: AtomicBool::new(false),
975        sending: Mutex::new(()),
976    });
977    let (completion, resolver) = shared.completion();
978    shared.state.lock().attach = Some(resolver);
979    // Held until `then` returns: the session's thread delivers the attach's
980    // result after, inside its driver call.
981    let sending = Arc::clone(&shared);
982    let held = sending.hold_sending();
983    map.claim_session(id, Arc::downgrade(&shared))?;
984    let mut thread_end = None;
985    if options.driver == Driver::CoreWorker {
986        match start_thread(Arc::clone(&shared)) {
987            Ok((thread, end)) => {
988                let _ = shared.thread.set(thread);
989                thread_end = end.map(Arc::new);
990            }
991            Err(error) => {
992                map.release_session_claim(id);
993                return Err(error);
994            }
995        }
996    }
997    let session = RenderSession { handle: Arc::new(SessionHandle { shared, thread_end }) };
998    if let Err(error) = map.bind_session(id, queue, Arc::clone(&session.shared().awaited_command), size) {
999        // The map was released meanwhile: the session lets go of it. Its
1000        // drop waits for its thread, which waits for the sending lock.
1001        drop(held);
1002        drop(session);
1003        return Err(error);
1004    }
1005    if options.driver == Driver::CallerThread {
1006        #[cfg(target_family = "wasm")]
1007        prepare_caller_driven(session.shared());
1008        // The first service builds the renderer, which is work that is ready
1009        // now: this wakes the host, unless the map's first update, posted
1010        // from the runtime's thread, woke it already.
1011        session.shared().queue.wake();
1012    }
1013    let attached = then(&session, completion);
1014    // Before the session, whose drop may wait for its thread, which waits
1015    // for the sending lock.
1016    drop(held);
1017    Ok(attached)
1018}
1019
1020/// Starts a core worker's thread, which builds the session's renderer, then
1021/// runs the session's queue until the session ends.
1022#[cfg(not(target_family = "wasm"))]
1023fn start_thread(shared: Arc<SessionShared>) -> Result<(ThreadId, Option<Joined>), Error> {
1024    let thread = mln_engine::exec::thread::spawn("RenderSession", move || {
1025        let queue = shared.queue.clone();
1026        let mut worker = None;
1027        worker::build(&shared, &mut worker, &mut None);
1028        // The worker holds the session from here on.
1029        drop(shared);
1030        queue.run(&mut worker);
1031        // The session's work that comes from now on drops at once, so tasks
1032        // that hold the queue can't keep it alive.
1033        queue.close();
1034        drop(worker);
1035    })
1036    .map_err(|error| Error::failed(format!("can't start the render session's thread: {error}")))?;
1037    let thread_id = thread.thread().id();
1038    // The thread ends by itself once the session ends.
1039    Ok((thread_id, Some(Joined::new(thread))))
1040}
1041
1042/// Runs a core worker on this thread, the browser's one, in the instance's
1043/// pump: it builds the session's renderer once its device is ready, which
1044/// may take the browser's WebGPU a while, then runs the session's queue until
1045/// the session ends.
1046#[cfg(target_family = "wasm")]
1047#[expect(clippy::unnecessary_wraps, reason = "the threads of other builds can fail to start")]
1048fn start_thread(shared: Arc<SessionShared>) -> Result<(ThreadId, Option<Joined>), Error> {
1049    let prepared = worker::prepare(&shared);
1050    wasm_bindgen_futures::spawn_local(async move {
1051        prepared.await;
1052        let queue = shared.queue.clone();
1053        let mut worker = None;
1054        worker::build(&shared, &mut worker, &mut None);
1055        let id = shared.id;
1056        // The worker holds the session from here on.
1057        drop(shared);
1058        let worker = RefCell::new(worker);
1059        crate::web::drive_session(id, queue.clone(), move || {
1060            queue.run_once(&mut worker.borrow_mut());
1061            if queue.is_stopped() {
1062                queue.close();
1063                drop(worker.borrow_mut().take());
1064            }
1065        });
1066    });
1067    Ok((std::thread::current().id(), None))
1068}
1069
1070/// In the browser, asks for the device that a caller-driven session's build
1071/// needs, as a core worker does before it builds, and wakes the host to
1072/// service the session once the device is there.
1073#[cfg(target_family = "wasm")]
1074fn prepare_caller_driven(shared: &Arc<SessionShared>) {
1075    shared.preparing.store(true, Ordering::SeqCst);
1076    let prepared = worker::prepare(shared);
1077    let shared = Arc::downgrade(shared);
1078    wasm_bindgen_futures::spawn_local(async move {
1079        prepared.await;
1080        if let Some(shared) = shared.upgrade() {
1081            shared.preparing.store(false, Ordering::SeqCst);
1082            shared.queue.wake();
1083        }
1084    });
1085}
1086
1087impl RenderSession {
1088    fn shared(&self) -> &Arc<SessionShared> {
1089        &self.handle.shared
1090    }
1091
1092    /// Sends a command with `send`, such as [`barrier`](Self::barrier), and
1093    /// calls `callback` once with its result, where the session delivers
1094    /// it: on the session's thread, inside its driver call, even when the
1095    /// command runs before `send` returns. A [`Completion::on_complete`]
1096    /// after the command returned would run at once on this thread instead.
1097    /// The callback doesn't run when `send` fails.
1098    ///
1099    /// Fails as `send` does.
1100    pub fn send_then<T: Send + 'static>(
1101        &self,
1102        send: impl FnOnce(&RenderSession) -> Result<Completion<T>, Error>,
1103        callback: impl FnOnce(Result<T, Error>) + Send + 'static,
1104    ) -> Result<(), Error> {
1105        // The wakes that the command runs wait for the lock's release, so a
1106        // host's wake that services the session can't wait for it.
1107        with_unlocked_wakes(|| {
1108            let ready = {
1109                let _sending = self.shared().hold_sending();
1110                send(self)?.on_complete_unless_ready(callback)
1111            };
1112            // A result that came without the session's thread, such as a
1113            // command dropped unrun, goes to the callback here.
1114            if let Some((callback, result)) = ready {
1115                callback(result);
1116            }
1117            Ok(())
1118        })
1119    }
1120
1121    /// Sends `task` to the session's thread, after the work sent before,
1122    /// resizes included, and completes with its result. A session that lost
1123    /// its graphics objects before the task runs completes it with
1124    /// [`ErrorKind::TargetLost`](mln_style::error::ErrorKind).
1125    pub(crate) fn operation<T: Send + 'static>(
1126        &self,
1127        task: impl FnOnce(&mut Worker, &mut Outbox) -> Result<T, Error> + Send + 'static,
1128    ) -> Result<Completion<T>, Error> {
1129        let shared = self.shared();
1130        with_unlocked_wakes(|| {
1131            let mut state = shared.state.lock();
1132            check_usable(&state)?;
1133            let (completion, resolver) = shared.completion();
1134            let work = state.register(resolver);
1135            let resizes = state.resizes_sent;
1136            worker::post(&shared.queue, move |worker, outbox| {
1137                let task: worker::Task = Box::new(move |worker, outbox| {
1138                    let Some(resolver) = worker.take_work(work) else { return };
1139                    let result = task(worker, outbox);
1140                    outbox.resolve(resolver, result);
1141                });
1142                worker.after_earlier_work(resizes, task, outbox);
1143            });
1144            drop(state);
1145            Ok(completion)
1146        })
1147    }
1148
1149    /// Hands out the work of a [`Driver::CallerThread`] session, for the
1150    /// calling thread to run: the session's graphics work runs only in its
1151    /// [`service`](DriverWork::service), and on no other thread.
1152    ///
1153    /// Take it once, on the host's graphics thread, from the attach on: the
1154    /// attach itself completes in a service. It stays available after a
1155    /// release, which the host services to its end.
1156    ///
1157    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
1158    /// session on a core worker, and with
1159    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once it was taken.
1160    pub fn take_driver_work(&self) -> Result<DriverWork, Error> {
1161        let shared = self.shared();
1162        if shared.driver != Driver::CallerThread {
1163            return Err(Error::unsupported("the render session runs on a core worker"));
1164        }
1165        if shared.driver_work_taken.swap(true, Ordering::SeqCst) {
1166            return Err(Error::invalid_state("the render session's driver work was taken already"));
1167        }
1168        let _ = shared.thread.set(std::thread::current().id());
1169        Ok(DriverWork::new(Arc::clone(shared)))
1170    }
1171
1172    /// What the session can do. Fails with
1173    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once it is released.
1174    pub fn capabilities(&self) -> Result<RenderSessionCapabilities, Error> {
1175        let state = self.shared().state.lock();
1176        if state.released {
1177            return Err(released());
1178        }
1179        Ok(self.shared().capabilities)
1180    }
1181
1182    /// The session's state now. Fails with
1183    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once it is released.
1184    pub fn snapshot(&self) -> Result<RenderSessionSnapshot, Error> {
1185        let state = self.shared().state.lock();
1186        if state.released {
1187            return Err(released());
1188        }
1189        Ok(RenderSessionSnapshot {
1190            state: state.lifecycle,
1191            extent: LogicalExtent { size: state.size, scale_factor: state.scale_factor },
1192            generation: state.generation,
1193            frame_generation: state.frame_generation,
1194            failure: state.failure.clone(),
1195            has_target: state.lifecycle == RenderSessionState::Attached && state.has_target,
1196            acquired_frames: state.acquired_frames,
1197        })
1198    }
1199
1200    /// Takes the newest frame that a borrowed ring rendered, if one waits:
1201    /// the older frames that the host didn't acquire are dropped, and the
1202    /// session may render into their textures again. While the host holds a
1203    /// frame in every texture, demands wait for a release.
1204    ///
1205    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
1206    /// session without a ring, and as a call that sends work does once the
1207    /// session no longer takes work.
1208    pub fn acquire_frame(&self) -> Result<Option<AcquiredFrame>, Error> {
1209        let shared = self.shared();
1210        let mut state = shared.state.lock();
1211        check_usable(&state)?;
1212        if !shared.capabilities.frame_acquisition {
1213            return Err(Error::unsupported("render session does not expose acquired texture frames"));
1214        }
1215        if state.pending_retargets != 0 {
1216            return Ok(None);
1217        }
1218        let newest = state
1219            .ring
1220            .iter()
1221            .enumerate()
1222            .filter(|(_, slot)| !slot.acquired && slot.frame.is_some())
1223            .max_by_key(|(_, slot)| slot.frame.as_ref().map_or(0, |frame| frame.result.frame_generation))
1224            .map(|(index, _)| index);
1225        let Some(index) = newest else { return Ok(None) };
1226        for (other, slot) in state.ring.iter_mut().enumerate() {
1227            if other != index && !slot.acquired {
1228                slot.frame = None;
1229            }
1230        }
1231        let slot = &mut state.ring[index];
1232        let Some(frame) = slot.frame.take() else { return Ok(None) };
1233        slot.acquired = true;
1234        state.acquired_frames += 1;
1235        Ok(Some(AcquiredFrame {
1236            shared: Arc::clone(shared),
1237            thread_end: self.handle.thread_end.clone(),
1238            slot: index,
1239            frame,
1240            done: false,
1241        }))
1242    }
1243
1244    /// Gives a borrowed ring new textures, of `size` logical pixels: as many
1245    /// as it has, of its format. The completion reports the map's change and
1246    /// the sync after which the host may use the old textures that the new
1247    /// ring doesn't have, as [`release_target`](Self::release_target) says.
1248    ///
1249    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
1250    /// session without a borrowed ring, with
1251    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for another number
1252    /// of textures, and with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
1253    /// while the host holds one of the ring's frames. Completes with
1254    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for textures of
1255    /// another format or kind.
1256    pub fn set_ring(&self, size: Size, ring: BorrowedRing) -> Result<Completion<(Applied, GpuSync)>, Error> {
1257        let shared = Arc::clone(self.shared());
1258        {
1259            let mut state = shared.state.lock();
1260            check_usable(&state)?;
1261            if shared.capabilities.readback {
1262                return Err(Error::unsupported("an offscreen session keeps its target"));
1263            }
1264            if !shared.capabilities.frame_acquisition {
1265                return Err(Error::unsupported("a surface session takes no caller-owned texture"));
1266            }
1267            if shared.capabilities.export_kind.is_some() {
1268                return Err(Error::unsupported("an exported ring resizes instead of taking new textures"));
1269            }
1270            if state.acquired_frames != 0 {
1271                return Err(Error::invalid_state("cannot replace the render target while a texture frame is acquired"));
1272            }
1273            if ring.depth() != state.ring.len() {
1274                return Err(Error::invalid_argument(
1275                    "texture_count must equal the ring depth the session attached with",
1276                ));
1277            }
1278            state.pending_retargets += 1;
1279        }
1280        let guard = RetargetGuard(Arc::clone(&shared));
1281        // The guard goes with the closure, whether the closure runs or the
1282        // resize drops it.
1283        self.resize_then(size, None, move |worker, size, scale_factor, applied, outbox| {
1284            let _guard = guard;
1285            Ok((applied, worker.set_ring(size, scale_factor, &ring, outbox)?))
1286        })
1287    }
1288
1289    /// Asks the session to render a frame, which shows the map commands sent
1290    /// before the call, except the changes that an open command group holds
1291    /// back, and the map's animations as they are at the call: demand each
1292    /// frame at the display's pace. A demand sent while the session attaches
1293    /// waits for it.
1294    ///
1295    /// Every demand finishes with one [`FrameResult`] that carries its token.
1296    /// A demand that isn't [`DemandMode::Force`](super::DemandMode::Force)
1297    /// replaces the demands with the same mode still on their way, which
1298    /// finish as [`FrameDisposition::Superseded`](super::FrameDisposition).
1299    /// While the session has no target, or a surface has no texture to
1300    /// render into, a demand finishes as
1301    /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition).
1302    pub fn demand_frame(&self, demand: FrameDemand) -> Result<(), Error> {
1303        let shared = self.shared();
1304        with_unlocked_wakes(|| shared.demand_locked(&mut shared.state.lock(), demand))
1305    }
1306
1307    /// Paces the session's frames with `pacer`, or with none, stops. At the
1308    /// first refresh that the pacer allows after the map has something new to
1309    /// draw, it demands a frame in
1310    /// [`DemandMode::IfChanged`](super::DemandMode::IfChanged) with token 0,
1311    /// unless a demand came first. One pacer can pace many sessions.
1312    ///
1313    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a
1314    /// session with a redraw wake.
1315    pub fn set_frame_pacer(&self, pacer: Option<Arc<FramePacer>>) -> Result<(), Error> {
1316        let shared = self.shared();
1317        let request = {
1318            let mut state = shared.state.lock();
1319            check_usable(&state)?;
1320            if shared.redraw_wake.is_some() {
1321                return Err(Error::invalid_state("a render session with a redraw wake takes no frame pacer"));
1322            }
1323            let same = match (&state.pacing, &pacer) {
1324                (Some(pacing), Some(pacer)) => Arc::ptr_eq(&pacing.pacer, pacer),
1325                (None, None) => true,
1326                _ => false,
1327            };
1328            if same {
1329                return Ok(());
1330            }
1331            state.pacing = pacer.map(|pacer| Pacing::new(pacer, Arc::downgrade(shared)));
1332            state.pacing.as_ref().filter(|_| !state.redraw_armed).map(Pacing::request)
1333        };
1334        if let Some(request) = request {
1335            request();
1336        }
1337        Ok(())
1338    }
1339
1340    /// Takes the frame results that wait, oldest first. Fails with
1341    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once the session is
1342    /// released.
1343    pub fn drain_frame_results(&self) -> Result<Vec<FrameResult>, Error> {
1344        let mut state = self.shared().state.lock();
1345        if state.released {
1346            return Err(released());
1347        }
1348        state.frame_woken = false;
1349        Ok(std::mem::take(&mut state.results))
1350    }
1351
1352    /// Resizes the target, and the map with it, to `extent`'s size in
1353    /// logical pixels, and sets the map's scale factor to `extent`'s, such
1354    /// as when a window moves to a display of another density. The map keeps
1355    /// its tiles, and the renderer draws the next frame at the new scale
1356    /// factor. A later demand shows the new extent, and one sent before
1357    /// shows the old. An exported ring gets images of the new size, and the
1358    /// frames that the host holds keep theirs until it gives them back.
1359    ///
1360    /// Fails first as a call that sends work does once the session no
1361    /// longer takes work. Then fails with
1362    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a borrowed ring,
1363    /// which [`set_ring`](Self::set_ring) resizes, and with
1364    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an empty size,
1365    /// or a scale factor that isn't finite and positive.
1366    pub fn resize(&self, extent: LogicalExtent) -> Result<Completion<Applied>, Error> {
1367        check_usable(&self.shared().state.lock())?;
1368        let capabilities = self.shared().capabilities;
1369        if capabilities.frame_acquisition && capabilities.export_kind.is_none() {
1370            return Err(Error::unsupported("a borrowed ring is sized by its owner: give it new textures instead"));
1371        }
1372        let LogicalExtent { size, scale_factor } = extent;
1373        if !scale_factor.is_finite() || scale_factor <= 0.0 {
1374            return Err(Error::invalid_argument(format!("scale factor {scale_factor} isn't finite and positive")));
1375        }
1376        self.resize_then(size, Some(scale_factor), |worker, size, scale_factor, applied, outbox| {
1377            worker.resize(size, scale_factor, outbox).map(|()| applied)
1378        })
1379    }
1380
1381    /// Sends a map command that resizes the map to `size`, at
1382    /// `scale_factor` or the session's when that is `None`, then runs
1383    /// `change` on the session's thread with the map's change, which resizes
1384    /// or replaces the target, and completes with its result.
1385    fn resize_then<T: Send + 'static>(
1386        &self,
1387        size: Size,
1388        scale_factor: Option<f64>,
1389        change: impl FnOnce(&mut Worker, Size, f64, Applied, &mut Outbox) -> Result<T, Error> + Send + 'static,
1390    ) -> Result<Completion<T>, Error> {
1391        if size.is_empty() {
1392            return Err(Error::invalid_argument("the target's size must not be empty"));
1393        }
1394        let shared = self.shared();
1395        with_unlocked_wakes(|| {
1396            let mut state = shared.state.lock();
1397            check_usable(&state)?;
1398            let map = state.map.clone().ok_or_else(|| Error::invalid_state("the render session has no map"))?;
1399            let scale_factor = scale_factor.unwrap_or(state.sent_scale_factor);
1400            state.sent_scale_factor = scale_factor;
1401            let (completion, resolver) = shared.completion();
1402            let work = state.register(resolver);
1403            // The work sent after waits for the resize to land, which it
1404            // does even when the map drops it.
1405            state.resizes_sent += 1;
1406            let landing = worker::ResizeLanding::new(shared.queue.clone());
1407            let sent =
1408                map.resize_for_session(size, scale_factor, shared.queue.clone(), move |worker, result, outbox| {
1409                    if let Some(resolver) = worker.take_work::<T>(work) {
1410                        let result = result.and_then(|applied| change(worker, size, scale_factor, applied, outbox));
1411                        outbox.resolve(resolver, result);
1412                    }
1413                    landing.land(worker, outbox);
1414                });
1415            if let Err(error) = sent {
1416                state.pending.remove(&work);
1417                return Err(error);
1418            }
1419            drop(state);
1420            Ok(completion)
1421        })
1422    }
1423
1424    /// Lets go of a surface session's surface, and keeps the rest of the
1425    /// session, such as when the platform takes the window away. The demands
1426    /// on their way, and later ones until
1427    /// [`set_surface`](Self::set_surface) gives the session a surface again,
1428    /// finish as [`FrameDisposition::TargetNotReady`](super::FrameDisposition).
1429    /// Once the release completes, the session no longer uses the surface or
1430    /// the window it was made from. For a ring, it completes with a sync of
1431    /// the session's producer kind, after which the host may use or destroy
1432    /// the textures: the session's GPU work on them, and its waits for the
1433    /// consumer syncs that they were given back with, end there. The session
1434    /// keeps the objects that the sync names until its next release or
1435    /// replacement of the target completes, or it ends. It keeps nothing of
1436    /// the released textures: one that a later ring has again starts fresh,
1437    /// even one that the host gave up.
1438    ///
1439    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for an
1440    /// offscreen session or an exported ring, whose targets are their own.
1441    /// Completes with [`ErrorKind::Failed`](mln_style::error::ErrorKind) when a ring
1442    /// can't submit its work on the textures, which it keeps then.
1443    pub fn release_target(&self) -> Result<Completion<Option<GpuSync>>, Error> {
1444        if self.shared().capabilities.export_kind.is_some() {
1445            return Err(Error::unsupported("an exported ring keeps its images until the session ends"));
1446        }
1447        let shared = Arc::clone(self.shared());
1448        let capabilities = shared.capabilities;
1449        if !capabilities.presentation && !capabilities.frame_acquisition {
1450            check_usable(&shared.state.lock())?;
1451            return Err(Error::unsupported("an offscreen session keeps its target"));
1452        }
1453        let guard = {
1454            let mut state = shared.state.lock();
1455            check_usable(&state)?;
1456            if state.acquired_frames != 0 {
1457                return Err(Error::invalid_state("release every acquired frame before the target"));
1458            }
1459            // No frame is acquired until the release runs: its textures go
1460            // with it.
1461            capabilities.frame_acquisition.then(|| {
1462                state.pending_retargets += 1;
1463                RetargetGuard(Arc::clone(&shared))
1464            })
1465        };
1466        self.operation(move |worker, outbox| {
1467            let _guard = guard;
1468            worker.release_target(outbox)
1469        })
1470    }
1471
1472    /// Gives a surface session a new surface of `size` logical pixels, after
1473    /// [`release_target`](Self::release_target), or in place of the one it
1474    /// has, and resizes the map to it. Once the completion reports success,
1475    /// the session no longer uses the old surface. The session presents to
1476    /// it on its device: a window becomes a surface of the device's backend,
1477    /// and a `Surface::wgpu` must come from the instance of a WebGPU
1478    /// device. Where the backend made for the old surface can't present to
1479    /// the new one, as OpenGL ES's context can't to another window, the
1480    /// session makes its backend and renderer again.
1481    ///
1482    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an
1483    /// empty size, with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for
1484    /// an offscreen session, and with
1485    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a window that is
1486    /// minimized or has no client area. Completes with
1487    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when the session's
1488    /// device can't present to the surface in the format that the session
1489    /// renders in: attach a new session instead. Completes with
1490    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the window had no
1491    /// area to present to by then. The session then keeps the surface it had,
1492    /// at the new size.
1493    pub fn set_surface(&self, size: Size, surface: Surface) -> Result<Completion<Applied>, Error> {
1494        check_usable(&self.shared().state.lock())?;
1495        let capabilities = self.shared().capabilities;
1496        if capabilities.frame_acquisition {
1497            return Err(Error::unsupported("a borrowed texture session takes no native surface"));
1498        }
1499        if !capabilities.presentation {
1500            return Err(Error::unsupported("an offscreen session keeps its target"));
1501        }
1502        surface.check_area()?;
1503        let surface = SentSurface::new(surface, self.shared().id);
1504        self.resize_then(size, None, move |worker, size, scale_factor, applied, outbox| {
1505            worker.set_surface(size, scale_factor, surface.receive()?, outbox).map(|()| applied)
1506        })
1507    }
1508
1509    /// Ends the frame demands on their way, including those that wait for a
1510    /// map update and the demand of a still image, which finish as
1511    /// [`FrameDisposition::NoUpdate`](super::FrameDisposition), and completes
1512    /// once the work sent before it has run. A still image that still waits
1513    /// gets a new demand once the barrier ran.
1514    pub fn barrier(&self) -> Result<Completion<()>, Error> {
1515        self.operation(|worker, outbox| {
1516            worker.barrier(outbox);
1517            Ok(())
1518        })
1519    }
1520
1521    /// Frees memory that the renderer can rebuild, such as caches.
1522    pub fn reduce_memory_use(&self) -> Result<Completion<()>, Error> {
1523        self.operation(|worker, _| worker.reduce_memory_use())
1524    }
1525
1526    /// Clears what the renderer holds, such as loaded tiles, so that the
1527    /// next frame loads and draws the map again.
1528    pub fn clear_data(&self) -> Result<Completion<()>, Error> {
1529        self.operation(Worker::clear_data)
1530    }
1531
1532    /// Logs the renderer's sources and tiles.
1533    pub fn dump_debug_logs(&self) -> Result<Completion<()>, Error> {
1534        self.operation(|worker, _| worker.dump_debug_logs())
1535    }
1536
1537    /// The pixels of the last frame that an offscreen session rendered:
1538    /// premultiplied RGBA, in rows from top to bottom, at the target's size
1539    /// in pixels.
1540    ///
1541    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
1542    /// surface session. Completes with
1543    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the session
1544    /// hasn't rendered a frame since it attached or resized.
1545    pub fn read_texture(&self) -> Result<Completion<PremultipliedImage>, Error> {
1546        check_usable(&self.shared().state.lock())?;
1547        if !self.shared().capabilities.readback {
1548            return Err(Error::unsupported("a surface session can't read its frames back"));
1549        }
1550        self.operation(|worker, _| worker.read_texture())
1551    }
1552
1553    /// The features that the session drew in an area of the screen, in its
1554    /// last frame. A feature that several layers draw appears once for each.
1555    /// The topmost layer's features come first, and the bottom layer's last.
1556    /// A box covers only its part inside the target, so one past every edge
1557    /// covers the whole target.
1558    ///
1559    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
1560    /// point that isn't finite or a line string without points.
1561    pub fn query_rendered_features(
1562        &self,
1563        geometry: RenderedQueryGeometry,
1564        options: RenderedQueryOptions,
1565    ) -> Result<Completion<Vec<Feature>>, Error> {
1566        geometry.points()?;
1567        self.operation(move |worker, _| match geometry.within(worker.size()).map(|geometry| geometry.points()) {
1568            Some(points) => worker.renderer()?.query_rendered_features(&points?, &options),
1569            None => Ok(Vec::new()),
1570        })
1571    }
1572
1573    /// The features of the source `source_id` in the tiles that it loaded
1574    /// for the current view. A source loads tiles only while a visible layer
1575    /// uses it.
1576    ///
1577    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an
1578    /// empty `source_id`.
1579    pub fn query_source_features(
1580        &self,
1581        source_id: impl Into<String>,
1582        options: SourceQueryOptions,
1583    ) -> Result<Completion<Vec<Feature>>, Error> {
1584        let source_id = source_id_of(source_id)?;
1585        self.operation(move |worker, _| worker.renderer()?.query_source_features(&source_id, &options))
1586    }
1587
1588    /// The clusters and points that a cluster of a clustered GeoJSON source
1589    /// splits into at the next zoom level. `cluster_id` is a cluster
1590    /// feature's `cluster_id` property.
1591    ///
1592    /// The query reads the source as the session's most recent render
1593    /// attempt had it. A cluster ID belongs to one version of the source's
1594    /// data, so query the features again after the data changes.
1595    ///
1596    /// Completes with [`ErrorKind::NotFound`](mln_style::error::ErrorKind) when that
1597    /// render had no source `source_id`, or the source has no cluster
1598    /// `cluster_id`, and with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind)
1599    /// when the source isn't a clustered GeoJSON source.
1600    pub fn cluster_children(
1601        &self,
1602        source_id: impl Into<String>,
1603        cluster_id: u32,
1604    ) -> Result<Completion<Vec<mln_style::feature::Feature<f64>>>, Error> {
1605        let source_id = source_id_of(source_id)?;
1606        self.operation(move |worker, _| worker.cluster(&source_id, cluster_id, |_, children| Ok(children)))
1607    }
1608
1609    /// The points in a cluster of a clustered GeoJSON source: it skips the
1610    /// first `offset`, then holds up to `limit`. It fails as
1611    /// [`cluster_children`](Self::cluster_children) does.
1612    pub fn cluster_leaves(
1613        &self,
1614        source_id: impl Into<String>,
1615        cluster_id: u32,
1616        limit: u32,
1617        offset: u32,
1618    ) -> Result<Completion<Vec<mln_style::feature::Feature<f64>>>, Error> {
1619        let source_id = source_id_of(source_id)?;
1620        self.operation(move |worker, _| {
1621            worker.cluster(&source_id, cluster_id, |index, _| index.leaves(cluster_id, limit, offset))
1622        })
1623    }
1624
1625    /// The zoom level at which a cluster of a clustered GeoJSON source splits
1626    /// into two or more clusters or points. It fails as
1627    /// [`cluster_children`](Self::cluster_children) does.
1628    pub fn cluster_expansion_zoom(
1629        &self,
1630        source_id: impl Into<String>,
1631        cluster_id: u32,
1632    ) -> Result<Completion<u8>, Error> {
1633        let source_id = source_id_of(source_id)?;
1634        self.operation(move |worker, _| {
1635            worker.cluster(&source_id, cluster_id, |index, _| index.cluster_expansion_zoom(cluster_id))
1636        })
1637    }
1638
1639    /// Detaches the session from its map and frees its graphics objects. The
1640    /// demands on their way finish as
1641    /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition). Once
1642    /// the detach completes, another session can attach to the map.
1643    pub fn detach(&self) -> Result<Completion<()>, Error> {
1644        let shared = self.shared();
1645        with_unlocked_wakes(|| {
1646            let mut state = shared.state.lock();
1647            if !matches!(state.lifecycle, RenderSessionState::Failed) {
1648                check_usable(&state)?;
1649            } else if state.released {
1650                return Err(released());
1651            }
1652            if state.acquired_frames != 0 {
1653                return Err(Error::invalid_state("release every acquired frame before the session detaches"));
1654            }
1655            let (completion, resolver) = shared.completion();
1656            state.detach_waiters.push(resolver);
1657            shared.start_detach(&mut state);
1658            Ok(completion)
1659        })
1660    }
1661
1662    /// Stops the session at once, without its pending graphics work: that
1663    /// work completes with [`ErrorKind::TargetLost`](mln_style::error::ErrorKind)
1664    /// before this returns, and the demands on their way finish as
1665    /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition). Once it
1666    /// returns, the session renders no more, and another session can attach
1667    /// to the map. Release the session afterward.
1668    ///
1669    /// Returns how many graphics objects the session keeps until the
1670    /// process exits. A caller-driven session abandoned on the thread that
1671    /// services it lets go of them there, at its next service or when its
1672    /// [`DriverWork`] drops, and keeps none. Abandoned on another thread, it
1673    /// keeps them, since only that thread may free them, and logs a warning.
1674    ///
1675    /// It waits for a core worker's driver call on another thread, such as a
1676    /// frame that it renders. Fails with
1677    /// [`ErrorKind::Busy`](mln_style::error::ErrorKind) inside a driver call on the
1678    /// session's own thread, such as from a completion that the session
1679    /// delivers, and while a caller-driven session's service runs on another
1680    /// thread. Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
1681    /// once the session is detached, abandoned or released.
1682    pub fn abandon(&self) -> Result<u32, Error> {
1683        self.shared().abandon(Abandoner::Host)
1684    }
1685
1686    /// Abandons the session as [`abandon`](Self::abandon) does, but makes no
1687    /// graphics call: the session keeps its graphics objects until the
1688    /// process exits. Returns how many it keeps, such as its renderer and
1689    /// the backend it draws with.
1690    ///
1691    /// This is for a host whose shutdown may already have destroyed the
1692    /// graphics objects behind the session.
1693    pub fn abandon_keeping_graphics(&self) -> Result<u32, Error> {
1694        with_unlocked_wakes(|| self.shared().abandon_locked(Abandoner::Host, true))
1695    }
1696
1697    /// Releases the session, detaching it first when it is attached. The
1698    /// completion reports when the session has let go of its map and its
1699    /// graphics objects, and nothing waits for its thread to end after
1700    /// that. Every call on the session fails with
1701    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) after.
1702    ///
1703    /// A caller-driven session detaches at the host's next service, so keep
1704    /// servicing it until the release completes. One that isn't attached,
1705    /// such as while it attaches or after it failed, is abandoned instead,
1706    /// and so is one whose map is released before that service.
1707    pub fn release(&self) -> Result<Completion<()>, Error> {
1708        {
1709            let state = self.shared().state.lock();
1710            let live = matches!(state.lifecycle, RenderSessionState::Attaching | RenderSessionState::Attached);
1711            if live && !state.released && state.acquired_frames != 0 {
1712                return Err(Error::invalid_state("release every acquired frame before the session is released"));
1713            }
1714        }
1715        let (completion, resolver) = self.shared().completion();
1716        self.shared().dispose(Some(resolver))?;
1717        self.detach_thread();
1718        Ok(completion)
1719    }
1720
1721    /// Releases the session in any state, without waiting, and nothing waits
1722    /// for its thread to end. Dropping the last handle does the same, then
1723    /// waits for the thread.
1724    pub fn dispose(&self) -> Result<(), Error> {
1725        self.shared().dispose(None)?;
1726        self.detach_thread();
1727        Ok(())
1728    }
1729
1730    /// Releases the session in any state, without waiting and without a
1731    /// graphics call past the one in progress. A session that hasn't ended
1732    /// is abandoned, keeping its graphics objects until the process exits,
1733    /// as [`abandon_keeping_graphics`](Self::abandon_keeping_graphics) does.
1734    /// Nothing waits for its thread to end.
1735    pub fn dispose_keeping_graphics(&self) -> Result<(), Error> {
1736        self.shared().dispose_keeping_graphics()?;
1737        self.detach_thread();
1738        Ok(())
1739    }
1740
1741    /// Leaves a core worker's thread to end alone, for a release or
1742    /// disposal, which don't wait for it.
1743    fn detach_thread(&self) {
1744        if let Some(thread) = &self.handle.thread_end {
1745            thread.detach();
1746        }
1747    }
1748}
1749
1750/// Counts a ring replacement or release on its way until it runs, or never
1751/// will.
1752struct RetargetGuard(Arc<SessionShared>);
1753
1754impl Drop for RetargetGuard {
1755    fn drop(&mut self) {
1756        let mut state = self.0.state.lock();
1757        state.pending_retargets = state.pending_retargets.saturating_sub(1);
1758    }
1759}
1760
1761/// A frame of a borrowed ring that the host acquired, until it gives it
1762/// back. Dropping it gives it back as [`release`](Self::release) with
1763/// [`SyncKind::CpuComplete`] does.
1764pub struct AcquiredFrame {
1765    shared: Arc<SessionShared>,
1766    /// Dropped after the frame is given back.
1767    thread_end: ThreadEnd,
1768    slot: usize,
1769    frame: Published,
1770    done: bool,
1771}
1772
1773impl std::fmt::Debug for AcquiredFrame {
1774    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1775        f.debug_struct("AcquiredFrame").field("slot", &self.slot).field("frame", &self.frame).finish_non_exhaustive()
1776    }
1777}
1778
1779impl AcquiredFrame {
1780    /// The index of the frame's texture in the ring.
1781    #[must_use]
1782    pub fn slot(&self) -> usize {
1783        self.slot
1784    }
1785
1786    /// The result of the demand that rendered the frame.
1787    #[must_use]
1788    pub fn result(&self) -> &FrameResult {
1789        &self.frame.result
1790    }
1791
1792    /// What to wait for before reading the frame's texture. The object it
1793    /// names is the session's, and stays valid until the frame is given
1794    /// back.
1795    #[must_use]
1796    pub fn producer_sync(&self) -> GpuSync {
1797        self.frame.sync
1798    }
1799
1800    /// The host's texture that holds the frame.
1801    #[must_use]
1802    pub fn texture(&self) -> Option<&FrameTexture> {
1803        self.frame.texture.as_ref()
1804    }
1805
1806    /// Whether [`release`](Self::release) takes a sync of `kind`.
1807    #[must_use]
1808    pub fn accepts(&self, kind: SyncKind) -> bool {
1809        self.shared.capabilities.consumer_sync_kinds.contains(kind)
1810    }
1811
1812    /// Opens a view of the frame, which keeps the frame's texture and sync
1813    /// objects in place until the view drops: an
1814    /// [`abandon`](RenderSession::abandon) fails while one is open, and a
1815    /// dispose of the session keeps them until the last view ends. Keep the
1816    /// frame until its views end.
1817    ///
1818    /// Fails with [`ErrorKind::TargetLost`](mln_style::error::ErrorKind) once the
1819    /// session can no longer render.
1820    pub fn view(&self) -> Result<FrameView, Error> {
1821        let mut state = self.shared.state.lock();
1822        if !matches!(
1823            state.lifecycle,
1824            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
1825        ) {
1826            return Err(Error::target_lost("the render session failed, or was detached, abandoned, or disposed"));
1827        }
1828        state.views += 1;
1829        Ok(FrameView { shared: Arc::clone(&self.shared), _thread_end: self.thread_end.clone() })
1830    }
1831
1832    /// Whether the session can still render: the frame's objects stay valid
1833    /// until it ends.
1834    #[must_use]
1835    pub fn session_live(&self) -> bool {
1836        matches!(
1837            self.shared.state.lock().lifecycle,
1838            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
1839        )
1840    }
1841
1842    /// Gives the frame back once the host's reads of its texture reach
1843    /// `consumer`: the session waits for it before it renders into the
1844    /// texture again, and takes the sync file or GL fence that it names.
1845    ///
1846    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind), handing
1847    /// back the frame and `consumer`, for a kind that the session's
1848    /// [`consumer_sync_kinds`](RenderSessionCapabilities::consumer_sync_kinds)
1849    /// lacks.
1850    #[expect(
1851        clippy::result_large_err,
1852        reason = "the error hands back the frame and the consumer's sync, so that the caller can release it another way"
1853    )]
1854    pub fn release(mut self, consumer: ConsumerSync) -> Result<(), (AcquiredFrame, ConsumerSync, Error)> {
1855        if !self.shared.capabilities.consumer_sync_kinds.contains(consumer.sync.kind) {
1856            return Err((self, consumer, Error::unsupported("render backend does not support this gpu sync kind")));
1857        }
1858        self.done = true;
1859        give_back(&self.shared, self.slot, Some(consumer));
1860        Ok(())
1861    }
1862
1863    /// Gives the frame up without saying when the host's reads end: the
1864    /// session never renders into its texture again, even when
1865    /// [`set_ring`](RenderSession::set_ring) gives the ring the texture
1866    /// again, until a [`release_target`](RenderSession::release_target) of
1867    /// the ring.
1868    pub fn discard(mut self) {
1869        self.done = true;
1870        give_back(&self.shared, self.slot, None);
1871    }
1872}
1873
1874/// A view of an acquired frame, which [`AcquiredFrame::view`] opens, until
1875/// it drops.
1876pub struct FrameView {
1877    shared: Arc<SessionShared>,
1878    /// Dropped after the view ends.
1879    _thread_end: ThreadEnd,
1880}
1881
1882impl std::fmt::Debug for FrameView {
1883    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1884        f.debug_struct("FrameView").finish_non_exhaustive()
1885    }
1886}
1887
1888impl Drop for FrameView {
1889    fn drop(&mut self) {
1890        let release = {
1891            let mut state = self.shared.state.lock();
1892            state.views = state.views.saturating_sub(1);
1893            state.views == 0 && std::mem::take(&mut state.viewed_teardown)
1894        };
1895        if release {
1896            worker::post(&self.shared.queue, |worker, _| worker.release_viewed());
1897        }
1898    }
1899}
1900
1901impl Drop for AcquiredFrame {
1902    fn drop(&mut self) {
1903        if !self.done {
1904            give_back(&self.shared, self.slot, Some(ConsumerSync::of(GpuSync::of(SyncKind::CpuComplete))));
1905        }
1906    }
1907}
1908
1909/// Gives the ring's `slot` back to the session, with the host's `consumer`
1910/// sync, or discarded without one.
1911fn give_back(shared: &Arc<SessionShared>, slot: usize, consumer: Option<ConsumerSync>) {
1912    with_unlocked_wakes(|| {
1913        let mut state = shared.state.lock();
1914        state.acquired_frames = state.acquired_frames.saturating_sub(1);
1915        let live = matches!(
1916            state.lifecycle,
1917            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
1918        );
1919        if !live {
1920            if let Some(entry) = state.ring.get_mut(slot) {
1921                entry.acquired = false;
1922                // The host's GPU may still read a texture whose wait never
1923                // ran.
1924                entry.quarantined |=
1925                    consumer.as_ref().is_none_or(|consumer| consumer.sync.kind != SyncKind::CpuComplete);
1926            }
1927            // A sync file that no backend waits on closes with `consumer`.
1928            return;
1929        }
1930        if let Some(sync) = consumer {
1931            worker::post(&shared.queue, move |worker, outbox| worker.release_slot(slot, sync, outbox));
1932        } else {
1933            if let Some(entry) = state.ring.get_mut(slot) {
1934                entry.acquired = false;
1935                entry.quarantined = !entry.retired;
1936                entry.retired = false;
1937            }
1938            worker::post(&shared.queue, move |worker, outbox| worker.discard_slot(slot, outbox));
1939        }
1940    });
1941}
1942
1943fn source_id_of(source_id: impl Into<String>) -> Result<String, Error> {
1944    let source_id = source_id.into();
1945    if source_id.is_empty() {
1946        return Err(Error::invalid_argument("the source ID must not be empty"));
1947    }
1948    Ok(source_id)
1949}
1950
1951// Handles cross threads; the renderer never leaves its own.
1952const _: () = {
1953    const fn assert_send_sync<T: Send + Sync>() {}
1954    assert_send_sync::<RenderSession>();
1955};