Skip to main content

unityrs_texture/sprite/
fields.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/export/SpriteHelper.py's get_image_from_sprite (the render data it reads). See THIRD_PARTY_LICENSES.
2//! What `get_image_from_sprite` reads of a Sprite and of its atlas
3//! (`export/SpriteHelper.py:63-88`), from a [`Parsed`] object: the
4//! Sprite's `m_PixelsToUnits`, `m_RD`, `m_SpriteAtlas`, `m_AtlasTags` and
5//! `m_RenderDataKey`, and an atlas's `m_RenderDataMap` entry for the
6//! sprite's key.
7//!
8//! [`select_render_data`] settles which render data a sprite renders
9//! from, as `get_image_from_sprite` settles it (`:63-81`): a non-null
10//! `m_SpriteAtlas` ([`Pptr::is_set`]) names the atlas; else, where
11//! `m_AtlasTags` is not empty, the file's first `SpriteAtlas` whose name is
12//! its first tag (a `SpriteAtlas` of another name before it is skipped, and
13//! none found is no atlas); with an atlas, the entry of its
14//! `m_RenderDataMap` whose key equals `m_RenderDataKey`
15//! ([`atlas_render_data`]; none is `StopIteration`,
16//! [`SpriteError::NoAtlasData`]); with none, the Sprite's own `m_RD`
17//! ([`SpriteFields::rd`]). The caller resolves the pointer and lists the
18//! file's atlases, since both are the file's. The mesh is always the
19//! Sprite's own `m_RD`'s.
20//!
21//! A key's `GUID` is UnityPy's `GUID` class, whose equality compares
22//! `data_0_` to `data_3_` in that order (`classes/generated.py`), so its
23//! words are read by name (`data[0]` to `data[3]`), whatever order the
24//! typetree gives them.
25//!
26//! Each step of every loop here counts decode work on the caller's meter
27//! before it runs, so that a file of many atlases, an atlas of many entries
28//! or fields, or names of many bytes, scanned for each of many sprites, is
29//! bounded by the caller's allowance: each field a lookup walks (`field`,
30//! the [`Parsed::field`] scan, metered), each atlas compared, each map
31//! entry, and each tag checked, counts one unit, and each name or tag
32//! comparison as many more as the bytes it may read (`compared`).
33
34use std::sync::Arc;
35
36use unityrs_core::limits::Meter;
37use unityrs_core::{Map, Parsed, Value};
38
39use super::{SpriteData, SpriteError};
40
41/// A `PPtr`'s two ids.
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43pub struct Pptr {
44    /// `m_FileID`.
45    pub file_id: i64,
46    /// `m_PathID`.
47    pub path_id: i64,
48}
49
50impl Pptr {
51    /// `bool(pptr)`: `m_PathID != 0` (`classes/PPtr.py`).
52    #[must_use]
53    pub fn is_set(&self) -> bool {
54        self.path_id != 0
55    }
56}
57
58/// A `GUID`'s four words, `data[0]` to `data[3]`, by name.
59pub type Guid = [u64; 4];
60
61/// A `pair<GUID, SInt64>`: `m_RenderDataKey`, and a key of an atlas's
62/// `m_RenderDataMap`, equal as UnityPy's tuples of a `GUID` and an `int`
63/// are, field by field.
64#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
65pub struct AtlasKey {
66    /// The `GUID`.
67    pub guid: Guid,
68    /// The `SInt64`.
69    pub id: i64,
70}
71
72/// A render data's texture, alpha texture, rectangle and settings: a
73/// `SpriteRenderData` (`m_RD`) or an atlas's `SpriteAtlasData`
74/// (`:83-86`).
75#[derive(Clone, Copy, Debug, PartialEq)]
76pub struct RenderData {
77    /// `texture`.
78    pub texture: Pptr,
79    /// `alphaTexture`, `None` where the version has none; merged in only
80    /// where [`Pptr::is_set`] (`get_image`, `:47`).
81    pub alpha_texture: Option<Pptr>,
82    /// `textureRect`: `x`, `y`, `width`, `height`.
83    pub texture_rect: [f64; 4],
84    /// `settingsRaw`.
85    pub settings_raw: u64,
86}
87
88const _: () = crate::send_sync::<RenderData>();
89const _: () = crate::send_sync::<Pptr>();
90const _: () = crate::send_sync::<Guid>();
91const _: () = crate::send_sync::<AtlasKey>();
92const _: () = crate::send_sync::<SpriteFields<'static>>();
93
94/// What [`render()`](super::render()) and [`select_render_data`] read of
95/// a Sprite, borrowing from its [`Parsed`] tree.
96#[derive(Clone, Debug, PartialEq)]
97pub struct SpriteFields<'p> {
98    /// `m_PixelsToUnits`.
99    pub pixels_to_units: f64,
100    /// `m_RD`'s render data.
101    pub rd: RenderData,
102    /// `m_SpriteAtlas`, where the version has it.
103    pub sprite_atlas: Option<Pptr>,
104    /// `m_AtlasTags[0]` (raw bytes, as the file holds them), where the
105    /// version has the field and it is not empty: the one tag UnityPy
106    /// reads. Borrowed, so a Sprite of many tags costs nothing here.
107    pub atlas_tag: Option<&'p [u8]>,
108    /// `m_RenderDataKey`, where the version has it.
109    pub render_data_key: Option<AtlasKey>,
110}
111
112impl<'p> SpriteFields<'p> {
113    /// Reads them from a parsed Sprite, counting each lookup's and the tag
114    /// check's work on `meter` (module docs); a field missing, or of
115    /// another type than its typetree's (a tag that is not a string among
116    /// them), is [`SpriteError::Malformed`].
117    pub fn read(sprite: &'p Parsed, meter: &Arc<Meter>) -> Result<Self, SpriteError> {
118        let top = |name: &[u8]| top(sprite, name, meter);
119        let pixels_to_units = top(b"m_PixelsToUnits")?
120            .and_then(Value::as_f64)
121            .ok_or(SpriteError::Malformed("m_PixelsToUnits"))?;
122        let rd = top(b"m_RD")?.ok_or(SpriteError::Malformed("m_RD"))?;
123        let rd = render_data(sprite, rd, "m_RD", meter)?;
124        let sprite_atlas = match top(b"m_SpriteAtlas")? {
125            None => None,
126            Some(v) => {
127                Some(pptr(sprite, v, meter)?.ok_or(SpriteError::Malformed("m_SpriteAtlas"))?)
128            }
129        };
130        let atlas_tag = match top(b"m_AtlasTags")? {
131            None => None,
132            Some(Value::List(items)) => {
133                for v in items {
134                    meter.count_decode(1)?;
135                    if v.as_bytes().is_none() {
136                        return Err(SpriteError::Malformed("m_AtlasTags"));
137                    }
138                }
139                items.first().and_then(Value::as_bytes)
140            }
141            Some(_) => return Err(SpriteError::Malformed("m_AtlasTags")),
142        };
143        let render_data_key = match top(b"m_RenderDataKey")? {
144            None => None,
145            Some(v) => {
146                Some(key(sprite, v, meter)?.ok_or(SpriteError::Malformed("m_RenderDataKey"))?)
147            }
148        };
149        Ok(Self {
150            pixels_to_units,
151            rd,
152            sprite_atlas,
153            atlas_tag,
154            render_data_key,
155        })
156    }
157
158    /// The render data `rd` (the Sprite's own or its atlas's) with the
159    /// Sprite's `m_PixelsToUnits`.
160    #[must_use]
161    pub fn data(&self, rd: &RenderData) -> SpriteData {
162        SpriteData {
163            texture_rect: rd.texture_rect,
164            settings_raw: rd.settings_raw,
165            pixels_to_units: self.pixels_to_units,
166        }
167    }
168}
169
170/// The render data `get_image_from_sprite` renders `sprite` from (module
171/// docs, `:63-81`): `deref` resolves `m_SpriteAtlas` where it is set
172/// (`None`, no object, is [`SpriteError::AtlasUnresolved`]); else, where
173/// the Sprite has an atlas tag, `file_atlases` lists the file's
174/// `SpriteAtlas` objects in its order, each as its name (`peek_name`) and a
175/// parse of it, which is called only for the first whose name is the tag;
176/// else, or with no atlas found, the Sprite's own `m_RD`. Each atlas
177/// compared counts one unit of `meter`'s decode work, and as many more as
178/// the bytes its name's comparison with the tag may read (`compared`),
179/// before it is compared; [`atlas_render_data`] counts its own (module
180/// docs).
181pub fn select_render_data<'a, D, I, F>(
182    sprite: &SpriteFields<'_>,
183    deref: D,
184    file_atlases: I,
185    meter: &Arc<Meter>,
186) -> Result<RenderData, SpriteError>
187where
188    D: FnOnce(Pptr) -> Option<&'a Parsed>,
189    I: IntoIterator<Item = (&'a [u8], F)>,
190    F: FnOnce() -> Option<&'a Parsed>,
191{
192    let key = sprite.render_data_key.as_ref();
193    if let Some(p) = sprite.sprite_atlas.filter(Pptr::is_set) {
194        let atlas = deref(p).ok_or(SpriteError::AtlasUnresolved)?;
195        return atlas_render_data(atlas, key, meter);
196    }
197    if let Some(tag) = sprite.atlas_tag {
198        for (name, parse) in file_atlases {
199            meter.count_decode(compared(name, tag))?;
200            if name == tag {
201                let atlas = parse().ok_or(SpriteError::AtlasUnresolved)?;
202                return atlas_render_data(atlas, key, meter);
203            }
204        }
205    }
206    Ok(sprite.rd)
207}
208
209/// The `SpriteAtlasData` of `atlas`'s `m_RenderDataMap` whose key is `key`
210/// (`next(value for key, value in ...)`, `:78`): the first such entry, or
211/// [`SpriteError::NoAtlasData`] where none is. A Sprite with no
212/// `m_RenderDataKey` compares `None` with every key, which matches none.
213/// Each entry counts one unit of `meter`'s decode work before it is read,
214/// and each field lookup its own (module docs): the atlas's fields walked
215/// to `m_RenderDataMap`, each key's to its words.
216pub fn atlas_render_data(
217    atlas: &Parsed,
218    key: Option<&AtlasKey>,
219    meter: &Arc<Meter>,
220) -> Result<RenderData, SpriteError> {
221    let map =
222        top(atlas, b"m_RenderDataMap", meter)?.ok_or(SpriteError::Malformed("m_RenderDataMap"))?;
223    let Value::List(entries) = map else {
224        return Err(SpriteError::Malformed("m_RenderDataMap"));
225    };
226    for entry in entries {
227        meter.count_decode(1)?;
228        let Value::Tuple(pair) = entry else {
229            return Err(SpriteError::Malformed("m_RenderDataMap"));
230        };
231        let (Some(k), Some(v)) = (pair.first(), pair.get(1)) else {
232            return Err(SpriteError::Malformed("m_RenderDataMap"));
233        };
234        let k = self::key(atlas, k, meter)?.ok_or(SpriteError::Malformed("m_RenderDataMap"))?;
235        if Some(&k) == key {
236            return render_data(atlas, v, "m_RenderDataMap", meter);
237        }
238    }
239    Err(SpriteError::NoAtlasData)
240}
241
242fn render_data(
243    parsed: &Parsed,
244    v: &Value,
245    what: &'static str,
246    meter: &Meter,
247) -> Result<RenderData, SpriteError> {
248    let Value::Dict(m) = v else {
249        return Err(SpriteError::Malformed(what));
250    };
251    let field = |name: &[u8]| field(parsed, m, name, meter);
252    let texture = match field(b"texture")? {
253        Some(t) => pptr(parsed, t, meter)?,
254        None => None,
255    }
256    .ok_or(SpriteError::Malformed(what))?;
257    let alpha_texture = match field(b"alphaTexture")? {
258        None => None,
259        Some(t) => Some(pptr(parsed, t, meter)?.ok_or(SpriteError::Malformed(what))?),
260    };
261    let rect = field(b"textureRect")?
262        .and_then(Value::as_dict)
263        .ok_or(SpriteError::Malformed(what))?;
264    let mut texture_rect = [0.0; 4];
265    for (out, name) in texture_rect
266        .iter_mut()
267        .zip([&b"x"[..], b"y", b"width", b"height"])
268    {
269        *out = self::field(parsed, rect, name, meter)?
270            .and_then(Value::as_f64)
271            .ok_or(SpriteError::Malformed(what))?;
272    }
273    let settings_raw = field(b"settingsRaw")?
274        .and_then(Value::as_u64)
275        .ok_or(SpriteError::Malformed(what))?;
276    Ok(RenderData {
277        texture,
278        alpha_texture,
279        texture_rect,
280        settings_raw,
281    })
282}
283
284/// A `PPtr`'s ids, or `Ok(None)` where `v` is no `PPtr`.
285fn pptr(parsed: &Parsed, v: &Value, meter: &Meter) -> Result<Option<Pptr>, SpriteError> {
286    let Some(m) = v.as_dict() else {
287        return Ok(None);
288    };
289    let id =
290        |name: &[u8]| Ok::<_, SpriteError>(field(parsed, m, name, meter)?.and_then(Value::as_i64));
291    let (Some(file_id), Some(path_id)) = (id(b"m_FileID")?, id(b"m_PathID")?) else {
292        return Ok(None);
293    };
294    Ok(Some(Pptr { file_id, path_id }))
295}
296
297/// A `pair<GUID, SInt64>`, or `Ok(None)` where `v` is none.
298fn key(parsed: &Parsed, v: &Value, meter: &Meter) -> Result<Option<AtlasKey>, SpriteError> {
299    let Value::Tuple(pair) = v else {
300        return Ok(None);
301    };
302    let (Some(guid), Some(id)) = (
303        pair.first().and_then(Value::as_dict),
304        pair.get(1).and_then(Value::as_i64),
305    ) else {
306        return Ok(None);
307    };
308    let mut words = [0_u64; 4];
309    for (w, name) in words
310        .iter_mut()
311        .zip([&b"data[0]"[..], b"data[1]", b"data[2]", b"data[3]"])
312    {
313        let Some(word) = field(parsed, guid, name, meter)?.and_then(Value::as_u64) else {
314            return Ok(None);
315        };
316        *w = word;
317    }
318    Ok(Some(AtlasKey { guid: words, id }))
319}
320
321/// The work of comparing two names: one unit, and as many more as the bytes
322/// the comparison may read, which is every byte where their lengths are
323/// equal (a slice comparison reads none where they differ).
324fn compared(a: &[u8], b: &[u8]) -> u64 {
325    1 + if a.len() == b.len() {
326        a.len() as u64
327    } else {
328        0
329    }
330}
331
332/// [`Parsed::field`], metered: the value under `name` in `map`, each field
333/// walked to it (or past it, with none found) counted with its name's
334/// comparison ([`compared`]) before it is compared.
335fn field<'a>(
336    parsed: &'a Parsed,
337    map: &'a Map,
338    name: &[u8],
339    meter: &Meter,
340) -> Result<Option<&'a Value>, SpriteError> {
341    for (n, v) in parsed.entries(map) {
342        meter.count_decode(compared(n, name))?;
343        if n == name {
344            return Ok(Some(v));
345        }
346    }
347    Ok(None)
348}
349
350/// [`field`] of the root value of `parsed` (`parsed.get(&[name])`).
351fn top<'a>(
352    parsed: &'a Parsed,
353    name: &[u8],
354    meter: &Meter,
355) -> Result<Option<&'a Value>, SpriteError> {
356    match parsed.value() {
357        Value::Dict(m) => field(parsed, m, name, meter),
358        _ => Ok(None),
359    }
360}