Skip to main content

mln_engine/draw/
texture2d.rs

1//! The renderer's textures. Each is a [`Texture2D`] in the context's store,
2//! which its owner and the draws that bind it hold as a
3//! [`SharedTexture`](crate::draw::store::SharedTexture).
4
5use std::rc::Rc;
6
7use mln_gfx::Size;
8use mln_gfx::gpu::{Gpu, GpuError, SamplerId, TextureDesc, TextureFormat, TextureId, TextureRegion, TextureUsage};
9use mln_gfx::rendering_stats::RenderingStats;
10use mln_gfx::texture2d::SamplerState;
11use mln_style::bitmap::PremultipliedImage;
12
13use crate::draw::resources::{Device, SharedGpuTexture};
14use crate::draw::texture_size;
15
16/// A texture of the renderer: its size, format and sampler state, the image
17/// it waits to upload, and once made, a texture of the backend's
18/// [`Gpu`](mln_gfx::gpu::Gpu), which the texture lets go of when it
19/// replaces it or drops, and which bindings made of it hold until they go. The context changes it, and lends it to set up as a
20/// `TextureMut`.
21pub struct Texture2D {
22    texture: Option<SharedGpuTexture>,
23    size: Size,
24    format: TextureFormat,
25    render_target: bool,
26    /// Whether it is made with a full chain of mip levels.
27    mipmapped: bool,
28    sampler: SamplerState,
29    /// The context's sampler of `sampler`, once a draw bound it.
30    sampler_id: Option<SamplerId>,
31    /// The image the next upload writes.
32    image: Option<Rc<PremultipliedImage>>,
33}
34
35impl Texture2D {
36    /// An RGBA texture without a size.
37    pub(crate) fn new() -> Texture2D {
38        Texture2D {
39            texture: None,
40            size: Size::new(0, 0),
41            format: TextureFormat::Rgba8Unorm,
42            render_target: false,
43            mipmapped: false,
44            sampler: SamplerState::default(),
45            sampler_id: None,
46            image: None,
47        }
48    }
49
50    /// The texture's size, in texels.
51    #[must_use]
52    pub fn size(&self) -> Size {
53        self.size
54    }
55
56    /// Sets the size the texture is made with. A texture made with another
57    /// size goes.
58    fn set_size(&mut self, size: Size) {
59        if size != self.size {
60            self.release();
61            self.size = size;
62        }
63    }
64
65    #[must_use]
66    pub(crate) fn format(&self) -> TextureFormat {
67        self.format
68    }
69
70    /// Sets the format the texture is made with. A texture made with
71    /// another format goes.
72    fn set_format(&mut self, format: TextureFormat) {
73        if format != self.format {
74            self.release();
75            self.format = format;
76        }
77    }
78
79    /// How shaders sample the texture.
80    #[must_use]
81    pub(crate) fn sampler(&self) -> SamplerState {
82        self.sampler
83    }
84
85    /// The context's sampler of the texture's sampler state, once a draw
86    /// bound it.
87    pub(crate) fn sampler_id(&self) -> Option<SamplerId> {
88        self.sampler_id
89    }
90
91    pub(crate) fn set_sampler_id(&mut self, sampler: SamplerId) {
92        self.sampler_id = Some(sampler);
93    }
94
95    /// Whether the texture has an image to upload.
96    pub(crate) fn has_image(&self) -> bool {
97        self.image.is_some()
98    }
99
100    /// The backend's texture, once made, which bindings made of it hold.
101    pub(crate) fn gpu_texture(&self) -> Option<&SharedGpuTexture> {
102        self.texture.as_ref()
103    }
104
105    /// Makes the backend's texture of the size and format set through `gpu`
106    /// and `device`, unless it is made. Fails for an empty size.
107    pub(crate) fn create(&mut self, gpu: &mut dyn Gpu, device: &mut Device) -> Result<TextureId, GpuError> {
108        if let Some(texture) = &self.texture {
109            return Ok(texture.id());
110        }
111        let desc = TextureDesc {
112            label: if self.render_target { "render target" } else { "texture" },
113            size: self.size,
114            format: self.format,
115            usage: TextureUsage { sampled: true, render_target: self.render_target, copy_src: self.render_target },
116            mipmapped: self.mipmapped,
117        };
118        let texture = device.texture(gpu, &desc, Some(self.bytes()))?;
119        let id = texture.id();
120        self.texture = Some(Rc::new(texture));
121        Ok(id)
122    }
123
124    /// Writes `data`, the texels of a texture of `size` in rows from the top,
125    /// to the whole texture, first making it of that size. Empty `data`
126    /// leaves the texels unspecified, and an empty size makes no texture.
127    pub(crate) fn upload_data(
128        &mut self,
129        gpu: &mut dyn Gpu,
130        device: &mut Device,
131        data: &[u8],
132        size: Size,
133    ) -> Result<(), GpuError> {
134        self.set_size(size);
135        if size.is_empty() {
136            return Ok(());
137        }
138        let texture = self.create(gpu, device)?;
139        if data.is_empty() {
140            return Ok(());
141        }
142        write(gpu, &mut device.stats, texture, data, TextureRegion { x: 0, y: 0, size })
143    }
144
145    /// Writes `data`, the texels of a region of `size` in rows from the top,
146    /// at `x`, `y` of the texture, first making it.
147    pub(crate) fn upload_sub_region(
148        &mut self,
149        gpu: &mut dyn Gpu,
150        device: &mut Device,
151        data: &[u8],
152        size: Size,
153        x: u16,
154        y: u16,
155    ) -> Result<(), GpuError> {
156        let texture = self.create(gpu, device)?;
157        let region = TextureRegion { x: u32::from(x), y: u32::from(y), size };
158        write(gpu, &mut device.stats, texture, data, region)
159    }
160
161    /// Writes the image [`TextureMut::set_image`] set, if any.
162    pub(crate) fn upload(&mut self, gpu: &mut dyn Gpu, device: &mut Device) -> Result<(), GpuError> {
163        match self.image.take() {
164            Some(image) if image.valid() => self.upload_data(gpu, device, &image.data, texture_size(image.size)),
165            _ => Ok(()),
166        }
167    }
168
169    /// The texture a draw binds, made through `gpu` and holding its image.
170    pub(crate) fn bind(&mut self, gpu: &mut dyn Gpu, device: &mut Device) -> Result<TextureId, GpuError> {
171        self.upload(gpu, device)?;
172        self.create(gpu, device)
173    }
174
175    /// The bytes the texture takes, its mip levels' included.
176    pub(crate) fn bytes(&self) -> usize {
177        let texel = self.format.bytes_per_texel().unwrap_or(4) as usize;
178        let bytes = self.size.width as usize * self.size.height as usize * texel;
179        // The levels below the first add up to a third of it.
180        if self.mipmapped { bytes + bytes / 3 } else { bytes }
181    }
182
183    /// Lets go of the backend's texture, which goes once the bindings made
184    /// of it do.
185    fn release(&mut self) {
186        self.texture = None;
187    }
188}
189
190/// A texture of the context's store, to set up: changes that replace its
191/// backend's texture let go of that.
192pub struct TextureMut<'a> {
193    texture: &'a mut Texture2D,
194}
195
196impl<'a> TextureMut<'a> {
197    pub(crate) fn new(texture: &'a mut Texture2D) -> TextureMut<'a> {
198        TextureMut { texture }
199    }
200
201    /// Sets the size the texture is made with. A texture made with another
202    /// size goes.
203    pub(crate) fn set_size(&mut self, size: Size) {
204        self.texture.set_size(size);
205    }
206
207    /// Sets the format the texture is made with. A texture made with
208    /// another format goes.
209    pub fn set_format(&mut self, format: TextureFormat) {
210        self.texture.set_format(format);
211    }
212
213    /// Makes the texture one that passes draw into, as well as one that
214    /// shaders sample.
215    pub(crate) fn set_render_target(&mut self) {
216        self.texture.render_target = true;
217    }
218
219    /// Makes the texture with a full chain of mip levels, or with one. A
220    /// texture made otherwise goes.
221    pub(crate) fn set_mipmapped(&mut self, mipmapped: bool) {
222        if mipmapped != self.texture.mipmapped {
223            self.texture.release();
224            self.texture.mipmapped = mipmapped;
225        }
226    }
227
228    /// Sets how shaders sample the texture, with an anisotropy of at least 1.
229    pub fn set_sampler(&mut self, sampler: SamplerState) {
230        let texture = &mut *self.texture;
231        let sampler = SamplerState { max_anisotropy: sampler.max_anisotropy.max(1), ..sampler };
232        if sampler != texture.sampler {
233            texture.sampler = sampler;
234            texture.sampler_id = None;
235        }
236    }
237
238    /// Sets the RGBA image the next upload writes, and the texture's size to
239    /// the image's.
240    pub fn set_image(&mut self, image: Option<Rc<PremultipliedImage>>) {
241        if let Some(image) = &image {
242            self.set_size(texture_size(image.size));
243            self.set_format(TextureFormat::Rgba8Unorm);
244        }
245        self.texture.image = image;
246    }
247}
248
249/// Writes `data` to `region` of `texture` through `gpu`, and counts the
250/// write in `stats`.
251fn write(
252    gpu: &mut dyn Gpu,
253    stats: &mut RenderingStats,
254    texture: TextureId,
255    data: &[u8],
256    region: TextureRegion,
257) -> Result<(), GpuError> {
258    gpu.write_texture(texture, region, data)?;
259    stats.num_texture_updates += 1;
260    stats.texture_update_bytes += data.len();
261    Ok(())
262}