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// and whether a `let` of one variant is irrefutable, depends on the build.
10#![allow(
11    unreachable_patterns,
12    irrefutable_let_patterns,
13    reason = "the backends' variants depend on the build's features and target"
14)]
15#![cfg_attr(
16    all(target_family = "wasm", not(feature = "webgpu")),
17    expect(dead_code, reason = "WebGL2 renders only into a canvas, whose target makes its backend")
18)]
19
20use std::sync::Arc;
21
22use mln_gfx::gpu::Gpu;
23#[cfg(not(target_family = "wasm"))]
24use mln_gfx::offscreen_target::OffscreenTarget;
25use mln_gfx::rendering_stats::RenderingStats;
26use mln_gfx::ring::{self, Exporter, RingBackend};
27use mln_gfx::{
28    ConsumerSync, ExportKind, ExportedFrame, ExportedRing, FrameImage, FrameTarget, GpuSync, Handoff, RendererBackend,
29    SyncKind, Window,
30};
31use mln_renderer::{Renderer, UpdateParameters};
32use mln_util::error::Error;
33use mln_util::image::PremultipliedImage;
34use mln_util::size::Size;
35
36use super::target::{
37    BorrowedRing, Device, DeviceOptions, FrameTexture, RingKind, Surface, SurfaceKind, SurfaceOverlay,
38};
39
40/// A target of the backend `B` that a session draws into.
41type Target<B> = Box<dyn FrameTarget<Gpu = <B as RendererBackend>::Gpu>>;
42
43/// Frames given back to the host: a ring of its textures, on the backend
44/// `B`.
45trait Borrowed<B: LocalBackend>: FrameTarget<Gpu = B::Gpu> {
46    fn select(&mut self, slot: usize);
47    fn release(&mut self, gpu: &mut B::Gpu, slot: usize, consumer: ConsumerSync) -> Result<(), Error>;
48    fn discard(&mut self, gpu: &mut B::Gpu, slot: usize);
49    /// Renders into `textures` from now on, and returns the sync after
50    /// which the host may use the textures that it let go of.
51    fn replace(&mut self, gpu: &mut B::Gpu, textures: B::RingTextures) -> Result<GpuSync, Error>;
52    /// Lets go of its textures, and returns the sync after which the host
53    /// may use them. It keeps what the sync names until the next release or
54    /// replacement, or until it goes, and draws no frame until then.
55    fn release_textures(&mut self, gpu: &mut B::Gpu) -> Result<GpuSync, Error>;
56}
57
58/// Frames queued for the host: a ring of the target's own images, which it
59/// exports, on the backend `B`.
60trait Exported<B: RendererBackend>: FrameTarget<Gpu = B::Gpu> {
61    fn select(&mut self, slot: usize);
62    fn release(&mut self, gpu: &mut B::Gpu, slot: usize, consumer: ConsumerSync) -> Result<(), Error>;
63    fn discard(&mut self, gpu: &mut B::Gpu, slot: usize);
64    fn resize_images(&mut self, backend: &mut B, size: Size, held: &[usize]) -> Result<bool, Error>;
65    fn size(&self) -> Size;
66    fn image(&self, slot: usize) -> Option<ExportedFrame>;
67}
68
69impl<R: RingBackend + 'static> Borrowed<R::Renderer> for ring::BorrowedTarget<R>
70where
71    R::Renderer: LocalBackend<RingTextures = R::Textures>,
72{
73    fn select(&mut self, slot: usize) {
74        ring::BorrowedTarget::select(self, slot);
75    }
76    fn release(&mut self, gpu: &mut R::Gpu, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
77        ring::BorrowedTarget::release(self, gpu, slot, consumer)
78    }
79    fn discard(&mut self, gpu: &mut R::Gpu, slot: usize) {
80        ring::BorrowedTarget::discard(self, gpu, slot);
81    }
82    fn replace(&mut self, gpu: &mut R::Gpu, textures: R::Textures) -> Result<GpuSync, Error> {
83        ring::BorrowedTarget::replace(self, gpu, textures)
84    }
85    fn release_textures(&mut self, gpu: &mut R::Gpu) -> Result<GpuSync, Error> {
86        ring::BorrowedTarget::release_textures(self, gpu)
87    }
88}
89
90#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
91impl Borrowed<mln_webgpu::RendererBackend> for mln_webgpu::BorrowedTarget {
92    fn select(&mut self, slot: usize) {
93        mln_webgpu::BorrowedTarget::select(self, slot);
94    }
95    fn release(&mut self, _gpu: &mut mln_webgpu::WebGpu, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
96        mln_webgpu::BorrowedTarget::release(self, slot, consumer)
97    }
98    fn discard(&mut self, _gpu: &mut mln_webgpu::WebGpu, slot: usize) {
99        mln_webgpu::BorrowedTarget::discard(self, slot);
100    }
101    fn replace(
102        &mut self,
103        gpu: &mut mln_webgpu::WebGpu,
104        textures: mln_webgpu::BorrowedTextures,
105    ) -> Result<GpuSync, Error> {
106        mln_webgpu::BorrowedTarget::replace(self, gpu, textures)
107    }
108    fn release_textures(&mut self, gpu: &mut mln_webgpu::WebGpu) -> Result<GpuSync, Error> {
109        mln_webgpu::BorrowedTarget::release_textures(self, gpu)
110    }
111}
112
113#[cfg(all(feature = "gl", not(target_family = "wasm")))]
114impl Borrowed<mln_gl::RendererBackend> for mln_gl::BorrowedTarget {
115    fn select(&mut self, slot: usize) {
116        mln_gl::BorrowedTarget::select(self, slot);
117    }
118    fn release(&mut self, gpu: &mut mln_gl::GlGpu, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
119        mln_gl::BorrowedTarget::release(self, gpu, slot, consumer)
120    }
121    fn discard(&mut self, gpu: &mut mln_gl::GlGpu, slot: usize) {
122        mln_gl::BorrowedTarget::discard(self, gpu, slot);
123    }
124    fn replace(&mut self, gpu: &mut mln_gl::GlGpu, textures: mln_gl::BorrowedTextures) -> Result<GpuSync, Error> {
125        mln_gl::BorrowedTarget::replace(self, gpu, textures)
126    }
127    fn release_textures(&mut self, gpu: &mut mln_gl::GlGpu) -> Result<GpuSync, Error> {
128        mln_gl::BorrowedTarget::release_textures(self, gpu)
129    }
130}
131
132impl<E: Exporter> Exported<<E::Ring as RingBackend>::Renderer> for ring::ExportedTarget<E> {
133    fn select(&mut self, slot: usize) {
134        ring::ExportedTarget::select(self, slot);
135    }
136    fn release(
137        &mut self,
138        gpu: &mut <E::Ring as RingBackend>::Gpu,
139        slot: usize,
140        consumer: ConsumerSync,
141    ) -> Result<(), Error> {
142        ring::ExportedTarget::release(self, gpu, slot, consumer)
143    }
144    fn discard(&mut self, gpu: &mut <E::Ring as RingBackend>::Gpu, slot: usize) {
145        ring::ExportedTarget::discard(self, gpu, slot);
146    }
147    fn resize_images(
148        &mut self,
149        backend: &mut <E::Ring as RingBackend>::Renderer,
150        size: Size,
151        held: &[usize],
152    ) -> Result<bool, Error> {
153        ring::ExportedTarget::resize(self, backend, size, held)
154    }
155    fn size(&self) -> Size {
156        ring::ExportedTarget::size(self)
157    }
158    fn image(&self, slot: usize) -> Option<ExportedFrame> {
159        ring::ExportedTarget::image(self, slot)
160    }
161}
162
163#[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
164impl Exported<mln_gl::RendererBackend> for mln_gl::ExportedTarget {
165    fn select(&mut self, slot: usize) {
166        mln_gl::ExportedTarget::select(self, slot);
167    }
168    fn release(&mut self, gpu: &mut mln_gl::GlGpu, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
169        mln_gl::ExportedTarget::release(self, gpu, slot, consumer)
170    }
171    fn discard(&mut self, gpu: &mut mln_gl::GlGpu, slot: usize) {
172        mln_gl::ExportedTarget::discard(self, gpu, slot);
173    }
174    fn resize_images(
175        &mut self,
176        backend: &mut mln_gl::RendererBackend,
177        size: Size,
178        held: &[usize],
179    ) -> Result<bool, Error> {
180        mln_gl::ExportedTarget::resize(self, &mut backend.gpu(), size, held)
181    }
182    fn size(&self) -> Size {
183        mln_gl::ExportedTarget::size(self)
184    }
185    fn image(&self, slot: usize) -> Option<ExportedFrame> {
186        mln_gl::ExportedTarget::image(self, slot)
187    }
188}
189
190/// What a [`BackendGfx`] draws into, which it makes on its backend.
191enum FramesInit<'a> {
192    Offscreen(Size),
193    Borrowed(BorrowedRing, SyncKind),
194    Exported { device: &'a Device, ring: &'a ExportedRing, kind: ExportKind, size: Size, producer: SyncKind },
195    Surface(Surface, Option<SurfaceOverlay>, Size),
196}
197
198fn no_ring() -> Error {
199    Error::unsupported("the session's backend renders into no ring of this kind")
200}
201
202fn no_surface() -> Error {
203    Error::unsupported("the session's backend presents to no surface of this kind")
204}
205
206/// A backend of the build, and the targets that the session makes on it.
207/// A kind of target that a backend has none of fails with `Unsupported`.
208trait LocalBackend: RendererBackend + Sized {
209    /// The host's textures of a ring that the backend renders into.
210    type RingTextures;
211
212    /// The backend's textures of `ring`, `None` for another backend's.
213    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures>;
214
215    /// The backend, by its type.
216    fn by_type(&self) -> BackendRef<'_>;
217
218    /// A target on the backend that renders into the ring of `textures`,
219    /// handing frames over with sync of the kind `producer`.
220    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
221        let _ = (textures, producer);
222        Err(no_ring())
223    }
224
225    /// A target on the backend that renders into a ring of `ring.depth`
226    /// images of `size` pixels, which it exports as `kind`, and hands frames
227    /// over with sync of the kind `producer`.
228    fn exported(
229        &mut self,
230        device: &Device,
231        ring: &ExportedRing,
232        kind: ExportKind,
233        size: Size,
234        producer: SyncKind,
235    ) -> Result<Box<dyn Exported<Self>>, Error> {
236        let _ = (device, ring, kind, size, producer);
237        Err(Error::unsupported("the session's backend exports no ring"))
238    }
239
240    /// A target on the backend that presents to `surface`, at `size`
241    /// pixels, with `overlay` drawn over its frames. Fails with
242    /// `Unsupported` when only a backend of the target's own can present to
243    /// it: see [`surface_backend`].
244    fn surface(
245        &mut self,
246        surface: Surface,
247        overlay: Option<SurfaceOverlay>,
248        size: Size,
249    ) -> Result<Target<Self>, Error> {
250        let _ = (surface, overlay, size);
251        Err(no_surface())
252    }
253}
254
255#[cfg(feature = "webgpu")]
256impl LocalBackend for mln_webgpu::RendererBackend {
257    #[cfg(not(target_family = "wasm"))]
258    type RingTextures = mln_webgpu::BorrowedTextures;
259    #[cfg(target_family = "wasm")]
260    type RingTextures = std::convert::Infallible;
261
262    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures> {
263        match ring {
264            #[cfg(not(target_family = "wasm"))]
265            RingKind::WebGpu(textures) => Some(textures),
266            _ => None,
267        }
268    }
269
270    fn by_type(&self) -> BackendRef<'_> {
271        BackendRef::WebGpu(self)
272    }
273
274    #[cfg(not(target_family = "wasm"))]
275    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
276        Ok(Box::new(mln_webgpu::BorrowedTarget::new(self, textures, producer)?))
277    }
278
279    fn surface(
280        &mut self,
281        surface: Surface,
282        overlay: Option<SurfaceOverlay>,
283        size: Size,
284    ) -> Result<Target<Self>, Error> {
285        let kind = surface.kind;
286        #[cfg(target_family = "wasm")]
287        let format = match &kind {
288            SurfaceKind::WebCanvas { format: Some(format), .. } => Some(match format {
289                super::target::CanvasFormat::Bgra8Unorm => wgpu::TextureFormat::Bgra8Unorm,
290                super::target::CanvasFormat::Rgba8Unorm => wgpu::TextureFormat::Rgba8Unorm,
291                super::target::CanvasFormat::Rgba16Float => wgpu::TextureFormat::Rgba16Float,
292            }),
293            _ => None,
294        };
295        #[cfg(not(target_family = "wasm"))]
296        let format = None;
297        let overlay = overlay_of(overlay, |overlay| {
298            if let SurfaceOverlay::WebGpu(overlay) = overlay { Ok(overlay) } else { Err(overlay) }
299        })?;
300        let target = webgpu_surface(self, kind)?;
301        let options = mln_webgpu::SurfaceOptions {
302            cap_frame_rate: surface.cap_frame_rate,
303            format,
304            ..mln_webgpu::SurfaceOptions::default()
305        };
306        let mut target = mln_webgpu::SurfaceTarget::new(self, target, size, options)?;
307        target.set_overlay(overlay);
308        Ok(Box::new(target))
309    }
310}
311
312#[cfg(all(feature = "metal", target_vendor = "apple"))]
313impl LocalBackend for mln_mtl::RendererBackend {
314    type RingTextures = mln_mtl::BorrowedTextures;
315
316    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures> {
317        if let RingKind::Metal(textures) = ring { Some(textures) } else { None }
318    }
319
320    fn by_type(&self) -> BackendRef<'_> {
321        BackendRef::Metal(self)
322    }
323
324    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
325        Ok(Box::new(mln_mtl::BorrowedTarget::new(self, textures, producer)?))
326    }
327
328    fn exported(
329        &mut self,
330        _device: &Device,
331        ring: &ExportedRing,
332        kind: ExportKind,
333        size: Size,
334        producer: SyncKind,
335    ) -> Result<Box<dyn Exported<Self>>, Error> {
336        Ok(Box::new(mln_mtl::ExportedTarget::new(self, ring, kind, size, producer)?))
337    }
338
339    fn surface(
340        &mut self,
341        surface: Surface,
342        overlay: Option<SurfaceOverlay>,
343        size: Size,
344    ) -> Result<Target<Self>, Error> {
345        let SurfaceKind::MetalLayer(layer) = surface.kind else {
346            return Err(no_surface());
347        };
348        let overlay =
349            overlay_of(
350                overlay,
351                |overlay| {
352                    if let SurfaceOverlay::Metal(overlay) = overlay { Ok(overlay) } else { Err(overlay) }
353                },
354            )?;
355        let mut target = mln_mtl::SurfaceTarget::new(self, layer, size, surface.cap_frame_rate);
356        target.set_overlay(overlay);
357        Ok(Box::new(target))
358    }
359}
360
361#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
362impl LocalBackend for mln_vulkan::RendererBackend {
363    type RingTextures = mln_vulkan::BorrowedImages;
364
365    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures> {
366        if let RingKind::Vulkan(images) = ring { Some(images) } else { None }
367    }
368
369    fn by_type(&self) -> BackendRef<'_> {
370        BackendRef::Vulkan(self)
371    }
372
373    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
374        Ok(Box::new(mln_vulkan::BorrowedTarget::new(self, textures, producer)?))
375    }
376
377    fn exported(
378        &mut self,
379        _device: &Device,
380        ring: &ExportedRing,
381        kind: ExportKind,
382        size: Size,
383        producer: SyncKind,
384    ) -> Result<Box<dyn Exported<Self>>, Error> {
385        Ok(Box::new(mln_vulkan::ExportedTarget::new(self, ring, kind, size, producer)?))
386    }
387
388    fn surface(
389        &mut self,
390        surface: Surface,
391        overlay: Option<SurfaceOverlay>,
392        size: Size,
393    ) -> Result<Target<Self>, Error> {
394        let overlay = vulkan_overlay(overlay)?;
395        let mut target = match surface.kind {
396            SurfaceKind::Window(window) => mln_vulkan::SurfaceTarget::new(self, window, size, surface.cap_frame_rate)?,
397            SurfaceKind::Vulkan(host) => {
398                mln_vulkan::SurfaceTarget::on_host_surface(self, host, size, surface.cap_frame_rate)?
399            }
400            _ => return Err(no_surface()),
401        };
402        target.set_overlay(self.gpu(), overlay);
403        Ok(Box::new(target))
404    }
405}
406
407#[cfg(all(feature = "d3d12", windows))]
408impl LocalBackend for mln_d3d12::RendererBackend {
409    type RingTextures = mln_d3d12::BorrowedTextures;
410
411    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures> {
412        if let RingKind::D3d12(textures) = ring { Some(textures) } else { None }
413    }
414
415    fn by_type(&self) -> BackendRef<'_> {
416        BackendRef::D3d12(self)
417    }
418
419    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
420        Ok(Box::new(mln_d3d12::BorrowedTarget::new(self, textures, producer)?))
421    }
422
423    fn exported(
424        &mut self,
425        _device: &Device,
426        ring: &ExportedRing,
427        kind: ExportKind,
428        size: Size,
429        producer: SyncKind,
430    ) -> Result<Box<dyn Exported<Self>>, Error> {
431        Ok(Box::new(mln_d3d12::ExportedTarget::new(self, ring, kind, size, producer)?))
432    }
433
434    fn surface(
435        &mut self,
436        surface: Surface,
437        overlay: Option<SurfaceOverlay>,
438        size: Size,
439    ) -> Result<Target<Self>, Error> {
440        let overlay = || {
441            overlay_of(overlay, |overlay| match overlay {
442                SurfaceOverlay::D3d12(overlay) => Ok(overlay),
443                other => Err(other),
444            })
445        };
446        let (mut target, overlay) = match surface.kind {
447            SurfaceKind::Window(window) => {
448                let overlay = overlay()?;
449                (mln_d3d12::SurfaceTarget::new(self, window, size)?, overlay)
450            }
451            SurfaceKind::D3d12Composition { composition, thread } => {
452                if composition.is_swap_chain_panel() && thread != std::thread::current().id() {
453                    return Err(Error::unsupported(
454                        "a SwapChainPanel takes its swap chain on its UI thread, which made the surface: attach it \
455                         with Driver::CallerThread, serviced there",
456                    ));
457                }
458                let overlay = overlay()?;
459                (mln_d3d12::SurfaceTarget::for_composition(self, composition, size)?, overlay)
460            }
461            _ => return Err(no_surface()),
462        };
463        target.set_overlay(self.gpu(), overlay);
464        Ok(Box::new(target))
465    }
466}
467
468#[cfg(feature = "gl")]
469impl LocalBackend for mln_gl::RendererBackend {
470    #[cfg(not(target_family = "wasm"))]
471    type RingTextures = mln_gl::BorrowedTextures;
472    #[cfg(target_family = "wasm")]
473    type RingTextures = std::convert::Infallible;
474
475    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures> {
476        match ring {
477            #[cfg(not(target_family = "wasm"))]
478            RingKind::Gl(textures) => Some(textures),
479            _ => None,
480        }
481    }
482
483    fn by_type(&self) -> BackendRef<'_> {
484        BackendRef::Gl(self)
485    }
486
487    #[cfg(not(target_family = "wasm"))]
488    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
489        Ok(Box::new(mln_gl::BorrowedTarget::new(textures, producer)?))
490    }
491
492    #[cfg(all(unix, not(target_vendor = "apple")))]
493    fn exported(
494        &mut self,
495        device: &Device,
496        ring: &ExportedRing,
497        kind: ExportKind,
498        size: Size,
499        producer: SyncKind,
500    ) -> Result<Box<dyn Exported<Self>>, Error> {
501        // Irrefutable in a build with OpenGL alone, which has no other kind
502        // of device, and refutable in one with other backends.
503        let Device::Gl(device) = device else {
504            return Err(Error::unsupported("an OpenGL backend renders on an OpenGL device"));
505        };
506        Ok(Box::new(mln_gl::ExportedTarget::new(self, device, ring, kind, size, producer)?))
507    }
508}
509
510/// What a session draws with and into, whatever its backend: the methods of
511/// [`LocalTarget`] that reach the backend, each one dynamic call.
512trait Gfx {
513    fn backend(&self) -> BackendRef<'_>;
514    fn frames(&self) -> FramesKind;
515    fn renderer(&self) -> Option<&Renderer>;
516    fn renderer_mut(&mut self) -> Option<&mut Renderer>;
517    fn renderer_or(&mut self, make: &mut dyn FnMut(&dyn Gpu) -> Renderer) -> &mut Renderer;
518    fn with_gpu(&mut self, f: &mut dyn FnMut(&mut dyn Gpu, Option<&mut Renderer>));
519    fn tear_down_renderer(&mut self) -> Option<RenderingStats>;
520    fn render(&mut self, update: &Arc<UpdateParameters>) -> Option<Handoff>;
521    fn ready_for_frame(&mut self) -> bool;
522    fn with_frame(&mut self, draw: &mut dyn FnMut(&mut dyn Gpu, &FrameImage));
523    fn select_slot(&mut self, slot: usize) -> Result<(), Error>;
524    fn release_slot(&mut self, slot: usize, consumer: ConsumerSync) -> Result<(), Error>;
525    fn discard_slot(&mut self, slot: usize) -> Result<(), Error>;
526    fn exported_size(&self) -> Option<Size>;
527    fn resize_exported(&mut self, size: Size, held: &[usize]) -> Result<bool, Error>;
528    fn exported_image(&self, slot: usize) -> Option<ExportedFrame>;
529    fn set_ring(&mut self, ring: BorrowedRing) -> Result<GpuSync, Error>;
530    fn resize(&mut self, size: Size);
531    fn read_image(&mut self) -> Result<PremultipliedImage, Error>;
532    fn release_surface(&mut self) -> Result<Option<GpuSync>, Error>;
533    fn set_surface(&mut self, surface: Surface, overlay: Option<SurfaceOverlay>, size: Size) -> Result<(), Error>;
534}
535
536/// What a session draws into.
537#[derive(Clone, Copy, PartialEq, Eq)]
538enum FramesKind {
539    Offscreen,
540    Presenting,
541    Borrowed { released: bool },
542    Exported,
543}
544
545/// A backend's GPU objects, which the session owns by value: the backend,
546/// the target it draws into, and the renderer that draws, once there is
547/// one. Each call that reaches the backend's `Gpu` lends it, for its scope,
548/// to the renderer and the target. Dropping it tears the renderer and the
549/// target down on the `Gpu`, and drops the target before the backend.
550struct BackendGfx<B: LocalBackend> {
551    // Fields drop in order: the target's native objects, such as a swap
552    // chain, go while the backend's device and `Gpu` live.
553    frames: Frames<B>,
554    renderer: Option<Renderer>,
555    backend: B,
556}
557
558/// What a [`BackendGfx`] draws into.
559enum Frames<B: LocalBackend> {
560    /// None in the browser, which renders into canvases only.
561    #[cfg(not(target_family = "wasm"))]
562    Offscreen(OffscreenTarget<B::Gpu>),
563    /// `None` once the surface is released.
564    Presenting(Option<Target<B>>),
565    /// `released` once the target let go of the ring's textures, which it
566    /// keeps without them until it gets new ones.
567    Borrowed {
568        target: Box<dyn Borrowed<B>>,
569        released: bool,
570        producer: SyncKind,
571    },
572    Exported(Box<dyn Exported<B>>),
573}
574
575impl<B: LocalBackend> Frames<B> {
576    /// The target to draw into, or `None` while there is no surface or ring.
577    fn target(&mut self) -> Option<&mut dyn FrameTarget<Gpu = B::Gpu>> {
578        match self {
579            #[cfg(not(target_family = "wasm"))]
580            Frames::Offscreen(target) => Some(target),
581            Frames::Presenting(target) => Some(&mut **target.as_mut()?),
582            Frames::Borrowed { target, released: false, .. } => Some(&mut **target),
583            Frames::Borrowed { released: true, .. } => None,
584            Frames::Exported(target) => Some(&mut **target),
585        }
586    }
587
588    /// The ring that the frames draw into.
589    fn ring(&mut self) -> Result<&mut dyn Borrowed<B>, Error> {
590        match self {
591            Frames::Borrowed { target, released: false, .. } => Ok(&mut **target),
592            Frames::Borrowed { released: true, .. } => Err(Error::invalid_state("the ring was released")),
593            _ => Err(Error::unsupported("the target has no ring")),
594        }
595    }
596}
597
598/// `backend`, and what `init` says it draws into, made on it.
599fn gfx<B: LocalBackend>(mut backend: B, init: FramesInit<'_>) -> Result<Box<dyn Gfx>, Error> {
600    let frames = match init {
601        #[cfg(not(target_family = "wasm"))]
602        FramesInit::Offscreen(size) => Frames::Offscreen(OffscreenTarget::new(size)),
603        #[cfg(target_family = "wasm")]
604        FramesInit::Offscreen(size) => {
605            let _ = size;
606            return Err(Error::unsupported("the browser build renders into canvases only"));
607        }
608        FramesInit::Borrowed(ring, producer) => {
609            let textures = B::ring_textures(ring.kind).ok_or_else(no_ring)?;
610            Frames::Borrowed { target: backend.borrowed(textures, producer)?, released: false, producer }
611        }
612        FramesInit::Exported { device, ring, kind, size, producer } => {
613            Frames::Exported(backend.exported(device, ring, kind, size, producer)?)
614        }
615        FramesInit::Surface(surface, overlay, size) => {
616            Frames::Presenting(Some(backend.surface(surface, overlay, size)?))
617        }
618    };
619    Ok(Box::new(BackendGfx { backend, frames, renderer: None }))
620}
621
622/// `backend`, presenting with `target`.
623#[cfg_attr(
624    not(any(feature = "gl", all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))),
625    expect(dead_code, reason = "only Vulkan and OpenGL make backends of a surface's own")
626)]
627fn presenting<B: LocalBackend>(backend: B, target: impl FrameTarget<Gpu = B::Gpu> + 'static) -> Box<dyn Gfx> {
628    Box::new(BackendGfx { backend, frames: Frames::Presenting(Some(Box::new(target))), renderer: None })
629}
630
631impl<B: LocalBackend> Gfx for BackendGfx<B> {
632    fn backend(&self) -> BackendRef<'_> {
633        self.backend.by_type()
634    }
635
636    fn frames(&self) -> FramesKind {
637        match &self.frames {
638            #[cfg(not(target_family = "wasm"))]
639            Frames::Offscreen(_) => FramesKind::Offscreen,
640            Frames::Presenting(_) => FramesKind::Presenting,
641            Frames::Borrowed { released, .. } => FramesKind::Borrowed { released: *released },
642            Frames::Exported(_) => FramesKind::Exported,
643        }
644    }
645
646    fn renderer(&self) -> Option<&Renderer> {
647        self.renderer.as_ref()
648    }
649
650    fn renderer_mut(&mut self) -> Option<&mut Renderer> {
651        self.renderer.as_mut()
652    }
653
654    fn renderer_or(&mut self, make: &mut dyn FnMut(&dyn Gpu) -> Renderer) -> &mut Renderer {
655        let BackendGfx { backend, renderer, .. } = self;
656        renderer.get_or_insert_with(|| make(&*backend.gpu()))
657    }
658
659    fn with_gpu(&mut self, f: &mut dyn FnMut(&mut dyn Gpu, Option<&mut Renderer>)) {
660        f(&mut *self.backend.gpu(), self.renderer.as_mut());
661    }
662
663    fn tear_down_renderer(&mut self) -> Option<RenderingStats> {
664        let renderer = self.renderer.take()?;
665        Some(renderer.tear_down(&mut *self.backend.gpu()))
666    }
667
668    fn render(&mut self, update: &Arc<UpdateParameters>) -> Option<Handoff> {
669        let renderer = self.renderer.as_mut()?;
670        let target = self.frames.target()?;
671        let mut gpu = self.backend.gpu();
672        let gpu = &mut *gpu;
673        let frame = renderer.update(gpu, update)?;
674        let image = target.begin_frame(gpu)?;
675        let drawn = renderer.render(gpu, &image, frame);
676        let handoff = target.end_frame(gpu);
677        renderer.finish_frame(gpu, drawn, handoff);
678        Some(handoff)
679    }
680
681    fn ready_for_frame(&mut self) -> bool {
682        let Some(target) = self.frames.target() else { return false };
683        target.begin_frame(&mut self.backend.gpu()).is_some()
684    }
685
686    fn with_frame(&mut self, draw: &mut dyn FnMut(&mut dyn Gpu, &FrameImage)) {
687        let Some(target) = self.frames.target() else { return };
688        let mut gpu = self.backend.gpu();
689        if let Some(image) = target.begin_frame(&mut gpu) {
690            draw(&mut *gpu, &image);
691        }
692    }
693
694    fn select_slot(&mut self, slot: usize) -> Result<(), Error> {
695        match &mut self.frames {
696            Frames::Exported(target) => target.select(slot),
697            frames => frames.ring()?.select(slot),
698        }
699        Ok(())
700    }
701
702    fn release_slot(&mut self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
703        let gpu = &mut *self.backend.gpu();
704        match &mut self.frames {
705            Frames::Exported(target) => target.release(gpu, slot, consumer),
706            frames => frames.ring()?.release(gpu, slot, consumer),
707        }
708    }
709
710    fn discard_slot(&mut self, slot: usize) -> Result<(), Error> {
711        let gpu = &mut *self.backend.gpu();
712        match &mut self.frames {
713            Frames::Exported(target) => target.discard(gpu, slot),
714            frames => frames.ring()?.discard(gpu, slot),
715        }
716        Ok(())
717    }
718
719    fn exported_size(&self) -> Option<Size> {
720        match &self.frames {
721            Frames::Exported(target) => Some(target.size()),
722            _ => None,
723        }
724    }
725
726    fn resize_exported(&mut self, size: Size, held: &[usize]) -> Result<bool, Error> {
727        match &mut self.frames {
728            Frames::Exported(target) => target.resize_images(&mut self.backend, size, held),
729            _ => Err(Error::unsupported("the target exports no ring")),
730        }
731    }
732
733    fn exported_image(&self, slot: usize) -> Option<ExportedFrame> {
734        match &self.frames {
735            Frames::Exported(target) => target.image(slot),
736            _ => None,
737        }
738    }
739
740    fn set_ring(&mut self, ring: BorrowedRing) -> Result<GpuSync, Error> {
741        let Frames::Borrowed { target, released, producer } = &mut self.frames else {
742            return Err(Error::unsupported("the target has no ring"));
743        };
744        let textures = B::ring_textures(ring.kind).ok_or_else(no_ring)?;
745        if !*released {
746            return target.replace(&mut self.backend.gpu(), textures);
747        }
748        // The released target, which kept what its release's sync names
749        // until now, goes once its frames are done.
750        let next = self.backend.borrowed(textures, *producer)?;
751        std::mem::replace(target, next).tear_down(&mut self.backend.gpu());
752        *released = false;
753        Ok(GpuSync::of(SyncKind::CpuComplete))
754    }
755
756    fn resize(&mut self, size: Size) {
757        if let Some(target) = self.frames.target() {
758            target.resize(&mut self.backend.gpu(), size);
759        }
760    }
761
762    fn read_image(&mut self) -> Result<PremultipliedImage, Error> {
763        match &mut self.frames {
764            #[cfg(not(target_family = "wasm"))]
765            Frames::Offscreen(target) => target.read_image(&mut self.backend.gpu()),
766            Frames::Presenting(_) => Err(Error::unsupported("a surface session can't read its frames back")),
767            Frames::Borrowed { .. } | Frames::Exported(_) => {
768                Err(Error::unsupported("a ring's frames are the host's to read"))
769            }
770        }
771    }
772
773    fn release_surface(&mut self) -> Result<Option<GpuSync>, Error> {
774        let gpu = &mut *self.backend.gpu();
775        match &mut self.frames {
776            Frames::Presenting(target) => {
777                if let Some(mut target) = target.take() {
778                    target.tear_down(gpu);
779                }
780                Ok(None)
781            }
782            Frames::Borrowed { released: true, .. } => Ok(Some(GpuSync::of(SyncKind::CpuComplete))),
783            Frames::Borrowed { target, released, .. } => {
784                let sync = target.release_textures(gpu)?;
785                *released = true;
786                Ok(Some(sync))
787            }
788            #[cfg(not(target_family = "wasm"))]
789            Frames::Offscreen(_) => Ok(None),
790            Frames::Exported(_) => Ok(None),
791        }
792    }
793
794    fn set_surface(&mut self, surface: Surface, overlay: Option<SurfaceOverlay>, size: Size) -> Result<(), Error> {
795        let target = self.backend.surface(surface, overlay, size)?;
796        if let Frames::Presenting(old) = &mut self.frames
797            && let Some(mut old) = old.take()
798        {
799            old.tear_down(&mut self.backend.gpu());
800        }
801        self.frames = Frames::Presenting(Some(target));
802        Ok(())
803    }
804}
805
806impl<B: LocalBackend> Drop for BackendGfx<B> {
807    fn drop(&mut self) {
808        let mut gpu = self.backend.gpu();
809        if let Some(renderer) = self.renderer.take() {
810            renderer.tear_down(&mut *gpu);
811        }
812        // A released ring keeps the objects that its release's sync names.
813        if let Frames::Borrowed { target, .. } = &mut self.frames {
814            target.tear_down(&mut gpu);
815        } else if let Some(target) = self.frames.target() {
816            target.tear_down(&mut gpu);
817        }
818    }
819}
820
821/// A backend on `device`, and what `init` says it draws into.
822fn new_gfx(device: &Device, init: FramesInit<'_>) -> Result<Box<dyn Gfx>, Error> {
823    match device {
824        #[cfg(feature = "webgpu")]
825        Device::WebGpu(device) => gfx(mln_webgpu::RendererBackend::new(device), init),
826        #[cfg(all(feature = "metal", target_vendor = "apple"))]
827        Device::Metal(device) => gfx(mln_mtl::RendererBackend::new(device), init),
828        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
829        Device::Vulkan(device) => gfx(mln_vulkan::RendererBackend::new(device)?, init),
830        #[cfg(all(feature = "d3d12", windows))]
831        Device::D3d12(device) => {
832            gfx(mln_d3d12::RendererBackend::new(device).map_err(|error| Error::native(error.to_string()))?, init)
833        }
834        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
835        Device::Gl(device) => gfx(mln_gl::RendererBackend::new(device)?, init),
836        #[cfg(all(feature = "gl", target_family = "wasm"))]
837        Device::WebGl => {
838            drop(init);
839            Err(Error::unsupported("WebGL2 renders only into a canvas, with the canvas's own context"))
840        }
841    }
842}
843
844/// The overlay of the backend that `own` picks out of `overlay`. Fails with
845/// `Unsupported` for another backend's.
846#[cfg_attr(
847    not(any(
848        feature = "webgpu",
849        all(feature = "metal", target_vendor = "apple"),
850        all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))),
851        all(feature = "d3d12", windows),
852        all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))),
853    )),
854    expect(dead_code, reason = "a build without a backend that takes overlays uses none")
855)]
856fn overlay_of<T>(
857    overlay: Option<SurfaceOverlay>,
858    own: impl FnOnce(SurfaceOverlay) -> Result<T, SurfaceOverlay>,
859) -> Result<Option<T>, Error> {
860    overlay
861        .map(own)
862        .transpose()
863        .map_err(|_| Error::unsupported("the surface's overlay is for another backend than the session's"))
864}
865
866#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
867fn vulkan_overlay(overlay: Option<SurfaceOverlay>) -> Result<Option<Box<dyn mln_vulkan::Overlay>>, Error> {
868    overlay_of(overlay, |overlay| match overlay {
869        SurfaceOverlay::Vulkan(overlay) => Ok(overlay),
870        other => Err(other),
871    })
872}
873
874/// A wgpu surface of `kind`, made with the instance of `backend`'s device
875/// where the host didn't make it.
876#[cfg(feature = "webgpu")]
877fn webgpu_surface(backend: &mln_webgpu::RendererBackend, kind: SurfaceKind) -> Result<wgpu::Surface<'static>, Error> {
878    let instance = || {
879        backend
880            .device()
881            .instance()
882            .ok_or_else(|| Error::invalid_argument("the session's device has no instance to make a surface with"))
883    };
884    let made = match kind {
885        #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
886        SurfaceKind::Wgpu(surface) => return Ok(surface),
887        SurfaceKind::Window(window) => instance()?.create_surface(window),
888        #[cfg(target_family = "wasm")]
889        SurfaceKind::WebCanvas { canvas, .. } => {
890            use wasm_bindgen::JsCast as _;
891            let target = match canvas.dyn_into::<web_sys::OffscreenCanvas>() {
892                Ok(canvas) => wgpu::SurfaceTarget::OffscreenCanvas(canvas),
893                Err(canvas) => wgpu::SurfaceTarget::Canvas(canvas.unchecked_into()),
894            };
895            instance()?.create_surface(target)
896        }
897        #[cfg(all(feature = "metal", target_vendor = "apple"))]
898        SurfaceKind::MetalLayer(_) => return Err(Error::unsupported("a Metal layer presents on a Metal device")),
899        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
900        SurfaceKind::Vulkan(_) => return Err(Error::unsupported("a Vulkan surface presents on a Vulkan device")),
901        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
902        SurfaceKind::Gl(_) => return Err(Error::unsupported("an EGL surface presents on an OpenGL device")),
903        #[cfg(all(feature = "d3d12", windows))]
904        SurfaceKind::D3d12Composition { .. } => {
905            return Err(Error::unsupported("a composition swap chain presents on a D3D12 device"));
906        }
907    };
908    made.map_err(|error| Error::native(format!("can't make a surface on the window: {error}")))
909}
910
911/// A backend of the target's own on `device` and a target that presents to
912/// `surface` with `overlay` drawn over its frames, for the backends whose
913/// context or device is made for the window: Vulkan's, whose instance and
914/// device take the window's surface extensions, and OpenGL ES's, whose
915/// context is of the window's display.
916fn surface_backend(
917    device: &Device,
918    surface: Surface,
919    overlay: Option<SurfaceOverlay>,
920    size: Size,
921) -> Result<Box<dyn Gfx>, Error> {
922    let cap_frame_rate = surface.cap_frame_rate;
923    match (device, surface.kind) {
924        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
925        (Device::Vulkan(device), SurfaceKind::Window(window)) => {
926            let overlay = vulkan_overlay(overlay)?;
927            let (mut backend, mut target) =
928                mln_vulkan::SurfaceTarget::with_backend(device, window, size, cap_frame_rate)?;
929            target.set_overlay(backend.gpu(), overlay);
930            Ok(presenting(backend, target))
931        }
932        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
933        (Device::Vulkan(device), kind @ SurfaceKind::Vulkan(_)) => gfx(
934            mln_vulkan::RendererBackend::presenting(device)?,
935            FramesInit::Surface(Surface { kind, cap_frame_rate }, overlay, size),
936        ),
937        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
938        (Device::Gl(device), SurfaceKind::Gl(host)) => {
939            if overlay.is_some() {
940                return Err(Error::unsupported("a host's EGL surface takes no overlay"));
941            }
942            let (backend, target) = mln_gl::HostSurfaceTarget::with_backend(device, host, size)?;
943            Ok(presenting(backend, target))
944        }
945        #[cfg(all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))))]
946        (Device::Gl(_), SurfaceKind::Window(window)) => {
947            let overlay = overlay_of(overlay, |overlay| match overlay {
948                SurfaceOverlay::Gl(overlay) => Ok(overlay),
949                other => Err(other),
950            })?;
951            let (mut backend, mut target) = mln_gl::SurfaceTarget::with_backend(window, size, cap_frame_rate)?;
952            target.set_overlay(&mut backend.gpu(), overlay);
953            Ok(presenting(backend, target))
954        }
955        #[cfg(all(feature = "gl", target_family = "wasm"))]
956        (Device::WebGl, SurfaceKind::WebCanvas { canvas, .. }) => {
957            use wasm_bindgen::JsCast as _;
958            // WebGL draws no overlay.
959            let canvas = match canvas.dyn_into::<web_sys::OffscreenCanvas>() {
960                Ok(canvas) => mln_gl::WebCanvas::Offscreen(canvas),
961                Err(canvas) => mln_gl::WebCanvas::Element(canvas.unchecked_into()),
962            };
963            let (backend, target) = mln_gl::CanvasTarget::with_backend(canvas, size)?;
964            Ok(presenting(backend, target))
965        }
966        (_, kind) => new_gfx(device, FramesInit::Surface(Surface { kind, cap_frame_rate }, overlay, size)),
967    }
968}
969
970/// A target's backend, by its type, for a host that reads what the backend
971/// tells of its device.
972#[non_exhaustive]
973pub enum BackendRef<'a> {
974    #[cfg(feature = "webgpu")]
975    WebGpu(&'a mln_webgpu::RendererBackend),
976    #[cfg(all(feature = "metal", target_vendor = "apple"))]
977    Metal(&'a mln_mtl::RendererBackend),
978    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
979    Vulkan(&'a mln_vulkan::RendererBackend),
980    #[cfg(all(feature = "d3d12", windows))]
981    D3d12(&'a mln_d3d12::RendererBackend),
982    #[cfg(feature = "gl")]
983    Gl(&'a mln_gl::RendererBackend),
984}
985
986/// A render target built on this thread: the backend, on the target's
987/// device, the frames it draws into, and the renderer that draws them,
988/// which the target owns and lends the backend's `Gpu` to.
989pub struct LocalTarget {
990    device: Device,
991    gfx: Box<dyn Gfx>,
992    /// The window that a surface target presents to, if it presents to one.
993    window: Option<Arc<dyn Window>>,
994}
995
996impl LocalTarget {
997    /// An offscreen target of `size` pixels on `device`, or on a device that
998    /// [`Device::new`] makes when that is `None`.
999    ///
1000    /// Fails as [`Device::new`] does, and with the backend's error when it
1001    /// can't render on the device.
1002    pub fn offscreen(device: Option<Device>, size: Size) -> Result<LocalTarget, Error> {
1003        let device = match device {
1004            Some(device) => device,
1005            None => Device::new(DeviceOptions::default())?,
1006        };
1007        let gfx = new_gfx(&device, FramesInit::Offscreen(size))?;
1008        Ok(LocalTarget { device, gfx, window: None })
1009    }
1010
1011    /// A target of `size` pixels that presents to `surface`, with `overlay`
1012    /// drawn over its frames, on `device` or, when that is `None`, on the
1013    /// device the surface's kind takes
1014    /// ([`RenderTarget::Surface`](super::RenderTarget::Surface)).
1015    ///
1016    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a
1017    /// surface that the host made without the host's device, with
1018    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) for a window or
1019    /// surface without an area to present to, such as a minimized window,
1020    /// with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the device
1021    /// can't present to the surface or draw the overlay, and with the error
1022    /// of the device or the window's surface.
1023    pub fn surface(
1024        surface: Surface,
1025        overlay: Option<SurfaceOverlay>,
1026        device: Option<Device>,
1027        size: Size,
1028    ) -> Result<LocalTarget, Error> {
1029        surface.check_area()?;
1030        let window = surface.host_window();
1031        let device = match device {
1032            Some(device) => device,
1033            None => default_surface_device(&surface)?,
1034        };
1035        let gfx = surface_backend(&device, surface, overlay, size)?;
1036        Ok(LocalTarget { device, gfx, window })
1037    }
1038
1039    /// A target of `size` pixels on `device` that renders into the host's
1040    /// `ring`, and hands each frame over with sync of the kind `producer`.
1041    ///
1042    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
1043    /// device can't render into the ring with `producer`, and with the
1044    /// backend's error.
1045    pub fn borrowed(device: Device, ring: BorrowedRing, producer: SyncKind) -> Result<LocalTarget, Error> {
1046        let gfx = new_gfx(&device, FramesInit::Borrowed(ring, producer))?;
1047        Ok(LocalTarget { device, gfx, window: None })
1048    }
1049
1050    /// A target on `device` that renders into a ring of `ring.depth` images
1051    /// of `size` pixels, which it exports as `kind`, one that
1052    /// [`Device::export_plan`] picked, and hands each frame over with sync of
1053    /// the kind `producer`.
1054    ///
1055    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
1056    /// device can't export `kind` or hand frames over with `producer`, and
1057    /// with the backend's error.
1058    pub fn exported(
1059        device: Device,
1060        ring: &ExportedRing,
1061        kind: ExportKind,
1062        size: Size,
1063        producer: SyncKind,
1064    ) -> Result<LocalTarget, Error> {
1065        let gfx = new_gfx(&device, FramesInit::Exported { device: &device, ring, kind, size, producer })?;
1066        Ok(LocalTarget { device, gfx, window: None })
1067    }
1068
1069    /// The device the target renders on.
1070    #[must_use]
1071    pub fn device(&self) -> &Device {
1072        &self.device
1073    }
1074
1075    /// The backend the target and its renderer draw with.
1076    #[must_use]
1077    pub fn backend(&self) -> BackendRef<'_> {
1078        self.gfx.backend()
1079    }
1080
1081    /// Runs `f` with the backend's `Gpu`, as when the host waits for the
1082    /// frames drawn so far.
1083    pub fn with_gpu(&mut self, mut f: impl FnMut(&mut dyn Gpu)) {
1084        self.gfx.with_gpu(&mut |gpu, _| f(gpu));
1085    }
1086
1087    /// The renderer that draws into the target, which `make` makes with the
1088    /// backend's `Gpu` unless the target has one: the renderer draws with
1089    /// that `Gpu` only.
1090    pub fn renderer_or(&mut self, mut make: impl FnMut(&dyn Gpu) -> Renderer) -> &mut Renderer {
1091        self.gfx.renderer_or(&mut make)
1092    }
1093
1094    /// The renderer that draws into the target, if it has one.
1095    #[must_use]
1096    pub fn renderer(&self) -> Option<&Renderer> {
1097        self.gfx.renderer()
1098    }
1099
1100    /// The renderer that draws into the target, if it has one.
1101    pub fn renderer_mut(&mut self) -> Option<&mut Renderer> {
1102        self.gfx.renderer_mut()
1103    }
1104
1105    /// Runs `f` with the target's renderer and the backend's `Gpu`, which the
1106    /// renderer's calls that make, draw or free its GPU objects take, or
1107    /// returns `None` without a renderer.
1108    pub fn with_renderer<R>(&mut self, f: impl FnOnce(&mut Renderer, &mut dyn Gpu) -> R) -> Option<R> {
1109        self.gfx.renderer()?;
1110        let (mut f, mut result) = (Some(f), None);
1111        self.gfx.with_gpu(&mut |gpu, renderer| {
1112            if let (Some(renderer), Some(f)) = (renderer, f.take()) {
1113                result = Some(f(renderer, gpu));
1114            }
1115        });
1116        result
1117    }
1118
1119    /// Tears the renderer down on the backend's `Gpu`, if the target has
1120    /// one, and returns its rendering stats as it leaves them.
1121    pub fn tear_down_renderer(&mut self) -> Option<RenderingStats> {
1122        self.gfx.tear_down_renderer()
1123    }
1124
1125    /// Draws `update` with the target's renderer into a frame: the target
1126    /// begins the frame, the renderer draws into it, and the target ends
1127    /// it. Returns where the frame went, or `None` when nothing was drawn:
1128    /// there is no renderer, the target had nothing to draw into, or there
1129    /// was nothing to draw.
1130    pub fn render(&mut self, update: &Arc<UpdateParameters>) -> Option<Handoff> {
1131        self.gfx.render(update)
1132    }
1133
1134    /// Runs `draw` with the backend's `Gpu` and the textures of the target's
1135    /// frame, to draw into them alongside the map. The frame is the one the
1136    /// next render draws into, which the target begins unless it has
1137    /// begun it. `None` when the target has nothing to draw into now.
1138    pub fn with_frame<R>(&mut self, draw: impl FnOnce(&mut dyn Gpu, &FrameImage) -> R) -> Option<R> {
1139        let (mut draw, mut result) = (Some(draw), None);
1140        self.gfx.with_frame(&mut |gpu, image| result = draw.take().map(|draw| draw(gpu, image)));
1141        result
1142    }
1143
1144    /// Whether the target can take a frame now: its window, if any, has an
1145    /// area to present to, and it begins a frame, which a surface needs a
1146    /// texture for, and which the next render draws into.
1147    pub fn ready_for_frame(&mut self) -> bool {
1148        self.window_has_area() && self.gfx.ready_for_frame()
1149    }
1150
1151    /// Whether the target can take a frame as far as its window says: it
1152    /// presents to no window, or to one with an area to present to
1153    /// ([`mln_gfx::window::has_area`]).
1154    #[must_use]
1155    pub fn window_has_area(&self) -> bool {
1156        self.window.as_deref().is_none_or(mln_gfx::window::has_area)
1157    }
1158
1159    /// Whether frames are presented to a window or surface.
1160    #[must_use]
1161    pub fn is_presenting(&self) -> bool {
1162        self.gfx.frames() == FramesKind::Presenting
1163    }
1164
1165    /// Whether frames go to the host in images of the target's own.
1166    #[must_use]
1167    pub fn is_exported(&self) -> bool {
1168        self.gfx.frames() == FramesKind::Exported
1169    }
1170
1171    /// Whether frames go to the host's ring.
1172    #[must_use]
1173    pub fn is_borrowed(&self) -> bool {
1174        matches!(self.gfx.frames(), FramesKind::Borrowed { .. })
1175    }
1176
1177    /// Whether the target is a ring that let go of its textures.
1178    #[must_use]
1179    pub fn ring_released(&self) -> bool {
1180        self.gfx.frames() == FramesKind::Borrowed { released: true }
1181    }
1182
1183    /// Whether frames are read back rather than presented.
1184    #[must_use]
1185    pub fn is_offscreen(&self) -> bool {
1186        self.gfx.frames() == FramesKind::Offscreen
1187    }
1188
1189    /// Has the next frame render into the ring's texture at `slot`.
1190    pub fn select_slot(&mut self, slot: usize) -> Result<(), Error> {
1191        self.gfx.select_slot(slot)
1192    }
1193
1194    /// The host gave the ring's texture at `slot` back: the next frame
1195    /// rendered into it waits for `consumer`.
1196    pub fn release_slot(&mut self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
1197        self.gfx.release_slot(slot, consumer)
1198    }
1199
1200    /// The host gave up the ring's texture at `slot`, which the target
1201    /// renders into no more.
1202    pub fn discard_slot(&mut self, slot: usize) -> Result<(), Error> {
1203        self.gfx.discard_slot(slot)
1204    }
1205
1206    /// The size in pixels of an exported ring's images, or `None` for
1207    /// another target.
1208    #[must_use]
1209    pub fn exported_size(&self) -> Option<Size> {
1210        self.gfx.exported_size()
1211    }
1212
1213    /// Renders an exported ring's next frames into images of `size` pixels.
1214    /// The frames that the host holds, at `held` slots, keep their images.
1215    /// Returns whether the ring has new images, which it doesn't when they
1216    /// have `size` already.
1217    ///
1218    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
1219    /// target that isn't an exported ring, and with the backend's error, when
1220    /// the ring keeps its images.
1221    pub fn resize_exported(&mut self, size: Size, held: &[usize]) -> Result<bool, Error> {
1222        self.gfx.resize_exported(size, held)
1223    }
1224
1225    /// The exported image of the frame at `slot`, of the size it has.
1226    #[must_use]
1227    pub fn exported_texture(&self, slot: usize) -> Option<FrameTexture> {
1228        let image = self.gfx.exported_image(slot)?;
1229        Some(FrameTexture::exported(image, &self.device))
1230    }
1231
1232    /// Renders into `ring` from now on, in place of the ring's textures, and
1233    /// returns the sync after which the host may use the textures that it
1234    /// let go of: of the target's producer kind, or
1235    /// [`SyncKind::CpuComplete`] when it had none since a release.
1236    ///
1237    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
1238    /// target that isn't a ring, or a ring of another format, and with the
1239    /// backend's error. The target then keeps its textures.
1240    pub(crate) fn set_ring(&mut self, ring: BorrowedRing) -> Result<GpuSync, Error> {
1241        self.gfx.set_ring(ring)
1242    }
1243
1244    /// Draws the next frame at `size` pixels.
1245    pub fn resize(&mut self, size: Size) {
1246        self.gfx.resize(size);
1247    }
1248
1249    /// The last frame's pixels.
1250    ///
1251    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
1252    /// target that presents its frames, with
1253    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) before a frame, and
1254    /// with [`ErrorKind::Native`](mln_util::ErrorKind) where the backend
1255    /// reads nothing back.
1256    pub fn read_image(&mut self) -> Result<PremultipliedImage, Error> {
1257        self.gfx.read_image()
1258    }
1259
1260    /// Lets go of a surface target's surface, or of a ring's textures, and
1261    /// returns, for a ring, the sync after which the host may use them. The
1262    /// backend and its renderer stay.
1263    ///
1264    /// Fails with [`ErrorKind::Native`](mln_util::ErrorKind) when a ring
1265    /// can't submit its work on the textures, which it keeps then.
1266    pub(crate) fn release_surface(&mut self) -> Result<Option<GpuSync>, Error> {
1267        let sync = self.gfx.release_surface()?;
1268        if self.is_presenting() {
1269            self.window = None;
1270        }
1271        Ok(sync)
1272    }
1273
1274    /// Presents to `surface` at `size` pixels from now on, with `overlay`
1275    /// drawn over its frames, in place of the surface the target has, if
1276    /// any: on the same backend where it can present to `surface`, and on a
1277    /// new one of the device otherwise, which the target then returns true
1278    /// for, and which draws no overlay. The renderer on the old backend is
1279    /// torn down with it, and the target has none until one is made again
1280    /// on the new backend ([`renderer_or`](Self::renderer_or)).
1281    ///
1282    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for an
1283    /// offscreen target or when the device can't present to `surface`, and
1284    /// as [`surface`](Self::surface) does. The target then keeps what it
1285    /// had.
1286    pub fn set_surface(
1287        &mut self,
1288        surface: Surface,
1289        overlay: Option<SurfaceOverlay>,
1290        size: Size,
1291    ) -> Result<bool, Error> {
1292        if !self.is_presenting() {
1293            return Err(Error::unsupported("only a surface target presents to another surface"));
1294        }
1295        surface.check_area()?;
1296        let window = surface.host_window();
1297        let retry = surface.clone_window();
1298        let new_backend = match self.gfx.set_surface(surface, overlay, size) {
1299            Ok(()) => false,
1300            Err(error) if error.kind == mln_util::ErrorKind::Unsupported => {
1301                let surface = retry.ok_or(error)?;
1302                self.gfx = surface_backend(&self.device, surface, None, size)?;
1303                true
1304            }
1305            Err(error) => return Err(error),
1306        };
1307        self.window = window;
1308        Ok(new_backend)
1309    }
1310}
1311
1312/// The device a surface renders on without the host's: the native one where
1313/// its backend takes the surface's kind.
1314fn default_surface_device(surface: &Surface) -> Result<Device, Error> {
1315    match surface.kind {
1316        SurfaceKind::Window(_) if cfg!(target_vendor = "apple") => {
1317            Device::with_backend(super::target::BackendType::WebGPU, DeviceOptions::default())
1318        }
1319        SurfaceKind::Window(_) => Device::new(DeviceOptions::default()),
1320        #[cfg(all(feature = "metal", target_vendor = "apple"))]
1321        SurfaceKind::MetalLayer(_) => Device::with_backend(super::target::BackendType::Metal, DeviceOptions::default()),
1322        #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
1323        SurfaceKind::Wgpu(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
1324        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1325        SurfaceKind::Vulkan(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
1326        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
1327        SurfaceKind::Gl(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
1328        #[cfg(all(feature = "d3d12", windows))]
1329        SurfaceKind::D3d12Composition { .. } => {
1330            Device::with_backend(super::target::BackendType::D3D12, DeviceOptions::default())
1331        }
1332        // A WebGPU build asked the browser for a device before the build.
1333        #[cfg(all(target_family = "wasm", feature = "gl"))]
1334        SurfaceKind::WebCanvas { .. } => Ok(Device::WebGl),
1335        #[cfg(all(target_family = "wasm", not(feature = "gl")))]
1336        SurfaceKind::WebCanvas { .. } => Err(Error::invalid_state("the browser's WebGPU device isn't there yet")),
1337    }
1338}