Skip to main content

unityrs_texture/write/
mod.rs

1// Ported from UnityPy 1.25.2 (MIT): export/Texture2DConverter.py and classes/legacy_patch/Texture2D.py. See LICENSE-UNITYPY.
2//! Raw texture writes, format promotion and mip chains. The converter is
3//! `export/Texture2DConverter.py:118-234`; field edits and mip termination are
4//! `classes/legacy_patch/Texture2D.py:14-60`. The `encode` feature supplies
5//! etcpak and astcenc; without it compressed writes return a typed refusal.
6use std::sync::Arc;
7use unityrs_core::Bytes;
8use unityrs_core::budget::DecodeBuf;
9use unityrs_core::error::LimitKind;
10use unityrs_core::limits::{Charge, ChargeError, Meter, heap_cost};
11use unityrs_imageio::writers::resample::{self, Filter};
12use unityrs_imageio::{Buffer, Charger, Image};
13
14#[cfg(feature = "encode")]
15mod encoders;
16#[cfg(feature = "encode")]
17mod ffi;
18mod lab;
19mod object;
20mod source;
21mod ycbcr;
22pub use object::set_image;
23pub use source::Source;
24
25/// Errors leave the installed object data unchanged.
26#[derive(Debug, thiserror::Error)]
27pub enum WriteError {
28    /// This build does not include the optional encoders.
29    #[error("encoder unavailable for TextureFormat {0}")]
30    EncoderUnavailable(i32),
31    /// A vendored encoder refused a checked request; no bytes are installed.
32    #[error("texture encoder failed with code {0}")]
33    Encoder(i32),
34    /// A named Tier U refusal.
35    #[error("unsupported set_image: {0}")]
36    Unsupported(&'static str),
37    /// Invalid image storage or object fields.
38    #[error("invalid set_image input: {0}")]
39    Invalid(&'static str),
40    /// Bounds, allocation or work refusal.
41    #[error(transparent)]
42    Charge(#[from] ChargeError),
43    /// Platform padding/layout refusal.
44    #[error(transparent)]
45    Decode(#[from] crate::DecodeError),
46    /// Pillow resize refusal.
47    #[error(transparent)]
48    Resize(#[from] unityrs_imageio::writers::SaveError<ChargeError>),
49    /// Object read failure.
50    #[error(transparent)]
51    Parse(#[from] unityrs_core::walk::ParseError),
52    /// Object re-save failure.
53    #[error(transparent)]
54    Save(#[from] unityrs_core::files::SaveError),
55}
56const _: () = crate::send_sync::<WriteError>();
57
58/// Converter options. Platform blobs are preserved verbatim by object writes.
59#[derive(Clone, Copy, Debug)]
60pub struct Options<'a> {
61    /// Target `TextureFormat`, before UnityPy's promotion.
62    pub format: i32,
63    /// `BuildTarget`; zero for a detached texture.
64    pub platform: i32,
65    /// Existing platform blob, interpreted as little-endian GOB metadata.
66    pub platform_blob: Option<&'a [u8]>,
67    /// Flip before padding and packing (UnityPy's default).
68    pub flip: bool,
69    /// Requested mip count; zero and negative counts are retained by UnityPy.
70    pub mipmap_count: i32,
71}
72const _: () = crate::send_sync::<Options<'static>>();
73impl Options<'_> {
74    /// One flipped level on platform zero.
75    #[must_use]
76    pub const fn new(format: i32) -> Self {
77        Self {
78            format,
79            platform: 0,
80            platform_blob: None,
81            flip: true,
82            mipmap_count: 1,
83        }
84    }
85}
86
87/// Inline image bytes and the fields computed by the writer.
88#[derive(Debug)]
89pub struct Encoded {
90    /// Charged bytes, top level followed by smaller levels.
91    pub data: Bytes,
92    /// The written (possibly promoted) `TextureFormat`.
93    pub format: i32,
94    /// Actual mip count, including UnityPy's retained nonpositive counts.
95    pub mipmap_count: i32,
96}
97const _: () = crate::send_sync::<Encoded>();
98
99struct Budget<'a>(&'a Arc<Meter>);
100impl Charger for Budget<'_> {
101    type Charge = Charge;
102    type Refusal = ChargeError;
103    fn charge(&mut self, _: Buffer, requests: &[usize]) -> Result<Charge, ChargeError> {
104        self.0.charge(
105            requests
106                .iter()
107                .fold(0u64, |n, &r| n.saturating_add(heap_cost(r as u64))),
108        )
109    }
110}
111
112// R/RGB are byte layouts, not the requested texture's stored channel widths.
113fn mapped(format: i32, rgb: bool) -> Result<(i32, usize, bool), WriteError> {
114    if crate::texture_format_name(format).is_none() {
115        return Err(WriteError::Invalid("unknown TextureFormat"));
116    }
117    let (format, channels, encoder) = match format {
118        10 | 28 => (10, 4, true),
119        12 | 29 => (12, 4, true),
120        25..=27 | 48..=59 => (format, 4, true),
121        66..=71 => (format - if rgb { 18 } else { 12 }, 4, true),
122        34 | 64 | 60 => (if format == 60 { 60 } else { 34 }, 4, true),
123        45 => (45, 4, true),
124        46 | 47 | 65 => (47, 4, true),
125        1 => (1, 1, false),
126        63 | 9 | 15 | 18 | 41 | 42 => (63, 1, false),
127        7 | 3 | 8 | 22 | 30 | 32 | 35 => (3, 3, false),
128        _ => (4, 4, false),
129    };
130    Ok((format, channels, encoder))
131}
132
133/// `image_to_texture2d`, including repeated BICUBIC mip resizes when requested.
134/// Zero sides write empty data for every known target (PARITY 19.1). Tier U
135/// gates precede the encoder availability check; no encoder is needed to
136/// represent an empty linear texture.
137pub fn image_to_texture2d(
138    source: &Source<'_>,
139    options: Options<'_>,
140    meter: &Arc<Meter>,
141) -> Result<Encoded, WriteError> {
142    let (format, mut channels, encoder) = mapped(options.format, source.mode() == "RGB")?;
143    let switch = crate::is_switch_swizzled(options.platform, options.platform_blob);
144    let empty = source.width() == 0 || source.height() == 0;
145    if switch && empty {
146        return Err(WriteError::Unsupported("zero-size Switch texture"));
147    }
148    if switch && options.mipmap_count > 1 && source.width() >= 8 && source.height() >= 8 {
149        return Err(WriteError::Unsupported("Switch mip chain"));
150    }
151    let switch_format = if format == 3 { 4 } else { format };
152    if switch && crate::platform::switch_block(switch_format).is_none() {
153        return Err(WriteError::Unsupported("Switch texel block"));
154    }
155    if !empty && options.platform == crate::XBOX360 && crate::XBOX_SWAP_FORMATS.contains(&format) {
156        return Err(WriteError::Unsupported("Xbox byte-swapped write"));
157    }
158    if empty {
159        return Ok(Encoded {
160            data: Bytes::new(),
161            format,
162            mipmap_count: if options.mipmap_count > 1 {
163                1
164            } else {
165                options.mipmap_count
166            },
167        });
168    }
169    source.check_convertible()?;
170    if encoder && !cfg!(feature = "encode") {
171        return Err(WriteError::EncoderUnavailable(format));
172    }
173    if switch && format == 3 {
174        channels = 4;
175    }
176    let prepared = source.prepare(channels, format == 1, meter)?;
177    let mut image = prepared.image()?;
178    let mut out = DecodeBuf::new(meter, 0, i32::MAX as u64, LimitKind::BlockOutput)?;
179    write_level(
180        &image,
181        options,
182        format,
183        channels,
184        (prepared.alpha_band, source.auxiliary()),
185        meter,
186        &mut out,
187    )?;
188    let mut mipmap_count = options.mipmap_count;
189    let mut resized = None;
190    let mut width = image.width();
191    let mut height = image.height();
192    for i in 1..options.mipmap_count {
193        width /= 2;
194        height /= 2;
195        if width < 4 || height < 4 {
196            mipmap_count = i;
197            break;
198        }
199        meter.count_decode((image.pixels().len() as u64).saturating_mul(8))?;
200        let next = resample::resize(&image, width, height, Filter::Bicubic, &mut Budget(meter))?;
201        // Drop the previous view before replacing its storage.
202        resized = Some(next);
203        let Some(level) = &resized else {
204            return Err(WriteError::Invalid("missing mip storage"));
205        };
206        image = Image::new(width, height, prepared.mode, &level.bytes)
207            .map_err(|_| WriteError::Invalid("mip size"))?;
208        write_level(
209            &image,
210            Options {
211                platform: 0,
212                platform_blob: None,
213                ..options
214            },
215            format,
216            channels,
217            (prepared.alpha_band, Some(&[])),
218            meter,
219            &mut out,
220        )?;
221    }
222    // Keep the last resize charge alive through its view's final use.
223    drop(resized);
224    Ok(Encoded {
225        data: out.into_bytes()?,
226        format,
227        mipmap_count,
228    })
229}
230
231fn write_level(
232    image: &Image<'_>,
233    options: Options<'_>,
234    format: i32,
235    channels: usize,
236    (alpha_band, auxiliary): (usize, Option<&[u8]>),
237    meter: &Arc<Meter>,
238    out: &mut DecodeBuf,
239) -> Result<(), WriteError> {
240    let layout = if crate::is_switch_swizzled(options.platform, options.platform_blob) {
241        let exponent = options
242            .platform_blob
243            .and_then(|b| b.get(8..12))
244            .and_then(|b| <[u8; 4]>::try_from(b).ok())
245            .map(u32::from_le_bytes)
246            .ok_or(WriteError::Invalid("Switch blob"))?;
247        Some(crate::platform::switch_layout(
248            if format == 3 { 4 } else { format },
249            i32::try_from(image.width()).map_err(|_| WriteError::Invalid("width"))?,
250            i32::try_from(image.height()).map_err(|_| WriteError::Invalid("height"))?,
251            exponent,
252        )?)
253    } else {
254        None
255    };
256    let (width, height) = layout.as_ref().map_or(
257        (image.width(), image.height()),
258        crate::platform::SwitchLayout::padded_size,
259    );
260    #[cfg(feature = "encode")]
261    let (width, height) = if encoders::is_encoded(format) {
262        encoders::padded_size(format, width, height)?
263    } else {
264        (width, height)
265    };
266    let len = u64::from(width) * u64::from(height) * channels as u64;
267    meter.count_decode(len)?;
268    let mut linear = DecodeBuf::new(meter, len, len, LimitKind::BlockOutput)?;
269    for y in 0..height {
270        let bottom = y >= image.height();
271        let y = y.min(image.height() - 1);
272        let y = if options.flip {
273            image.height() - 1 - y
274        } else {
275            y
276        };
277        for x in 0..width {
278            let at = (y as usize * image.width() as usize + x.min(image.width() - 1) as usize)
279                * image.mode().channels();
280            let pixel = image
281                .pixels()
282                .get(at..at + image.mode().channels())
283                .ok_or(WriteError::Invalid("pixel span"))?;
284            if channels == 1 {
285                linear.extend_from_slice(
286                    pixel
287                        .get(if format == 1 { alpha_band } else { 0 }..)
288                        .and_then(|b| b.get(..1))
289                        .ok_or(WriteError::Invalid("band"))?,
290                )?;
291            } else if channels == 4 && image.mode() == unityrs_imageio::Mode::Rgb {
292                // Pillow's RGB resampler leaves the unused fourth storage
293                // byte zero. Its raw RGBA packer copies that byte verbatim.
294                linear.extend_from_slice(pixel)?;
295                // pad_image copies strips but constructs its corner with
296                // Image.new(mode, size, getpixel(...)). RGB's three-band
297                // colour initializes that new pixel's hidden byte to 255.
298                let padding = if bottom && x >= image.width() {
299                    255
300                } else {
301                    auxiliary.map_or(255, |b| b.get(at / 3).copied().unwrap_or(0))
302                };
303                linear.extend_from_slice(&[padding])?;
304            } else {
305                linear.extend_from_slice(
306                    pixel
307                        .get(..channels)
308                        .ok_or(WriteError::Invalid("channels"))?,
309                )?;
310            }
311        }
312    }
313    #[cfg(feature = "encode")]
314    let compressed = if encoders::is_encoded(format) {
315        Some(encoders::encode(
316            linear.as_slice(),
317            width,
318            height,
319            format,
320            meter,
321        )?)
322    } else {
323        None
324    };
325    #[cfg(feature = "encode")]
326    let data = compressed
327        .as_ref()
328        .map_or(linear.as_slice(), |v| v.as_slice());
329    #[cfg(not(feature = "encode"))]
330    let data = linear.as_slice();
331    if let Some(layout) = layout {
332        let swizzled = crate::platform::swizzle(data, &layout, meter)?;
333        out.extend_from_slice(swizzled.as_slice())?;
334    } else {
335        out.extend_from_slice(data)?;
336    }
337    Ok(())
338}
339
340/// Compresses standalone U8 RGBA context storage at a legal 2D ASTC footprint.
341pub fn astc_context(
342    rgba: &[u8],
343    width: u32,
344    height: u32,
345    block: (u8, u8),
346    meter: &Arc<Meter>,
347) -> Result<unityrs_core::limits::MeteredVec<u8>, WriteError> {
348    #[cfg(feature = "encode")]
349    {
350        encoders::astc_context(rgba, width, height, block, meter)
351    }
352    #[cfg(not(feature = "encode"))]
353    {
354        let _ = (rgba, width, height, block, meter);
355        Err(WriteError::EncoderUnavailable(54))
356    }
357}