1#![allow(
36 clippy::many_single_char_names,
37 clippy::similar_names,
38 clippy::float_cmp
39)]
40
41use std::sync::Arc;
42
43use unityrs_core::limits::{Charge, Meter, MeteredVec};
44
45use super::SpriteError;
46use super::exact::Int;
47use crate::MAX_PIXELS;
48use crate::decode::{Image, MAX_CROP_PIXELS};
49use crate::format::Mode;
50
51#[derive(Debug)]
54pub struct Sheet<'a> {
55 image: SheetImage<'a>,
56}
57
58#[derive(Debug)]
59enum SheetImage<'a> {
60 Texture(&'a Image),
61 Merged(Image),
62}
63
64const _: () = crate::send_sync::<Sheet<'static>>();
65
66impl<'a> Sheet<'a> {
67 pub fn new(
89 texture: &'a Image,
90 alpha: Option<&Image>,
91 meter: &Arc<Meter>,
92 ) -> Result<Self, SpriteError> {
93 match alpha {
94 None => {
95 verified(texture.mode())?;
96 Ok(Self {
97 image: SheetImage::Texture(texture),
98 })
99 }
100 Some(alpha) => Sheet::merged(texture, alpha, meter),
101 }
102 }
103
104 pub fn merged(
107 texture: &Image,
108 alpha: &Image,
109 meter: &Arc<Meter>,
110 ) -> Result<Sheet<'static>, SpriteError> {
111 if texture.mode() == Mode::L {
114 return Err(SpriteError::AlphaBandCount);
115 }
116 if texture.width() != alpha.width() || texture.height() != alpha.height() {
117 return Err(SpriteError::AlphaSizeMismatch);
118 }
119 verified(alpha.mode())?;
120 let mut merged = Canvas::new(Mode::Rgba, texture.width(), texture.height(), meter)?;
121 let tb = bpp(texture.mode());
122 let ab = bpp(alpha.mode());
123 let (tp, ap) = (texture.pixels(), alpha.pixels());
124 super::contained(|| {
125 for (i, out) in merged.pixels.as_chunks_mut::<4>().0.iter_mut().enumerate() {
126 let t = tp.get(i * tb..i * tb + 3).unwrap_or(&[0; 3]);
127 out.get_mut(..3).unwrap_or_default().copy_from_slice(t);
128 if let (Some(o), Some(a)) = (out.get_mut(3), ap.get(i * ab)) {
129 *o = *a;
130 }
131 }
132 })?;
133 Ok(Sheet {
134 image: SheetImage::Merged(merged.into_image()),
135 })
136 }
137
138 fn image(&self) -> &Image {
139 match &self.image {
140 SheetImage::Texture(i) => i,
141 SheetImage::Merged(i) => i,
142 }
143 }
144
145 #[must_use]
147 pub fn mode(&self) -> Mode {
148 self.image().mode()
149 }
150
151 #[must_use]
153 pub fn width(&self) -> u32 {
154 self.image().width()
155 }
156
157 #[must_use]
159 pub fn height(&self) -> u32 {
160 self.image().height()
161 }
162
163 pub(crate) fn pixel(&self, x: i64, y: i64) -> Option<&[u8]> {
166 let image = self.image();
167 let (w, h) = (i64::from(image.width()), i64::from(image.height()));
168 if x < 0 || y < 0 || x >= w || y >= h {
169 return None;
170 }
171 let b = bpp(image.mode());
172 let at =
173 usize::try_from(((h - 1 - y) * w + x).checked_mul(i64::try_from(b).ok()?)?).ok()?;
174 image.pixels().get(at..at.checked_add(b)?)
175 }
176}
177
178fn verified(mode: Mode) -> Result<(), SpriteError> {
181 match mode {
182 Mode::Rgb | Mode::Rgba => Ok(()),
183 Mode::L => Err(SpriteError::UnverifiedMode { mode: mode.name() }),
184 }
185}
186
187pub(crate) const fn bpp(mode: Mode) -> usize {
189 match mode {
190 Mode::L => 1,
191 Mode::Rgb => 3,
192 Mode::Rgba => 4,
193 }
194}
195
196#[derive(Debug)]
198pub(crate) struct Canvas {
199 pub(crate) mode: Mode,
200 pub(crate) width: u32,
201 pub(crate) height: u32,
202 pub(crate) pixels: Vec<u8>,
203 charge: Charge,
205}
206
207pub(crate) const WIDTH_CAP: u32 = 536_870_910;
209
210pub(crate) fn width_cap(width: u32) -> Result<(), SpriteError> {
213 if width > WIDTH_CAP {
214 Err(SpriteError::ImageTooWide)
215 } else {
216 Ok(())
217 }
218}
219
220impl Canvas {
221 pub(crate) fn new(
234 mode: Mode,
235 width: u32,
236 height: u32,
237 meter: &Arc<Meter>,
238 ) -> Result<Self, SpriteError> {
239 width_cap(width)?;
240 let pixels = u64::from(width) * u64::from(height);
241 if pixels > MAX_PIXELS {
242 return Err(SpriteError::TooLarge { what: "canvas" });
243 }
244 let len = usize::try_from(pixels * bpp(mode) as u64)
245 .map_err(|_| SpriteError::TooLarge { what: "canvas" })?;
246 meter.count_decode(len as u64 + u64::from(height))?;
247 let (mut buf, charge) = MeteredVec::<u8>::with_capacity(meter, len)?.into_parts();
248 buf.resize(len, 0);
250 Ok(Self {
251 mode,
252 width,
253 height,
254 pixels: buf,
255 charge,
256 })
257 }
258
259 fn at(&self, x: u32, y: u32) -> usize {
260 (y as usize * self.width as usize + x as usize) * bpp(self.mode)
261 }
262
263 pub(crate) fn get(&self, x: u32, y: u32) -> &[u8] {
265 let at = self.at(x, y);
266 self.pixels.get(at..at + bpp(self.mode)).unwrap_or_default()
267 }
268
269 pub(crate) fn get_mut(&mut self, x: u32, y: u32) -> &mut [u8] {
271 let at = self.at(x, y);
272 let b = bpp(self.mode);
273 self.pixels.get_mut(at..at + b).unwrap_or_default()
274 }
275
276 pub(crate) fn into_image(self) -> Image {
278 Image::from_parts(self.mode, self.width, self.height, self.pixels, self.charge)
279 }
280
281 fn count_pass(&self, meter: &Meter) -> Result<(), SpriteError> {
284 meter.count_decode(self.pixels.len() as u64 + u64::from(self.height))?;
285 Ok(())
286 }
287
288 pub(crate) fn flip_top_bottom(&mut self, meter: &Meter) -> Result<(), SpriteError> {
290 self.count_pass(meter)?;
291 let row = self.width as usize * bpp(self.mode);
292 let h = self.height as usize;
293 let pixels = &mut self.pixels;
294 if row == 0 {
296 return Ok(());
297 }
298 super::contained(|| {
299 for y in 0..h / 2 {
300 let (top, bottom) = pixels.split_at_mut((h - 1 - y) * row);
301 if let (Some(a), Some(b)) =
302 (top.get_mut(y * row..(y + 1) * row), bottom.get_mut(..row))
303 {
304 a.swap_with_slice(b);
305 }
306 }
307 })
308 }
309
310 pub(crate) fn flip_left_right(&mut self, meter: &Meter) -> Result<(), SpriteError> {
312 self.count_pass(meter)?;
313 let b = bpp(self.mode);
314 let row = self.width as usize * b;
315 let pixels = &mut self.pixels;
316 super::contained(|| {
317 if row == 0 {
318 return;
319 }
320 for line in pixels.chunks_exact_mut(row) {
321 let w = line.len() / b;
322 for x in 0..w / 2 {
323 let (l, r) = line.split_at_mut((w - 1 - x) * b);
324 if let (Some(p), Some(q)) = (l.get_mut(x * b..(x + 1) * b), r.get_mut(..b)) {
325 p.swap_with_slice(q);
326 }
327 }
328 }
329 })
330 }
331
332 pub(crate) fn rotate_180(&mut self, meter: &Meter) -> Result<(), SpriteError> {
334 self.flip_top_bottom(meter)?;
335 self.flip_left_right(meter)
336 }
337
338 pub(crate) fn rotate_270(&self, meter: &Arc<Meter>) -> Result<Self, SpriteError> {
343 let mut out = Self::new(self.mode, self.height, self.width, meter)?;
344 let (w, h) = (self.width, self.height);
345 meter.count_decode(u64::from(h))?;
347 if w == 0 || h == 0 {
348 return Ok(out);
349 }
350 super::contained(|| {
351 for y in 0..h {
352 for x in 0..w {
353 let p = self.get(x, y);
354 out.get_mut(h - 1 - y, x).copy_from_slice(p);
355 }
356 }
357 })?;
358 Ok(out)
359 }
360}
361
362pub(crate) fn py_round(v: f64) -> Result<f64, SpriteError> {
365 if v.is_nan() {
366 Err(SpriteError::RoundNan)
367 } else if v.is_infinite() {
368 Err(SpriteError::RoundInfinity)
369 } else {
370 Ok(v.round_ties_even())
371 }
372}
373
374pub(crate) fn c_int(v: f64) -> Result<i32, SpriteError> {
376 c_int_of(Int::of_f64(v))
377}
378
379pub(crate) fn c_int_of(v: Int) -> Result<i32, SpriteError> {
383 let Int::I(i) = v else {
384 return Err(SpriteError::CLongOverflow);
385 };
386 if i64::try_from(i).is_err() {
387 return Err(SpriteError::CLongOverflow);
388 }
389 i32::try_from(i).map_err(|_| SpriteError::CIntOverflow { above: i > 0 })
390}
391
392#[allow(clippy::cast_possible_truncation)]
396pub(crate) fn c_trunc(v: f64) -> i32 {
397 if v > -2_147_483_649.0 && v < 2_147_483_648.0 {
398 v as i32
399 } else {
400 i32::MIN
401 }
402}
403
404pub(crate) fn crop_box(rect: [f64; 4]) -> Result<[i32; 4], SpriteError> {
407 let [x, y, w, h] = rect;
408 let edges = [x, y, x + w, y + h];
409 let [x0, y0, x1, y1] = edges;
410 if x1 < x0 {
411 return Err(SpriteError::CropRightLeft);
412 }
413 if y1 < y0 {
414 return Err(SpriteError::CropLowerUpper);
415 }
416 let mut r = [Int::I(0); 4];
417 for (out, e) in r.iter_mut().zip(edges) {
418 *out = Int::of_f64(py_round(e)?);
419 }
420 bomb_check(r)?;
421 let mut out = [0; 4];
422 for (o, e) in out.iter_mut().zip(r) {
423 *o = c_int_of(e)?;
424 }
425 Ok(out)
426}
427
428pub(crate) fn bomb_check([x0, y0, x1, y1]: [Int; 4]) -> Result<(), SpriteError> {
432 let pixels = x1.abs_diff(x0).mul(&y1.abs_diff(y0));
433 if pixels.above(MAX_CROP_PIXELS) {
434 return Err(SpriteError::DecompressionBomb {
435 pixels: pixels.decimal(),
436 });
437 }
438 Ok(())
439}
440
441pub(crate) fn crop_size([x0, y0, x1, y1]: [i32; 4]) -> (u32, u32) {
444 let side = |a: i32, b: i32| u32::try_from(b.wrapping_sub(a).max(0)).unwrap_or(0);
445 (side(x0, x1), side(y0, y1))
446}
447
448pub(crate) fn crop(
451 sheet: &Sheet<'_>,
452 crop_box: [i32; 4],
453 meter: &Arc<Meter>,
454) -> Result<Canvas, SpriteError> {
455 let [x0, y0, ..] = crop_box;
456 let (w, h) = crop_size(crop_box);
457 let mut out = Canvas::new(sheet.mode(), w, h, meter)?;
458 meter.count_decode(u64::from(h))?;
461 if w == 0 || h == 0 {
462 return Ok(out);
463 }
464 super::contained(|| {
465 for y in 0..h {
466 for x in 0..w {
467 if let Some(p) =
468 sheet.pixel(i64::from(x0) + i64::from(x), i64::from(y0) + i64::from(y))
469 {
470 out.get_mut(x, y).copy_from_slice(p);
471 }
472 }
473 }
474 })?;
475 Ok(out)
476}
477
478#[cfg(test)]
479mod tests {
480 use super::*;
481 use crate::{Format, decode};
482
483 #[test]
490 fn an_l_sheet_or_alpha_is_refused_before_anything_is_drawn() {
491 let meter = Meter::unlimited();
492 let l = decode(Format::Bc4, &[0; 8], 4, 4, &meter).unwrap();
493 let wide_l = decode(Format::Bc4, &[0; 16], 8, 4, &meter).unwrap();
494 let rgba = decode(Format::Rgba32, &[0; 64], 4, 4, &meter).unwrap();
495 let wide = decode(Format::Rgba32, &[0; 128], 8, 4, &meter).unwrap();
496 let rgb = decode(Format::Rgb24, &[0; 48], 4, 4, &meter).unwrap();
497 assert_eq!(l.mode(), Mode::L);
498 let held = meter.used();
499 let refused = |texture: &Image, alpha: Option<&Image>| {
500 Sheet::new(texture, alpha, &meter)
501 .map(|_| ())
502 .expect_err("refused")
503 };
504 for alpha in [&rgba, &rgb, &l, &wide] {
506 let e = refused(&l, Some(alpha));
507 assert!(matches!(e, SpriteError::AlphaBandCount), "{e:?}");
508 assert_eq!(
509 e.python(),
510 Some(("ValueError", "wrong number of bands".to_owned()))
511 );
512 }
513 let e = refused(&rgba, Some(&wide_l));
514 assert!(matches!(e, SpriteError::AlphaSizeMismatch), "{e:?}");
515 for e in [
518 refused(&rgba, Some(&l)),
519 refused(&rgb, Some(&l)),
520 refused(&l, None),
521 ] {
522 assert!(
523 matches!(e, SpriteError::UnverifiedMode { mode: "L" }),
524 "{e:?}"
525 );
526 assert_eq!(e.python(), None);
527 }
528 assert_eq!(meter.used(), held);
529 assert!(Sheet::new(&rgb, None, &meter).is_ok());
531 assert!(Sheet::new(&rgb, Some(&rgba), &meter).is_ok());
532 }
533
534 #[test]
538 fn a_canvas_past_the_bounds_is_refused_before_it_is_charged() {
539 let meter = Meter::unlimited();
540 let wide = Canvas::new(Mode::Rgba, WIDTH_CAP + 1, 0, &meter);
541 assert!(matches!(wide, Err(SpriteError::ImageTooWide)));
542 assert_eq!(
543 wide.err().and_then(|e| e.python()),
544 Some(("MemoryError", String::new()))
545 );
546 assert!(Canvas::new(Mode::Rgba, WIDTH_CAP, 0, &meter).is_ok());
547 let big = Canvas::new(Mode::Rgb, 16_385, 16_384, &meter);
548 assert!(matches!(big, Err(SpriteError::TooLarge { what: "canvas" })));
549 assert_eq!(meter.used(), 0);
550 }
551
552 #[test]
553 fn a_box_edge_is_taken_as_pyarg_s_i_takes_it() {
554 assert_eq!(c_int(-3.0).ok(), Some(-3));
555 let err = |v: f64| c_int(v).err().and_then(|e| e.python());
556 let over = |m: &str| Some(("OverflowError", m.to_owned()));
557 assert_eq!(
558 err(2_147_483_648.0),
559 over("signed integer is greater than maximum")
560 );
561 assert_eq!(
562 err(-2_147_483_649.0),
563 over("signed integer is less than minimum")
564 );
565 assert_eq!(
566 err(9.223_372_036_854_776e18),
567 over("Python int too large to convert to C long")
568 );
569 assert_eq!(
570 err(-9.223_372_036_854_776e18),
571 over("signed integer is less than minimum")
572 );
573 assert_eq!(
574 err(1e300),
575 over("Python int too large to convert to C long")
576 );
577 }
578}