use super::texture::{Texture, TextureFormat};
use std::sync::Arc;
const MAGIC: &[u8; 8] = b"THREERSX";
const VERSION: u32 = 1;
fn format_code(f: TextureFormat) -> Option<u32> {
Some(match f {
TextureFormat::Bc1RgbaUnormSrgb => 1,
TextureFormat::Bc7RgbaUnormSrgb => 2,
TextureFormat::Rgba8UnormSrgb => 3,
TextureFormat::Rgba8Unorm => 4,
TextureFormat::R8Unorm => 5,
TextureFormat::Rgba16Float => return None,
})
}
fn format_from(code: u32) -> Option<TextureFormat> {
Some(match code {
1 => TextureFormat::Bc1RgbaUnormSrgb,
2 => TextureFormat::Bc7RgbaUnormSrgb,
3 => TextureFormat::Rgba8UnormSrgb,
4 => TextureFormat::Rgba8Unorm,
5 => TextureFormat::R8Unorm,
_ => return None,
})
}
pub fn save(
path: impl AsRef<std::path::Path>,
width: u32,
height: u32,
format: TextureFormat,
level0: &[u8],
mips: &[Vec<u8>],
) -> Result<(), String> {
let code = format_code(format).ok_or_else(|| format!("{format:?} has no blob encoding"))?;
let want = format.data_len(width, height);
if level0.len() != want {
return Err(format!(
"level 0 is {} bytes, expected {want} for {width}x{height} {format:?}",
level0.len()
));
}
let mut out =
Vec::with_capacity(level0.len() + mips.iter().map(|m| m.len()).sum::<usize>() + 32);
out.extend_from_slice(MAGIC);
out.extend_from_slice(&VERSION.to_le_bytes());
out.extend_from_slice(&width.to_le_bytes());
out.extend_from_slice(&height.to_le_bytes());
out.extend_from_slice(&code.to_le_bytes());
out.extend_from_slice(&(mips.len() as u32 + 1).to_le_bytes());
out.extend_from_slice(level0);
let (mut w, mut h) = (width, height);
for (i, m) in mips.iter().enumerate() {
w = (w / 2).max(1);
h = (h / 2).max(1);
let want = format.data_len(w, h);
if m.len() != want {
return Err(format!(
"mip {} is {} bytes, expected {want} for {w}x{h}",
i + 1,
m.len()
));
}
out.extend_from_slice(m);
}
std::fs::write(path.as_ref(), out).map_err(|e| format!("{}: {e}", path.as_ref().display()))
}
pub fn load(path: impl AsRef<std::path::Path>) -> Result<Texture, String> {
let p = path.as_ref();
let bytes = std::fs::read(p).map_err(|e| format!("{}: {e}", p.display()))?;
if bytes.len() < 28 || &bytes[..8] != MAGIC {
return Err(format!("{}: not a threers texture blob", p.display()));
}
let u32_at =
|o: usize| u32::from_le_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]]);
let version = u32_at(8);
if version != VERSION {
return Err(format!(
"{}: version {version}, expected {VERSION}",
p.display()
));
}
let (width, height) = (u32_at(12), u32_at(16));
let format = format_from(u32_at(20))
.ok_or_else(|| format!("{}: unknown format code {}", p.display(), u32_at(20)))?;
let levels = u32_at(24) as usize;
let mut off = 28;
let (mut w, mut h) = (width.max(1), height.max(1));
let mut chain: Vec<Arc<Vec<u8>>> = Vec::new();
let mut level0 = Vec::new();
for i in 0..levels {
if i > 0 {
w = (w / 2).max(1);
h = (h / 2).max(1);
}
let n = format.data_len(w, h);
if off + n > bytes.len() {
return Err(format!(
"{}: truncated at level {i} — wanted {n} bytes for {w}x{h}, {} left",
p.display(),
bytes.len() - off
));
}
let data = bytes[off..off + n].to_vec();
off += n;
if i == 0 {
level0 = data;
} else {
chain.push(Arc::new(data));
}
}
let mut t = Texture::new(width, height, format, level0);
t.flip_y = false;
t.mips = chain;
Ok(t)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::textures::bc1;
fn tmp(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!("threers_blob_{name}"))
}
#[test]
fn round_trips_a_chain() {
let (w, h) = (64u32, 40u32);
let px: Vec<u8> = (0..w * h)
.flat_map(|i| [(i % 251) as u8, (i % 199) as u8, (i % 97) as u8, 255])
.collect();
let (l0, mips) = bc1::encode_with_mips(&px, w, h);
let path = tmp("roundtrip.tex");
save(&path, w, h, TextureFormat::Bc1RgbaUnormSrgb, &l0, &mips).unwrap();
let t = load(&path).unwrap();
assert_eq!((t.width, t.height), (w, h));
assert_eq!(t.format, TextureFormat::Bc1RgbaUnormSrgb);
assert_eq!(*t.data, l0);
assert_eq!(t.mips.len(), mips.len());
for (a, b) in t.mips.iter().zip(&mips) {
assert_eq!(&**a.as_ref(), b.as_slice());
}
assert!(!t.flip_y);
std::fs::remove_file(&path).ok();
}
#[test]
fn rejects_what_it_cannot_trust() {
let path = tmp("bad.tex");
std::fs::write(&path, b"not a texture at all").unwrap();
assert!(load(&path)
.unwrap_err()
.contains("not a threers texture blob"));
let (w, h) = (32u32, 32u32);
let px = vec![128u8; (w * h * 4) as usize];
let (l0, mips) = bc1::encode_with_mips(&px, w, h);
save(&path, w, h, TextureFormat::Bc1RgbaUnormSrgb, &l0, &mips).unwrap();
let mut bytes = std::fs::read(&path).unwrap();
bytes.truncate(bytes.len() - 8);
std::fs::write(&path, &bytes).unwrap();
assert!(load(&path).unwrap_err().contains("truncated"));
let err = save(
&path,
w,
h,
TextureFormat::Bc1RgbaUnormSrgb,
&l0[..l0.len() - 8],
&mips,
)
.unwrap_err();
assert!(err.contains("level 0"), "{err}");
std::fs::remove_file(&path).ok();
}
}