unityrs_export/ngui/mod.rs
1//! The NGUI atlas cutter (`docs/plans/extract.md` E21 to E26, X5;
2//! `docs/BATCH_SPEC.md` sections 3, 4.3, 4.4 and 5), over one input's view.
3//!
4//! The cutter is one phase of an attempt the engine owns
5//! (`docs/plans/batch.md` 2.6; [`seam`]). The engine registers the view
6//! ([`register`]: X's own open on `M_X`, the private Environment, each
7//! bundle's marked rows reached) and hands [`cut`] a [`Context`]: the
8//! registered view, `M_X`, its hooks (the stop flag, the refusal count,
9//! export work), the sink's prefix, the archives' member templates, the key
10//! table and the sink. [`cut`] opens every top-level row of X's own handle
11//! (section 3's selection), plans (4.4: names, the skips that need no
12//! pixels, keys, in the textures, sprites, atlases order) and exports
13//! (sprite groups, then sheet groups, then the other textures), handing
14//! each output to the sink as it is made, and returns its skips (the
15//! plan's and the export's apart), sheets and counts. Its reasons are
16//! 9.3's, its details 7.3's, classified as 2.7's `classify` does
17//! ([`classify`]). [`winners`] decides 4.5's steps 1 to 3 over several
18//! inputs' cuts. The `sprites` kind (`outputs.sprites`, E17) is
19//! [`sprites`]'s: one image per Sprite of the input's own files, rendered by
20//! `unityrs_texture::sprite` from a sheet that may be in a dependency.
21//!
22//! Not here, being the engine's: staging, the peek pass, the attempt's
23//! budget and its counts, the spool and a file's export work, the records'
24//! files and 4.6.
25
26mod attempt;
27pub mod classify;
28mod export;
29mod kept;
30pub mod keys;
31mod plan;
32#[cfg(feature = "gltf")]
33mod prefab;
34#[cfg(feature = "gltf")]
35pub use prefab::failure::export as classify_gltf;
36#[cfg(feature = "gltf")]
37pub use prefab::{Prefabs, Selection, cut_prefabs};
38pub mod read;
39pub mod recognize;
40pub mod register;
41mod resource;
42pub mod seam;
43mod select;
44mod sprites;
45mod table;
46pub mod winners;
47
48use unityrs_core::limits::Charge;
49use unityrs_core::{Bytes, RawStr};
50
51pub use classify::{Class, Reason};
52pub use keys::{KeyRule, KeyTable, Template, TemplateError, TemplateKind};
53pub use register::{
54 Admit, Bits, Data, PeekBits, Registration, Staged, peek, register, register_bytes, same_open,
55};
56pub use seam::{Context, Hooks, MemberTemplate, NoHooks, Registered};
57pub use select::select_own;
58pub use unityrs_texture::{Format, Formats, TEXTURE_FORMATS};
59pub use winners::{Candidate, Decision, Prefer, Rule, decide};
60
61/// What section 1.5's `atlases` (and `outputs.textures`) ask for.
62#[derive(Clone, Debug)]
63pub struct Options {
64 /// `atlases.sprite_key`.
65 pub sprite_key: Template,
66 /// `atlases.json_key`.
67 pub json_key: Template,
68 /// `outputs.textures.key`, when textures are exported.
69 pub texture_key: Option<Template>,
70 /// `outputs.sprites.key`, when Sprites are exported (E17).
71 pub sprites_key: Option<Template>,
72 /// `atlases.script_classes`.
73 pub script_classes: Vec<Vec<u8>>,
74 /// `atlases.skip_name_suffixes`.
75 pub skip_name_suffixes: Vec<Vec<u8>>,
76 /// Whether atlases are cut (`atlases` present in the spec): without
77 /// it, the plan's atlas stage does not run.
78 pub atlases: bool,
79 /// The formats a texture is exported in, a sheet's included
80 /// (`outputs.formats`, `docs/BATCH_SPEC.md` 1.5 and section 3):
81 /// [`Formats::V1`] for a version 1 spec.
82 pub formats: Formats,
83 /// Image writer for every texture, sprite and atlas crop.
84 pub image: ImageEncoding,
85}
86
87/// Still-image writer; keys and archive member templates stay caller-controlled.
88#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
89pub enum ImageEncoding {
90 /// Pillow's default PNG.
91 #[default]
92 Png,
93 /// Lossless PNG with zlib level 1 and fixed Sub filtering.
94 PngFast,
95 /// Lossy WebP with integer quality 0..=100, method 4, exact false.
96 Webp { quality: u8 },
97}
98impl ImageEncoding {
99 /// Writer name in the run manifest.
100 #[must_use]
101 pub fn name(self) -> &'static str {
102 match self {
103 Self::Png => "png",
104 Self::PngFast => "png_fast",
105 Self::Webp { .. } => "webp",
106 }
107 }
108}
109
110/// A bundle of the view: its spec id and its bytes.
111#[derive(Clone, Debug)]
112pub struct Member {
113 /// Its id.
114 pub id: String,
115 /// Its bytes.
116 pub data: Bytes,
117}
118
119/// One input's view (4.2): the input, and every other bundle of the view.
120#[derive(Clone, Copy, Debug)]
121pub struct View<'a> {
122 /// The input, `X`.
123 pub input: &'a Member,
124 /// `view(X)` less `X`, in any order.
125 pub members: &'a [Member],
126}
127
128/// An output's kind (7.3's `outputs.kind`).
129#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
130pub enum OutputKind {
131 /// `texture`.
132 Texture,
133 /// `sprite`: a Sprite's image (E17).
134 Sprite,
135 /// `atlas_json`.
136 AtlasJson,
137 /// `atlas_sprite`.
138 AtlasSprite,
139 /// `glb`.
140 Glb,
141}
142
143impl OutputKind {
144 /// Its name.
145 #[must_use]
146 pub fn name(self) -> &'static str {
147 match self {
148 Self::Texture => "texture",
149 Self::Sprite => "sprite",
150 Self::AtlasJson => "atlas_json",
151 Self::AtlasSprite => "atlas_sprite",
152 Self::Glb => "glb",
153 }
154 }
155}
156
157/// What a skip skips (7.3's `skips.output`).
158#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
159pub enum SkipOutput {
160 /// `texture`.
161 Texture,
162 /// `sprite`: a Sprite's image.
163 Sprite,
164 /// `atlas_json`.
165 AtlasJson,
166 /// `atlas_sprite`.
167 AtlasSprite,
168 /// `atlas`: an atlas's JSON and crops together.
169 Atlas,
170 /// `glb`.
171 Glb,
172}
173
174impl SkipOutput {
175 /// Its name.
176 #[must_use]
177 pub fn name(self) -> &'static str {
178 match self {
179 Self::Texture => "texture",
180 Self::Sprite => "sprite",
181 Self::AtlasJson => "atlas_json",
182 Self::AtlasSprite => "atlas_sprite",
183 Self::Atlas => "atlas",
184 Self::Glb => "glb",
185 }
186 }
187}
188
189/// An image output's source pixels, before encoding.
190#[derive(Clone, Debug, PartialEq, Eq)]
191pub struct Picture {
192 /// Its mode: `RGB` or `RGBA`.
193 pub mode: &'static str,
194 /// Its width.
195 pub width: u32,
196 /// Its height.
197 pub height: u32,
198 /// E20's visible hash.
199 pub visible_hash: [u8; 32],
200}
201
202/// An archive member path an output's variables expand to (4.7): its
203/// archive's index, and the path or why it is left out.
204#[derive(Clone, Debug, PartialEq, Eq)]
205pub struct MemberPath {
206 /// The archive's index.
207 pub archive: usize,
208 /// The path, or why it is left out (`unwritable_path(<rule>)`).
209 pub path: Result<String, Rejected>,
210}
211
212/// A member path 2.3's rules leave out, as 2.8's `archive_members` row
213/// records it: the rule, and the path as expanded (at most its first 1,025
214/// bytes) under 7.3's text rule: cut to 1,024 bytes at a code point
215/// boundary, each invalid byte U+FFFD, and whether it was cut (review
216/// round 2's S5).
217#[derive(Clone, Debug, PartialEq, Eq)]
218pub struct Rejected {
219 /// The rule it breaks.
220 pub rule: KeyRule,
221 /// The path, under the text rule.
222 pub path: String,
223 /// Whether the text rule cut it.
224 pub cut: bool,
225}
226
227/// Stored row identity, separate from the resolved root and chosen key.
228#[derive(Clone, Debug, PartialEq, Eq)]
229pub struct PrefabRow {
230 pub file_index: u32,
231 pub ordinal: u32,
232 pub serialized_file: RawStr,
233 pub path: Option<RawStr>,
234 pub root: Option<(RawStr, i64)>,
235}
236
237#[derive(Debug)]
238pub struct GlbDiagnostic {
239 #[cfg(feature = "gltf")]
240 pub resource: Option<unityrs_gltf::RendererResource>,
241 pub key: String,
242 pub node: usize,
243 pub reason: &'static str,
244}
245
246/// An output the cut made, handed to the sink as it is made.
247#[derive(Debug)]
248pub struct Output {
249 pub prefab: Option<PrefabRow>,
250 /// Stable planning ordinal, independent of export grouping.
251 pub plan_index: u64,
252 /// Its key.
253 pub key: String,
254 /// Its kind.
255 pub kind: OutputKind,
256 /// Its unit key (4.5), or none.
257 pub unit: Option<String>,
258 /// Its object's SerializedFile, by its stored name.
259 pub serialized_file: RawStr,
260 /// Its object's path id (an atlas's outputs, the MonoBehaviour's; a
261 /// Sprite's, the Sprite's).
262 pub path_id: i64,
263 /// An atlas sprite's index in `mSprites`.
264 pub sprite: Option<usize>,
265 /// The file: a PNG, or the atlas JSON.
266 pub bytes: Vec<u8>,
267 /// The bytes' MD5.
268 pub md5: [u8; 16],
269 /// A PNG's image; none for an atlas JSON.
270 pub picture: Option<Picture>,
271 /// Its archive member paths, expanded at the plan.
272 pub members: Vec<MemberPath>,
273 /// What `bytes`, its unit key and member paths are charged as, on the
274 /// input's meter (E59), returned when the sink drops it.
275 _charge: Option<Charge>,
276}
277
278/// A skip (7.3's `skips` row, but its input).
279#[derive(Clone, Debug, PartialEq, Eq)]
280pub struct Skip {
281 /// The object's SerializedFile.
282 pub serialized_file: RawStr,
283 /// The object's path id.
284 pub path_id: i64,
285 /// The object's class: UnityPy 1.25.2's `ClassIDType` name.
286 pub class: String,
287 /// What it skips.
288 pub output: SkipOutput,
289 /// An atlas sprite's index.
290 pub sprite: Option<usize>,
291 /// Why.
292 pub reason: Reason,
293}
294
295/// The prefab's stored row accompanies its skip without growing 2D rows.
296#[derive(Clone, Debug, PartialEq, Eq)]
297pub struct PrefabSkip {
298 pub skip: Skip,
299 pub row: PrefabRow,
300}
301
302/// How an atlas's sheet was found (section 5 step 2).
303#[derive(Clone, Copy, Debug, PartialEq, Eq)]
304pub enum SheetBy {
305 /// By its material's main-texture name.
306 MaterialName,
307 /// By the atlas's own name.
308 AtlasName,
309}
310
311/// An atlas whose sheet was found: the atlas, how, and the texture.
312#[derive(Clone, Debug, PartialEq, Eq)]
313pub struct SheetRow {
314 /// The atlas's SerializedFile.
315 pub atlas_file: RawStr,
316 /// The atlas's path id.
317 pub atlas_path_id: i64,
318 /// How the texture was found.
319 pub by: SheetBy,
320 /// The texture's SerializedFile.
321 pub texture_file: RawStr,
322 /// The texture's path id.
323 pub texture_path_id: i64,
324}
325
326/// What one input's cut records beside its outputs, which went to the
327/// sink.
328#[derive(Debug, Default)]
329pub struct Cut {
330 pub glb_diagnostics: Vec<GlbDiagnostic>,
331 pub prefab_plan_skips: Vec<PrefabSkip>,
332 pub prefab_export_skips: Vec<PrefabSkip>,
333 /// The plan's skips, in plan order.
334 pub plan_skips: Vec<Skip>,
335 /// The export's skips, in export order; record order is the plan's,
336 /// then these.
337 pub export_skips: Vec<Skip>,
338 /// `MonoBehaviour`s whose `m_Script` read failed (section 5).
339 pub unresolved_scripts: u64,
340 /// Every atlas whose sheet was found, in plan order.
341 pub sheets: Vec<SheetRow>,
342 /// The input's nested containers (`nested_container`), in directory
343 /// order.
344 pub nested_containers: Vec<RawStr>,
345 /// What these records are charged as on `M_X` (their tables and
346 /// strings), returned when the cut is dropped (review round 2's S3).
347 _charge: Option<Charge>,
348}
349
350/// Why the input failed, or the run, or that the attempt stopped.
351#[derive(Clone, Debug, PartialEq, Eq)]
352pub enum Failure {
353 /// The input fails with this reason.
354 Input(Reason),
355 /// The run fails with this reason.
356 Run(Reason),
357 /// The run stopped (2.11): the attempt returned at its next check, its
358 /// end message `Stopped`.
359 Stopped,
360}
361
362impl From<Class> for Failure {
363 /// A class as an input's failure: an object-level reason met where an
364 /// object's skip is not the site (an open, a load) fails the input.
365 fn from(c: Class) -> Self {
366 match c {
367 Class::Skip(r) | Class::Input(r) => Self::Input(r),
368 Class::Run(r) => Self::Run(r),
369 }
370 }
371}
372
373/// Cuts one input inside the engine's attempt (`ctx`): selects over X's
374/// own handle, plans and exports, every output to the sink. A failure the
375/// site rules make the input's, or the run's, or a stop, ends the cut.
376pub fn cut(ctx: Context<'_>, options: &Options) -> Result<Cut, Failure> {
377 cut_inner(
378 ctx,
379 options,
380 #[cfg(feature = "gltf")]
381 None,
382 )
383}
384
385fn cut_inner(
386 ctx: Context<'_>,
387 options: &Options,
388 #[cfg(feature = "gltf")] mut prefabs: Option<Prefabs<'_, '_>>,
389) -> Result<Cut, Failure> {
390 let Context {
391 registered,
392 meter,
393 input,
394 hooks,
395 max_evictions,
396 prefix,
397 members,
398 keys,
399 sink,
400 } = ctx;
401 let seam = seam::Seam {
402 registered,
403 meter,
404 hooks,
405 max_evictions,
406 prefix,
407 members,
408 };
409 seam.stop()?;
410 let mut attempt = attempt::Attempt::new(seam, options, input, keys, sink)?;
411 let files = attempt.select()?;
412 let planned = attempt.plan(files.as_slice())?;
413 #[cfg(feature = "gltf")]
414 let prefab_plan = prefabs
415 .as_mut()
416 .map(|prefabs| attempt.plan_prefabs(files.as_slice(), planned.next_ordinal, prefabs))
417 .transpose()?;
418 attempt.export(&planned)?;
419 #[cfg(feature = "gltf")]
420 if let Some((prefabs, plan)) = prefabs.as_ref().zip(prefab_plan) {
421 attempt.export_prefabs(prefabs, plan)?;
422 }
423 drop(planned);
424 drop(files);
425 Ok(attempt.finish())
426}