Skip to main content

unityrs_testkit/ngui/
scenes.rs

1//! The NGUI scenes, one function each, and [`scenes`], which lists them by
2//! name for `tools/parity/ngui_scenes.py`.
3//!
4//! Each scene is a set of bundles with the `deps` a job spec would give them
5//! (`docs/BATCH_SPEC.md` 1.2), the inputs to cut, each over its own view
6//! (4.2), and the cutter's options (1.5's `atlases`, and `textures`'s key
7//! when the scene exports textures). Sheets are [`super::sheet`]s, so a
8//! test computes every crop's pixels from [`super::pixel`] by hand.
9
10use super::{
11    BuildError, Object, PropName, V, atlas, file, format, material, mono_behaviour, mono_script,
12    sheet, sprite, texture, vector,
13};
14use crate::env::{bundle, res_bytes};
15
16mod failures;
17mod outputs;
18mod recognition;
19mod shapes;
20mod sheets;
21mod winners;
22
23pub use failures::failure_scenes;
24
25pub use outputs::{
26    duplicates, floats, json_bytes, json_bytes_with_textures, non_ascii, sheet_texture_key_taken,
27    texture_key_is_json_key, two_atlases_one_sheet, two_atlases_without_textures, two_sheet_groups,
28};
29pub use recognition::{failed_reads, layouts};
30pub use shapes::{
31    bad_script_pointer, cleaned_names, list_pairs, long_keys, platform_blobs, raw_names,
32    wide_texture_fields,
33};
34pub use sheets::{
35    crop_bounds, failed_sheet_rows, fallback_rows, repeated_rows, sheet_skips, streamed_sheets,
36    webfile_sibling,
37};
38pub use winners::{textured_winners, winners};
39
40/// One bundle of a scene: its spec `id`, its bytes and its `deps`.
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct SceneBundle {
43    /// The spec `id`.
44    pub id: String,
45    /// The bundle's bytes.
46    pub data: Vec<u8>,
47    /// The spec `deps`.
48    pub deps: Vec<String>,
49}
50
51/// The cutter's options (`docs/BATCH_SPEC.md` 1.5), the sheet scope
52/// `own_files_by_name` being version 1's only one.
53#[derive(Clone, Debug, PartialEq, Eq)]
54pub struct CutOptions {
55    /// `atlases.sprite_key`.
56    pub sprite_key: String,
57    /// `atlases.json_key`.
58    pub json_key: String,
59    /// `textures.key`, when the scene exports textures.
60    pub texture_key: Option<String>,
61    /// `sprites.key`, when the scene exports Sprites.
62    pub sprites_key: Option<String>,
63    /// `atlases.script_classes`.
64    pub script_classes: Vec<String>,
65    /// `atlases.skip_name_suffixes`.
66    pub skip_name_suffixes: Vec<String>,
67}
68
69impl Default for CutOptions {
70    fn default() -> Self {
71        Self {
72            sprite_key: "{atlas}/{sprite}.png".to_owned(),
73            json_key: "{atlas}.json".to_owned(),
74            texture_key: None,
75            sprites_key: None,
76            script_classes: vec!["NGUIAtlas".to_owned()],
77            skip_name_suffixes: Vec::new(),
78        }
79    }
80}
81
82impl CutOptions {
83    /// The defaults, with textures exported under `key`.
84    #[must_use]
85    pub fn textures(key: &str) -> Self {
86        Self {
87            texture_key: Some(key.to_owned()),
88            ..Self::default()
89        }
90    }
91}
92
93/// A scene: bundles, the inputs cut (each over its view) and the options.
94#[derive(Clone, Debug, PartialEq, Eq)]
95pub struct AtlasScene {
96    /// The bundles, inputs and dependencies alike.
97    pub bundles: Vec<SceneBundle>,
98    /// The ids of the inputs, in the order a test cuts them.
99    pub inputs: Vec<String>,
100    /// The cutter's options.
101    pub options: CutOptions,
102}
103
104/// A scene's result.
105pub type Built = Result<AtlasScene, BuildError>;
106
107/// A scene's builder.
108pub(super) type Make = fn() -> Built;
109
110pub(super) fn one(id: &str, cabs: &[(&str, Vec<u8>)], deps: &[&str]) -> SceneBundle {
111    SceneBundle {
112        id: id.to_owned(),
113        data: bundle(cabs),
114        deps: deps.iter().map(|d| (*d).to_owned()).collect(),
115    }
116}
117
118pub(super) fn scene(bundles: Vec<SceneBundle>, inputs: &[&str], options: CutOptions) -> AtlasScene {
119    AtlasScene {
120        bundles,
121        inputs: inputs.iter().map(|i| (*i).to_owned()).collect(),
122        options,
123    }
124}
125
126/// One input, `x.bundle`, of one SerializedFile `cab`, with default options.
127pub(super) fn alone(cab: &str, objects: &[Object]) -> Built {
128    let data = file(&[], objects, true)?;
129    Ok(scene(
130        vec![one("x.bundle", &[(cab, data)], &[])],
131        &["x.bundle"],
132        CutOptions::default(),
133    ))
134}
135
136/// The atlas script every scene's atlases name, at path id 1.
137pub(super) const SCRIPT: (i32, i64) = (0, 1);
138
139pub(super) const NULL: (i32, i64) = (0, 0);
140
141pub(super) fn rgba(path_id: i64, name: &str, base: u8, w: u8, h: u8) -> Object {
142    let size = (i32::from(w), i32::from(h));
143    texture(
144        path_id,
145        name.as_bytes(),
146        format::RGBA32,
147        size,
148        sheet(base, w, h, false),
149    )
150}
151
152pub(super) fn plain(name: &str, rect: (i32, i32, i32, i32)) -> V {
153    sprite(name.as_bytes(), rect, [0; 8])
154}
155
156/// `v`, a struct, with `extra` fields after its own.
157pub(super) fn with(v: V, extra: Vec<(&str, V)>) -> V {
158    match v {
159        V::Struct(ty, mut fields) => {
160            fields.extend(extra.into_iter().map(|(n, f)| (n.to_owned(), f)));
161            V::Struct(ty, fields)
162        }
163        other => other,
164    }
165}
166
167/// An atlas with a null material, cutting the own texture of its name.
168pub(super) fn by_name(path_id: i64, name: &str, sprites: Vec<V>) -> Object {
169    atlas(path_id, name.as_bytes(), SCRIPT, NULL, sprites, Vec::new())
170}
171
172/// Step 1 by a plain-string `_MainTex`, in the atlas's own file. A texture
173/// named as the atlas comes first in object order, and loses to the
174/// material's. The sprites cover a crop inside the sheet, one past its right
175/// and bottom edges, one past its top-left, and two empty rectangles; the
176/// first has borders and paddings, which are not applied, and a `rotated`
177/// field is written as read.
178pub fn own_sheet_by_material_name() -> Built {
179    let trimmed = with(
180        sprite(b"a", (0, 0, 2, 2), [1, 2, 3, 4, 5, 6, 7, 8]),
181        vec![("rotated", V::Bool(true))],
182    );
183    let mut sprites = vec![trimmed];
184    for (name, rect) in [
185        ("b", (1, 2, 3, 2)),
186        ("edge", (3, 3, 2, 2)),
187        ("neg", (-1, -1, 2, 2)),
188        ("zero", (0, 0, 0, 2)),
189        ("negw", (2, 2, -1, 1)),
190    ] {
191        sprites.push(with(plain(name, rect), vec![("rotated", V::Bool(false))]));
192    }
193    alone(
194        "CAB-x1",
195        &[
196            mono_script(1, "NGUIAtlas"),
197            rgba(2, "ui", 0x90, 2, 2),
198            rgba(3, "sheet_a", 1, 4, 4),
199            material(
200                4,
201                "ui_mat",
202                PropName::Plain,
203                &[("_BumpMap", NULL), ("_MainTex", (0, 3))],
204            ),
205            atlas(5, b"ui", SCRIPT, (0, 4), sprites, Vec::new()),
206        ],
207    )
208}
209
210/// Step 1 by a `FastPropertyName` `_MainTex` whose texture is in a
211/// dependency: its name is read there, and matched among the input's own
212/// textures, where a texture of that name is the sheet (and a texture named
213/// as the atlas loses to it).
214pub fn struct_maintex_in_dependency() -> Built {
215    let dep = file(&[], &[rgba(10, "shared_sheet", 0x50, 1, 1)], true)?;
216    let cab = file(
217        &["archive:/CAB-d1/CAB-d1"],
218        &[
219            mono_script(1, "NGUIAtlas"),
220            material(2, "m", PropName::Fast, &[("_MainTex", (1, 10))]),
221            rgba(3, "shared_sheet", 0x30, 3, 3),
222            atlas(
223                4,
224                b"far",
225                SCRIPT,
226                (0, 2),
227                vec![plain("s", (0, 0, 3, 3))],
228                Vec::new(),
229            ),
230            rgba(5, "far", 0x70, 1, 1),
231        ],
232        true,
233    )?;
234    Ok(scene(
235        vec![
236            one("d.bundle", &[("CAB-d1", dep)], &[]),
237            one("x.bundle", &[("CAB-x2", cab)], &["d.bundle"]),
238        ],
239        &["x.bundle"],
240        CutOptions::default(),
241    ))
242}
243
244/// The material and its `_MainTex` texture both in a dependency: the name
245/// read there is none of the input's textures, so step 2 takes the texture
246/// named as the atlas, an RGB24 sheet, cropped past its edge.
247pub fn material_in_dependency() -> Built {
248    let dep = file(
249        &[],
250        &[
251            material(20, "m2", PropName::Plain, &[("_MainTex", (0, 21))]),
252            rgba(21, "only_in_dep", 0x60, 1, 1),
253        ],
254        true,
255    )?;
256    let sheet_b = texture(22, b"atlas_b", format::RGB24, (2, 2), sheet(5, 2, 2, true));
257    let cab = file(
258        &["archive:/CAB-d2/CAB-d2"],
259        &[
260            mono_script(1, "NGUIAtlas"),
261            atlas(
262                2,
263                b"atlas_b",
264                SCRIPT,
265                (1, 20),
266                vec![plain("wide", (1, 0, 3, 3)), plain("in", (0, 1, 2, 1))],
267                Vec::new(),
268            ),
269            sheet_b,
270        ],
271        true,
272    )?;
273    Ok(scene(
274        vec![
275            one("d.bundle", &[("CAB-d2", dep)], &[]),
276            one("x.bundle", &[("CAB-x3", cab)], &["d.bundle"]),
277        ],
278        &["x.bundle"],
279        CutOptions::default(),
280    ))
281}
282
283/// A null material gives no name, so step 2 takes the texture named as the
284/// atlas; `skip_name_suffixes` `["_ref"]` skips the reference atlas; a null
285/// material with no texture of the atlas's name is `sheet_not_found`; and an
286/// atlas with no `material` field at all gives no name either, so step 2
287/// takes the texture of its name.
288pub fn null_material_and_reference() -> Built {
289    let one_sprite = || vec![plain("p", (0, 0, 2, 1))];
290    let no_field = mono_behaviour(
291        6,
292        b"nomat",
293        SCRIPT,
294        vec![
295            (
296                "mSprites",
297                vector(plain("q", (0, 0, 1, 1)), vec![plain("q", (0, 0, 1, 1))]),
298            ),
299            ("mPixelSize", V::Float(1.0)),
300        ],
301    );
302    let mut built = alone(
303        "CAB-x4",
304        &[
305            mono_script(1, "NGUIAtlas"),
306            rgba(2, "plain", 7, 2, 1),
307            by_name(3, "plain", one_sprite()),
308            by_name(4, "plain_ref", one_sprite()),
309            by_name(5, "lost", one_sprite()),
310            no_field,
311            rgba(7, "nomat", 0x0B, 1, 1),
312        ],
313    )?;
314    built.options.skip_name_suffixes = vec!["_ref".to_owned()];
315    Ok(built)
316}
317
318/// Every way step 1 gives no name, each atlas then cutting the own texture
319/// of its name (step 2): no `_MainTex` pair (n1, whose `_BumpMap` names an
320/// own texture, which a cutter taking the first pair would find), a
321/// material in a CAB outside the view (n2), a missing object (n3), a null
322/// `m_Texture` (n4), an `m_FileID` past the externals (n5), a `_MainTex`
323/// texture, read in a dependency, whose name no own texture has (n6), a
324/// pointer into the input's raw `.resS` row (n7), and a CAB outside the view
325/// whose name is a directory at the root of a Linux host (n8), which
326/// UnityPy's own lookup would try to open. And n9, whose material pointer's
327/// `m_FileID` is -2: it counts from the end of the four externals, as
328/// UnityPy's `PPtr.deref` indexes them, to `CAB-d5`, whose material names
329/// `far`, so n9 cuts the own texture `far` (step 1), not its own name's.
330pub fn missing_sheets() -> Built {
331    let one_sprite = || vec![plain("p", (0, 0, 1, 1))];
332    let dep = file(
333        &[],
334        &[
335            rgba(1, "elsewhere", 0x21, 1, 1),
336            material(2, "dmat", PropName::Plain, &[("_MainTex", (0, 3))]),
337            rgba(3, "far", 0x22, 1, 1),
338        ],
339        true,
340    )?;
341    let mut objects = vec![
342        mono_script(1, "NGUIAtlas"),
343        material(2, "no_main", PropName::Plain, &[("_BumpMap", (0, 4))]),
344        material(3, "null_tex", PropName::Plain, &[("_MainTex", NULL)]),
345        rgba(4, "bump", 3, 1, 1),
346        material(5, "named", PropName::Plain, &[("_MainTex", (2, 1))]),
347    ];
348    let materials = [
349        (0, 2),
350        (1, 99),
351        (0, 98),
352        (0, 3),
353        (5, 2),
354        (0, 5),
355        (3, 1),
356        (4, 1),
357    ];
358    for (n, at) in (1u8..).zip(materials) {
359        let name = format!("n{n}");
360        let path_id = 9 + i64::from(n);
361        objects.push(atlas(
362            path_id,
363            name.as_bytes(),
364            SCRIPT,
365            at,
366            one_sprite(),
367            Vec::new(),
368        ));
369        objects.push(rgba(path_id + 10, &name, 0x30 + n, 1, 1));
370    }
371    objects.push(atlas(18, b"n9", SCRIPT, (-2, 2), one_sprite(), Vec::new()));
372    objects.push(rgba(28, "n9", 0x39, 1, 1));
373    objects.push(rgba(29, "far", 0x3A, 1, 1));
374    let externals = [
375        "archive:/CAB-gone/CAB-gone",
376        "archive:/CAB-d5/CAB-d5",
377        "archive:/CAB-x5/CAB-x5.resS",
378        "archive:/etc/etc",
379    ];
380    let cab = file(&externals, &objects, true)?;
381    Ok(scene(
382        vec![
383            one("d.bundle", &[("CAB-d5", dep)], &[]),
384            one(
385                "x.bundle",
386                &[("CAB-x5", cab), ("CAB-x5.resS", res_bytes(16, 0))],
387                &["d.bundle"],
388            ),
389        ],
390        &["x.bundle"],
391        CutOptions::default(),
392    ))
393}
394
395/// Every scene, by name.
396pub fn scenes() -> Result<Vec<(&'static str, AtlasScene)>, BuildError> {
397    let all: [(&'static str, Make); 33] = [
398        ("own_sheet_by_material_name", own_sheet_by_material_name),
399        ("struct_maintex_in_dependency", struct_maintex_in_dependency),
400        ("material_in_dependency", material_in_dependency),
401        ("null_material_and_reference", null_material_and_reference),
402        ("missing_sheets", missing_sheets),
403        ("duplicates", duplicates),
404        ("two_atlases_one_sheet", two_atlases_one_sheet),
405        ("two_atlases_without_textures", two_atlases_without_textures),
406        ("sheet_texture_key_taken", sheet_texture_key_taken),
407        ("texture_key_is_json_key", texture_key_is_json_key),
408        ("two_sheet_groups", two_sheet_groups),
409        ("json_bytes", json_bytes),
410        ("json_bytes_with_textures", json_bytes_with_textures),
411        ("floats", floats),
412        ("non_ascii", non_ascii),
413        ("layouts", layouts),
414        ("failed_reads", failed_reads),
415        ("sheet_skips", sheet_skips),
416        ("streamed_sheets", streamed_sheets),
417        ("repeated_rows", repeated_rows),
418        ("fallback_rows", fallback_rows),
419        ("crop_bounds", crop_bounds),
420        ("failed_sheet_rows", failed_sheet_rows),
421        ("winners", winners),
422        ("textured_winners", textured_winners),
423        ("webfile_sibling", webfile_sibling),
424        ("cleaned_names", cleaned_names),
425        ("wide_texture_fields", wide_texture_fields),
426        ("platform_blobs", platform_blobs),
427        ("list_pairs", list_pairs),
428        ("bad_script_pointer", bad_script_pointer),
429        ("raw_names", raw_names),
430        ("long_keys", long_keys),
431    ];
432    all.into_iter().map(|(name, f)| Ok((name, f()?))).collect()
433}