Skip to main content

nadir_render/
texture.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The texture asset: a QOI file, uploaded to the GPU.
16
17use nadir_assets::{Asset, AssetError, DecodeCtx, FinalizeCtx};
18use nadir_codec::qoi::{self, ColorSpace, Image};
19use nadir_core::UVec2;
20use nadir_gfx::{Device, TextureDesc, TextureFormat, TextureId};
21
22/// A texture on the GPU, loaded from a QOI file through `nadir-assets`.
23///
24/// It is made by [`Asset::finalize`], which needs the [`Device`] in the
25/// [`FinalizeCtx`]. A QOI file marked sRGB becomes an
26/// [`TextureFormat::Rgba8Srgb`] texture, and one marked linear an
27/// [`TextureFormat::Rgba8`]. Once its scopes are unloaded,
28/// [`Asset::release`] destroys it on the device, which then refuses its id.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub struct Texture {
31    id: TextureId,
32    size: UVec2,
33    format: TextureFormat,
34}
35
36impl Texture {
37    /// The texture on the device.
38    pub fn id(&self) -> TextureId {
39        self.id
40    }
41
42    /// Its size in pixels.
43    pub fn size(&self) -> UVec2 {
44        self.size
45    }
46
47    /// How its pixels are stored.
48    pub fn format(&self) -> TextureFormat {
49        self.format
50    }
51}
52
53/// A texture decoded from its file, waiting to go to the GPU.
54#[derive(Debug)]
55pub struct DecodedTexture {
56    label: String,
57    image: Image,
58}
59
60/// The placeholder's width and height: an 8×8 checker of single texels,
61/// magenta and black, starting with magenta in the top-left corner.
62const PLACEHOLDER_SIZE: u32 = 8;
63const MAGENTA: [u8; 4] = [255, 0, 255, 255];
64const BLACK: [u8; 4] = [0, 0, 0, 255];
65
66/// The placeholder's pixels, from the top row.
67fn checker() -> Vec<u8> {
68    (0..PLACEHOLDER_SIZE * PLACEHOLDER_SIZE)
69        .flat_map(|i| {
70            let (x, y) = (i % PLACEHOLDER_SIZE, i / PLACEHOLDER_SIZE);
71            if (x + y) % 2 == 0 { MAGENTA } else { BLACK }
72        })
73        .collect()
74}
75
76impl Asset for Texture {
77    type Decoded = DecodedTexture;
78    const EXTENSIONS: &'static [&'static str] = &["qoi"];
79
80    fn decode(bytes: &[u8], ctx: &DecodeCtx<'_>) -> Result<DecodedTexture, AssetError> {
81        let image = qoi::decode(bytes, ctx.limits()).map_err(AssetError::Decode)?;
82        Ok(DecodedTexture {
83            label: ctx.path().to_string(),
84            image,
85        })
86    }
87
88    fn finalize(decoded: DecodedTexture, ctx: &mut FinalizeCtx<'_>) -> Result<Self, AssetError> {
89        let header = &decoded.image.header;
90        let format = match header.color_space {
91            ColorSpace::Srgb => TextureFormat::Rgba8Srgb,
92            ColorSpace::Linear => TextureFormat::Rgba8,
93        };
94        let size = UVec2::new(header.width, header.height);
95        upload(
96            ctx.get_mut::<Device>()?,
97            &decoded.label,
98            size,
99            format,
100            &decoded.image.pixels,
101        )
102    }
103
104    /// An 8×8 checker of magenta and black texels.
105    fn placeholder(ctx: &mut FinalizeCtx<'_>) -> Result<Self, AssetError> {
106        let size = UVec2::new(PLACEHOLDER_SIZE, PLACEHOLDER_SIZE);
107        upload(
108            ctx.get_mut::<Device>()?,
109            "placeholder",
110            size,
111            TextureFormat::Rgba8Srgb,
112            &checker(),
113        )
114    }
115
116    /// Destroys the texture on the [`Device`] in the context.
117    fn release(self, ctx: &mut FinalizeCtx<'_>) -> Result<(), AssetError> {
118        ctx.get_mut::<Device>()?.destroy(self.id);
119        Ok(())
120    }
121}
122
123fn upload(
124    device: &mut Device,
125    label: &str,
126    size: UVec2,
127    format: TextureFormat,
128    pixels: &[u8],
129) -> Result<Texture, AssetError> {
130    let id = device
131        .create_texture(
132            &TextureDesc {
133                label,
134                size,
135                format,
136            },
137            Some(pixels),
138        )
139        .map_err(|error| AssetError::Invalid(error.to_string()))?;
140    Ok(Texture { id, size, format })
141}
142
143#[cfg(test)]
144mod tests {
145    use nadir_codec::Limits;
146    use nadir_codec::qoi::{Channels, Header};
147
148    use super::*;
149
150    fn decode(bytes: &[u8]) -> Result<DecodedTexture, AssetError> {
151        Texture::decode(
152            bytes,
153            &DecodeCtx::new("sprites/hero.qoi", Limits::default()),
154        )
155    }
156
157    #[test]
158    fn a_qoi_file_decodes_with_its_path_as_label() {
159        let header = Header {
160            width: 2,
161            height: 1,
162            channels: Channels::Rgba,
163            color_space: ColorSpace::Linear,
164        };
165        let pixels = [1, 2, 3, 4, 5, 6, 7, 8];
166        let bytes = qoi::encode(&header, &pixels).expect("an image");
167        let decoded = decode(&bytes).expect("a texture");
168        assert_eq!(decoded.label, "sprites/hero.qoi");
169        assert_eq!(decoded.image.header, header);
170        assert_eq!(decoded.image.pixels, pixels);
171    }
172
173    #[test]
174    fn a_file_that_is_not_qoi_fails_to_decode() {
175        assert!(matches!(decode(b"PNG"), Err(AssetError::Decode(_))));
176    }
177
178    #[test]
179    fn the_placeholder_is_a_magenta_and_black_checker() {
180        let pixels = checker();
181        let texels: Vec<[u8; 4]> = pixels.as_chunks::<4>().0.to_vec();
182        assert_eq!(texels.len(), 64);
183        assert_eq!(texels[0], MAGENTA);
184        assert_eq!(texels[1], BLACK);
185        assert_eq!(texels[8], BLACK, "the second row starts black");
186        assert_eq!(texels[9], MAGENTA);
187        assert_eq!(texels.iter().filter(|&&texel| texel == MAGENTA).count(), 32);
188    }
189}