Skip to main content

mln_engine/draw/
resources.rs

1//! What the renderer makes its buffers and textures with on its backend's
2//! `Gpu`, with the rendering stats that count them and the queue that they
3//! go to when they drop, and the handle a layer makes its meshes and
4//! targets with ([`Resources`]).
5
6use std::rc::Rc;
7
8use mln_gfx::gpu::{
9    BufferDesc, BufferUsage, Caps, Gpu, GpuError, ShaderKey, TextureDesc, TextureFormat, TextureId, TextureUsage,
10};
11use mln_gfx::projection_variant::ProjectionVariant;
12use mln_gfx::rendering_stats::RenderingStats;
13use mln_gfx::shaders::program::Program;
14use mln_gfx::texture2d::SamplerState;
15use mln_gfx::types::TextureChannelDataType;
16use mln_gfx::{Rgba, Size};
17use mln_style::bitmap::PremultipliedImage;
18
19use crate::draw::buffer::{self, Buffer};
20use crate::draw::context::Context;
21use crate::draw::indexes::Indexes;
22use crate::draw::objects::{Mesh, MeshDesc};
23use crate::draw::release::{Release, ReleaseQueue};
24use crate::draw::store::{IndexBuffer, Texture};
25use crate::draw::target::Target;
26use crate::draw::texture2d::Texture2D;
27use crate::draw::vertex_attribute::Uniforms;
28use crate::draw::vertices::VertexBuffer;
29use crate::log_target;
30
31/// The renderer's GPU resources, as a layer's hooks make and read them: the
32/// vertex and index buffers and the textures of its meshes, the meshes it
33/// draws ([`mesh`](Self::mesh)), and the targets its draws draw into
34/// ([`target`](Self::target)). What it makes stays while the layer keeps a
35/// handle to it, and the buffers and textures while a mesh reads them.
36pub struct Resources<'a> {
37    pub(crate) gpu: &'a mut dyn Gpu,
38    pub(crate) context: &'a mut Context,
39}
40
41impl<'a> Resources<'a> {
42    pub(crate) fn new(gpu: &'a mut dyn Gpu, context: &'a mut Context) -> Self {
43        Resources { gpu, context }
44    }
45
46    /// The mesh that `desc` describes.
47    #[must_use]
48    pub fn mesh(&mut self, desc: MeshDesc) -> Mesh {
49        Mesh::of(self.context, desc)
50    }
51
52    /// A target of `size`, whose texture's channels are of `type_`, or of
53    /// the type the backend draws into for it, and which clears to `clear`
54    /// before its draws. Its texture is sampled linearly and clamped to its
55    /// edges.
56    #[must_use]
57    pub fn target(&mut self, size: Size, type_: TextureChannelDataType, clear: Rgba) -> Target {
58        Target::new(self.context, size, type_, clear)
59    }
60
61    /// A buffer of a copy of `vertices`, which the first draw that reads it
62    /// uploads.
63    #[must_use]
64    pub fn vertices<V: bytemuck::Pod>(&mut self, vertices: &[V]) -> VertexBuffer {
65        self.context.add_vertices(vertices.to_vec())
66    }
67
68    /// A buffer of a copy of `vertices`, as [`vertices`](Self::vertices)
69    /// makes it, that [`update_vertices`](Self::update_vertices) replaces
70    /// often: it keeps the vertices' storage for the next update.
71    #[must_use]
72    pub fn dynamic_vertices<V: bytemuck::Pod>(&mut self, vertices: &[V]) -> VertexBuffer {
73        self.context.add_dynamic_vertices(vertices)
74    }
75
76    /// Replaces the vertices of `buffer`, of the type `V`, with a copy of
77    /// `vertices`, as many, which the next draw that reads them uploads.
78    /// Returns false, leaving them be, for another number of vertices.
79    pub fn update_vertices<V: bytemuck::Pod>(&mut self, buffer: &VertexBuffer, vertices: &[V]) -> bool {
80        self.context.update_vertices(buffer, vertices)
81    }
82
83    /// A buffer of a copy of `indexes`, which the first draw that reads it
84    /// uploads.
85    #[must_use]
86    pub fn indexes(&mut self, indexes: &[u16]) -> IndexBuffer {
87        self.context.add_indexes(Indexes::new(indexes.to_vec()))
88    }
89
90    /// The indexes of as many quads as 16-bit indexes reach, four vertices
91    /// apart, two triangles each, which every mesh that draws such quads
92    /// shares.
93    #[must_use]
94    pub fn quad_indexes(&mut self) -> IndexBuffer {
95        self.context.quad_indexes()
96    }
97
98    /// A texture of `format`, sampled as `sampler` says, which
99    /// [`write_texture`](Self::write_texture) makes and fills.
100    #[must_use]
101    pub fn texture(&mut self, format: TextureFormat, sampler: SamplerState) -> Texture {
102        self.context.add_texture_with(|texture| {
103            texture.set_format(format);
104            texture.set_sampler(sampler);
105        })
106    }
107
108    /// A texture of `image`, sampled as `sampler` says, which the first draw
109    /// that binds it uploads.
110    #[must_use]
111    pub fn image_texture(&mut self, image: Rc<PremultipliedImage>, sampler: SamplerState) -> Texture {
112        self.context.add_texture_with(|texture| {
113            texture.set_image(Some(image));
114            texture.set_sampler(sampler);
115        })
116    }
117
118    /// Makes `image` what `texture` holds, which the next draw that binds it
119    /// uploads.
120    pub fn set_image(&mut self, texture: &Texture, image: Rc<PremultipliedImage>) {
121        if let Some(mut texture) = self.context.texture_mut(texture) {
122            texture.set_image(Some(image));
123        }
124    }
125
126    /// Writes `data`, the texels of an image of `size` in rows from the top,
127    /// to the whole of `texture`, first making it of that size.
128    pub fn write_texture(&mut self, texture: &Texture, data: &[u8], size: Size) -> Result<(), GpuError> {
129        self.context.upload_texture_data(self.gpu, texture, data, size)
130    }
131
132    /// Samples `texture` as `sampler` says, where a mesh doesn't say
133    /// otherwise ([`Mesh::set_sampler`]).
134    pub fn set_sampler(&mut self, texture: &Texture, sampler: SamplerState) {
135        if let Some(mut texture) = self.context.texture_mut(texture) {
136            texture.set_sampler(sampler);
137        }
138    }
139
140    /// The size of `texture`, empty before it has one.
141    #[must_use]
142    pub fn texture_size(&self, texture: &Texture) -> Size {
143        self.context.texture(texture).map(Texture2D::size).unwrap_or_default()
144    }
145
146    /// The key of the variant of `program` that reads its properties of
147    /// `uniforms` from their uniforms, for `projection`, at the frame's
148    /// pixel ratio.
149    pub fn shader_key(
150        &mut self,
151        program: &'static Program,
152        uniforms: Uniforms,
153        projection: ProjectionVariant,
154    ) -> ShaderKey {
155        self.context.shader_key(program, uniforms, projection)
156    }
157
158    /// What the backend's device allows.
159    #[must_use]
160    pub fn caps(&self) -> &Caps {
161        self.context.caps()
162    }
163
164    /// Fails the frame being encoded with `message`, for a GPU operation of
165    /// a layer that failed.
166    pub fn fail(&mut self, message: String) {
167        self.context.fail(message);
168    }
169}
170
171/// A texture of the context's `Gpu`, which goes to the context's release
172/// queue when it drops, as a [`Buffer`] does.
173pub(crate) struct GpuTexture {
174    id: TextureId,
175    /// The bytes the rendering stats count it with, `None` where they don't.
176    counted: Option<usize>,
177    queue: Rc<ReleaseQueue>,
178}
179
180impl GpuTexture {
181    #[must_use]
182    pub(crate) fn id(&self) -> TextureId {
183        self.id
184    }
185}
186
187impl Drop for GpuTexture {
188    fn drop(&mut self) {
189        self.queue.push(match self.counted {
190            Some(bytes) => Release::Texture(self.id, bytes),
191            None => Release::Resource(self.id.into()),
192        });
193    }
194}
195
196/// A texture of the context's `Gpu` that draws share: a
197/// [`Texture2D`](crate::draw::texture2d::Texture2D)'s, which bindings made
198/// of it hold after the texture replaces it.
199pub(crate) type SharedGpuTexture = Rc<GpuTexture>;
200
201/// What the renderer makes its buffers and textures with: the rendering
202/// stats that count them, the queue that they go to when they drop, the
203/// epochs of its uniform buffer arrays, and what failed on the GPU in the
204/// frame being encoded.
205#[derive(Default)]
206pub(crate) struct Device {
207    pub(crate) stats: RenderingStats,
208    pub(crate) queue: Rc<ReleaseQueue>,
209    /// The last epoch a uniform buffer array took.
210    uniform_epoch: u64,
211    /// Why the first GPU failure since [`take_failure`](Self::take_failure)
212    /// failed.
213    failure: Option<String>,
214}
215
216impl Device {
217    /// Logs `message`, why something of the frame being encoded failed on
218    /// the GPU, and keeps it as the frame's failure unless one came first.
219    pub(crate) fn fail(&mut self, message: String) {
220        tracing::error!(target: log_target::RENDER, error = message, "A GPU operation of the frame failed");
221        self.failure.get_or_insert(message);
222    }
223
224    /// Whether something failed since the last [`take_failure`](Self::take_failure).
225    pub(crate) fn failed(&self) -> bool {
226        self.failure.is_some()
227    }
228
229    /// Why the first GPU failure since the last call failed, if one did.
230    pub(crate) fn take_failure(&mut self) -> Option<String> {
231        self.failure.take()
232    }
233
234    /// An epoch for a uniform buffer array that changed, one that no array
235    /// of the device has had, and never 0.
236    pub(crate) fn next_uniform_epoch(&mut self) -> u64 {
237        self.uniform_epoch += 1;
238        self.uniform_epoch
239    }
240
241    /// A buffer of `gpu` of `usage` holding `data`.
242    pub(crate) fn buffer(&mut self, gpu: &mut dyn Gpu, usage: BufferUsage, data: &[u8]) -> Result<Buffer, GpuError> {
243        let buffer = self.allocate(gpu, usage, data.len())?;
244        write_bytes(gpu, &buffer, data)?;
245        buffer::count_write(&mut self.stats, usage, data.len(), false);
246        Ok(buffer)
247    }
248
249    /// A buffer of `usage` holding the bytes of `data`, written from the JS
250    /// array they're in.
251    #[cfg(target_family = "wasm")]
252    pub(crate) fn buffer_from_host(
253        &mut self,
254        gpu: &mut dyn Gpu,
255        usage: BufferUsage,
256        data: &mln_wire::host_bytes::HostBytes,
257    ) -> Result<Buffer, GpuError> {
258        let buffer = self.allocate(gpu, usage, data.len())?;
259        if !data.is_empty()
260            && let Some(array) = data.array()
261        {
262            gpu.write_buffer_from_host(buffer.id(), 0, &array)?;
263        }
264        Ok(buffer)
265    }
266
267    /// A buffer of `usage` that writes of up to `size` bytes fit in, which
268    /// the stats count until the context destroys it.
269    fn allocate(&mut self, gpu: &mut dyn Gpu, usage: BufferUsage, size: usize) -> Result<Buffer, GpuError> {
270        let allocated = buffer::allocated_size(usage, size);
271        let id = gpu.create_buffer(&BufferDesc { label: buffer::label(usage), usage, size: allocated as u64 })?;
272        buffer::count(&mut self.stats, usage, allocated, 1);
273        self.stats.total_buffers += 1;
274        self.stats.total_buffer_objs += 1;
275        Ok(Buffer::new(id, usage, size, &self.queue))
276    }
277
278    /// Writes `data` at the start of `buffer`, and counts the write. Fails
279    /// if `data` is longer than the buffer.
280    pub(crate) fn write(&mut self, gpu: &mut dyn Gpu, buffer: &Buffer, data: &[u8]) -> Result<(), GpuError> {
281        write_bytes(gpu, buffer, data)?;
282        buffer::count_write(&mut self.stats, buffer.usage(), data.len(), true);
283        Ok(())
284    }
285
286    /// Writes `data` to the uniform or, with `storage`, storage buffer in
287    /// `slot`, first making one if the slot has none or `data` doesn't fit
288    /// in it. Returns whether it made one in place of one the slot had,
289    /// whose bindings its owner then drops.
290    pub(crate) fn write_uniforms(
291        &mut self,
292        gpu: &mut dyn Gpu,
293        slot: &mut Option<Buffer>,
294        data: &[u8],
295        storage: bool,
296    ) -> bool {
297        let usage = if storage { BufferUsage::Storage } else { BufferUsage::Uniform };
298        if let Some(buffer) = slot.as_ref().filter(|buffer| buffer.usage() == usage && buffer.size() >= data.len()) {
299            if let Err(error) = self.write(gpu, buffer, data) {
300                self.fail(format!("Writing a buffer failed: {error}"));
301            }
302            return false;
303        }
304        let replaced = slot.is_some();
305        *slot = match self.buffer(gpu, usage, data) {
306            Ok(buffer) => Some(buffer),
307            Err(error) => {
308                self.fail(format!("Making a buffer failed: {error}"));
309                None
310            }
311        };
312        replaced
313    }
314
315    /// A texture of `gpu` of `desc`, which the stats count with `counted`
316    /// bytes, or not at all with `None`, until the context destroys it.
317    pub(crate) fn texture(
318        &mut self,
319        gpu: &mut dyn Gpu,
320        desc: &TextureDesc<'_>,
321        counted: Option<usize>,
322    ) -> Result<GpuTexture, GpuError> {
323        let id = gpu.create_texture(desc)?;
324        if let Some(bytes) = counted {
325            self.stats.num_created_textures += 1;
326            self.stats.num_active_textures += 1;
327            self.stats.mem_textures += bytes as i32;
328        }
329        Ok(GpuTexture { id, counted, queue: Rc::clone(&self.queue) })
330    }
331
332    /// A texture of `size` and `format` that passes draw into and nothing
333    /// samples, such as a target's depth and stencil. The stats don't count
334    /// it.
335    pub(crate) fn attachment(
336        &mut self,
337        gpu: &mut dyn Gpu,
338        label: &str,
339        size: Size,
340        format: TextureFormat,
341    ) -> Result<GpuTexture, GpuError> {
342        let usage = TextureUsage { render_target: true, ..TextureUsage::default() };
343        self.texture(gpu, &TextureDesc { label, size, format, usage, mipmapped: false }, None)
344    }
345}
346
347/// The bytes a texture of `size` and `format` that passes draw into takes,
348/// as [`RenderingStats`] counts it: a depth and stencil format at 4 bytes a
349/// texel, or 8 with a 32-bit depth and a stencil, though a backend may
350/// store it in more.
351pub(crate) fn attachment_bytes(size: Size, format: TextureFormat) -> u64 {
352    let texel = match format {
353        TextureFormat::Depth32Float | TextureFormat::Depth24PlusStencil8 => 4,
354        TextureFormat::Depth32FloatStencil8 => 8,
355        format => u64::from(format.bytes_per_texel().unwrap_or(4)),
356    };
357    u64::from(size.width) * u64::from(size.height) * texel
358}
359
360/// Writes `data` at the start of `buffer` through `gpu`. Fails if `data` is
361/// longer than the buffer.
362fn write_bytes(gpu: &mut dyn Gpu, buffer: &Buffer, data: &[u8]) -> Result<(), GpuError> {
363    if data.len() > buffer.size() {
364        return Err(GpuError::Invalid(format!("a write of {} bytes to a buffer of {}", data.len(), buffer.size())));
365    }
366    if data.is_empty() {
367        return Ok(());
368    }
369    // `Gpu::write_buffer` takes whole 4-byte words.
370    if data.len().is_multiple_of(4) {
371        gpu.write_buffer(buffer.id(), 0, data)
372    } else {
373        let mut padded = data.to_vec();
374        padded.resize(data.len().next_multiple_of(4), 0);
375        gpu.write_buffer(buffer.id(), 0, &padded)
376    }
377}
378
379/// What the tests of a crate of layer types read of the resources: not
380/// API.
381#[doc(hidden)]
382impl Resources<'_> {
383    /// Runs `f` with resources over `gpu`, at a pixel ratio of 1, which it
384    /// then tears down.
385    pub fn with_test_resources<R>(gpu: &mut dyn Gpu, f: impl FnOnce(&mut Resources<'_>) -> R) -> R {
386        let mut context = Context::new(*gpu.caps(), 1.0);
387        let result = f(&mut Resources::new(gpu, &mut context));
388        context.tear_down(gpu);
389        result
390    }
391
392    /// The bytes of `vertices` that the next upload writes, empty once the
393    /// upload wrote and freed them.
394    #[must_use]
395    pub fn test_vertex_bytes(&self, vertices: &VertexBuffer) -> Option<&[u8]> {
396        self.context.vertices(vertices).map(crate::draw::vertices::Vertices::bytes)
397    }
398
399    /// Whether the next upload writes `vertices`.
400    #[must_use]
401    pub fn test_vertices_need_upload(&self, vertices: &VertexBuffer) -> bool {
402        self.context.vertices(vertices).is_some_and(crate::draw::vertices::Vertices::needs_upload)
403    }
404
405    /// The buffer of `vertices`, which this uploads.
406    pub fn test_upload_vertices(&mut self, vertices: &VertexBuffer) -> Option<mln_gfx::gpu::BufferId> {
407        self.context.upload_vertices(self.gpu, vertices).ok().flatten()
408    }
409
410    /// The buffer of `indexes`, which this uploads, and whether their data
411    /// stays after, with their count.
412    pub fn test_upload_indexes(&mut self, indexes: &IndexBuffer) -> (Option<mln_gfx::gpu::BufferId>, bool, usize) {
413        let mut draw = crate::draw::indexes::DrawIndexes::Shared(indexes.clone());
414        let uploaded = draw.upload(self.gpu, self.context).ok().and_then(|()| draw.buffer(self.context));
415        (uploaded, draw.has_data(self.context), draw.len(self.context))
416    }
417
418    /// Uploads `mesh`, as a frame that draws it does.
419    pub fn test_upload_mesh(&mut self, mesh: &Mesh) {
420        mesh.upload(self.gpu, self.context);
421    }
422
423    /// The buffer `mesh` binds as its storage buffer `id`, as of its last
424    /// upload.
425    #[must_use]
426    pub fn test_storage_buffer(&self, mesh: &Mesh, id: usize) -> Option<mln_gfx::gpu::BufferId> {
427        mesh.storage_buffer(self.context, id)
428    }
429
430    /// The rendering stats so far.
431    #[must_use]
432    pub fn test_rendering_stats(&mut self) -> RenderingStats {
433        self.context.rendering_stats().clone()
434    }
435}