Skip to main content

unityrs_texture/
array.rs

1// Ported from UnityPy 1.25.2 (MIT): classes/legacy_patch/Texture2DArray.py's slice extraction and enums/GraphicsFormat.py's map. See THIRD_PARTY_LICENSES.
2//! Array slices (`classes/legacy_patch/Texture2DArray.py:12-43`) use integer
3//! division and range stepping, retaining per-slice mip tails. Platform 0
4//! is UnityPy's convention; Switch/Xbox arrays are explicitly Tier U.
5//! Empty inline data uses the supplied resource (Tier B). The eight 8-bit
6//! integer entries use the corresponding UNorm/SNorm channel counts (B/C),
7//! as PARITY section 19.2 specifies. Signed byte conversion is the closed
8//! form in section 17.1; no 16-bit decoder is used for those stored bytes.
9//! The six ASTC HDR graphics formats use the corresponding HDR decoders
10//! despite the pinned UnityPy map omitting them (Tier B).
11use crate::{DecodeError, Format, Image, Plan};
12use std::sync::Arc;
13use unityrs_core::limits::{ChargeError, Meter, MeteredVec, heap_cost};
14mod object;
15pub use object::images;
16
17/// Array metadata; `data_size` includes every slice's mip chain.
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub struct ArrayFields {
20    /// `m_Format`, a `GraphicsFormat` rather than `TextureFormat`.
21    pub graphics_format: i32,
22    /// `m_Width`.
23    pub width: i32,
24    /// `m_Height`.
25    pub height: i32,
26    /// `m_Depth`.
27    pub depth: i32,
28    /// `m_DataSize`.
29    pub data_size: u64,
30    /// The owning file's platform; Switch and Xbox360 are refused.
31    pub platform: i32,
32}
33const _: () = crate::send_sync::<ArrayFields>();
34
35/// Array mapping, layout or decode failure, without allocating an error message.
36#[derive(Debug, PartialEq, Eq, thiserror::Error)]
37pub enum ArrayError {
38    /// A missing or wrongly typed object field.
39    #[error("invalid Texture2DArray field {0}")]
40    Field(&'static str),
41    /// Object parsing failed.
42    #[error(transparent)]
43    Parse(#[from] unityrs_core::walk::ParseError),
44    /// Resource resolution failed.
45    #[error(transparent)]
46    Resource(#[from] unityrs_core::Error),
47    /// `GraphicsFormat`'s enum has no such value.
48    #[error("unknown GraphicsFormat {0}")]
49    UnknownGraphicsFormat(i32),
50    /// Known enum member with no entry in UnityPy's map.
51    #[error("unmapped GraphicsFormat {0}")]
52    UnmappedGraphicsFormat(i32),
53    /// No independent reference for either platform's array storage.
54    #[error("unsupported Texture2DArray platform {0}")]
55    UnsupportedPlatform(i32),
56    /// Zero/negative depth, zero step, or host-size overflow.
57    #[error("invalid Texture2DArray slice layout")]
58    Layout,
59    /// No decoder for the mapped format is linked yet.
60    #[error("unsupported array TextureFormat {0}")]
61    UnsupportedFormat(i32),
62    /// A slice failed to decode.
63    #[error(transparent)]
64    Decode(#[from] DecodeError),
65    /// A table or work charge was refused.
66    #[error(transparent)]
67    Charge(#[from] ChargeError),
68}
69const _: () = crate::send_sync::<ArrayError>();
70
71/// UnityPy's original map, including its eight wrong 8-bit integer targets
72/// (`enums/GraphicsFormat.py:179-277`). Call [`texture_format`] for decoding.
73pub fn unitypy_texture_format(value: i32) -> Result<i32, ArrayError> {
74    let format = match value {
75        1 | 5 => 63,
76        2 | 6 => 62,
77        3 | 7 => 3,
78        4 | 8 => 4,
79        9..=12 => 75 + value - 9,
80        13 | 21 | 29 => 9,
81        14 | 22 | 30 => 72,
82        15 | 23 | 31 => 73,
83        16 | 24 | 32 => 74,
84        17 | 25 | 33 => 79,
85        18 | 26 | 34 => 80,
86        19 | 27 | 35 => 81,
87        20 | 28 | 36 => 82,
88        56 | 58 => 8,
89        57 | 59 => 14,
90        96 | 97 => 10,
91        98 | 99 => 11,
92        100 | 101 => 12,
93        102 => 26,
94        104 => 27,
95        106 => 24,
96        108 | 109 => 25,
97        110 | 111 => 30,
98        112 | 113 => 32,
99        114 | 115 => 31,
100        116 | 117 => 33,
101        118 => 34,
102        119 | 120 => 45,
103        121 | 122 => 46,
104        123 | 124 => 47,
105        125 => 41,
106        126 => 42,
107        127 => 43,
108        128 => 44,
109        129 | 130 => 54,
110        131 | 132 => 55,
111        133 | 134 => 56,
112        135 | 136 => 57,
113        137 | 138 => 58,
114        139 | 140 => 59,
115        141 => 21,
116        _ => {
117            return Err(
118                if matches!(value, 0..=52 | 56..=86 | 90..=141 | 145..=151) {
119                    ArrayError::UnmappedGraphicsFormat(value)
120                } else {
121                    ArrayError::UnknownGraphicsFormat(value)
122                },
123            );
124        }
125    };
126    Ok(format)
127}
128
129/// Corrected mapping for the eight 8-bit integer graphics formats and six
130/// ASTC HDR graphics formats, otherwise the original map. The byte correction's
131/// targets are `enums/GraphicsFormat.py:184-191`; ASTC HDR adds the corresponding
132/// HDR `TextureFormat` values omitted by UnityPy's map (PARITY section 19.2).
133pub fn texture_format(value: i32) -> Result<i32, ArrayError> {
134    match value {
135        13 => Ok(63),
136        14 => Ok(62),
137        15 => Ok(3),
138        16 => Ok(4),
139        17..=20 => Ok(75 + value - 17),
140        145..=150 => Ok(66 + value - 145),
141        _ => unitypy_texture_format(value),
142    }
143}
144
145/// Length-only array plan, with a bound for retained images and the list.
146#[derive(Clone, Copy, Debug, PartialEq, Eq)]
147pub struct ArrayPlan {
148    /// Python range's count (also for a non-divisible data size).
149    pub slice_count: usize,
150    /// `m_DataSize // m_Depth`, including mip tails.
151    pub slice_bytes: usize,
152    /// Each slice's final image.
153    pub image: Plan,
154    /// Upper bound for retained output, table, and one decoder's scratch.
155    pub peak_charge: u64,
156}
157const _: () = crate::send_sync::<ArrayPlan>();
158
159fn slice_plan(format: i32, len: usize, w: i32, h: i32) -> Result<Plan, ArrayError> {
160    // UnityPy export/Texture2DConverter.py:254-320 returns empty RGBA
161    // before checking data or looking up a decoder. Mapping and slicing
162    // still precede this in classes/legacy_patch/Texture2DArray.py:12-43.
163    if w == 0 || h == 0 {
164        return Ok(crate::plan(Format::Rgba32, len, w, h)?);
165    }
166    let f = Format::from_texture_format(format).ok_or(ArrayError::UnsupportedFormat(format))?;
167    Ok(crate::plan(f, len, w, h)?)
168}
169
170/// Plan after resolving inline/resource data, without reading or allocating it.
171pub fn plan(fields: &ArrayFields, data_len: usize) -> Result<ArrayPlan, ArrayError> {
172    if matches!(fields.platform, crate::SWITCH | crate::XBOX360) {
173        return Err(ArrayError::UnsupportedPlatform(fields.platform));
174    }
175    let format = texture_format(fields.graphics_format)?;
176    let depth = u64::try_from(fields.depth)
177        .ok()
178        .filter(|n| *n > 0)
179        .ok_or(ArrayError::Layout)?;
180    let step = fields.data_size / depth;
181    if step == 0 {
182        return Err(ArrayError::Layout);
183    }
184    let count = fields.data_size.div_ceil(step);
185    let end = (count - 1).checked_mul(step).ok_or(ArrayError::Layout)?;
186    // Match slicing's clamping: even the final short slice must decode.
187    let last_len = (data_len as u64).saturating_sub(end).min(step);
188    let image = slice_plan(
189        format,
190        usize::try_from(last_len).map_err(|_| ArrayError::Layout)?,
191        fields.width,
192        fields.height,
193    )?;
194    let slice_count = usize::try_from(count).map_err(|_| ArrayError::Layout)?;
195    let slice_bytes = usize::try_from(step).map_err(|_| ArrayError::Layout)?;
196    let table = count
197        .checked_mul(std::mem::size_of::<Image>() as u64)
198        .ok_or(ArrayError::Layout)?;
199    let peak_charge = image
200        .charge()
201        .checked_mul(count)
202        .and_then(|n| n.checked_add(heap_cost(table)))
203        .and_then(|n| n.checked_add(image.scratch))
204        .ok_or(ArrayError::Layout)?;
205    Ok(ArrayPlan {
206        slice_count,
207        slice_bytes,
208        image,
209        peak_charge,
210    })
211}
212
213/// Decode each slice from inline data, falling back on a resolved resource
214/// when inline is empty. Output table and all pixels are charged before allocation.
215pub fn decode(
216    fields: &ArrayFields,
217    inline: &[u8],
218    resource: Option<&[u8]>,
219    meter: &Arc<Meter>,
220) -> Result<MeteredVec<Image>, ArrayError> {
221    let data = if inline.is_empty() {
222        resource.unwrap_or(inline)
223    } else {
224        inline
225    };
226    let p = plan(fields, data.len())?;
227    let format = texture_format(fields.graphics_format)?;
228    meter.count_decode(p.slice_count as u64)?;
229    let mut images = MeteredVec::with_capacity(meter, p.slice_count)?;
230    for i in 0..p.slice_count {
231        let start = i.checked_mul(p.slice_bytes).ok_or(ArrayError::Layout)?;
232        let end = start.saturating_add(p.slice_bytes).min(data.len());
233        let input = data.get(start..end).unwrap_or_default();
234        let img = if fields.width == 0 || fields.height == 0 {
235            // The same pre-decoder shortcut as slice_plan, including formats
236            // without a linked decoder (Texture2DConverter.py:254-320).
237            crate::decode(Format::Rgba32, input, fields.width, fields.height, meter)?
238        } else {
239            let f =
240                Format::from_texture_format(format).ok_or(ArrayError::UnsupportedFormat(format))?;
241            crate::decode(f, input, fields.width, fields.height, meter)?
242        };
243        images.push(img)?;
244    }
245    Ok(images)
246}