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