Skip to main content

mln_webgpu/
borrowed_target.rs

1//! A ring of the host's textures, on the device that renders into them, that
2//! frames are drawn into and given back to the host. Both sides submit to the
3//! device's one queue, which orders the host's reads after the frame and the
4//! next frame after the host's reads.
5
6use mln_gfx::frame::{FrameImage, FrameTarget, Handoff};
7use mln_gfx::gpu::{Gpu as _, ResourceId, TargetFormats, destroy_unused};
8use mln_gfx::{ConsumerSync, DepthStencilFormat, DepthStencilFormats, Error, GpuSync, Size, SyncKind, SyncKinds};
9
10use crate::gpu::{WebGpu, from_wgpu_format};
11use crate::log_target;
12use crate::renderer_backend::RendererBackend;
13
14/// A ring of the host's 2D textures, of `size` pixels and one format, with
15/// one layer, one mip level, one sample and `RENDER_ATTACHMENT` usage.
16#[derive(Clone, Debug, PartialEq)]
17pub struct BorrowedTextures {
18    pub textures: Vec<wgpu::Texture>,
19    pub size: Size,
20    /// The host's textures that frames draw their depth and stencil into
21    /// and store, one for each of `textures`, of their size and kind and one
22    /// depth and stencil format, or none for depth of the target's own.
23    pub depth_textures: Vec<wgpu::Texture>,
24}
25
26impl BorrowedTextures {
27    /// The kinds of sync with which the host can wait for a frame (the
28    /// producer's) and the target for the host's reads (the consumer's):
29    /// both share the device's queue.
30    #[must_use]
31    pub fn sync_kinds() -> (SyncKinds, SyncKinds) {
32        let kinds = SyncKinds::of(&[SyncKind::CpuComplete, SyncKind::QueueOrder]);
33        (kinds, kinds)
34    }
35
36    /// The formats of the depth textures that frames draw into on `device`.
37    #[must_use]
38    pub fn depth_stencil_formats(device: &wgpu::Device) -> DepthStencilFormats {
39        let formats = DepthStencilFormats::of(&[DepthStencilFormat::Depth24Stencil8]);
40        if device.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
41            formats.with(DepthStencilFormat::Depth32FloatStencil8)
42        } else {
43            formats
44        }
45    }
46
47    /// Checks the textures against their ring.
48    ///
49    /// Fails with [`ErrorKind::InvalidArgument`](mln_gfx::ErrorKind) for a
50    /// texture of another size than the ring's, of another format than the
51    /// first, or that a frame can't render into, for depth textures that
52    /// aren't one for each texture, and with
53    /// [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) for depth textures of
54    /// no depth and stencil format.
55    pub fn check(&self) -> Result<(), Error> {
56        let Some(first) = self.textures.first() else {
57            return Err(Error::invalid_argument("a ring needs at least one texture"));
58        };
59        if let Some(depth) = self.depth_textures.first() {
60            if self.depth_textures.len() != self.textures.len() {
61                return Err(Error::invalid_argument("a ring's depth textures must be one for each of its textures"));
62            }
63            if depth_stencil_format(depth.format()).is_none() {
64                return Err(Error::unsupported("a ring's depth textures must have a depth and stencil format"));
65            }
66        }
67        for texture in self.textures.iter().chain(&self.depth_textures) {
68            let size = texture.size();
69            if (size.width, size.height) != (self.size.width, self.size.height) {
70                return Err(Error::invalid_argument("each texture's size must match the ring's physical size"));
71            }
72            let kin =
73                if texture.format().is_depth_stencil_format() { self.depth_textures.first() } else { Some(first) };
74            if Some(texture.format()) != kin.map(wgpu::Texture::format) {
75                return Err(Error::invalid_argument("the ring's textures must share a format"));
76            }
77            if !texture.usage().contains(wgpu::TextureUsages::RENDER_ATTACHMENT)
78                || texture.dimension() != wgpu::TextureDimension::D2
79                || texture.mip_level_count() != 1
80                || texture.sample_count() != 1
81                || size.depth_or_array_layers != 1
82            {
83                return Err(Error::invalid_argument(
84                    "each texture must be 2D with one layer, mip level and sample, and render-attachment usage",
85                ));
86            }
87        }
88        Ok(())
89    }
90
91    fn format(&self) -> Option<wgpu::TextureFormat> {
92        self.textures.first().map(wgpu::Texture::format)
93    }
94
95    fn depth_format(&self) -> Option<wgpu::TextureFormat> {
96        self.depth_textures.first().map(wgpu::Texture::format)
97    }
98}
99
100/// The depth and stencil format that `format` is, if it is one.
101#[must_use]
102pub fn depth_stencil_format(format: wgpu::TextureFormat) -> Option<DepthStencilFormat> {
103    match format {
104        wgpu::TextureFormat::Depth24PlusStencil8 => Some(DepthStencilFormat::Depth24Stencil8),
105        wgpu::TextureFormat::Depth32FloatStencil8 => Some(DepthStencilFormat::Depth32FloatStencil8),
106        _ => None,
107    }
108}
109
110/// Frames drawn into the host's textures, each given back to the host.
111pub struct BorrowedTarget {
112    device: wgpu::Device,
113    /// `None` once the target let go of them.
114    textures: Option<BorrowedTextures>,
115    /// The slot that the next frame draws into.
116    selected: usize,
117    producer: SyncKind,
118    depth_stencil_format: wgpu::TextureFormat,
119    /// The target's own depth and stencil texture, where the host gave
120    /// none.
121    depth_stencil: Option<wgpu::Texture>,
122    /// The slot of the frame begun and its textures, imported into the
123    /// backend's `WebGpu`, until the frame ends.
124    imports: Option<(usize, FrameImage)>,
125}
126
127impl BorrowedTarget {
128    /// A target on `backend` that draws into `textures`, which are of its
129    /// device, and hands each frame to the host with sync of the kind
130    /// `producer`, one of [`BorrowedTextures::sync_kinds`]'s.
131    ///
132    /// Fails as [`BorrowedTextures::check`] does, and with
133    /// [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) for a producer kind
134    /// the target can't hand over.
135    pub fn new(backend: &RendererBackend, textures: BorrowedTextures, producer: SyncKind) -> Result<Self, Error> {
136        textures.check()?;
137        if !BorrowedTextures::sync_kinds().0.contains(producer) {
138            return Err(Error::unsupported(format!("a WebGPU target hands frames over with no {producer:?}")));
139        }
140        let device = backend.device().device().clone();
141        let depth_stencil_format = if device.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
142            wgpu::TextureFormat::Depth32FloatStencil8
143        } else {
144            wgpu::TextureFormat::Depth24PlusStencil8
145        };
146        Ok(BorrowedTarget {
147            device,
148            textures: Some(textures),
149            selected: 0,
150            producer,
151            depth_stencil_format,
152            depth_stencil: None,
153            imports: None,
154        })
155    }
156
157    /// Has the next frame draw into the texture at `slot`.
158    pub fn select(&mut self, slot: usize) {
159        self.selected = slot;
160    }
161
162    /// The host gave the texture at `slot` back. The host's reads went to
163    /// the queue before the next frame does, or have finished.
164    #[expect(
165        clippy::needless_pass_by_value,
166        reason = "the release takes the host's sync, as every backend's does, and drops it"
167    )]
168    pub fn release(&mut self, _slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
169        match consumer.sync.kind {
170            SyncKind::CpuComplete | SyncKind::QueueOrder => Ok(()),
171            kind => Err(Error::unsupported(format!("the WebGPU target waits for no {kind:?}"))),
172        }
173    }
174
175    /// The host gave up the texture at `slot`, which is never drawn into
176    /// again.
177    pub fn discard(&mut self, _slot: usize) {}
178
179    /// Draws into `textures` from now on, which must be as many, of the
180    /// ring's format. Returns the sync after which the host may use the old
181    /// textures, as [`release_textures`](Self::release_textures) does.
182    ///
183    /// Fails with [`ErrorKind::InvalidArgument`](mln_gfx::ErrorKind) for
184    /// another number of textures, with
185    /// [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) for another format,
186    /// with [`ErrorKind::InvalidState`](mln_gfx::ErrorKind) once the target
187    /// let go of its textures, as [`BorrowedTextures::check`] does, and as
188    /// [`release_textures`](Self::release_textures) does. The target then
189    /// keeps its textures.
190    pub fn replace(&mut self, gpu: &mut WebGpu, textures: BorrowedTextures) -> Result<GpuSync, Error> {
191        let Some(current) = &self.textures else {
192            return Err(Error::invalid_state("the ring let go of its textures"));
193        };
194        if textures.textures.len() != current.textures.len() {
195            return Err(Error::invalid_argument("a ring keeps its depth"));
196        }
197        if (textures.format(), textures.depth_format()) != (current.format(), current.depth_format()) {
198            return Err(Error::unsupported("a ring keeps its formats, and its depth textures or their lack"));
199        }
200        textures.check()?;
201        let sync = self.end_work(gpu)?;
202        self.textures = Some(textures);
203        Ok(sync)
204    }
205
206    /// Lets go of the textures, and returns the sync after which the host
207    /// may use them, of the producer's kind. The target draws no frame
208    /// after.
209    ///
210    /// Fails with [`ErrorKind::InvalidState`](mln_gfx::ErrorKind) once the
211    /// target let go of its textures, and with
212    /// [`ErrorKind::Failed`](mln_gfx::ErrorKind) when it can't submit its
213    /// work, or wait for it for [`SyncKind::CpuComplete`]. It keeps its
214    /// textures then.
215    pub fn release_textures(&mut self, gpu: &mut WebGpu) -> Result<GpuSync, Error> {
216        if self.textures.is_none() {
217            return Err(Error::invalid_state("the ring let go of its textures"));
218        }
219        let sync = self.end_work(gpu)?;
220        self.textures = None;
221        self.depth_stencil = None;
222        Ok(sync)
223    }
224
225    /// Forgets a frame begun on the textures, submits the work recorded so
226    /// far, and returns the sync that ends it.
227    fn end_work(&mut self, gpu: &mut WebGpu) -> Result<GpuSync, Error> {
228        if let Some((_, image)) = self.imports.take() {
229            destroy_imports(gpu, image);
230        }
231        let wait = self.producer == SyncKind::CpuComplete;
232        gpu.flush(wait).map_err(|error| Error::failed(format!("Submitting a ring's frames failed: {error}")))?;
233        Ok(GpuSync::of(self.producer))
234    }
235}
236
237/// A target's own depth and stencil texture of `size` and `format`, made
238/// on `device` in `own` when it has none of that size.
239fn own_depth_stencil(
240    device: &wgpu::Device,
241    format: wgpu::TextureFormat,
242    own: &mut Option<wgpu::Texture>,
243    size: Size,
244) -> wgpu::Texture {
245    match own {
246        Some(texture) if (texture.width(), texture.height()) == (size.width, size.height) => texture.clone(),
247        _ => own
248            .insert(device.create_texture(&wgpu::TextureDescriptor {
249                label: Some("borrowed ring depth and stencil"),
250                size: wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1 },
251                mip_level_count: 1,
252                sample_count: 1,
253                dimension: wgpu::TextureDimension::D2,
254                format,
255                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
256                view_formats: &[],
257            }))
258            .clone(),
259    }
260}
261
262fn destroy_imports(gpu: &mut WebGpu, image: FrameImage) {
263    let imports = [Some(image.color), image.depth_stencil].into_iter().flatten();
264    destroy_unused(gpu, imports.map(ResourceId::Texture));
265}
266
267impl FrameTarget for BorrowedTarget {
268    type Gpu = WebGpu;
269
270    fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
271        let slot = self.selected;
272        match self.imports {
273            Some((imported, image)) if imported == slot => return Some(image),
274            // A slot was selected since the frame began.
275            Some((_, image)) => {
276                self.imports = None;
277                destroy_imports(gpu, image);
278            }
279            None => {}
280        }
281        let textures = self.textures.as_ref()?;
282        let texture = textures.textures.get(slot)?.clone();
283        // The host's depth and stencil texture of the slot, or the
284        // target's own of the ring's size.
285        let depth_stencil = match textures.depth_textures.get(slot) {
286            Some(depth) => depth.clone(),
287            None => own_depth_stencil(&self.device, self.depth_stencil_format, &mut self.depth_stencil, textures.size),
288        };
289        let image = FrameImage {
290            size: textures.size,
291            color: gpu.import_texture(&texture),
292            depth_stencil: Some(gpu.import_texture(&depth_stencil)),
293            targets: TargetFormats {
294                color: from_wgpu_format(texture.format()),
295                depth_stencil: from_wgpu_format(depth_stencil.format()),
296            },
297        };
298        self.imports = Some((slot, image));
299        Some(image)
300    }
301
302    fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
303        let Some((_, image)) = self.imports.take() else {
304            return Handoff::Dropped;
305        };
306        destroy_imports(gpu, image);
307        let sync = if self.producer == SyncKind::QueueOrder {
308            GpuSync::of(SyncKind::QueueOrder)
309        } else {
310            if let Err(error) = gpu.flush(true) {
311                tracing::error!(
312                    target: log_target::RENDER,
313                    error = %error,
314                    "WebGPU: waiting for a borrowed texture's frame failed"
315                );
316                return Handoff::Dropped;
317            }
318            GpuSync::of(SyncKind::CpuComplete)
319        };
320        Handoff::GivenBack { slot: self.selected, sync }
321    }
322
323    /// Forgets the textures of a frame begun and not ended.
324    fn tear_down(&mut self, gpu: &mut WebGpu) {
325        if let Some((_, image)) = self.imports.take() {
326            destroy_imports(gpu, image);
327        }
328    }
329}