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