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    target_family = "wasm",
17    expect(
18        unused_macros,
19        unused_imports,
20        reason = "the browser build has only canvases' backends, and none of the targets that the others make"
21    )
22)]
23
24use std::rc::Rc;
25use std::sync::Arc;
26
27use mln_gfx::{ConsumerSync, ExportKind, ExportedFrame, ExportedRing, FrameTarget, RendererBackend, SyncKind, Window};
28use mln_util::error::Error;
29use mln_util::image::PremultipliedImage;
30use mln_util::size::Size;
31
32use super::target::{
33    BorrowedRing, Device, DeviceOptions, FrameTexture, RingKind, Surface, SurfaceKind, SurfaceOverlay,
34};
35
36/// Frames read back: an offscreen target.
37trait Offscreen: FrameTarget {
38    fn resize(&self, size: Size);
39    fn read_image(&self) -> Result<PremultipliedImage, Error>;
40}
41
42/// Frames presented: a surface target.
43trait Presenting: FrameTarget {
44    fn resize(&self, size: Size);
45}
46
47#[cfg(all(feature = "metal", target_vendor = "apple"))]
48impl Borrowed for mln_mtl::BorrowedTarget {
49    fn select(&self, slot: usize) {
50        mln_mtl::BorrowedTarget::select(self, slot);
51    }
52    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
53        mln_mtl::BorrowedTarget::release(self, slot, consumer)
54    }
55    fn discard(&self, slot: usize) {
56        mln_mtl::BorrowedTarget::discard(self, slot);
57    }
58    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
59        let RingKind::Metal(textures) = ring.kind else {
60            return Err(Error::unsupported("a ring of Metal textures takes Metal textures only"));
61        };
62        mln_mtl::BorrowedTarget::replace(self, textures).map(pending)
63    }
64    fn take_pending(&self) -> Pending {
65        pending(mln_mtl::BorrowedTarget::take_pending(self))
66    }
67}
68
69#[cfg(all(feature = "metal", target_vendor = "apple"))]
70impl PendingReads for mln_mtl::PendingReads {
71    fn poll(&mut self) -> bool {
72        mln_mtl::PendingReads::poll(self)
73    }
74}
75
76/// Frames given back to the host: a ring of its textures.
77trait Borrowed: FrameTarget {
78    fn select(&self, slot: usize);
79    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error>;
80    fn discard(&self, slot: usize);
81    /// Renders into `ring` from now on, and returns the host's reads of the
82    /// textures that it let go of.
83    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error>;
84    /// Takes the host's reads of the textures that they still wait for, for
85    /// the ring to wait for before it lets go of them. A target that waits
86    /// for the host's reads as it takes each texture back has none.
87    fn take_pending(&self) -> Pending {
88        None
89    }
90}
91
92/// The host's reads of textures that a ring let go of, which the session
93/// waits for before the release or replacement completes. Dropping it stops
94/// waiting.
95pub(crate) trait PendingReads {
96    /// Whether every read ended, which it checks without blocking.
97    fn poll(&mut self) -> bool;
98}
99
100/// The host's reads that a ring waits for, if any.
101pub(crate) type Pending = Option<Box<dyn PendingReads>>;
102
103/// `reads`, unless they ended already.
104#[cfg(any(
105    all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))),
106    all(feature = "metal", target_vendor = "apple"),
107    all(feature = "d3d12", windows)
108))]
109fn pending(mut reads: impl PendingReads + 'static) -> Pending {
110    (!reads.poll()).then(|| -> Box<dyn PendingReads> { Box::new(reads) })
111}
112
113#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
114impl Borrowed for mln_vulkan::BorrowedTarget {
115    fn select(&self, slot: usize) {
116        mln_vulkan::BorrowedTarget::select(self, slot);
117    }
118    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
119        mln_vulkan::BorrowedTarget::release(self, slot, consumer)
120    }
121    fn discard(&self, slot: usize) {
122        mln_vulkan::BorrowedTarget::discard(self, slot);
123    }
124    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
125        let RingKind::Vulkan(images) = ring.kind else {
126            return Err(Error::unsupported("a ring of Vulkan images takes Vulkan images only"));
127        };
128        mln_vulkan::BorrowedTarget::replace(self, images).map(pending)
129    }
130    fn take_pending(&self) -> Pending {
131        pending(mln_vulkan::BorrowedTarget::take_pending(self))
132    }
133}
134
135#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
136impl PendingReads for mln_vulkan::PendingReads {
137    fn poll(&mut self) -> bool {
138        mln_vulkan::PendingReads::poll(self)
139    }
140}
141
142#[cfg(all(feature = "d3d12", windows))]
143impl Borrowed for mln_d3d12::BorrowedTarget {
144    fn select(&self, slot: usize) {
145        mln_d3d12::BorrowedTarget::select(self, slot);
146    }
147    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
148        mln_d3d12::BorrowedTarget::release(self, slot, consumer)
149    }
150    fn discard(&self, slot: usize) {
151        mln_d3d12::BorrowedTarget::discard(self, slot);
152    }
153    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
154        let RingKind::D3d12(textures) = ring.kind else {
155            return Err(Error::unsupported("a ring of D3D12 textures takes D3D12 textures only"));
156        };
157        mln_d3d12::BorrowedTarget::replace(self, textures).map(pending)
158    }
159    fn take_pending(&self) -> Pending {
160        pending(mln_d3d12::BorrowedTarget::take_pending(self))
161    }
162}
163
164#[cfg(all(feature = "d3d12", windows))]
165impl PendingReads for mln_d3d12::PendingReads {
166    fn poll(&mut self) -> bool {
167        mln_d3d12::PendingReads::poll(self)
168    }
169}
170
171/// Frames queued for the host: a ring of the target's own images, which it
172/// exports.
173trait Exported: FrameTarget {
174    fn select(&self, slot: usize);
175    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error>;
176    fn discard(&self, slot: usize);
177    fn resize(&self, size: Size, held: &[usize]) -> Result<bool, Error>;
178    fn size(&self) -> Size;
179    fn image(&self, slot: usize) -> Option<ExportedFrame>;
180}
181
182macro_rules! exported {
183    ($type:ty) => {
184        impl Exported for $type {
185            fn select(&self, slot: usize) {
186                <$type>::select(self, slot);
187            }
188            fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
189                <$type>::release(self, slot, consumer)
190            }
191            fn discard(&self, slot: usize) {
192                <$type>::discard(self, slot);
193            }
194            fn resize(&self, size: Size, held: &[usize]) -> Result<bool, Error> {
195                <$type>::resize(self, size, held)
196            }
197            fn size(&self) -> Size {
198                <$type>::size(self)
199            }
200            fn image(&self, slot: usize) -> Option<ExportedFrame> {
201                <$type>::image(self, slot)
202            }
203        }
204    };
205}
206
207#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
208exported!(mln_vulkan::ExportedTarget);
209#[cfg(all(feature = "metal", target_vendor = "apple"))]
210exported!(mln_mtl::ExportedTarget);
211#[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
212exported!(mln_gl::ExportedTarget);
213#[cfg(all(feature = "d3d12", windows))]
214exported!(mln_d3d12::ExportedTarget);
215
216macro_rules! offscreen {
217    ($type:ty) => {
218        impl Offscreen for $type {
219            fn resize(&self, size: Size) {
220                <$type>::resize(self, size);
221            }
222            fn read_image(&self) -> Result<PremultipliedImage, Error> {
223                <$type>::read_image(self)
224            }
225        }
226    };
227}
228
229macro_rules! presenting {
230    ($type:ty) => {
231        impl Presenting for $type {
232            fn resize(&self, size: Size) {
233                <$type>::resize(self, size);
234            }
235        }
236    };
237}
238
239#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
240offscreen!(mln_webgpu::OffscreenTarget);
241#[cfg(feature = "webgpu")]
242presenting!(mln_webgpu::SurfaceTarget);
243#[cfg(all(feature = "metal", target_vendor = "apple"))]
244offscreen!(mln_mtl::OffscreenTarget);
245#[cfg(all(feature = "metal", target_vendor = "apple"))]
246presenting!(mln_mtl::SurfaceTarget);
247#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
248offscreen!(mln_vulkan::OffscreenTarget);
249#[cfg(all(feature = "d3d12", windows))]
250offscreen!(mln_d3d12::OffscreenTarget);
251#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
252presenting!(mln_vulkan::SurfaceTarget);
253#[cfg(all(feature = "d3d12", windows))]
254presenting!(mln_d3d12::SurfaceTarget);
255#[cfg(all(feature = "gl", not(target_family = "wasm")))]
256offscreen!(mln_gl::OffscreenTarget);
257#[cfg(all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))))]
258presenting!(mln_gl::SurfaceTarget);
259#[cfg(all(feature = "gl", not(target_family = "wasm")))]
260presenting!(mln_gl::HostSurfaceTarget);
261#[cfg(all(feature = "gl", target_family = "wasm"))]
262presenting!(mln_gl::CanvasTarget);
263
264#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
265impl Borrowed for mln_webgpu::BorrowedTarget {
266    fn select(&self, slot: usize) {
267        mln_webgpu::BorrowedTarget::select(self, slot);
268    }
269    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
270        mln_webgpu::BorrowedTarget::release(self, slot, consumer)
271    }
272    fn discard(&self, slot: usize) {
273        mln_webgpu::BorrowedTarget::discard(self, slot);
274    }
275    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
276        let RingKind::WebGpu(textures) = ring.kind else {
277            return Err(Error::unsupported("a ring of WebGPU textures takes WebGPU textures only"));
278        };
279        mln_webgpu::BorrowedTarget::replace(self, textures).map(|()| None)
280    }
281}
282
283#[cfg(all(feature = "gl", not(target_family = "wasm")))]
284impl Borrowed for mln_gl::BorrowedTarget {
285    fn select(&self, slot: usize) {
286        mln_gl::BorrowedTarget::select(self, slot);
287    }
288    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
289        mln_gl::BorrowedTarget::release(self, slot, consumer)
290    }
291    fn discard(&self, slot: usize) {
292        mln_gl::BorrowedTarget::discard(self, slot);
293    }
294    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
295        let RingKind::Gl(textures) = ring.kind else {
296            return Err(Error::unsupported("a ring of OpenGL textures takes OpenGL textures only"));
297        };
298        mln_gl::BorrowedTarget::replace(self, textures).map(|()| None)
299    }
300}
301
302/// A backend, by its type.
303#[derive(Clone)]
304enum Backend {
305    #[cfg(feature = "webgpu")]
306    WebGpu(Rc<mln_webgpu::RendererBackend>),
307    #[cfg(all(feature = "metal", target_vendor = "apple"))]
308    Metal(Rc<mln_mtl::RendererBackend>),
309    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
310    Vulkan(Rc<mln_vulkan::RendererBackend>),
311    #[cfg(all(feature = "d3d12", windows))]
312    D3d12(Rc<mln_d3d12::RendererBackend>),
313    #[cfg(feature = "gl")]
314    Gl(Rc<mln_gl::RendererBackend>),
315}
316
317impl Backend {
318    fn as_dyn(&self) -> Rc<dyn RendererBackend> {
319        match *self {
320            #[cfg(feature = "webgpu")]
321            Backend::WebGpu(ref backend) => Rc::<mln_webgpu::RendererBackend>::clone(backend),
322            #[cfg(all(feature = "metal", target_vendor = "apple"))]
323            Backend::Metal(ref backend) => Rc::<mln_mtl::RendererBackend>::clone(backend),
324            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
325            Backend::Vulkan(ref backend) => Rc::<mln_vulkan::RendererBackend>::clone(backend),
326            #[cfg(all(feature = "d3d12", windows))]
327            Backend::D3d12(ref backend) => Rc::<mln_d3d12::RendererBackend>::clone(backend),
328            #[cfg(feature = "gl")]
329            Backend::Gl(ref backend) => Rc::<mln_gl::RendererBackend>::clone(backend),
330        }
331    }
332
333    /// A backend on `device`, for offscreen targets and the surfaces that
334    /// the device's backend makes on it.
335    #[cfg_attr(
336        not(any(
337            feature = "gl",
338            all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))),
339            all(feature = "d3d12", windows)
340        )),
341        expect(clippy::unnecessary_wraps, reason = "only Vulkan, D3D12 and OpenGL backends can fail to start")
342    )]
343    fn new(device: &Device) -> Result<Backend, Error> {
344        match *device {
345            #[cfg(feature = "webgpu")]
346            Device::WebGpu(ref device) => Ok(Backend::WebGpu(Rc::new(mln_webgpu::RendererBackend::new(device)))),
347            #[cfg(all(feature = "metal", target_vendor = "apple"))]
348            Device::Metal(ref device) => Ok(Backend::Metal(Rc::new(mln_mtl::RendererBackend::new(device)))),
349            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
350            Device::Vulkan(ref device) => Ok(Backend::Vulkan(Rc::new(mln_vulkan::RendererBackend::new(device)?))),
351            #[cfg(all(feature = "d3d12", windows))]
352            Device::D3d12(ref device) => Ok(Backend::D3d12(Rc::new(
353                mln_d3d12::RendererBackend::new(device).map_err(|error| Error::native(error.to_string()))?,
354            ))),
355            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
356            Device::Gl(ref device) => Ok(Backend::Gl(Rc::new(mln_gl::RendererBackend::new(device)?))),
357            #[cfg(all(feature = "gl", target_family = "wasm"))]
358            Device::WebGl => {
359                Err(Error::unsupported("WebGL2 renders only into a canvas, with the canvas's own context"))
360            }
361        }
362    }
363
364    /// A target on the backend that renders into `ring`, handing frames over
365    /// with sync of the kind `producer`.
366    fn borrowed(&self, ring: BorrowedRing, producer: SyncKind) -> Result<Box<dyn Borrowed>, Error> {
367        match (self, ring.kind) {
368            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
369            (Backend::Vulkan(backend), RingKind::Vulkan(images)) => {
370                Ok(Box::new(mln_vulkan::BorrowedTarget::new(Rc::clone(backend), images, producer)?))
371            }
372            #[cfg(all(feature = "metal", target_vendor = "apple"))]
373            (Backend::Metal(backend), RingKind::Metal(textures)) => {
374                Ok(Box::new(mln_mtl::BorrowedTarget::new(Rc::clone(backend), textures, producer)?))
375            }
376            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
377            (Backend::WebGpu(backend), RingKind::WebGpu(textures)) => {
378                Ok(Box::new(mln_webgpu::BorrowedTarget::new(Rc::clone(backend), textures, producer)?))
379            }
380            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
381            (Backend::Gl(backend), RingKind::Gl(textures)) => {
382                Ok(Box::new(mln_gl::BorrowedTarget::new(Rc::clone(backend), textures, producer)?))
383            }
384            #[cfg(all(feature = "d3d12", windows))]
385            (Backend::D3d12(backend), RingKind::D3d12(textures)) => {
386                Ok(Box::new(mln_d3d12::BorrowedTarget::new(Rc::clone(backend), textures, producer)?))
387            }
388            _ => {
389                let _ = producer;
390                Err(Error::unsupported("the session's backend renders into no ring of this kind"))
391            }
392        }
393    }
394
395    /// A target on the backend that renders into a ring of `ring.depth`
396    /// images of `size` pixels, which it exports as `kind`, and hands frames
397    /// over with sync of the kind `producer`.
398    fn exported(
399        &self,
400        device: &Device,
401        ring: &ExportedRing,
402        kind: ExportKind,
403        size: Size,
404        producer: SyncKind,
405    ) -> Result<Box<dyn Exported>, Error> {
406        match self {
407            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
408            Backend::Vulkan(backend) => {
409                Ok(Box::new(mln_vulkan::ExportedTarget::new(Rc::clone(backend), ring, kind, size, producer)?))
410            }
411            #[cfg(all(feature = "metal", target_vendor = "apple"))]
412            Backend::Metal(backend) => {
413                Ok(Box::new(mln_mtl::ExportedTarget::new(Rc::clone(backend), ring, kind, size, producer)?))
414            }
415            #[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
416            Backend::Gl(backend) => {
417                // Irrefutable in a build with OpenGL alone, which has no other
418                // kind of device, and refutable in one with other backends.
419                let Device::Gl(device) = device else {
420                    return Err(Error::unsupported("an OpenGL backend renders on an OpenGL device"));
421                };
422                Ok(Box::new(mln_gl::ExportedTarget::new(Rc::clone(backend), device, ring, kind, size, producer)?))
423            }
424            #[cfg(all(feature = "d3d12", windows))]
425            Backend::D3d12(backend) => {
426                Ok(Box::new(mln_d3d12::ExportedTarget::new(Rc::clone(backend), ring, kind, size, producer)?))
427            }
428            _ => {
429                let _ = (device, ring, kind, size, producer);
430                Err(Error::unsupported("the session's backend exports no ring"))
431            }
432        }
433    }
434
435    /// An offscreen target of `size` pixels on the backend: none in the
436    /// browser, which renders into canvases.
437    #[cfg(target_family = "wasm")]
438    #[expect(clippy::unused_self, reason = "the other builds' targets are of the backend")]
439    fn offscreen(&self, _size: Size) -> Result<Box<dyn Offscreen>, Error> {
440        Err(Error::unsupported("the browser build renders into canvases only"))
441    }
442
443    /// An offscreen target of `size` pixels on the backend.
444    #[cfg(not(target_family = "wasm"))]
445    #[expect(clippy::unnecessary_wraps, reason = "the browser build's fails")]
446    fn offscreen(&self, size: Size) -> Result<Box<dyn Offscreen>, Error> {
447        Ok(match *self {
448            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
449            Backend::WebGpu(ref backend) => Box::new(mln_webgpu::OffscreenTarget::new(Rc::clone(backend), size)),
450            #[cfg(all(feature = "metal", target_vendor = "apple"))]
451            Backend::Metal(ref backend) => Box::new(mln_mtl::OffscreenTarget::new(Rc::clone(backend), size)),
452            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
453            Backend::Vulkan(ref backend) => Box::new(mln_vulkan::OffscreenTarget::new(Rc::clone(backend), size)),
454            #[cfg(all(feature = "d3d12", windows))]
455            Backend::D3d12(ref backend) => Box::new(mln_d3d12::OffscreenTarget::new(Rc::clone(backend), size)),
456            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
457            Backend::Gl(ref backend) => Box::new(mln_gl::OffscreenTarget::new(Rc::clone(backend), size)),
458        })
459    }
460
461    /// A target on the backend that presents to `surface`, at `size`
462    /// pixels, with `overlay` drawn over its frames. Fails with
463    /// `Unsupported` when only a backend of the target's own can present to
464    /// it: see [`surface_backend`].
465    fn surface(
466        &self,
467        surface: Surface,
468        overlay: Option<SurfaceOverlay>,
469        size: Size,
470    ) -> Result<Box<dyn Presenting>, Error> {
471        match (self, surface.kind) {
472            #[cfg(feature = "webgpu")]
473            (Backend::WebGpu(backend), kind) => {
474                #[cfg(target_family = "wasm")]
475                let format = match &kind {
476                    SurfaceKind::WebCanvas { format: Some(format), .. } => Some(match format {
477                        super::target::CanvasFormat::Bgra8Unorm => wgpu::TextureFormat::Bgra8Unorm,
478                        super::target::CanvasFormat::Rgba8Unorm => wgpu::TextureFormat::Rgba8Unorm,
479                        super::target::CanvasFormat::Rgba16Float => wgpu::TextureFormat::Rgba16Float,
480                    }),
481                    _ => None,
482                };
483                #[cfg(not(target_family = "wasm"))]
484                let format = None;
485                let target = webgpu_surface(backend, kind)?;
486                let options = mln_webgpu::SurfaceOptions { format, ..mln_webgpu::SurfaceOptions::default() };
487                let target = mln_webgpu::SurfaceTarget::new(Rc::clone(backend), target, size, options)?;
488                target.set_overlay(overlay_of(overlay, |overlay| match overlay {
489                    SurfaceOverlay::WebGpu(overlay) => Ok(overlay),
490                    other => Err(other),
491                })?);
492                Ok(Box::new(target))
493            }
494            #[cfg(all(feature = "metal", target_vendor = "apple"))]
495            (Backend::Metal(backend), SurfaceKind::MetalLayer(layer)) => {
496                let target = mln_mtl::SurfaceTarget::new(backend, layer, size, true);
497                target.set_overlay(overlay_of(overlay, |overlay| match overlay {
498                    SurfaceOverlay::Metal(overlay) => Ok(overlay),
499                    other => Err(other),
500                })?);
501                Ok(Box::new(target))
502            }
503            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
504            (Backend::Vulkan(backend), SurfaceKind::Window(window)) => {
505                let target = mln_vulkan::SurfaceTarget::new(Rc::clone(backend), window, size, true)?;
506                target.set_overlay(vulkan_overlay(overlay)?);
507                Ok(Box::new(target))
508            }
509            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
510            (Backend::Vulkan(backend), SurfaceKind::Vulkan(surface)) => {
511                let target = mln_vulkan::SurfaceTarget::on_host_surface(Rc::clone(backend), surface, size, true)?;
512                target.set_overlay(vulkan_overlay(overlay)?);
513                Ok(Box::new(target))
514            }
515            #[cfg(all(feature = "d3d12", windows))]
516            (Backend::D3d12(backend), SurfaceKind::Window(window)) => {
517                let overlay = d3d12_overlay(overlay)?;
518                let target = mln_d3d12::SurfaceTarget::new(Rc::clone(backend), window, size)?;
519                target.set_overlay(overlay);
520                Ok(Box::new(target))
521            }
522            #[cfg(all(feature = "d3d12", windows))]
523            (Backend::D3d12(backend), SurfaceKind::D3d12Composition { composition, thread }) => {
524                if composition.is_swap_chain_panel() && thread != std::thread::current().id() {
525                    return Err(Error::unsupported(
526                        "a SwapChainPanel takes its swap chain on its UI thread, which made the surface: attach it \
527                         with Driver::CallerThread, serviced there",
528                    ));
529                }
530                let overlay = d3d12_overlay(overlay)?;
531                let target = mln_d3d12::SurfaceTarget::for_composition(Rc::clone(backend), composition, size)?;
532                target.set_overlay(overlay);
533                Ok(Box::new(target))
534            }
535            _ => {
536                let _ = (size, overlay);
537                Err(Error::unsupported("the session's backend presents to no surface of this kind"))
538            }
539        }
540    }
541}
542
543/// The overlay of the backend that `own` picks out of `overlay`. Fails with
544/// `Unsupported` for another backend's.
545#[cfg_attr(
546    not(any(
547        feature = "webgpu",
548        all(feature = "metal", target_vendor = "apple"),
549        all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))),
550        all(feature = "d3d12", windows),
551        all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))),
552    )),
553    expect(dead_code, reason = "a build without a backend that takes overlays uses none")
554)]
555fn overlay_of<T>(
556    overlay: Option<SurfaceOverlay>,
557    own: impl FnOnce(SurfaceOverlay) -> Result<T, SurfaceOverlay>,
558) -> Result<Option<T>, Error> {
559    overlay
560        .map(own)
561        .transpose()
562        .map_err(|_| Error::unsupported("the surface's overlay is for another backend than the session's"))
563}
564
565#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
566fn vulkan_overlay(overlay: Option<SurfaceOverlay>) -> Result<Option<Box<dyn mln_vulkan::Overlay>>, Error> {
567    overlay_of(overlay, |overlay| match overlay {
568        SurfaceOverlay::Vulkan(overlay) => Ok(overlay),
569        other => Err(other),
570    })
571}
572
573#[cfg(all(feature = "d3d12", windows))]
574fn d3d12_overlay(overlay: Option<SurfaceOverlay>) -> Result<Option<Box<dyn mln_d3d12::Overlay>>, Error> {
575    overlay_of(overlay, |overlay| match overlay {
576        SurfaceOverlay::D3d12(overlay) => Ok(overlay),
577        other => Err(other),
578    })
579}
580
581/// A wgpu surface of `kind`, made with the instance of `backend`'s device
582/// where the host didn't make it.
583#[cfg(feature = "webgpu")]
584fn webgpu_surface(backend: &mln_webgpu::RendererBackend, kind: SurfaceKind) -> Result<wgpu::Surface<'static>, Error> {
585    let instance = || {
586        backend
587            .device()
588            .instance()
589            .ok_or_else(|| Error::invalid_argument("the session's device has no instance to make a surface with"))
590    };
591    let made = match kind {
592        #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
593        SurfaceKind::Wgpu(surface) => return Ok(surface),
594        SurfaceKind::Window(window) => instance()?.create_surface(window),
595        #[cfg(target_family = "wasm")]
596        SurfaceKind::WebCanvas { canvas, .. } => {
597            use wasm_bindgen::JsCast as _;
598            let target = match canvas.dyn_into::<web_sys::OffscreenCanvas>() {
599                Ok(canvas) => wgpu::SurfaceTarget::OffscreenCanvas(canvas),
600                Err(canvas) => wgpu::SurfaceTarget::Canvas(canvas.unchecked_into()),
601            };
602            instance()?.create_surface(target)
603        }
604        #[cfg(all(feature = "metal", target_vendor = "apple"))]
605        SurfaceKind::MetalLayer(_) => return Err(Error::unsupported("a Metal layer presents on a Metal device")),
606        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
607        SurfaceKind::Vulkan(_) => return Err(Error::unsupported("a Vulkan surface presents on a Vulkan device")),
608        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
609        SurfaceKind::Gl(_) => return Err(Error::unsupported("an EGL surface presents on an OpenGL device")),
610        #[cfg(all(feature = "d3d12", windows))]
611        SurfaceKind::D3d12Composition { .. } => {
612            return Err(Error::unsupported("a composition swap chain presents on a D3D12 device"));
613        }
614    };
615    made.map_err(|error| Error::native(format!("can't make a surface on the window: {error}")))
616}
617
618/// A backend of the target's own on `device` and a target that presents to
619/// `surface` with `overlay` drawn over its frames, for the backends whose
620/// context or device is made for the window: Vulkan's, whose instance and
621/// device take the window's surface extensions, and OpenGL ES's, whose
622/// context is of the window's display.
623fn surface_backend(
624    device: &Device,
625    surface: Surface,
626    overlay: Option<SurfaceOverlay>,
627    size: Size,
628) -> Result<(Backend, Box<dyn Presenting>), Error> {
629    match (device, surface.kind) {
630        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
631        (Device::Vulkan(device), SurfaceKind::Window(window)) => {
632            let overlay = vulkan_overlay(overlay)?;
633            let (backend, target) = mln_vulkan::SurfaceTarget::with_backend(device, window, size, true)?;
634            target.set_overlay(overlay);
635            Ok((Backend::Vulkan(backend), Box::new(target)))
636        }
637        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
638        (Device::Vulkan(device), kind @ SurfaceKind::Vulkan(_)) => {
639            let backend = Backend::Vulkan(Rc::new(mln_vulkan::RendererBackend::presenting(device)?));
640            let target = backend.surface(Surface { kind }, overlay, size)?;
641            Ok((backend, target))
642        }
643        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
644        (Device::Gl(device), SurfaceKind::Gl(host)) => {
645            if overlay.is_some() {
646                return Err(Error::unsupported("a host's EGL surface takes no overlay"));
647            }
648            let (backend, target) = mln_gl::HostSurfaceTarget::with_backend(device, host, size)?;
649            Ok((Backend::Gl(backend), Box::new(target)))
650        }
651        #[cfg(all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))))]
652        (Device::Gl(_), SurfaceKind::Window(window)) => {
653            let overlay = overlay_of(overlay, |overlay| match overlay {
654                SurfaceOverlay::Gl(overlay) => Ok(overlay),
655                other => Err(other),
656            })?;
657            let (backend, target) = mln_gl::SurfaceTarget::with_backend(window, size, true)?;
658            target.set_overlay(overlay);
659            Ok((Backend::Gl(backend), Box::new(target)))
660        }
661        #[cfg(all(feature = "gl", target_family = "wasm"))]
662        (Device::WebGl, SurfaceKind::WebCanvas { canvas, .. }) => {
663            use wasm_bindgen::JsCast as _;
664            // WebGL draws no overlay.
665            let canvas = match canvas.dyn_into::<web_sys::OffscreenCanvas>() {
666                Ok(canvas) => mln_gl::WebCanvas::Offscreen(canvas),
667                Err(canvas) => mln_gl::WebCanvas::Element(canvas.unchecked_into()),
668            };
669            let (backend, target) = mln_gl::CanvasTarget::with_backend(canvas, size)?;
670            Ok((Backend::Gl(backend), Box::new(target)))
671        }
672        (_, kind) => {
673            let backend = Backend::new(device)?;
674            let target = backend.surface(Surface { kind }, overlay, size)?;
675            Ok((backend, target))
676        }
677    }
678}
679
680enum Frames {
681    Offscreen(Box<dyn Offscreen>),
682    /// `None` once the surface is released.
683    Presenting(Option<Box<dyn Presenting>>),
684    /// `target` is `None` once the ring is released.
685    Borrowed {
686        target: Option<Box<dyn Borrowed>>,
687        producer: SyncKind,
688    },
689    Exported(Box<dyn Exported>),
690}
691
692/// A render target built on this thread: the backend that a renderer draws
693/// with, on the target's device, and the frames it draws into.
694pub struct LocalTarget {
695    device: Device,
696    backend: Backend,
697    frames: Frames,
698    /// The window that a surface target presents to, if it presents to one.
699    window: Option<Arc<dyn Window>>,
700}
701
702impl LocalTarget {
703    /// An offscreen target of `size` pixels on `device`, or on a device that
704    /// [`Device::new`] makes when that is `None`.
705    ///
706    /// Fails as [`Device::new`] does, and with the backend's error when it
707    /// can't render on the device.
708    pub fn offscreen(device: Option<Device>, size: Size) -> Result<LocalTarget, Error> {
709        let device = match device {
710            Some(device) => device,
711            None => Device::new(DeviceOptions::default())?,
712        };
713        let backend = Backend::new(&device)?;
714        let frames = Frames::Offscreen(backend.offscreen(size)?);
715        Ok(LocalTarget { device, backend, frames, window: None })
716    }
717
718    /// A target of `size` pixels that presents to `surface`, with `overlay`
719    /// drawn over its frames, on `device` or, when that is `None`, on the
720    /// device the surface's kind takes
721    /// ([`RenderTarget::Surface`](super::RenderTarget::Surface)).
722    ///
723    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a
724    /// surface that the host made without the host's device, with
725    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) for a window or
726    /// surface without an area to present to, such as a minimized window,
727    /// with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the device
728    /// can't present to the surface or draw the overlay, and with the error
729    /// of the device or the window's surface.
730    pub fn surface(
731        surface: Surface,
732        overlay: Option<SurfaceOverlay>,
733        device: Option<Device>,
734        size: Size,
735    ) -> Result<LocalTarget, Error> {
736        surface.check_area()?;
737        let window = surface.host_window();
738        let device = match device {
739            Some(device) => device,
740            None => default_surface_device(&surface)?,
741        };
742        let (backend, target) = surface_backend(&device, surface, overlay, size)?;
743        Ok(LocalTarget { device, backend, frames: Frames::Presenting(Some(target)), window })
744    }
745
746    /// A target of `size` pixels on `device` that renders into the host's
747    /// `ring`, and hands each frame over with sync of the kind `producer`.
748    ///
749    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
750    /// device can't render into the ring with `producer`, and with the
751    /// backend's error.
752    pub fn borrowed(device: Device, ring: BorrowedRing, producer: SyncKind) -> Result<LocalTarget, Error> {
753        let backend = Backend::new(&device)?;
754        let frames = Frames::Borrowed { target: Some(backend.borrowed(ring, producer)?), producer };
755        Ok(LocalTarget { device, backend, frames, window: None })
756    }
757
758    /// A target on `device` that renders into a ring of `ring.depth` images
759    /// of `size` pixels, which it exports as `kind`, one that
760    /// [`Device::export_plan`] picked, and hands each frame over with sync of
761    /// the kind `producer`.
762    ///
763    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
764    /// device can't export `kind` or hand frames over with `producer`, and
765    /// with the backend's error.
766    pub fn exported(
767        device: Device,
768        ring: &ExportedRing,
769        kind: ExportKind,
770        size: Size,
771        producer: SyncKind,
772    ) -> Result<LocalTarget, Error> {
773        let backend = Backend::new(&device)?;
774        let frames = Frames::Exported(backend.exported(&device, ring, kind, size, producer)?);
775        Ok(LocalTarget { device, backend, frames, window: None })
776    }
777
778    /// The device the target renders on.
779    #[must_use]
780    pub fn device(&self) -> &Device {
781        &self.device
782    }
783
784    /// The backend that renderers drawing into the target draw with.
785    #[must_use]
786    pub fn backend(&self) -> Rc<dyn RendererBackend> {
787        self.backend.as_dyn()
788    }
789
790    /// The frames to draw into, or `None` while a surface target has no
791    /// surface.
792    #[must_use]
793    pub fn frames(&self) -> Option<&dyn FrameTarget> {
794        match &self.frames {
795            Frames::Offscreen(target) => Some(&**target),
796            Frames::Presenting(target) => target.as_deref().map(|target| -> &dyn FrameTarget { target }),
797            Frames::Borrowed { target, .. } => target.as_deref().map(|target| -> &dyn FrameTarget { target }),
798            Frames::Exported(target) => Some(&**target),
799        }
800    }
801
802    /// Whether the target can take a frame as far as its window says: it
803    /// presents to no window, or to one with an area to present to
804    /// ([`mln_gfx::window::has_area`]).
805    #[must_use]
806    pub fn window_has_area(&self) -> bool {
807        self.window.as_deref().is_none_or(mln_gfx::window::has_area)
808    }
809
810    /// Whether frames are presented to a window or surface.
811    #[must_use]
812    pub fn is_presenting(&self) -> bool {
813        matches!(self.frames, Frames::Presenting(_))
814    }
815
816    /// Whether frames go to the host in images of the target's own.
817    #[must_use]
818    pub fn is_exported(&self) -> bool {
819        matches!(self.frames, Frames::Exported(_))
820    }
821
822    /// Whether frames go to the host's ring.
823    #[must_use]
824    pub fn is_borrowed(&self) -> bool {
825        matches!(self.frames, Frames::Borrowed { .. })
826    }
827
828    /// Whether the target is a ring that let go of its textures.
829    #[must_use]
830    pub fn ring_released(&self) -> bool {
831        matches!(self.frames, Frames::Borrowed { target: None, .. })
832    }
833
834    fn ring(&self) -> Result<&dyn Borrowed, Error> {
835        match &self.frames {
836            Frames::Borrowed { target: Some(target), .. } => Ok(&**target),
837            Frames::Borrowed { target: None, .. } => Err(Error::invalid_state("the ring was released")),
838            _ => Err(Error::unsupported("the target has no ring")),
839        }
840    }
841
842    /// Has the next frame render into the ring's texture at `slot`.
843    pub fn select_slot(&self, slot: usize) -> Result<(), Error> {
844        if let Frames::Exported(target) = &self.frames {
845            target.select(slot);
846            return Ok(());
847        }
848        self.ring()?.select(slot);
849        Ok(())
850    }
851
852    /// The host gave the ring's texture at `slot` back: the next frame
853    /// rendered into it waits for `consumer`.
854    pub fn release_slot(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
855        if let Frames::Exported(target) = &self.frames {
856            return target.release(slot, consumer);
857        }
858        self.ring()?.release(slot, consumer)
859    }
860
861    /// The host gave up the ring's texture at `slot`, which the target
862    /// renders into no more.
863    pub fn discard_slot(&self, slot: usize) -> Result<(), Error> {
864        if let Frames::Exported(target) = &self.frames {
865            target.discard(slot);
866            return Ok(());
867        }
868        self.ring()?.discard(slot);
869        Ok(())
870    }
871
872    /// The size in pixels of an exported ring's images, or `None` for
873    /// another target.
874    #[must_use]
875    pub fn exported_size(&self) -> Option<Size> {
876        match &self.frames {
877            Frames::Exported(target) => Some(target.size()),
878            _ => None,
879        }
880    }
881
882    /// Renders an exported ring's next frames into images of `size` pixels.
883    /// The frames that the host holds, at `held` slots, keep their images.
884    /// Returns whether the ring has new images, which it doesn't when they
885    /// have `size` already.
886    ///
887    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
888    /// target that isn't an exported ring, and with the backend's error, when
889    /// the ring keeps its images.
890    pub fn resize_exported(&self, size: Size, held: &[usize]) -> Result<bool, Error> {
891        match &self.frames {
892            Frames::Exported(target) => target.resize(size, held),
893            _ => Err(Error::unsupported("the target exports no ring")),
894        }
895    }
896
897    /// The exported image of the frame at `slot`, of the size it has.
898    #[must_use]
899    pub fn exported_texture(&self, slot: usize) -> Option<FrameTexture> {
900        match &self.frames {
901            Frames::Exported(target) => target.image(slot).map(|frame| FrameTexture::exported(frame, &self.device)),
902            _ => None,
903        }
904    }
905
906    /// Renders into `ring` from now on, in place of the ring's textures, and
907    /// returns the host's reads of the textures that it let go of, which the
908    /// host may use once they end.
909    ///
910    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
911    /// target that isn't a ring, or a ring of another format, and with the
912    /// backend's error.
913    pub(crate) fn set_ring(&mut self, ring: BorrowedRing) -> Result<Pending, Error> {
914        match &mut self.frames {
915            Frames::Borrowed { target: Some(target), .. } => target.replace(ring),
916            Frames::Borrowed { target, producer } => {
917                *target = Some(self.backend.borrowed(ring, *producer)?);
918                Ok(None)
919            }
920            _ => Err(Error::unsupported("the target has no ring")),
921        }
922    }
923
924    /// Whether frames are read back rather than presented.
925    #[must_use]
926    pub fn is_offscreen(&self) -> bool {
927        matches!(self.frames, Frames::Offscreen(_))
928    }
929
930    /// Draws the next frame at `size` pixels.
931    pub fn resize(&self, size: Size) {
932        match &self.frames {
933            Frames::Offscreen(target) => target.resize(size),
934            Frames::Presenting(Some(target)) => target.resize(size),
935            Frames::Presenting(None) | Frames::Borrowed { .. } | Frames::Exported(_) => {}
936        }
937    }
938
939    /// The last frame's pixels.
940    ///
941    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
942    /// target that presents its frames, with
943    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) before a frame, and
944    /// with [`ErrorKind::Native`](mln_util::ErrorKind) where the backend
945    /// reads nothing back.
946    pub fn read_image(&self) -> Result<PremultipliedImage, Error> {
947        match &self.frames {
948            Frames::Offscreen(target) => target.read_image(),
949            Frames::Presenting(_) => Err(Error::unsupported("a surface session can't read its frames back")),
950            Frames::Borrowed { .. } | Frames::Exported(_) => {
951                Err(Error::unsupported("a ring's frames are the host's to read"))
952            }
953        }
954    }
955
956    /// Lets go of a surface target's surface, or of a ring's textures, and
957    /// returns the host's reads of the textures, which the host may use once
958    /// they end. The backend stays.
959    pub(crate) fn release_surface(&mut self) -> Pending {
960        match &mut self.frames {
961            Frames::Presenting(target) => {
962                drop(target.take());
963                self.window = None;
964                None
965            }
966            Frames::Borrowed { target, .. } => target.take().and_then(|target| target.take_pending()),
967            Frames::Offscreen(_) | Frames::Exported(_) => None,
968        }
969    }
970
971    /// Presents to `surface` at `size` pixels from now on, with `overlay`
972    /// drawn over its frames, in place of the surface the target has, if
973    /// any: on the same backend where it can present to `surface`, and on a
974    /// new one of the device otherwise, which the target then returns true
975    /// for, and which draws no overlay. A renderer on the old backend has to
976    /// be made again on the new one.
977    ///
978    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for an
979    /// offscreen target or when the device can't present to `surface`, and
980    /// as [`surface`](Self::surface) does. The target then keeps what it
981    /// had.
982    pub fn set_surface(
983        &mut self,
984        surface: Surface,
985        overlay: Option<SurfaceOverlay>,
986        size: Size,
987    ) -> Result<bool, Error> {
988        if !matches!(self.frames, Frames::Presenting(_)) {
989            return Err(Error::unsupported("only a surface target presents to another surface"));
990        }
991        surface.check_area()?;
992        let window = surface.host_window();
993        let retry = surface.clone_window();
994        let (new_backend, target) = match self.backend.surface(surface, overlay, size) {
995            Ok(target) => (false, target),
996            Err(error) if error.kind == mln_util::ErrorKind::Unsupported => {
997                let surface = retry.ok_or(error)?;
998                let (backend, target) = surface_backend(&self.device, surface, None, size)?;
999                self.backend = backend;
1000                (true, target)
1001            }
1002            Err(error) => return Err(error),
1003        };
1004        self.frames = Frames::Presenting(Some(target));
1005        self.window = window;
1006        Ok(new_backend)
1007    }
1008}
1009
1010/// The device a surface renders on without the host's: the native one where
1011/// its backend takes the surface's kind.
1012fn default_surface_device(surface: &Surface) -> Result<Device, Error> {
1013    match surface.kind {
1014        SurfaceKind::Window(_) if cfg!(target_vendor = "apple") => {
1015            Device::with_backend(super::target::BackendType::WebGPU, DeviceOptions::default())
1016        }
1017        SurfaceKind::Window(_) => Device::new(DeviceOptions::default()),
1018        #[cfg(all(feature = "metal", target_vendor = "apple"))]
1019        SurfaceKind::MetalLayer(_) => Device::with_backend(super::target::BackendType::Metal, DeviceOptions::default()),
1020        #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
1021        SurfaceKind::Wgpu(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
1022        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1023        SurfaceKind::Vulkan(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
1024        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
1025        SurfaceKind::Gl(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
1026        #[cfg(all(feature = "d3d12", windows))]
1027        SurfaceKind::D3d12Composition { .. } => {
1028            Device::with_backend(super::target::BackendType::D3D12, DeviceOptions::default())
1029        }
1030        // A WebGPU build asked the browser for a device before the build.
1031        #[cfg(all(target_family = "wasm", feature = "gl"))]
1032        SurfaceKind::WebCanvas { .. } => Ok(Device::WebGl),
1033        #[cfg(all(target_family = "wasm", not(feature = "gl")))]
1034        SurfaceKind::WebCanvas { .. } => Err(Error::invalid_state("the browser's WebGPU device isn't there yet")),
1035    }
1036}