1use std::path::Path;
16
17use crate::error::Error;
18use crate::textures::Texture;
19
20pub struct TextureLoader;
22
23impl Default for TextureLoader {
24 fn default() -> Self {
25 Self::new()
26 }
27}
28
29impl TextureLoader {
30 pub fn new() -> Self {
32 Self
33 }
34
35 pub fn load<P: AsRef<Path>>(&self, url: P) -> Result<Texture, Error> {
42 let path = url.as_ref();
43 let bytes = crate::io::read(path)?;
44 let image = decode_image(path, &bytes)?;
47 Ok(Texture::new(image.width, image.height, Some(image.data)))
48 }
49
50 pub fn from_bytes(&self, bytes: &[u8], mime_type: Option<&str>) -> Result<Texture, Error> {
60 let path = Path::new("<glTF image>");
61 let image = match mime_type {
62 Some("image/png") => decode_png(path, bytes)?,
63 Some("image/jpeg") => decode_jpeg_bytes(path, bytes)?,
64 Some("image/webp") => decode_webp(path, bytes)?,
65 _ => decode_image(path, bytes)?,
66 };
67
68 Ok(Texture::new(image.width, image.height, Some(image.data)))
69 }
70}
71
72pub(crate) fn decode_image(path: &Path, bytes: &[u8]) -> Result<crate::textures::Image, Error> {
81 if bytes.starts_with(b"GIF") {
82 super::gif::decode(path, bytes)
83 } else if bytes.starts_with(&[0x89, b'P', b'N', b'G']) {
84 decode_png(path, bytes)
85 } else if is_webp(bytes) {
86 decode_webp(path, bytes)
87 } else if is_avif(bytes) {
88 Err(Error::image(
89 path,
90 "AVIF is not decoded: no pure-Rust AV1 decoder is fit yet (issue #179)",
91 ))
92 } else {
93 decode_jpeg_bytes(path, bytes)
94 }
95}
96
97pub(crate) fn decode_png(path: &Path, bytes: &[u8]) -> Result<crate::textures::Image, Error> {
102 let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
103 decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
106
107 let mut reader = decoder
108 .read_info()
109 .map_err(|e| Error::image(path, e.to_string()))?;
110 let size = reader
112 .output_buffer_size()
113 .ok_or_else(|| Error::image(path, "PNG dimensions overflow".to_string()))?;
114 let mut buffer = vec![0; size];
115 let info = reader
116 .next_frame(&mut buffer)
117 .map_err(|e| Error::image(path, e.to_string()))?;
118 buffer.truncate(info.buffer_size());
119
120 let pixels = (info.width as usize) * (info.height as usize);
121 let data = match info.color_type {
122 png::ColorType::Rgba => buffer,
123 png::ColorType::Rgb => {
124 let mut out = Vec::with_capacity(pixels * 4);
125 for pixel in buffer.as_chunks::<3>().0 {
126 out.extend_from_slice(pixel);
127 out.push(255);
128 }
129 out
130 }
131 png::ColorType::Grayscale => {
132 let mut out = Vec::with_capacity(pixels * 4);
133 for &value in &buffer {
134 out.extend_from_slice(&[value, value, value, 255]);
135 }
136 out
137 }
138 png::ColorType::GrayscaleAlpha => {
139 let mut out = Vec::with_capacity(pixels * 4);
140 for pixel in buffer.as_chunks::<2>().0 {
141 out.extend_from_slice(&[pixel[0], pixel[0], pixel[0], pixel[1]]);
142 }
143 out
144 }
145 png::ColorType::Indexed => {
146 return Err(Error::image(path, "the PNG palette was not expanded"));
147 }
148 };
149
150 Ok(crate::textures::Image {
151 width: info.width,
152 height: info.height,
153 data,
154 })
155}
156
157pub(crate) fn decode_jpeg_bytes(
164 path: &Path,
165 bytes: &[u8],
166) -> Result<crate::textures::Image, Error> {
167 let options = zune_jpeg::zune_core::options::DecoderOptions::default()
168 .jpeg_set_out_colorspace(zune_jpeg::zune_core::colorspace::ColorSpace::RGBA);
169
170 let mut decoder =
171 zune_jpeg::JpegDecoder::new_with_options(std::io::Cursor::new(bytes), options);
172
173 let data = decoder
174 .decode()
175 .map_err(|e| Error::image(path, e.to_string()))?;
176 let (width, height) = decoder
177 .dimensions()
178 .ok_or_else(|| Error::image(path, "the JPEG has no dimensions"))?;
179
180 Ok(crate::textures::Image {
181 width: width as u32,
182 height: height as u32,
183 data,
184 })
185}
186
187fn is_webp(bytes: &[u8]) -> bool {
190 bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP"
191}
192
193fn is_avif(bytes: &[u8]) -> bool {
195 bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && matches!(&bytes[8..12], b"avif" | b"avis")
196}
197
198pub(crate) fn decode_webp(path: &Path, bytes: &[u8]) -> Result<crate::textures::Image, Error> {
208 let mut decoder = image_webp::WebPDecoder::new(std::io::Cursor::new(bytes))
209 .map_err(|e| Error::image(path, e.to_string()))?;
210 let (width, height) = decoder.dimensions();
211 let size = decoder
212 .output_buffer_size()
213 .ok_or_else(|| Error::image(path, "the WebP is too large to decode"))?;
214 let mut buffer = vec![0; size];
215 decoder
216 .read_image(&mut buffer)
217 .map_err(|e| Error::image(path, e.to_string()))?;
218
219 let data = if decoder.has_alpha() {
221 buffer
222 } else {
223 let mut out = Vec::with_capacity(buffer.len() / 3 * 4);
224 for pixel in buffer.as_chunks::<3>().0 {
225 out.extend_from_slice(pixel);
226 out.push(255);
227 }
228 out
229 };
230
231 Ok(crate::textures::Image {
232 width,
233 height,
234 data,
235 })
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241
242 const RED_LOSSLESS: [u8; 36] = [
244 0x52, 0x49, 0x46, 0x46, 0x1c, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38,
245 0x4c, 0x0f, 0x00, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x00, 0x00, 0x07, 0x10, 0xfd, 0x8f, 0xfe,
246 0x07, 0x22, 0xa2, 0xff, 0x01, 0x00,
247 ];
248
249 #[test]
250 fn webp_is_sniffed_and_decoded() {
251 assert!(is_webp(&RED_LOSSLESS));
252 for texture in [
253 TextureLoader::new().from_bytes(&RED_LOSSLESS, Some("image/webp")),
254 TextureLoader::new().from_bytes(&RED_LOSSLESS, None),
255 ] {
256 let texture = texture.unwrap();
257 assert_eq!(texture.size(), (1, 1));
258 assert_eq!(
259 texture.borrow().data.as_deref(),
260 Some(&[255, 0, 0, 255][..])
261 );
262 }
263 }
264
265 #[test]
266 fn avif_is_refused_by_name() {
267 let header = b"\0\0\0\x1cftypavif\0\0\0\0avifmif1miaf";
268 assert!(is_avif(header));
269 let error = TextureLoader::new()
270 .from_bytes(header, Some("image/avif"))
271 .err()
272 .unwrap()
273 .to_string();
274 assert!(error.contains("AVIF"), "{error}");
275 }
276}