Skip to main content

mln_runtime/render/
local.rs

1//! A render target built on the thread that renders: a [`RenderTarget`]'s
2//! device and surface made into the backend's objects, which belong to that
3//! thread.
4//!
5//! [`RenderTarget`]: super::RenderTarget
6
7// The matches over the backends' enums list a variant per backend that the
8// build's features and target have, so whether their `_` arm is unreachable,
9// or matches a single variant, and whether a `let` of one variant is
10// irrefutable, depends on the build.
11#![allow(
12    unreachable_patterns,
13    irrefutable_let_patterns,
14    clippy::match_wildcard_for_single_variants,
15    reason = "the backends' variants depend on the build's features and target"
16)]
17
18use std::sync::Arc;
19
20use mln_engine::{Renderer, UpdateParameters};
21use mln_gfx::gpu::Gpu;
22#[cfg(any(not(target_family = "wasm"), has_webgl))]
23use mln_gfx::offscreen_target::OffscreenTarget;
24use mln_gfx::rendering_stats::RenderingStats;
25use mln_gfx::ring::{self, Exporter, RingBackend};
26use mln_gfx::{
27    ConsumerSync, ExportKind, ExportedFrame, ExportedRing, FrameImage, FrameTarget, GpuSync, Handoff, RendererBackend,
28    SyncKind, Window,
29};
30use mln_style::bitmap::PremultipliedImage;
31use mln_style::error::Error;
32use mln_style::size::Size;
33
34use super::target::{
35    BorrowedRing, Device, DeviceOptions, FrameTexture, RingKind, Surface, SurfaceKind, SurfaceOverlay,
36};
37use super::{backends, gfx_error, gfx_size};
38
39/// A target of the backend `B` that a session draws into.
40pub(super) type Target<B> = Box<dyn FrameTarget<Gpu = <B as RendererBackend>::Gpu>>;
41
42/// Frames given back to the host: a ring of its textures, on the backend
43/// `B`.
44pub(super) trait Borrowed<B: LocalBackend>: FrameTarget<Gpu = B::Gpu> {
45    fn select(&mut self, slot: usize);
46    fn release(&mut self, gpu: &mut B::Gpu, slot: usize, consumer: ConsumerSync) -> Result<(), mln_gfx::Error>;
47    fn discard(&mut self, gpu: &mut B::Gpu, slot: usize);
48    /// Renders into `textures` from now on, and returns the sync after
49    /// which the host may use the textures that it let go of.
50    fn replace(&mut self, gpu: &mut B::Gpu, textures: B::RingTextures) -> Result<GpuSync, mln_gfx::Error>;
51    /// Lets go of its textures, and returns the sync after which the host
52    /// may use them. It keeps what the sync names until the next release or
53    /// replacement, or until it goes, and draws no frame until then.
54    fn release_textures(&mut self, gpu: &mut B::Gpu) -> Result<GpuSync, mln_gfx::Error>;
55}
56
57/// Frames queued for the host: a ring of the target's own images, which it
58/// exports, on the backend `B`.
59pub(super) trait Exported<B: RendererBackend>: FrameTarget<Gpu = B::Gpu> {
60    fn select(&mut self, slot: usize);
61    fn release(&mut self, gpu: &mut B::Gpu, slot: usize, consumer: ConsumerSync) -> Result<(), mln_gfx::Error>;
62    fn discard(&mut self, gpu: &mut B::Gpu, slot: usize);
63    fn resize_images(&mut self, backend: &mut B, size: mln_gfx::Size, held: &[usize]) -> Result<bool, mln_gfx::Error>;
64    fn size(&self) -> mln_gfx::Size;
65    fn image(&self, slot: usize) -> Option<ExportedFrame>;
66}
67
68impl<R: RingBackend + 'static> Borrowed<R::Renderer> for ring::BorrowedTarget<R>
69where
70    R::Renderer: LocalBackend<RingTextures = R::Textures>,
71{
72    fn select(&mut self, slot: usize) {
73        ring::BorrowedTarget::select(self, slot);
74    }
75    fn release(&mut self, gpu: &mut R::Gpu, slot: usize, consumer: ConsumerSync) -> Result<(), mln_gfx::Error> {
76        ring::BorrowedTarget::release(self, gpu, slot, consumer)
77    }
78    fn discard(&mut self, gpu: &mut R::Gpu, slot: usize) {
79        ring::BorrowedTarget::discard(self, gpu, slot);
80    }
81    fn replace(&mut self, gpu: &mut R::Gpu, textures: R::Textures) -> Result<GpuSync, mln_gfx::Error> {
82        ring::BorrowedTarget::replace(self, gpu, textures)
83    }
84    fn release_textures(&mut self, gpu: &mut R::Gpu) -> Result<GpuSync, mln_gfx::Error> {
85        ring::BorrowedTarget::release_textures(self, gpu)
86    }
87}
88
89impl<E: Exporter> Exported<<E::Ring as RingBackend>::Renderer> for ring::ExportedTarget<E> {
90    fn select(&mut self, slot: usize) {
91        ring::ExportedTarget::select(self, slot);
92    }
93    fn release(
94        &mut self,
95        gpu: &mut <E::Ring as RingBackend>::Gpu,
96        slot: usize,
97        consumer: ConsumerSync,
98    ) -> Result<(), mln_gfx::Error> {
99        ring::ExportedTarget::release(self, gpu, slot, consumer)
100    }
101    fn discard(&mut self, gpu: &mut <E::Ring as RingBackend>::Gpu, slot: usize) {
102        ring::ExportedTarget::discard(self, gpu, slot);
103    }
104    fn resize_images(
105        &mut self,
106        backend: &mut <E::Ring as RingBackend>::Renderer,
107        size: mln_gfx::Size,
108        held: &[usize],
109    ) -> Result<bool, mln_gfx::Error> {
110        ring::ExportedTarget::resize(self, backend, size, held)
111    }
112    fn size(&self) -> mln_gfx::Size {
113        ring::ExportedTarget::size(self)
114    }
115    fn image(&self, slot: usize) -> Option<ExportedFrame> {
116        ring::ExportedTarget::image(self, slot)
117    }
118}
119
120/// What a [`BackendGfx`] draws into, which it makes on its backend.
121pub(super) enum FramesInit<'a> {
122    Offscreen(mln_gfx::Size),
123    Borrowed(BorrowedRing, SyncKind),
124    Exported { device: &'a Device, ring: &'a ExportedRing, kind: ExportKind, size: mln_gfx::Size, producer: SyncKind },
125    Surface(Surface, Option<SurfaceOverlay>, mln_gfx::Size),
126}
127
128fn no_ring() -> Error {
129    Error::unsupported("the session's backend renders into no ring of this kind")
130}
131
132pub(super) fn no_surface() -> Error {
133    Error::unsupported("the session's backend presents to no surface of this kind")
134}
135
136/// A backend of the build, and the targets that the session makes on it.
137/// A kind of target that a backend has none of fails with `Unsupported`.
138pub(super) trait LocalBackend: RendererBackend + Sized {
139    /// The host's textures of a ring that the backend renders into.
140    type RingTextures;
141
142    /// The backend's textures of `ring`, `None` for another backend's.
143    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures>;
144
145    /// The backend, by its type.
146    fn by_type(&self) -> BackendRef<'_>;
147
148    /// A target on the backend that renders into the ring of `textures`,
149    /// handing frames over with sync of the kind `producer`.
150    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
151        let _ = (textures, producer);
152        Err(no_ring())
153    }
154
155    /// A target on the backend that renders into a ring of `ring.depth`
156    /// images of `size` pixels, which it exports as `kind`, and hands frames
157    /// over with sync of the kind `producer`.
158    fn exported(
159        &mut self,
160        device: &Device,
161        ring: &ExportedRing,
162        kind: ExportKind,
163        size: mln_gfx::Size,
164        producer: SyncKind,
165    ) -> Result<Box<dyn Exported<Self>>, Error> {
166        let _ = (device, ring, kind, size, producer);
167        Err(Error::unsupported("the session's backend exports no ring"))
168    }
169
170    /// A target on the backend that presents to `surface`, at `size`
171    /// pixels, with `overlay` drawn over its frames. Fails with
172    /// `Unsupported` when only a backend of the target's own can present to
173    /// it: see [`surface_backend`].
174    fn surface(
175        &mut self,
176        surface: Surface,
177        overlay: Option<SurfaceOverlay>,
178        size: mln_gfx::Size,
179    ) -> Result<Target<Self>, Error> {
180        let _ = (surface, overlay, size);
181        Err(no_surface())
182    }
183}
184
185/// What a session draws with and into, whatever its backend: the methods of
186/// [`LocalTarget`] that reach the backend, each one dynamic call.
187pub(super) trait Gfx {
188    fn backend(&self) -> BackendRef<'_>;
189    fn frames(&self) -> FramesKind;
190    fn renderer(&self) -> Option<&Renderer>;
191    fn renderer_mut(&mut self) -> Option<&mut Renderer>;
192    fn renderer_or(&mut self, make: &mut dyn FnMut(&dyn Gpu) -> Renderer) -> &mut Renderer;
193    fn with_gpu(&mut self, f: &mut dyn FnMut(&mut dyn Gpu, Option<&mut Renderer>));
194    fn tear_down_renderer(&mut self) -> Option<RenderingStats>;
195    fn render(&mut self, update: &Arc<UpdateParameters>) -> Option<Handoff>;
196    fn ready_for_frame(&mut self) -> bool;
197    fn with_frame(&mut self, draw: &mut dyn FnMut(&mut dyn Gpu, &FrameImage));
198    fn select_slot(&mut self, slot: usize) -> Result<(), Error>;
199    fn release_slot(&mut self, slot: usize, consumer: ConsumerSync) -> Result<(), Error>;
200    fn discard_slot(&mut self, slot: usize) -> Result<(), Error>;
201    fn exported_size(&self) -> Option<mln_gfx::Size>;
202    fn resize_exported(&mut self, size: mln_gfx::Size, held: &[usize]) -> Result<bool, Error>;
203    fn exported_image(&self, slot: usize) -> Option<ExportedFrame>;
204    fn set_ring(&mut self, ring: BorrowedRing) -> Result<GpuSync, Error>;
205    fn resize(&mut self, size: mln_gfx::Size);
206    fn read_image(&mut self) -> Result<PremultipliedImage, Error>;
207    fn release_surface(&mut self) -> Result<Option<GpuSync>, Error>;
208    fn set_surface(
209        &mut self,
210        surface: Surface,
211        overlay: Option<SurfaceOverlay>,
212        size: mln_gfx::Size,
213    ) -> Result<(), Error>;
214}
215
216/// What a session draws into.
217#[derive(Clone, Copy, PartialEq, Eq)]
218pub(super) enum FramesKind {
219    Offscreen,
220    Presenting,
221    Borrowed { released: bool },
222    Exported,
223}
224
225/// A backend's GPU objects, which the session owns by value: the backend,
226/// the target it draws into, and the renderer that draws, once there is
227/// one. Each call that reaches the backend's `Gpu` lends it, for its scope,
228/// to the renderer and the target. Dropping it tears the renderer and the
229/// target down on the `Gpu`, and drops the target before the backend.
230struct BackendGfx<B: LocalBackend> {
231    // Fields drop in order: the target's native objects, such as a swap
232    // chain, go while the backend's device and `Gpu` live.
233    frames: Frames<B>,
234    renderer: Option<Renderer>,
235    backend: B,
236}
237
238/// What a [`BackendGfx`] draws into.
239enum Frames<B: LocalBackend> {
240    /// Offscreen FBO target for pixel readback (unsupported on browser WebGPU).
241    #[cfg(any(not(target_family = "wasm"), has_webgl))]
242    Offscreen(OffscreenTarget<B::Gpu>),
243    /// `None` once the surface is released.
244    Presenting(Option<Target<B>>),
245    /// `released` once the target let go of the ring's textures, which it
246    /// keeps without them until it gets new ones.
247    Borrowed {
248        target: Box<dyn Borrowed<B>>,
249        released: bool,
250        producer: SyncKind,
251    },
252    Exported(Box<dyn Exported<B>>),
253}
254
255impl<B: LocalBackend> Frames<B> {
256    /// The target to draw into, or `None` while there is no surface or ring.
257    fn target(&mut self) -> Option<&mut dyn FrameTarget<Gpu = B::Gpu>> {
258        match self {
259            #[cfg(any(not(target_family = "wasm"), has_webgl))]
260            Frames::Offscreen(target) => Some(target),
261            Frames::Presenting(target) => Some(&mut **target.as_mut()?),
262            Frames::Borrowed { target, released: false, .. } => Some(&mut **target),
263            Frames::Borrowed { released: true, .. } => None,
264            Frames::Exported(target) => Some(&mut **target),
265        }
266    }
267
268    /// The ring that the frames draw into.
269    fn ring(&mut self) -> Result<&mut dyn Borrowed<B>, Error> {
270        match self {
271            Frames::Borrowed { target, released: false, .. } => Ok(&mut **target),
272            Frames::Borrowed { released: true, .. } => Err(Error::invalid_state("the ring was released")),
273            _ => Err(Error::unsupported("the target has no ring")),
274        }
275    }
276}
277
278/// `backend`, and what `init` says it draws into, made on it.
279pub(super) fn gfx<B: LocalBackend>(mut backend: B, init: FramesInit<'_>) -> Result<Box<dyn Gfx>, Error> {
280    let frames = match init {
281        #[cfg(any(not(target_family = "wasm"), has_webgl))]
282        FramesInit::Offscreen(size) => Frames::Offscreen(OffscreenTarget::new(size)),
283        #[cfg(all(target_family = "wasm", not(has_webgl)))]
284        FramesInit::Offscreen(size) => {
285            let _ = size;
286            return Err(Error::unsupported("the browser WebGPU build renders into canvases only"));
287        }
288        FramesInit::Borrowed(ring, producer) => {
289            let textures = B::ring_textures(ring.kind).ok_or_else(no_ring)?;
290            Frames::Borrowed { target: backend.borrowed(textures, producer)?, released: false, producer }
291        }
292        FramesInit::Exported { device, ring, kind, size, producer } => {
293            Frames::Exported(backend.exported(device, ring, kind, size, producer)?)
294        }
295        FramesInit::Surface(surface, overlay, size) => {
296            Frames::Presenting(Some(backend.surface(surface, overlay, size)?))
297        }
298    };
299    Ok(Box::new(BackendGfx { backend, frames, renderer: None }))
300}
301
302/// `backend`, presenting with `target`.
303#[cfg_attr(
304    not(any(feature = "gl", has_vulkan)),
305    expect(dead_code, reason = "only Vulkan and OpenGL make backends of a surface's own")
306)]
307pub(super) fn presenting<B: LocalBackend>(
308    backend: B,
309    target: impl FrameTarget<Gpu = B::Gpu> + 'static,
310) -> Box<dyn Gfx> {
311    Box::new(BackendGfx { backend, frames: Frames::Presenting(Some(Box::new(target))), renderer: None })
312}
313
314impl<B: LocalBackend> Gfx for BackendGfx<B> {
315    fn backend(&self) -> BackendRef<'_> {
316        self.backend.by_type()
317    }
318
319    fn frames(&self) -> FramesKind {
320        match &self.frames {
321            #[cfg(any(not(target_family = "wasm"), has_webgl))]
322            Frames::Offscreen(_) => FramesKind::Offscreen,
323            Frames::Presenting(_) => FramesKind::Presenting,
324            Frames::Borrowed { released, .. } => FramesKind::Borrowed { released: *released },
325            Frames::Exported(_) => FramesKind::Exported,
326        }
327    }
328
329    fn renderer(&self) -> Option<&Renderer> {
330        self.renderer.as_ref()
331    }
332
333    fn renderer_mut(&mut self) -> Option<&mut Renderer> {
334        self.renderer.as_mut()
335    }
336
337    fn renderer_or(&mut self, make: &mut dyn FnMut(&dyn Gpu) -> Renderer) -> &mut Renderer {
338        let BackendGfx { backend, renderer, .. } = self;
339        renderer.get_or_insert_with(|| make(&*backend.gpu()))
340    }
341
342    fn with_gpu(&mut self, f: &mut dyn FnMut(&mut dyn Gpu, Option<&mut Renderer>)) {
343        f(&mut *self.backend.gpu(), self.renderer.as_mut());
344    }
345
346    fn tear_down_renderer(&mut self) -> Option<RenderingStats> {
347        let renderer = self.renderer.take()?;
348        Some(renderer.tear_down(&mut *self.backend.gpu()))
349    }
350
351    fn render(&mut self, update: &Arc<UpdateParameters>) -> Option<Handoff> {
352        let renderer = self.renderer.as_mut()?;
353        let target = self.frames.target()?;
354        let mut gpu = self.backend.gpu();
355        let gpu = &mut *gpu;
356        let frame = renderer.update(gpu, update)?;
357        let image = target.begin_frame(gpu)?;
358        let drawn = renderer.render(gpu, &image, frame);
359        let handoff = target.end_frame(gpu);
360        renderer.finish_frame(gpu, drawn, handoff);
361        Some(handoff)
362    }
363
364    fn ready_for_frame(&mut self) -> bool {
365        let Some(target) = self.frames.target() else { return false };
366        target.begin_frame(&mut self.backend.gpu()).is_some()
367    }
368
369    fn with_frame(&mut self, draw: &mut dyn FnMut(&mut dyn Gpu, &FrameImage)) {
370        let Some(target) = self.frames.target() else { return };
371        let mut gpu = self.backend.gpu();
372        if let Some(image) = target.begin_frame(&mut gpu) {
373            draw(&mut *gpu, &image);
374        }
375    }
376
377    fn select_slot(&mut self, slot: usize) -> Result<(), Error> {
378        match &mut self.frames {
379            Frames::Exported(target) => target.select(slot),
380            frames => frames.ring()?.select(slot),
381        }
382        Ok(())
383    }
384
385    fn release_slot(&mut self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
386        let gpu = &mut *self.backend.gpu();
387        match &mut self.frames {
388            Frames::Exported(target) => target.release(gpu, slot, consumer),
389            frames => frames.ring()?.release(gpu, slot, consumer),
390        }
391        .map_err(gfx_error)
392    }
393
394    fn discard_slot(&mut self, slot: usize) -> Result<(), Error> {
395        let gpu = &mut *self.backend.gpu();
396        match &mut self.frames {
397            Frames::Exported(target) => target.discard(gpu, slot),
398            frames => frames.ring()?.discard(gpu, slot),
399        }
400        Ok(())
401    }
402
403    fn exported_size(&self) -> Option<mln_gfx::Size> {
404        match &self.frames {
405            Frames::Exported(target) => Some(target.size()),
406            _ => None,
407        }
408    }
409
410    fn resize_exported(&mut self, size: mln_gfx::Size, held: &[usize]) -> Result<bool, Error> {
411        match &mut self.frames {
412            Frames::Exported(target) => target.resize_images(&mut self.backend, size, held).map_err(gfx_error),
413            _ => Err(Error::unsupported("the target exports no ring")),
414        }
415    }
416
417    fn exported_image(&self, slot: usize) -> Option<ExportedFrame> {
418        match &self.frames {
419            Frames::Exported(target) => target.image(slot),
420            _ => None,
421        }
422    }
423
424    fn set_ring(&mut self, ring: BorrowedRing) -> Result<GpuSync, Error> {
425        let Frames::Borrowed { target, released, producer } = &mut self.frames else {
426            return Err(Error::unsupported("the target has no ring"));
427        };
428        let textures = B::ring_textures(ring.kind).ok_or_else(no_ring)?;
429        if !*released {
430            return target.replace(&mut self.backend.gpu(), textures).map_err(gfx_error);
431        }
432        // The released target, which kept what its release's sync names
433        // until now, goes once its frames are done.
434        let next = self.backend.borrowed(textures, *producer)?;
435        std::mem::replace(target, next).tear_down(&mut self.backend.gpu());
436        *released = false;
437        Ok(GpuSync::of(SyncKind::CpuComplete))
438    }
439
440    fn resize(&mut self, size: mln_gfx::Size) {
441        if let Some(target) = self.frames.target() {
442            target.resize(&mut self.backend.gpu(), size);
443        }
444    }
445
446    fn read_image(&mut self) -> Result<PremultipliedImage, Error> {
447        match &mut self.frames {
448            #[cfg(any(not(target_family = "wasm"), has_webgl))]
449            Frames::Offscreen(target) => {
450                let pixels = target.read_image(&mut self.backend.gpu()).map_err(gfx_error)?;
451                Ok(PremultipliedImage::from_vec(Size::new(pixels.size.width, pixels.size.height), pixels.data))
452            }
453            Frames::Presenting(_) => Err(Error::unsupported("a surface session can't read its frames back")),
454            Frames::Borrowed { .. } | Frames::Exported(_) => {
455                Err(Error::unsupported("a ring's frames are the host's to read"))
456            }
457        }
458    }
459
460    fn release_surface(&mut self) -> Result<Option<GpuSync>, Error> {
461        let gpu = &mut *self.backend.gpu();
462        match &mut self.frames {
463            Frames::Presenting(target) => {
464                if let Some(mut target) = target.take() {
465                    target.tear_down(gpu);
466                }
467                Ok(None)
468            }
469            Frames::Borrowed { released: true, .. } => Ok(Some(GpuSync::of(SyncKind::CpuComplete))),
470            Frames::Borrowed { target, released, .. } => {
471                let sync = target.release_textures(gpu).map_err(gfx_error)?;
472                *released = true;
473                Ok(Some(sync))
474            }
475            #[cfg(any(not(target_family = "wasm"), has_webgl))]
476            Frames::Offscreen(_) => Ok(None),
477            Frames::Exported(_) => Ok(None),
478        }
479    }
480
481    fn set_surface(
482        &mut self,
483        surface: Surface,
484        overlay: Option<SurfaceOverlay>,
485        size: mln_gfx::Size,
486    ) -> Result<(), Error> {
487        let target = self.backend.surface(surface, overlay, size)?;
488        if let Frames::Presenting(old) = &mut self.frames
489            && let Some(mut old) = old.take()
490        {
491            old.tear_down(&mut self.backend.gpu());
492        }
493        self.frames = Frames::Presenting(Some(target));
494        Ok(())
495    }
496}
497
498impl<B: LocalBackend> Drop for BackendGfx<B> {
499    fn drop(&mut self) {
500        let mut gpu = self.backend.gpu();
501        if let Some(renderer) = self.renderer.take() {
502            renderer.tear_down(&mut *gpu);
503        }
504        // A released ring keeps the objects that its release's sync names.
505        if let Frames::Borrowed { target, .. } = &mut self.frames {
506            target.tear_down(&mut gpu);
507        } else if let Some(target) = self.frames.target() {
508            target.tear_down(&mut gpu);
509        }
510    }
511}
512
513/// A backend on `device`, and what `init` says it draws into.
514fn new_gfx(device: &Device, init: FramesInit<'_>) -> Result<Box<dyn Gfx>, Error> {
515    match device {
516        #[cfg(feature = "webgpu")]
517        Device::WebGpu(device) => backends::webgpu::new_gfx(device, init),
518        #[cfg(has_metal)]
519        Device::Metal(device) => backends::metal::new_gfx(device, init),
520        #[cfg(has_vulkan)]
521        Device::Vulkan(device) => backends::vulkan::new_gfx(device, init),
522        #[cfg(has_d3d12)]
523        Device::D3d12(device) => backends::d3d12::new_gfx(device, init),
524        #[cfg(has_native_gl)]
525        Device::Gl(device) => backends::gl::new_gfx_native(device, init),
526        #[cfg(has_webgl)]
527        Device::WebGl(device) => backends::gl::new_gfx_webgl(device.as_ref(), init),
528    }
529}
530
531/// The overlay of the backend that `own` picks out of `overlay`. Fails with
532/// `Unsupported` for another backend's.
533#[cfg_attr(
534    not(any(feature = "webgpu", has_metal, has_vulkan, has_d3d12, has_gl_window)),
535    expect(dead_code, reason = "a build without a backend that takes overlays uses none")
536)]
537pub(super) fn overlay_of<T>(
538    overlay: Option<SurfaceOverlay>,
539    own: impl FnOnce(SurfaceOverlay) -> Result<T, SurfaceOverlay>,
540) -> Result<Option<T>, Error> {
541    overlay
542        .map(own)
543        .transpose()
544        .map_err(|_| Error::unsupported("the surface's overlay is for another backend than the session's"))
545}
546
547/// A backend of the target's own on `device` and a target that presents to
548/// `surface` with `overlay` drawn over its frames, for the backends whose
549/// context or device is made for the window: Vulkan's, whose instance and
550/// device take the window's surface extensions, and OpenGL ES's, whose
551/// context is of the window's display.
552fn surface_backend(
553    device: &Device,
554    surface: Surface,
555    overlay: Option<SurfaceOverlay>,
556    size: mln_gfx::Size,
557) -> Result<Box<dyn Gfx>, Error> {
558    let cap_frame_rate = surface.cap_frame_rate;
559    match (device, surface.kind) {
560        #[cfg(has_vulkan)]
561        (Device::Vulkan(device), SurfaceKind::Window(window)) => {
562            backends::vulkan::window_surface_gfx(device, window, overlay, size, cap_frame_rate)
563        }
564        #[cfg(has_vulkan)]
565        (Device::Vulkan(device), kind @ SurfaceKind::Vulkan(_)) => {
566            backends::vulkan::host_surface_gfx(device, kind, overlay, size, cap_frame_rate)
567        }
568        #[cfg(has_native_gl)]
569        (Device::Gl(device), SurfaceKind::Gl(host)) => {
570            backends::gl::host_surface_gfx(device, host, overlay.as_ref(), size)
571        }
572        #[cfg(has_gl_window)]
573        (Device::Gl(_), SurfaceKind::Window(window)) => {
574            backends::gl::window_surface_gfx(window, overlay, size, cap_frame_rate)
575        }
576        #[cfg(has_webgl)]
577        (Device::WebGl(wrapped), SurfaceKind::WebCanvas { canvas, .. }) => {
578            backends::gl::web_canvas_gfx(wrapped.as_ref(), canvas, size)
579        }
580        (_, kind) => new_gfx(device, FramesInit::Surface(Surface { kind, cap_frame_rate }, overlay, size)),
581    }
582}
583
584/// A target's backend, by its type, for a host that reads what the backend
585/// tells of its device.
586#[non_exhaustive]
587pub enum BackendRef<'a> {
588    #[cfg(feature = "webgpu")]
589    WebGpu(&'a mln_webgpu::RendererBackend),
590    #[cfg(has_metal)]
591    Metal(&'a mln_mtl::RendererBackend),
592    #[cfg(has_vulkan)]
593    Vulkan(&'a mln_vulkan::RendererBackend),
594    #[cfg(has_d3d12)]
595    D3d12(&'a mln_d3d12::RendererBackend),
596    #[cfg(feature = "gl")]
597    Gl(&'a mln_gl::RendererBackend),
598}
599
600/// A render target built on this thread: the backend, on the target's
601/// device, the frames it draws into, and the renderer that draws them,
602/// which the target owns and lends the backend's `Gpu` to.
603pub struct LocalTarget {
604    device: Device,
605    gfx: Box<dyn Gfx>,
606    /// The window that a surface target presents to, if it presents to one.
607    window: Option<Arc<dyn Window>>,
608}
609
610impl LocalTarget {
611    /// An offscreen target of `size` pixels on `device`, or on a device that
612    /// [`Device::new`] makes when that is `None`.
613    ///
614    /// Fails as [`Device::new`] does, and with the backend's error when it
615    /// can't render on the device.
616    pub fn offscreen(device: Option<Device>, size: Size) -> Result<LocalTarget, Error> {
617        let device = match device {
618            Some(device) => device,
619            #[cfg(has_webgl)]
620            None => Device::WebGl(None),
621            #[cfg(not(has_webgl))]
622            None => Device::new(DeviceOptions::default())?,
623        };
624        let gfx = new_gfx(&device, FramesInit::Offscreen(gfx_size(size)))?;
625        Ok(LocalTarget { device, gfx, window: None })
626    }
627
628    /// A target of `size` pixels that presents to `surface`, with `overlay`
629    /// drawn over its frames, on `device` or, when that is `None`, on the
630    /// device the surface's kind takes
631    /// ([`RenderTarget::Surface`](super::RenderTarget::Surface)).
632    ///
633    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
634    /// surface that the host made without the host's device, with
635    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a window or
636    /// surface without an area to present to, such as a minimized window,
637    /// with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when the device
638    /// can't present to the surface or draw the overlay, and with the error
639    /// of the device or the window's surface.
640    pub fn surface(
641        surface: Surface,
642        overlay: Option<SurfaceOverlay>,
643        device: Option<Device>,
644        size: Size,
645    ) -> Result<LocalTarget, Error> {
646        surface.check_area()?;
647        let window = surface.host_window();
648        let device = match device {
649            Some(device) => device,
650            None => default_surface_device(&surface)?,
651        };
652        let gfx = surface_backend(&device, surface, overlay, gfx_size(size))?;
653        Ok(LocalTarget { device, gfx, window })
654    }
655
656    /// A target of `size` pixels on `device` that renders into the host's
657    /// `ring`, and hands each frame over with sync of the kind `producer`.
658    ///
659    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when the
660    /// device can't render into the ring with `producer`, and with the
661    /// backend's error.
662    pub fn borrowed(device: Device, ring: BorrowedRing, producer: SyncKind) -> Result<LocalTarget, Error> {
663        let gfx = new_gfx(&device, FramesInit::Borrowed(ring, producer))?;
664        Ok(LocalTarget { device, gfx, window: None })
665    }
666
667    /// A target on `device` that renders into a ring of `ring.depth` images
668    /// of `size` pixels, which it exports as `kind`, one that
669    /// [`Device::export_plan`] picked, and hands each frame over with sync of
670    /// the kind `producer`.
671    ///
672    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when the
673    /// device can't export `kind` or hand frames over with `producer`, and
674    /// with the backend's error.
675    pub fn exported(
676        device: Device,
677        ring: &ExportedRing,
678        kind: ExportKind,
679        size: Size,
680        producer: SyncKind,
681    ) -> Result<LocalTarget, Error> {
682        let gfx =
683            new_gfx(&device, FramesInit::Exported { device: &device, ring, kind, size: gfx_size(size), producer })?;
684        Ok(LocalTarget { device, gfx, window: None })
685    }
686
687    /// The device the target renders on.
688    #[must_use]
689    pub fn device(&self) -> &Device {
690        &self.device
691    }
692
693    /// The backend the target and its renderer draw with.
694    #[must_use]
695    pub fn backend(&self) -> BackendRef<'_> {
696        self.gfx.backend()
697    }
698
699    /// Runs `f` with the backend's `Gpu`, as when the host waits for the
700    /// frames drawn so far.
701    pub fn with_gpu(&mut self, mut f: impl FnMut(&mut dyn Gpu)) {
702        self.gfx.with_gpu(&mut |gpu, _| f(gpu));
703    }
704
705    /// The renderer that draws into the target, which `make` makes with the
706    /// backend's `Gpu` unless the target has one: the renderer draws with
707    /// that `Gpu` only.
708    pub fn renderer_or(&mut self, mut make: impl FnMut(&dyn Gpu) -> Renderer) -> &mut Renderer {
709        self.gfx.renderer_or(&mut make)
710    }
711
712    /// The renderer that draws into the target, if it has one.
713    #[must_use]
714    pub fn renderer(&self) -> Option<&Renderer> {
715        self.gfx.renderer()
716    }
717
718    /// The renderer that draws into the target, if it has one.
719    pub fn renderer_mut(&mut self) -> Option<&mut Renderer> {
720        self.gfx.renderer_mut()
721    }
722
723    /// Runs `f` with the target's renderer and the backend's `Gpu`, which the
724    /// renderer's calls that make, draw or free its GPU objects take, or
725    /// returns `None` without a renderer.
726    pub fn with_renderer<R>(&mut self, f: impl FnOnce(&mut Renderer, &mut dyn Gpu) -> R) -> Option<R> {
727        self.gfx.renderer()?;
728        let (mut f, mut result) = (Some(f), None);
729        self.gfx.with_gpu(&mut |gpu, renderer| {
730            if let (Some(renderer), Some(f)) = (renderer, f.take()) {
731                result = Some(f(renderer, gpu));
732            }
733        });
734        result
735    }
736
737    /// Tears the renderer down on the backend's `Gpu`, if the target has
738    /// one, and returns its rendering stats as it leaves them.
739    pub fn tear_down_renderer(&mut self) -> Option<RenderingStats> {
740        self.gfx.tear_down_renderer()
741    }
742
743    /// Draws `update` with the target's renderer into a frame: the target
744    /// begins the frame, the renderer draws into it, and the target ends
745    /// it. Returns where the frame went, or `None` when nothing was drawn:
746    /// there is no renderer, the target had nothing to draw into, or there
747    /// was nothing to draw.
748    pub fn render(&mut self, update: &Arc<UpdateParameters>) -> Option<Handoff> {
749        self.gfx.render(update)
750    }
751
752    /// Runs `draw` with the backend's `Gpu` and the textures of the target's
753    /// frame, to draw into them alongside the map. The frame is the one the
754    /// next render draws into, which the target begins unless it has
755    /// begun it. `None` when the target has nothing to draw into now.
756    pub fn with_frame<R>(&mut self, draw: impl FnOnce(&mut dyn Gpu, &FrameImage) -> R) -> Option<R> {
757        let (mut draw, mut result) = (Some(draw), None);
758        self.gfx.with_frame(&mut |gpu, image| result = draw.take().map(|draw| draw(gpu, image)));
759        result
760    }
761
762    /// Whether the target can take a frame now: its window, if any, has an
763    /// area to present to, and it begins a frame, which a surface needs a
764    /// texture for, and which the next render draws into.
765    pub fn ready_for_frame(&mut self) -> bool {
766        self.window_has_area() && self.gfx.ready_for_frame()
767    }
768
769    /// Whether the target can take a frame as far as its window says: it
770    /// presents to no window, or to one with an area to present to
771    /// ([`mln_gfx::window::has_area`]).
772    #[must_use]
773    pub fn window_has_area(&self) -> bool {
774        self.window.as_deref().is_none_or(mln_gfx::window::has_area)
775    }
776
777    /// Whether frames are presented to a window or surface.
778    #[must_use]
779    pub fn is_presenting(&self) -> bool {
780        self.gfx.frames() == FramesKind::Presenting
781    }
782
783    /// Whether frames go to the host's ring.
784    #[must_use]
785    pub fn is_borrowed(&self) -> bool {
786        matches!(self.gfx.frames(), FramesKind::Borrowed { .. })
787    }
788
789    /// Whether the target is a ring that let go of its textures.
790    #[must_use]
791    pub fn ring_released(&self) -> bool {
792        self.gfx.frames() == FramesKind::Borrowed { released: true }
793    }
794
795    /// Whether frames are read back rather than presented.
796    #[must_use]
797    pub fn is_offscreen(&self) -> bool {
798        self.gfx.frames() == FramesKind::Offscreen
799    }
800
801    /// Has the next frame render into the ring's texture at `slot`.
802    pub fn select_slot(&mut self, slot: usize) -> Result<(), Error> {
803        self.gfx.select_slot(slot)
804    }
805
806    /// The host gave the ring's texture at `slot` back: the next frame
807    /// rendered into it waits for `consumer`.
808    pub fn release_slot(&mut self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
809        self.gfx.release_slot(slot, consumer)
810    }
811
812    /// The host gave up the ring's texture at `slot`, which the target
813    /// renders into no more.
814    pub fn discard_slot(&mut self, slot: usize) -> Result<(), Error> {
815        self.gfx.discard_slot(slot)
816    }
817
818    /// The size in pixels of an exported ring's images, or `None` for
819    /// another target.
820    #[must_use]
821    pub fn exported_size(&self) -> Option<Size> {
822        self.gfx.exported_size().map(|size| Size::new(size.width, size.height))
823    }
824
825    /// Renders an exported ring's next frames into images of `size` pixels.
826    /// The frames that the host holds, at `held` slots, keep their images.
827    /// Returns whether the ring has new images, which it doesn't when they
828    /// have `size` already.
829    ///
830    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
831    /// target that isn't an exported ring, and with the backend's error, when
832    /// the ring keeps its images.
833    pub fn resize_exported(&mut self, size: Size, held: &[usize]) -> Result<bool, Error> {
834        self.gfx.resize_exported(gfx_size(size), held)
835    }
836
837    /// The exported image of the frame at `slot`, of the size it has.
838    #[must_use]
839    pub fn exported_texture(&self, slot: usize) -> Option<FrameTexture> {
840        let image = self.gfx.exported_image(slot)?;
841        Some(FrameTexture::exported(image, &self.device))
842    }
843
844    /// Renders into `ring` from now on, in place of the ring's textures, and
845    /// returns the sync after which the host may use the textures that it
846    /// let go of: of the target's producer kind, or
847    /// [`SyncKind::CpuComplete`] when it had none since a release.
848    ///
849    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
850    /// target that isn't a ring, or a ring of another format, and with the
851    /// backend's error. The target then keeps its textures.
852    pub(crate) fn set_ring(&mut self, ring: BorrowedRing) -> Result<GpuSync, Error> {
853        self.gfx.set_ring(ring)
854    }
855
856    /// Draws the next frame at `size` pixels.
857    pub fn resize(&mut self, size: Size) {
858        self.gfx.resize(gfx_size(size));
859    }
860
861    /// The last frame's pixels.
862    ///
863    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
864    /// target that presents its frames, with
865    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) before a frame, and
866    /// with [`ErrorKind::Failed`](mln_style::error::ErrorKind) where the backend
867    /// reads nothing back.
868    pub fn read_image(&mut self) -> Result<PremultipliedImage, Error> {
869        self.gfx.read_image()
870    }
871
872    /// Lets go of a surface target's surface, or of a ring's textures, and
873    /// returns, for a ring, the sync after which the host may use them. The
874    /// backend and its renderer stay.
875    ///
876    /// Fails with [`ErrorKind::Failed`](mln_style::error::ErrorKind) when a ring
877    /// can't submit its work on the textures, which it keeps then.
878    pub(crate) fn release_surface(&mut self) -> Result<Option<GpuSync>, Error> {
879        let sync = self.gfx.release_surface()?;
880        if self.is_presenting() {
881            self.window = None;
882        }
883        Ok(sync)
884    }
885
886    /// Presents to `surface` at `size` pixels from now on, with `overlay`
887    /// drawn over its frames, in place of the surface the target has, if
888    /// any: on the same backend where it can present to `surface`, and on a
889    /// new one of the device otherwise, which the target then returns true
890    /// for, and which draws no overlay. The renderer on the old backend is
891    /// torn down with it, and the target has none until one is made again
892    /// on the new backend ([`renderer_or`](Self::renderer_or)).
893    ///
894    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for an
895    /// offscreen target or when the device can't present to `surface`, and
896    /// as [`surface`](Self::surface) does. The target then keeps what it
897    /// had.
898    pub fn set_surface(
899        &mut self,
900        surface: Surface,
901        overlay: Option<SurfaceOverlay>,
902        size: Size,
903    ) -> Result<bool, Error> {
904        if !self.is_presenting() {
905            return Err(Error::unsupported("only a surface target presents to another surface"));
906        }
907        surface.check_area()?;
908        let window = surface.host_window();
909        let retry = surface.clone_window();
910        let size = gfx_size(size);
911        let new_backend = match self.gfx.set_surface(surface, overlay, size) {
912            Ok(()) => false,
913            Err(error) if error.kind == mln_style::error::ErrorKind::Unsupported => {
914                let surface = retry.ok_or(error)?;
915                self.gfx = surface_backend(&self.device, surface, None, size)?;
916                true
917            }
918            Err(error) => return Err(error),
919        };
920        self.window = window;
921        Ok(new_backend)
922    }
923}
924
925/// The device a surface renders on without the host's: the native one where
926/// its backend takes the surface's kind.
927fn default_surface_device(surface: &Surface) -> Result<Device, Error> {
928    match surface.kind {
929        SurfaceKind::Window(_) => Device::new(DeviceOptions::default()),
930        #[cfg(has_metal)]
931        SurfaceKind::MetalLayer(_) => Device::with_backend(super::target::BackendType::Metal, DeviceOptions::default()),
932        #[cfg(has_native_webgpu)]
933        SurfaceKind::Wgpu(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
934        #[cfg(has_vulkan)]
935        SurfaceKind::Vulkan(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
936        #[cfg(has_native_gl)]
937        SurfaceKind::Gl(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
938        #[cfg(has_d3d12)]
939        SurfaceKind::D3d12Composition { .. } => {
940            Device::with_backend(super::target::BackendType::D3D12, DeviceOptions::default())
941        }
942        // A WebGPU build asked the browser for a device before the build.
943        #[cfg(has_webgl)]
944        SurfaceKind::WebCanvas { .. } => Ok(Device::WebGl(None)),
945        #[cfg(all(target_family = "wasm", not(feature = "gl")))]
946        SurfaceKind::WebCanvas { .. } => Err(Error::invalid_state("the browser's WebGPU device isn't there yet")),
947    }
948}