#![allow(
clippy::many_single_char_names,
clippy::similar_names,
clippy::float_cmp
)]
use std::sync::Arc;
use unityrs_core::limits::{Charge, Meter, MeteredVec};
use super::SpriteError;
use super::exact::Int;
use crate::MAX_PIXELS;
use crate::decode::{Image, MAX_CROP_PIXELS};
use crate::format::Mode;
#[derive(Debug)]
pub struct Sheet<'a> {
image: SheetImage<'a>,
}
#[derive(Debug)]
enum SheetImage<'a> {
Texture(&'a Image),
Merged(Image),
}
const _: () = crate::send_sync::<Sheet<'static>>();
impl<'a> Sheet<'a> {
pub fn new(
texture: &'a Image,
alpha: Option<&Image>,
meter: &Arc<Meter>,
) -> Result<Self, SpriteError> {
match alpha {
None => {
verified(texture.mode())?;
Ok(Self {
image: SheetImage::Texture(texture),
})
}
Some(alpha) => Sheet::merged(texture, alpha, meter),
}
}
pub fn merged(
texture: &Image,
alpha: &Image,
meter: &Arc<Meter>,
) -> Result<Sheet<'static>, SpriteError> {
if texture.mode() == Mode::L {
return Err(SpriteError::AlphaBandCount);
}
if texture.width() != alpha.width() || texture.height() != alpha.height() {
return Err(SpriteError::AlphaSizeMismatch);
}
verified(alpha.mode())?;
let mut merged = Canvas::new(Mode::Rgba, texture.width(), texture.height(), meter)?;
let tb = bpp(texture.mode());
let ab = bpp(alpha.mode());
let (tp, ap) = (texture.pixels(), alpha.pixels());
super::contained(|| {
for (i, out) in merged.pixels.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let t = tp.get(i * tb..i * tb + 3).unwrap_or(&[0; 3]);
out.get_mut(..3).unwrap_or_default().copy_from_slice(t);
if let (Some(o), Some(a)) = (out.get_mut(3), ap.get(i * ab)) {
*o = *a;
}
}
})?;
Ok(Sheet {
image: SheetImage::Merged(merged.into_image()),
})
}
fn image(&self) -> &Image {
match &self.image {
SheetImage::Texture(i) => i,
SheetImage::Merged(i) => i,
}
}
#[must_use]
pub fn mode(&self) -> Mode {
self.image().mode()
}
#[must_use]
pub fn width(&self) -> u32 {
self.image().width()
}
#[must_use]
pub fn height(&self) -> u32 {
self.image().height()
}
pub(crate) fn pixel(&self, x: i64, y: i64) -> Option<&[u8]> {
let image = self.image();
let (w, h) = (i64::from(image.width()), i64::from(image.height()));
if x < 0 || y < 0 || x >= w || y >= h {
return None;
}
let b = bpp(image.mode());
let at =
usize::try_from(((h - 1 - y) * w + x).checked_mul(i64::try_from(b).ok()?)?).ok()?;
image.pixels().get(at..at.checked_add(b)?)
}
}
fn verified(mode: Mode) -> Result<(), SpriteError> {
match mode {
Mode::Rgb | Mode::Rgba => Ok(()),
Mode::L => Err(SpriteError::UnverifiedMode { mode: mode.name() }),
}
}
pub(crate) const fn bpp(mode: Mode) -> usize {
match mode {
Mode::L => 1,
Mode::Rgb => 3,
Mode::Rgba => 4,
}
}
#[derive(Debug)]
pub(crate) struct Canvas {
pub(crate) mode: Mode,
pub(crate) width: u32,
pub(crate) height: u32,
pub(crate) pixels: Vec<u8>,
charge: Charge,
}
pub(crate) const WIDTH_CAP: u32 = 536_870_910;
pub(crate) fn width_cap(width: u32) -> Result<(), SpriteError> {
if width > WIDTH_CAP {
Err(SpriteError::ImageTooWide)
} else {
Ok(())
}
}
impl Canvas {
pub(crate) fn new(
mode: Mode,
width: u32,
height: u32,
meter: &Arc<Meter>,
) -> Result<Self, SpriteError> {
width_cap(width)?;
let pixels = u64::from(width) * u64::from(height);
if pixels > MAX_PIXELS {
return Err(SpriteError::TooLarge { what: "canvas" });
}
let len = usize::try_from(pixels * bpp(mode) as u64)
.map_err(|_| SpriteError::TooLarge { what: "canvas" })?;
meter.count_decode(len as u64 + u64::from(height))?;
let (mut buf, charge) = MeteredVec::<u8>::with_capacity(meter, len)?.into_parts();
buf.resize(len, 0);
Ok(Self {
mode,
width,
height,
pixels: buf,
charge,
})
}
fn at(&self, x: u32, y: u32) -> usize {
(y as usize * self.width as usize + x as usize) * bpp(self.mode)
}
pub(crate) fn get(&self, x: u32, y: u32) -> &[u8] {
let at = self.at(x, y);
self.pixels.get(at..at + bpp(self.mode)).unwrap_or_default()
}
pub(crate) fn get_mut(&mut self, x: u32, y: u32) -> &mut [u8] {
let at = self.at(x, y);
let b = bpp(self.mode);
self.pixels.get_mut(at..at + b).unwrap_or_default()
}
pub(crate) fn into_image(self) -> Image {
Image::from_parts(self.mode, self.width, self.height, self.pixels, self.charge)
}
fn count_pass(&self, meter: &Meter) -> Result<(), SpriteError> {
meter.count_decode(self.pixels.len() as u64 + u64::from(self.height))?;
Ok(())
}
pub(crate) fn flip_top_bottom(&mut self, meter: &Meter) -> Result<(), SpriteError> {
self.count_pass(meter)?;
let row = self.width as usize * bpp(self.mode);
let h = self.height as usize;
let pixels = &mut self.pixels;
if row == 0 {
return Ok(());
}
super::contained(|| {
for y in 0..h / 2 {
let (top, bottom) = pixels.split_at_mut((h - 1 - y) * row);
if let (Some(a), Some(b)) =
(top.get_mut(y * row..(y + 1) * row), bottom.get_mut(..row))
{
a.swap_with_slice(b);
}
}
})
}
pub(crate) fn flip_left_right(&mut self, meter: &Meter) -> Result<(), SpriteError> {
self.count_pass(meter)?;
let b = bpp(self.mode);
let row = self.width as usize * b;
let pixels = &mut self.pixels;
super::contained(|| {
if row == 0 {
return;
}
for line in pixels.chunks_exact_mut(row) {
let w = line.len() / b;
for x in 0..w / 2 {
let (l, r) = line.split_at_mut((w - 1 - x) * b);
if let (Some(p), Some(q)) = (l.get_mut(x * b..(x + 1) * b), r.get_mut(..b)) {
p.swap_with_slice(q);
}
}
}
})
}
pub(crate) fn rotate_180(&mut self, meter: &Meter) -> Result<(), SpriteError> {
self.flip_top_bottom(meter)?;
self.flip_left_right(meter)
}
pub(crate) fn rotate_270(&self, meter: &Arc<Meter>) -> Result<Self, SpriteError> {
let mut out = Self::new(self.mode, self.height, self.width, meter)?;
let (w, h) = (self.width, self.height);
meter.count_decode(u64::from(h))?;
if w == 0 || h == 0 {
return Ok(out);
}
super::contained(|| {
for y in 0..h {
for x in 0..w {
let p = self.get(x, y);
out.get_mut(h - 1 - y, x).copy_from_slice(p);
}
}
})?;
Ok(out)
}
}
pub(crate) fn py_round(v: f64) -> Result<f64, SpriteError> {
if v.is_nan() {
Err(SpriteError::RoundNan)
} else if v.is_infinite() {
Err(SpriteError::RoundInfinity)
} else {
Ok(v.round_ties_even())
}
}
pub(crate) fn c_int(v: f64) -> Result<i32, SpriteError> {
c_int_of(Int::of_f64(v))
}
pub(crate) fn c_int_of(v: Int) -> Result<i32, SpriteError> {
let Int::I(i) = v else {
return Err(SpriteError::CLongOverflow);
};
if i64::try_from(i).is_err() {
return Err(SpriteError::CLongOverflow);
}
i32::try_from(i).map_err(|_| SpriteError::CIntOverflow { above: i > 0 })
}
#[allow(clippy::cast_possible_truncation)]
pub(crate) fn c_trunc(v: f64) -> i32 {
if v > -2_147_483_649.0 && v < 2_147_483_648.0 {
v as i32
} else {
i32::MIN
}
}
pub(crate) fn crop_box(rect: [f64; 4]) -> Result<[i32; 4], SpriteError> {
let [x, y, w, h] = rect;
let edges = [x, y, x + w, y + h];
let [x0, y0, x1, y1] = edges;
if x1 < x0 {
return Err(SpriteError::CropRightLeft);
}
if y1 < y0 {
return Err(SpriteError::CropLowerUpper);
}
let mut r = [Int::I(0); 4];
for (out, e) in r.iter_mut().zip(edges) {
*out = Int::of_f64(py_round(e)?);
}
bomb_check(r)?;
let mut out = [0; 4];
for (o, e) in out.iter_mut().zip(r) {
*o = c_int_of(e)?;
}
Ok(out)
}
pub(crate) fn bomb_check([x0, y0, x1, y1]: [Int; 4]) -> Result<(), SpriteError> {
let pixels = x1.abs_diff(x0).mul(&y1.abs_diff(y0));
if pixels.above(MAX_CROP_PIXELS) {
return Err(SpriteError::DecompressionBomb {
pixels: pixels.decimal(),
});
}
Ok(())
}
pub(crate) fn crop_size([x0, y0, x1, y1]: [i32; 4]) -> (u32, u32) {
let side = |a: i32, b: i32| u32::try_from(b.wrapping_sub(a).max(0)).unwrap_or(0);
(side(x0, x1), side(y0, y1))
}
pub(crate) fn crop(
sheet: &Sheet<'_>,
crop_box: [i32; 4],
meter: &Arc<Meter>,
) -> Result<Canvas, SpriteError> {
let [x0, y0, ..] = crop_box;
let (w, h) = crop_size(crop_box);
let mut out = Canvas::new(sheet.mode(), w, h, meter)?;
meter.count_decode(u64::from(h))?;
if w == 0 || h == 0 {
return Ok(out);
}
super::contained(|| {
for y in 0..h {
for x in 0..w {
if let Some(p) =
sheet.pixel(i64::from(x0) + i64::from(x), i64::from(y0) + i64::from(y))
{
out.get_mut(x, y).copy_from_slice(p);
}
}
}
})?;
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Format, decode};
#[test]
fn an_l_sheet_or_alpha_is_refused_before_anything_is_drawn() {
let meter = Meter::unlimited();
let l = decode(Format::Bc4, &[0; 8], 4, 4, &meter).unwrap();
let wide_l = decode(Format::Bc4, &[0; 16], 8, 4, &meter).unwrap();
let rgba = decode(Format::Rgba32, &[0; 64], 4, 4, &meter).unwrap();
let wide = decode(Format::Rgba32, &[0; 128], 8, 4, &meter).unwrap();
let rgb = decode(Format::Rgb24, &[0; 48], 4, 4, &meter).unwrap();
assert_eq!(l.mode(), Mode::L);
let held = meter.used();
let refused = |texture: &Image, alpha: Option<&Image>| {
Sheet::new(texture, alpha, &meter)
.map(|_| ())
.expect_err("refused")
};
for alpha in [&rgba, &rgb, &l, &wide] {
let e = refused(&l, Some(alpha));
assert!(matches!(e, SpriteError::AlphaBandCount), "{e:?}");
assert_eq!(
e.python(),
Some(("ValueError", "wrong number of bands".to_owned()))
);
}
let e = refused(&rgba, Some(&wide_l));
assert!(matches!(e, SpriteError::AlphaSizeMismatch), "{e:?}");
for e in [
refused(&rgba, Some(&l)),
refused(&rgb, Some(&l)),
refused(&l, None),
] {
assert!(
matches!(e, SpriteError::UnverifiedMode { mode: "L" }),
"{e:?}"
);
assert_eq!(e.python(), None);
}
assert_eq!(meter.used(), held);
assert!(Sheet::new(&rgb, None, &meter).is_ok());
assert!(Sheet::new(&rgb, Some(&rgba), &meter).is_ok());
}
#[test]
fn a_canvas_past_the_bounds_is_refused_before_it_is_charged() {
let meter = Meter::unlimited();
let wide = Canvas::new(Mode::Rgba, WIDTH_CAP + 1, 0, &meter);
assert!(matches!(wide, Err(SpriteError::ImageTooWide)));
assert_eq!(
wide.err().and_then(|e| e.python()),
Some(("MemoryError", String::new()))
);
assert!(Canvas::new(Mode::Rgba, WIDTH_CAP, 0, &meter).is_ok());
let big = Canvas::new(Mode::Rgb, 16_385, 16_384, &meter);
assert!(matches!(big, Err(SpriteError::TooLarge { what: "canvas" })));
assert_eq!(meter.used(), 0);
}
#[test]
fn a_box_edge_is_taken_as_pyarg_s_i_takes_it() {
assert_eq!(c_int(-3.0).ok(), Some(-3));
let err = |v: f64| c_int(v).err().and_then(|e| e.python());
let over = |m: &str| Some(("OverflowError", m.to_owned()));
assert_eq!(
err(2_147_483_648.0),
over("signed integer is greater than maximum")
);
assert_eq!(
err(-2_147_483_649.0),
over("signed integer is less than minimum")
);
assert_eq!(
err(9.223_372_036_854_776e18),
over("Python int too large to convert to C long")
);
assert_eq!(
err(-9.223_372_036_854_776e18),
over("signed integer is less than minimum")
);
assert_eq!(
err(1e300),
over("Python int too large to convert to C long")
);
}
}