Skip to main content

unityrs_export/ngui/
recognize.rs

1//! Section 5's recognition 2: whether an atlas's typetree has an `mSprites`
2//! that UnityPy 1.25.2's `read_value` reads as a list of sprites, decided
3//! from the nodes alone, before any value is read.
4
5use unityrs_core::typetree::tree::py_kind_of;
6use unityrs_core::typetree::{Kind, NodeId, NodeList};
7
8/// Whether `FUNCTION_READ_MAP` (`helpers/TypeTreeHelper.py`) reads
9/// `ty`: the core's table of the kinds the pure-Python reader dispatches on
10/// ([`py_kind_of`]), its primitives, `string` and `TypelessData`.
11fn in_read_map(ty: &[u8]) -> bool {
12    is_integer(ty)
13        || matches!(
14            py_kind_of(ty),
15            Kind::F32 | Kind::F64 | Kind::Bool | Kind::Str | Kind::Bytes
16        )
17}
18
19/// Whether `ty` is an integer type of `FUNCTION_READ_MAP`.
20#[must_use]
21pub fn is_integer(ty: &[u8]) -> bool {
22    matches!(
23        py_kind_of(ty),
24        Kind::S8 | Kind::U8 | Kind::S16 | Kind::U16 | Kind::S32 | Kind::U32 | Kind::S64 | Kind::U64
25    )
26}
27
28/// Whether `read_value` reads `ty` by its own branch before the vector and
29/// class branches: `FUNCTION_READ_MAP`, `pair`, `ReferencedObject`.
30fn read_before_vector(ty: &[u8]) -> bool {
31    in_read_map(ty) || matches!(py_kind_of(ty), Kind::Pair | Kind::ReferencedObject)
32}
33
34/// The last child of `id` named `name`, raw: the one whose value a
35/// typetree's dict keeps under that name (`parse_as_dict`; review round 2's
36/// C2: an atlas is read as a dict, not an object).
37fn last_child(list: &NodeList, id: NodeId, name: &[u8]) -> Option<NodeId> {
38    list.children(id)
39        .iter()
40        .rev()
41        .find(|c| list.name(**c) == name)
42        .copied()
43}
44
45/// Whether `read_value` reads `id` as a vector: none of the earlier
46/// branches, and a first child of type `Array`.
47fn is_vector(list: &NodeList, id: NodeId) -> bool {
48    !read_before_vector(list.type_name(id))
49        && list
50            .children(id)
51            .first()
52            .is_some_and(|a| list.type_name(*a) == b"Array")
53}
54
55/// Recognition 2 over a typetree's nodes.
56#[must_use]
57pub fn has_sprite_list(list: &NodeList) -> bool {
58    let Some(sprites) = last_child(list, list.root(), b"mSprites") else {
59        return false;
60    };
61    if !is_vector(list, sprites) {
62        return false;
63    }
64    let Some(array) = list.children(sprites).first() else {
65        return false;
66    };
67    let Some(&element) = list.children(*array).get(1) else {
68        return false;
69    };
70    if read_before_vector(list.type_name(element)) || is_vector(list, element) {
71        return false;
72    }
73    let int = |name: &[u8]| {
74        last_child(list, element, name).is_some_and(|c| is_integer(list.type_name(c)))
75    };
76    int(b"x")
77        && int(b"y")
78        && int(b"width")
79        && int(b"height")
80        && last_child(list, element, b"name").is_some_and(|c| list.type_name(c) == b"string")
81}
82
83#[cfg(test)]
84mod tests {
85    use unityrs_core::typetree::{NodeList, NodeRow};
86
87    use super::{has_sprite_list, is_integer};
88
89    fn list(rows: &[(i32, &str, &str)]) -> NodeList {
90        NodeList::trusted(
91            rows.iter()
92                .map(|(l, t, n)| NodeRow::new(*l, *t, *n))
93                .collect(),
94        )
95        .unwrap()
96    }
97
98    fn atlas(element: &str, x: &str, extra: &[(i32, &str, &str)]) -> NodeList {
99        let mut rows = vec![
100            (0, "MonoBehaviour", "Base"),
101            (1, "vector", "mSprites"),
102            (2, "Array", "Array"),
103            (3, "int", "size"),
104            (3, element, "data"),
105            (4, "string", "name"),
106            (5, "Array", "Array"),
107            (6, "int", "size"),
108            (6, "char", "data"),
109            (4, x, "x"),
110            (4, "int", "y"),
111            (4, "SInt64", "width"),
112            (4, "UInt16", "height"),
113        ];
114        rows.extend_from_slice(extra);
115        list(&rows)
116    }
117
118    #[test]
119    fn a_struct_of_integer_rectangles_and_a_string_name_is_an_atlas() {
120        assert!(has_sprite_list(&atlas("UISpriteData", "int", &[])));
121        assert!(has_sprite_list(&atlas("PPtr<X>", "FileSize", &[])));
122    }
123
124    #[test]
125    fn other_shapes_are_not() {
126        assert!(!has_sprite_list(&atlas("UISpriteData", "float", &[])));
127        assert!(!has_sprite_list(&atlas("UISpriteData", "bool", &[])));
128        assert!(!has_sprite_list(&atlas("pair", "int", &[])));
129        assert!(!has_sprite_list(&atlas("string", "int", &[])));
130        // The last `x` decides: a later float `x` hides the int one.
131        assert!(!has_sprite_list(&atlas(
132            "UISpriteData",
133            "int",
134            &[(4, "float", "x")]
135        )));
136        // The last `mSprites` decides.
137        assert!(!has_sprite_list(&atlas(
138            "UISpriteData",
139            "int",
140            &[(1, "int", "mSprites")]
141        )));
142        // By raw name: an `x?` beside `x`, or an `mSprites?` beside
143        // `mSprites`, is another field.
144        assert!(has_sprite_list(&atlas(
145            "UISpriteData",
146            "int",
147            &[(4, "float", "x?"), (1, "int", "mSprites?")]
148        )));
149        // A `string` named mSprites reads as a string, not a vector.
150        let s = list(&[
151            (0, "MonoBehaviour", "Base"),
152            (1, "string", "mSprites"),
153            (2, "Array", "Array"),
154            (3, "int", "size"),
155            (3, "char", "data"),
156        ]);
157        assert!(!has_sprite_list(&s));
158        assert!(!has_sprite_list(&list(&[(0, "MonoBehaviour", "Base")])));
159    }
160
161    #[test]
162    fn integers_are_the_read_maps_less_five() {
163        for t in ["SInt8", "char", "Type*", "unsigned long long", "FileSize"] {
164            assert!(is_integer(t.as_bytes()), "{t}");
165        }
166        for t in ["float", "double", "bool", "string", "TypelessData", "Int"] {
167            assert!(!is_integer(t.as_bytes()), "{t}");
168        }
169    }
170}