unityrs-export 1.0.0

Unity asset exports beside the textures: sprites, the NGUI atlas cutter and its crops, and the UnityPy extractor tree.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! The NGUI atlas cutter (`docs/plans/extract.md` E21 to E26, X5;
//! `docs/BATCH_SPEC.md` sections 3, 4.3, 4.4 and 5), over one input's view.
//!
//! The cutter is one phase of an attempt the engine owns
//! (`docs/plans/batch.md` 2.6; [`seam`]). The engine registers the view
//! ([`register`]: X's own open on `M_X`, the private Environment, each
//! bundle's marked rows reached) and hands [`cut`] a [`Context`]: the
//! registered view, `M_X`, its hooks (the stop flag, the refusal count,
//! export work), the sink's prefix, the archives' member templates, the key
//! table and the sink. [`cut`] opens every top-level row of X's own handle
//! (section 3's selection), plans (4.4: names, the skips that need no
//! pixels, keys, in the textures, sprites, atlases order) and exports
//! (sprite groups, then sheet groups, then the other textures), handing
//! each output to the sink as it is made, and returns its skips (the
//! plan's and the export's apart), sheets and counts. Its reasons are
//! 9.3's, its details 7.3's, classified as 2.7's `classify` does
//! ([`classify`]). [`winners`] decides 4.5's steps 1 to 3 over several
//! inputs' cuts. The `sprites` kind (`outputs.sprites`, E17) is
//! [`sprites`]'s: one image per Sprite of the input's own files, rendered by
//! `unityrs_texture::sprite` from a sheet that may be in a dependency.
//!
//! Not here, being the engine's: staging, the peek pass, the attempt's
//! budget and its counts, the spool and a file's export work, the records'
//! files and 4.6.

mod attempt;
pub mod classify;
mod export;
mod kept;
pub mod keys;
mod plan;
#[cfg(feature = "gltf")]
mod prefab;
#[cfg(feature = "gltf")]
pub use prefab::failure::export as classify_gltf;
#[cfg(feature = "gltf")]
pub use prefab::{Prefabs, Selection, cut_prefabs};
pub mod read;
pub mod recognize;
pub mod register;
mod resource;
pub mod seam;
mod select;
mod sprites;
mod table;
pub mod winners;

use unityrs_core::limits::Charge;
use unityrs_core::{Bytes, RawStr};

pub use classify::{Class, Reason};
pub use keys::{KeyRule, KeyTable, Template, TemplateError, TemplateKind};
pub use register::{
    Admit, Bits, Data, PeekBits, Registration, Staged, peek, register, register_bytes, same_open,
};
pub use seam::{Context, Hooks, MemberTemplate, NoHooks, Registered};
pub use select::select_own;
pub use unityrs_texture::{Format, Formats, TEXTURE_FORMATS};
pub use winners::{Candidate, Decision, Prefer, Rule, decide};

/// What section 1.5's `atlases` (and `outputs.textures`) ask for.
#[derive(Clone, Debug)]
pub struct Options {
    /// `atlases.sprite_key`.
    pub sprite_key: Template,
    /// `atlases.json_key`.
    pub json_key: Template,
    /// `outputs.textures.key`, when textures are exported.
    pub texture_key: Option<Template>,
    /// `outputs.sprites.key`, when Sprites are exported (E17).
    pub sprites_key: Option<Template>,
    /// `atlases.script_classes`.
    pub script_classes: Vec<Vec<u8>>,
    /// `atlases.skip_name_suffixes`.
    pub skip_name_suffixes: Vec<Vec<u8>>,
    /// Whether atlases are cut (`atlases` present in the spec): without
    /// it, the plan's atlas stage does not run.
    pub atlases: bool,
    /// The formats a texture is exported in, a sheet's included
    /// (`outputs.formats`, `docs/BATCH_SPEC.md` 1.5 and section 3):
    /// [`Formats::V1`] for a version 1 spec.
    pub formats: Formats,
    /// Image writer for every texture, sprite and atlas crop.
    pub image: ImageEncoding,
}

/// Still-image writer; keys and archive member templates stay caller-controlled.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ImageEncoding {
    /// Pillow's default PNG.
    #[default]
    Png,
    /// Lossless PNG with zlib level 1 and fixed Sub filtering.
    PngFast,
    /// Lossy WebP with integer quality 0..=100, method 4, exact false.
    Webp { quality: u8 },
}
impl ImageEncoding {
    /// Writer name in the run manifest.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            Self::Png => "png",
            Self::PngFast => "png_fast",
            Self::Webp { .. } => "webp",
        }
    }
}

