Skip to main content

unityrs_texture/
image.rs

1// Ported from UnityPy 1.25.2 (MIT): export/Texture2DConverter.py's pad_image and crop-before-flip ordering. See THIRD_PARTY_LICENSES.
2//! Edge extension (`export/Texture2DConverter.py:53-80`) without temporary
3//! strips; Switch crop ordering is `export/Texture2DConverter.py:254-320`.
4use crate::{DecodeError, Image, MAX_PIXELS, Mode, PlatformError};
5use std::sync::Arc;
6use unityrs_core::limits::{Meter, MeteredVec};
7
8fn size(mode: Mode, w: u32, h: u32) -> Result<usize, DecodeError> {
9    let pixels = u64::from(w) * u64::from(h);
10    if pixels > MAX_PIXELS {
11        return Err(DecodeError::TooLarge {
12            pixels,
13            max: MAX_PIXELS,
14        });
15    }
16    Ok(
17        usize::try_from(pixels * mode.bytes_per_pixel())
18            .map_err(|_| PlatformError::SizeOverflow)?,
19    )
20}
21
22/// Copy already ordered pixels into a charged image, validating its length.
23pub fn image_from_pixels(
24    mode: Mode,
25    width: u32,
26    height: u32,
27    data: &[u8],
28    meter: &Arc<Meter>,
29) -> Result<Image, DecodeError> {
30    let n = size(mode, width, height)?;
31    if data.len() != n {
32        return Err(DecodeError::NotEnoughData {
33            needed: n as u64,
34            got: data.len() as u64,
35        });
36    }
37    meter.count_decode(n as u64)?;
38    let mut pixels = MeteredVec::with_capacity(meter, n)?;
39    pixels.extend_from_slice(data)?;
40    let (pixels, charge) = pixels.into_parts();
41    Ok(Image::from_parts(mode, width, height, pixels, charge))
42}
43
44/// Extend the final column, row and corner with NEAREST sampling. Equal
45/// dimensions return the original allocation and charge, without work.
46pub fn pad_image(
47    image: Image,
48    width: u32,
49    height: u32,
50    meter: &Arc<Meter>,
51) -> Result<Image, DecodeError> {
52    if (width, height) == (image.width(), image.height()) {
53        return Ok(image);
54    }
55    if width < image.width() || height < image.height() {
56        return Err(PlatformError::PaddingSize.into());
57    }
58    let n = size(image.mode(), width, height)?;
59    if image.width() == 0 || image.height() == 0 {
60        // Pillow's out-of-bounds single-edge crop supplies black pixels.
61        // Changing both dimensions reaches its undefined corner pixel.
62        // UnityPy export/Texture2DConverter.py:53-80 also resizes each strip:
63        // with a zero side Pillow accepts its unchanged size (a one-pixel
64        // extension), but refuses a resize to another zero-extent size.
65        if (width != image.width() && height != image.height())
66            || (image.height() == 0 && width - image.width() > 1)
67            || (image.width() == 0 && height - image.height() > 1)
68        {
69            return Err(PlatformError::PaddingSize.into());
70        }
71        meter.count_decode(n as u64)?;
72        let mut out = MeteredVec::with_capacity(meter, n)?;
73        for _ in 0..n {
74            out.push(0)?;
75        }
76        let (pixels, charge) = out.into_parts();
77        return Ok(Image::from_parts(
78            image.mode(),
79            width,
80            height,
81            pixels,
82            charge,
83        ));
84    }
85    meter.count_decode(n as u64)?;
86    let mut out = MeteredVec::with_capacity(meter, n)?;
87    let channels =
88        usize::try_from(image.mode().bytes_per_pixel()).map_err(|_| PlatformError::SizeOverflow)?;
89    for y in 0..height {
90        for x in 0..width {
91            let sx = x.min(image.width() - 1);
92            let sy = y.min(image.height() - 1);
93            let at = (u64::from(sy) * u64::from(image.width()) + u64::from(sx)) * channels as u64;
94            let at = usize::try_from(at).map_err(|_| PlatformError::SizeOverflow)?;
95            out.extend_from_slice(
96                image
97                    .pixels()
98                    .get(at..at + channels)
99                    .ok_or(PlatformError::SizeOverflow)?,
100            )?;
101        }
102    }
103    let (pixels, charge) = out.into_parts();
104    Ok(Image::from_parts(
105        image.mode(),
106        width,
107        height,
108        pixels,
109        charge,
110    ))
111}
112
113pub(crate) fn crop_flipped(
114    image: &Image,
115    width: u32,
116    height: u32,
117    meter: &Arc<Meter>,
118) -> Result<Image, DecodeError> {
119    let n = size(image.mode(), width, height)?;
120    meter.count_decode(n as u64)?;
121    let mut out = MeteredVec::with_capacity(meter, n)?;
122    let row = width as usize
123        * usize::try_from(image.mode().bytes_per_pixel())
124            .map_err(|_| PlatformError::SizeOverflow)?;
125    let stride = image.width() as usize
126        * usize::try_from(image.mode().bytes_per_pixel())
127            .map_err(|_| PlatformError::SizeOverflow)?;
128    let start = image
129        .height()
130        .checked_sub(height)
131        .ok_or(PlatformError::SizeOverflow)? as usize;
132    for y in start..start + height as usize {
133        let at = y * stride;
134        out.extend_from_slice(
135            image
136                .pixels()
137                .get(at..at + row)
138                .ok_or(PlatformError::SizeOverflow)?,
139        )?;
140    }
141    let (pixels, charge) = out.into_parts();
142    Ok(Image::from_parts(
143        image.mode(),
144        width,
145        height,
146        pixels,
147        charge,
148    ))
149}