use std::path::Path;
use super::lut_cube_loader::lut_texture;
use super::texture_loader::decode_image;
use crate::error::Error;
use crate::textures::Data3DTexture;
const LOADER: &str = "LUTImageLoader";
#[derive(Debug, Clone)]
pub struct LutImage {
pub size: u32,
pub texture_3d: Data3DTexture,
}
#[derive(Debug, Clone, Default)]
pub struct LutImageLoader {
pub flip: bool,
}
impl LutImageLoader {
pub fn new() -> Self {
Self::default()
}
pub fn load<P: AsRef<Path>>(&self, path: P) -> Result<LutImage, Error> {
let path = path.as_ref();
let bytes = crate::io::read(path)?;
let image = decode_image(path, &bytes)?;
let mut data = if image.width < image.height {
self.image_data(image.width, image.height, &image.data)
} else {
self.horz_to_vert(image.width, image.height, &image.data)
};
let size = image.width.min(image.height);
let expected = (size as usize).pow(3) * 4;
if data.len() < expected {
return Err(Error::Lut {
loader: LOADER,
reason: format!(
"a {}x{} image holds fewer than {size} slices of {size}x{size}",
image.width, image.height
),
});
}
data.truncate(expected);
Ok(self.parse(data, size))
}
pub fn parse(&self, data: Vec<u8>, size: u32) -> LutImage {
LutImage {
size,
texture_3d: lut_texture(data, size, wgpu::TextureFormat::Rgba8Unorm),
}
}
fn image_data(&self, width: u32, height: u32, pixels: &[u8]) -> Vec<u8> {
let row = width as usize * 4;
if !self.flip {
return pixels.to_vec();
}
let mut out = vec![0u8; pixels.len()];
for y in 0..height as usize {
let flipped = height as usize - 1 - y;
out[flipped * row..][..row].copy_from_slice(&pixels[y * row..][..row]);
}
out
}
fn horz_to_vert(&self, image_width: u32, image_height: u32, pixels: &[u8]) -> Vec<u8> {
let size = image_height as usize;
let (canvas_width, canvas_height) = (size, image_width as usize);
let mut out = vec![0u8; canvas_width * canvas_height * 4];
for i in 0..size {
for r in 0..size {
let dest = if self.flip {
match (i * size).checked_sub(r + 1) {
Some(row) => row,
None => continue,
}
} else {
i * size + r
};
if dest >= canvas_height {
continue;
}
for x in 0..size {
let sx = i * size + x;
if sx >= image_width as usize {
break;
}
let from = (r * image_width as usize + sx) * 4;
let to = (dest * canvas_width + x) * 4;
out[to..to + 4].copy_from_slice(&pixels[from..from + 4]);
}
}
}
out
}
}