1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub struct Texture {
31 id: TextureId,
32 size: UVec2,
33 format: TextureFormat,
34}
35
36impl Texture {
37 pub fn id(&self) -> TextureId {
39 self.id
40 }
41
42 pub fn size(&self) -> UVec2 {
44 self.size
45 }
46
47 pub fn format(&self) -> TextureFormat {
49 self.format
50 }
51}
52
53#[derive(Debug)]
55pub struct DecodedTexture {
56 label: String,
57 image: Image,
58}
59
60const PLACEHOLDER_SIZE: u32 = 8;
63const MAGENTA: [u8; 4] = [255, 0, 255, 255];
64const BLACK: [u8; 4] = [0, 0, 0, 255];
65
66fn 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 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 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}