/// A bundle of the view: its spec id and its bytes.
#[derive(Clone, Debug)]
pub struct Member {
    /// Its id.
    pub id: String,
    /// Its bytes.
    pub data: Bytes,
}

/// One input's view (4.2): the input, and every other bundle of the view.
#[derive(Clone, Copy, Debug)]
pub struct View<'a> {
    /// The input, `X`.
    pub input: &'a Member,
    /// `view(X)` less `X`, in any order.
    pub members: &'a [Member],
}

/// An output's kind (7.3's `outputs.kind`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum OutputKind {
    /// `texture`.
    Texture,
    /// `sprite`: a Sprite's image (E17).
    Sprite,
    /// `atlas_json`.
    AtlasJson,
    /// `atlas_sprite`.
    AtlasSprite,
    /// `glb`.
    Glb,
}

impl OutputKind {
    /// Its name.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            Self::Texture => "texture",
            Self::Sprite => "sprite",
            Self::AtlasJson => "atlas_json",
            Self::AtlasSprite => "atlas_sprite",
            Self::Glb => "glb",
        }
    }
}

/// What a skip skips (7.3's `skips.output`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SkipOutput {
    /// `texture`.
    Texture,
    /// `sprite`: a Sprite's image.
    Sprite,
    /// `atlas_json`.
    AtlasJson,
    /// `atlas_sprite`.
    AtlasSprite,
    /// `atlas`: an atlas's JSON and crops together.
    Atlas,
    /// `glb`.
    Glb,
}

impl SkipOutput {
    /// Its name.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            Self::Texture => "texture",
            Self::Sprite => "sprite",
            Self::AtlasJson => "atlas_json",
            Self::AtlasSprite => "atlas_sprite",
            Self::Atlas => "atlas",
            Self::Glb => "glb",
        }
    }
}

/// An image output's source pixels, before encoding.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Picture {
    /// Its mode: `RGB` or `RGBA`.
    pub mode: &'static str,
    /// Its width.
    pub width: u32,
    /// Its height.
    pub height: u32,
    /// E20's visible hash.
    pub visible_hash: [u8; 32],
}

/// An archive member path an output's variables expand to (4.7): its
/// archive's index, and the path or why it is left out.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MemberPath {
    /// The archive's index.
    pub archive: usize,
    /// The path, or why it is left out (`unwritable_path(<rule>)`).
    pub path: Result<String, Rejected>,
}

/// A member path 2.3's rules leave out, as 2.8's `archive_members` row
/// records it: the rule, and the path as expanded (at most its first 1,025
/// bytes) under 7.3's text rule: cut to 1,024 bytes at a code point
/// boundary, each invalid byte U+FFFD, and whether it was cut (review
/// round 2's S5).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rejected {
    /// The rule it breaks.
    pub rule: KeyRule,
    /// The path, under the text rule.
    pub path: String,
    /// Whether the text rule cut it.
    pub cut: bool,
}

/// Stored row identity, separate from the resolved root and chosen key.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PrefabRow {
    pub file_index: u32,
    pub ordinal: u32,
    pub serialized_file: RawStr,
    pub path: Option<RawStr>,
    pub root: Option<(RawStr, i64)>,
}

#[derive(Debug)]
pub struct GlbDiagnostic {
    #[cfg(feature = "gltf")]
    pub resource: Option<unityrs_gltf::RendererResource>,
    pub key: String,
    pub node: usize,
    pub reason: &'static str,
}

/// An output the cut made, handed to the sink as it is made.
#[derive(Debug)]
pub struct Output {
    pub prefab: Option<PrefabRow>,
    /// Stable planning ordinal, independent of export grouping.
    pub plan_index: u64,
    /// Its key.
    pub key: String,
    /// Its kind.
    pub kind: OutputKind,
    /// Its unit key (4.5), or none.
    pub unit: Option<String>,
    /// Its object's SerializedFile, by its stored name.
    pub serialized_file: RawStr,
    /// Its object's path id (an atlas's outputs, the MonoBehaviour's; a
    /// Sprite's, the Sprite's).
    pub path_id: i64,
    /// An atlas sprite's index in `mSprites`.
    pub sprite: Option<usize>,
    /// The file: a PNG, or the atlas JSON.
    pub bytes: Vec<u8>,
    /// The bytes' MD5.
    pub md5: [u8; 16],
    /// A PNG's image; none for an atlas JSON.
    pub picture: Option<Picture>,
    /// Its archive member paths, expanded at the plan.
    pub members: Vec<MemberPath>,
    /// What `bytes`, its unit key and member paths are charged as, on the
    /// input's meter (E59), returned when the sink drops it.
    _charge: Option<Charge>,
}

/// A skip (7.3's `skips` row, but its input).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Skip {
    /// The object's SerializedFile.
    pub serialized_file: RawStr,
    /// The object's path id.
    pub path_id: i64,
    /// The object's class: UnityPy 1.25.2's `ClassIDType` name.
    pub class: String,
    /// What it skips.
    pub output: SkipOutput,
    /// An atlas sprite's index.
    pub sprite: Option<usize>,
    /// Why.
    pub reason: Reason,
}

/// The prefab's stored row accompanies its skip without growing 2D rows.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PrefabSkip {
    pub skip: Skip,
    pub row: PrefabRow,
}

/// How an atlas's sheet was found (section 5 step 2).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SheetBy {
    /// By its material's main-texture name.
    MaterialName,
    /// By the atlas's own name.
    AtlasName,
}

/// An atlas whose sheet was found: the atlas, how, and the texture.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SheetRow {
    /// The atlas's SerializedFile.
    pub atlas_file: RawStr,
    /// The atlas's path id.
    pub atlas_path_id: i64,
    /// How the texture was found.
    pub by: SheetBy,
    /// The texture's SerializedFile.
    pub texture_file: RawStr,
    /// The texture's path id.
    pub texture_path_id: i64,
}

/// What one input's cut records beside its outputs, which went to the
/// sink.
#[derive(Debug, Default)]
pub struct Cut {
    pub glb_diagnostics: Vec<GlbDiagnostic>,
    pub prefab_plan_skips: Vec<PrefabSkip>,
    pub prefab_export_skips: Vec<PrefabSkip>,
    /// The plan's skips, in plan order.
    pub plan_skips: Vec<Skip>,
    /// The export's skips, in export order; record order is the plan's,
    /// then these.
    pub export_skips: Vec<Skip>,
    /// `MonoBehaviour`s whose `m_Script` read failed (section 5).
    pub unresolved_scripts: u64,
    /// Every atlas whose sheet was found, in plan order.
    pub sheets: Vec<SheetRow>,
    /// The input's nested containers (`nested_container`), in directory
    /// order.
    pub nested_containers: Vec<RawStr>,
    /// What these records are charged as on `M_X` (their tables and
    /// strings), returned when the cut is dropped (review round 2's S3).
    _charge: Option<Charge>,
}

/// Why the input failed, or the run, or that the attempt stopped.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Failure {
    /// The input fails with this reason.
    Input(Reason),
    /// The run fails with this reason.
    Run(Reason),
    /// The run stopped (2.11): the attempt returned at its next check, its
    /// end message `Stopped`.
    Stopped,
}

impl From<Class> for Failure {
    /// A class as an input's failure: an object-level reason met where an
    /// object's skip is not the site (an open, a load) fails the input.
    fn from(c: Class) -> Self {
        match c {
            Class::Skip(r) | Class::Input(r) => Self::Input(r),
            Class::Run(r) => Self::Run(r),
        }
    }
}

/// Cuts one input inside the engine's attempt (`ctx`): selects over X's
/// own handle, plans and exports, every output to the sink. A failure the
/// site rules make the input's, or the run's, or a stop, ends the cut.
pub fn cut(ctx: Context<'_>, options: &Options) -> Result<Cut, Failure> {
    cut_inner(
        ctx,
        options,
        #[cfg(feature = "gltf")]
        None,
    )
}

fn cut_inner(
    ctx: Context<'_>,
    options: &Options,
    #[cfg(feature = "gltf")] mut prefabs: Option<Prefabs<'_, '_>>,
) -> Result<Cut, Failure> {
    let Context {
        registered,
        meter,
        input,
        hooks,
        max_evictions,
        prefix,
        members,
        keys,
        sink,
    } = ctx;
    let seam = seam::Seam {
        registered,
        meter,
        hooks,
        max_evictions,
        prefix,
        members,
    };
    seam.stop()?;
    let mut attempt = attempt::Attempt::new(seam, options, input, keys, sink)?;
    let files = attempt.select()?;
    let planned = attempt.plan(files.as_slice())?;
    #[cfg(feature = "gltf")]
    let prefab_plan = prefabs
        .as_mut()
        .map(|prefabs| attempt.plan_prefabs(files.as_slice(), planned.next_ordinal, prefabs))
        .transpose()?;
    attempt.export(&planned)?;
    #[cfg(feature = "gltf")]
    if let Some((prefabs, plan)) = prefabs.as_ref().zip(prefab_plan) {
        attempt.export_prefabs(prefabs, plan)?;
    }
    drop(planned);
    drop(files);
    Ok(attempt.finish())
}