unityripper 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,500 @@
1
+ from __future__ import annotations
2
+
3
+ import struct
4
+ import zlib
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import Any, Iterable, Sequence
8
+
9
+ from ..materials import MaterialData
10
+ from ..mathutil import Mat4, IDENTITY, det3, scale_matrix, transform_normal, transform_point
11
+ from ..scene import MeshAsset, MeshData, RendererModel
12
+ from ..textures import TextureAsset, TextureStore
13
+ from ..util import format_size, log, sanitize_filename
14
+ from .common import (
15
+ ExportOptions,
16
+ compute_normals,
17
+ flatten_triangles,
18
+ material_key,
19
+ needs_winding_reverse,
20
+ renderer_stem,
21
+ srgb_tuple,
22
+ texture_relpath,
23
+ usable_normals,
24
+ )
25
+
26
+ FBX_VERSION = 7400
27
+ _HEAD_MAGIC = b"Kaydara FBX Binary \x00\x1a\x00"
28
+ _FOOT_ID = b"\xfa\xbc\xab\x09\xd0\xc8\xd4\x66\xb1\x76\xfb\x83\x1c\xf7\x26\x7e"
29
+ _FOOT_MAGIC = b"\xf8\x5a\x8c\x6a\xde\xf5\xd9\x7e\xec\xe9\x0c\xe3\x75\x8f\x29\x0b"
30
+
31
+ @dataclass
32
+ class Node:
33
+ name: str
34
+ props: list[Any] = field(default_factory=list)
35
+ children: list["Node"] = field(default_factory=list)
36
+
37
+ def add(self, name: str, *props: Any) -> "Node":
38
+ child = Node(name, list(props))
39
+ self.children.append(child)
40
+ return child
41
+
42
+ def child(self, name: str) -> "Node":
43
+ node = Node(name)
44
+ self.children.append(node)
45
+ return node
46
+
47
+ @dataclass
48
+ class Array:
49
+
50
+ kind: str
51
+ values: Sequence[float] | Sequence[int]
52
+
53
+ def pack(self) -> bytes:
54
+ values = self.values
55
+ count = len(values)
56
+ if self.kind == "d":
57
+ raw = struct.pack(f"<{count}d", *values)
58
+ elif self.kind == "f":
59
+ raw = struct.pack(f"<{count}f", *values)
60
+ elif self.kind == "i":
61
+ raw = struct.pack(f"<{count}i", *values)
62
+ elif self.kind == "l":
63
+ raw = struct.pack(f"<{count}q", *values)
64
+ elif self.kind == "b":
65
+ raw = bytes(1 if value else 0 for value in values)
66
+ else:
67
+ raise ValueError(f"unsupported FBX array kind {self.kind!r}")
68
+ data = zlib.compress(raw, 6)
69
+ if len(data) < len(raw):
70
+ return self.kind.encode() + struct.pack("<III", count, 1, len(data)) + data
71
+ return self.kind.encode() + struct.pack("<III", count, 0, len(raw)) + raw
72
+
73
+ class Long(int):
74
+ pass
75
+
76
+ def pack_prop(value: Any) -> bytes:
77
+ if isinstance(value, bool):
78
+ return b"B" + (b"\x01" if value else b"\x00")
79
+ if isinstance(value, Long):
80
+ return b"L" + struct.pack("<q", value)
81
+ if isinstance(value, int):
82
+ if -(2**31) <= value < 2**31:
83
+ return b"I" + struct.pack("<i", value)
84
+ return b"L" + struct.pack("<q", value)
85
+ if isinstance(value, float):
86
+ return b"D" + struct.pack("<d", value)
87
+ if isinstance(value, str):
88
+ raw = value.encode("utf-8")
89
+ return b"S" + struct.pack("<I", len(raw)) + raw
90
+ if isinstance(value, Array):
91
+ return value.pack()
92
+ raise TypeError(f"cannot encode FBX property {type(value).__name__}")
93
+
94
+ def _write_node(fp, node: Node) -> None:
95
+ start = fp.tell()
96
+ name = node.name.encode("ascii")
97
+ fp.write(b"\x00" * (13 + len(name)))
98
+ body = b"".join(pack_prop(prop) for prop in node.props)
99
+ fp.write(body)
100
+ for child in node.children:
101
+ _write_node(fp, child)
102
+ if node.children:
103
+ fp.write(b"\x00" * 13)
104
+ end = fp.tell()
105
+ fp.seek(start)
106
+ fp.write(struct.pack("<IIIB", end, len(node.props), len(body), len(name)))
107
+ fp.write(name)
108
+ fp.seek(end)
109
+
110
+ def write_fbx(path: Path, root: list[Node]) -> Path:
111
+ path.parent.mkdir(parents=True, exist_ok=True)
112
+ with path.open("wb") as fp:
113
+ fp.write(_HEAD_MAGIC)
114
+ fp.write(struct.pack("<I", FBX_VERSION))
115
+ for node in root:
116
+ _write_node(fp, node)
117
+ fp.write(b"\x00" * 13)
118
+
119
+ fp.write(_FOOT_ID)
120
+ fp.write(b"\x00" * 4)
121
+ offset = fp.tell()
122
+ pad = ((offset + 15) & ~15) - offset
123
+ fp.write(b"\x00" * (pad if pad else 16))
124
+ fp.write(struct.pack("<I", FBX_VERSION))
125
+ fp.write(b"\x00" * 120)
126
+ fp.write(_FOOT_MAGIC)
127
+ return path
128
+
129
+ @dataclass
130
+ class _MaterialIds:
131
+ material_id: int
132
+ textures: list[int] = field(default_factory=list)
133
+
134
+ class FbxBuilder:
135
+ def __init__(self, output_file: Path, textures: TextureStore, options: ExportOptions):
136
+ self.output_file = output_file
137
+ self.base_dir = output_file.parent
138
+ self.textures = textures
139
+ self.options = options
140
+ self.objects: list[Node] = []
141
+ self.connections: list[Node] = []
142
+ self._materials: dict[tuple, _MaterialIds] = {}
143
+ self._used_models: set[str] = set()
144
+ self._next_id = 1_000_000
145
+ self._counts = {"Model": 0, "Geometry": 0, "Material": 0, "Texture": 0}
146
+
147
+ def _id(self) -> Long:
148
+ value = Long(self._next_id)
149
+ self._next_id += 1
150
+ return value
151
+
152
+ def _connect(self, kind: str, child: int, parent: int, prop: str | None = None) -> None:
153
+ props: list[Any] = [kind, Long(child), Long(parent)]
154
+ if prop is not None:
155
+ props.append(prop)
156
+ self.connections.append(Node("C", props))
157
+
158
+ def _add_texture(self, asset: TextureAsset) -> int | None:
159
+ rel = texture_relpath(asset.file, self.base_dir)
160
+ name = sanitize_filename(asset.file.stem, "texture", 60)
161
+ texture_id = self._id()
162
+
163
+ texture = Node("Texture", [texture_id, f"{name}\x00\x01Texture", ""])
164
+ texture.add("Type", "TextureVideoClip")
165
+ texture.add("Version", 202)
166
+ texture.add("TextureName", f"Texture::{name}")
167
+ texture.add("FileName", rel)
168
+ texture.add("RelativeFilename", rel)
169
+ texture.add("ModelUVTranslation", Array("d", [0.0, 0.0]))
170
+ texture.add("ModelUVScaling", Array("d", [1.0, 1.0]))
171
+ texture.add("Texture_Alpha_Source", "None")
172
+ texture.add("Cropping", Array("d", [0.0, 0.0, 0.0, 0.0]))
173
+ self.objects.append(texture)
174
+ self._counts["Texture"] += 1
175
+ return texture_id
176
+
177
+ def add_material(self, material: MaterialData) -> _MaterialIds:
178
+ key = material_key(material)
179
+ cached = self._materials.get(key)
180
+ if cached is not None:
181
+ return cached
182
+
183
+ mat_id = self._id()
184
+ name = sanitize_filename(material.name or "material", "material", 60)
185
+ r, g, b = srgb_tuple(material.base_color)
186
+ alpha = 1.0 if material.alpha_mode == "OPAQUE" else material.base_color[3]
187
+ er, eg, eb = srgb_tuple(material.emission_color)
188
+
189
+ node = Node("Material", [mat_id, f"{name}\x00\x01Material", ""])
190
+ node.add("Version", 102)
191
+ node.add("ShadingModel", "phong")
192
+ node.add("MultiLayer", 0)
193
+ props = node.child("Properties70")
194
+ props.add("P", "DiffuseColor", "Color", "", "A", float(r), float(g), float(b))
195
+ props.add("P", "DiffuseFactor", "Number", "", "A", 1.0)
196
+ props.add("P", "TransparencyFactor", "Number", "", "A", float(1.0 - alpha))
197
+ props.add("P", "Opacity", "Number", "", "A", float(alpha))
198
+ props.add("P", "EmissiveColor", "Color", "", "A", float(er), float(eg), float(eb))
199
+ props.add("P", "AmbientColor", "Color", "", "A", 0.0, 0.0, 0.0)
200
+ props.add("P", "SpecularColor", "Color", "", "A", 1.0, 1.0, 1.0)
201
+ props.add("P", "Shininess", "Number", "", "A", float(max(0.0, min(1.0, 1.0 - material.roughness)) * 100.0))
202
+ self.objects.append(node)
203
+ self._counts["Material"] += 1
204
+
205
+ ids = _MaterialIds(mat_id)
206
+ if self.textures.enabled:
207
+ for binding, role, link in (
208
+ (material.albedo, "albedo", "DiffuseColor"),
209
+ (material.normal, "normal", "NormalMap"),
210
+ (material.emission_map, "emission", "EmissiveColor"),
211
+ ):
212
+ if binding is None or binding.texture is None:
213
+ continue
214
+ hint = f"{name}_{role}"
215
+ try:
216
+ asset = self.textures.save(binding.texture, hint=hint, role=role)
217
+ except Exception as exc:
218
+ log.warning("texture %s failed: %s: %s", hint, type(exc).__name__, exc)
219
+ asset = None
220
+ if asset is None:
221
+ continue
222
+ texture_id = self._add_texture(asset)
223
+ if texture_id is None:
224
+ continue
225
+ ids.textures.append(texture_id)
226
+ self._connect("OP", texture_id, mat_id, link)
227
+
228
+ self._materials[key] = ids
229
+ return ids
230
+
231
+ def add_mesh(
232
+ self,
233
+ mesh: MeshData,
234
+ materials: Sequence[MaterialData],
235
+ name: str,
236
+ world: Mat4 = IDENTITY,
237
+ ) -> str | None:
238
+ if not mesh.vertices or mesh.triangle_count == 0:
239
+ return None
240
+ reverse = needs_winding_reverse(det3(world), self.options.mirror_x)
241
+ mirror = self.options.mirror_x
242
+ scale = self.options.scale
243
+
244
+ positions: list[tuple[float, float, float]] = []
245
+ for vertex in mesh.vertices:
246
+ p = transform_point(world, vertex)
247
+ if mirror:
248
+ p = (-p[0], p[1], p[2])
249
+ positions.append((p[0] * scale, p[1] * scale, p[2] * scale))
250
+
251
+ normals = usable_normals(mesh)
252
+ if normals is None:
253
+ normals = compute_normals(mesh.vertices, flatten_triangles(mesh))
254
+ transformed_normals: list[tuple[float, float, float]] = []
255
+ for normal in normals:
256
+ n = transform_normal(world, normal)
257
+ if mirror:
258
+ n = (-n[0], n[1], n[2])
259
+ transformed_normals.append(n)
260
+
261
+ polygon_indices: list[int] = []
262
+ polygon_normals: list[float] = []
263
+ polygon_uvs: list[int] = []
264
+ polygon_materials: list[int] = []
265
+
266
+ for sub_index, triangles in enumerate(mesh.triangles):
267
+ if not triangles:
268
+ continue
269
+ material_index = min(sub_index, len(materials) - 1) if materials else 0
270
+ for tri in triangles:
271
+ a, b, c = tri
272
+ if reverse:
273
+ b, c = c, b
274
+ polygon_indices.extend([a, b, -(c + 1)])
275
+ polygon_normals.extend(transformed_normals[a])
276
+ polygon_normals.extend(transformed_normals[b])
277
+ polygon_normals.extend(transformed_normals[c])
278
+ if mesh.uvs:
279
+ polygon_uvs.extend([a, b, c])
280
+ polygon_materials.append(material_index)
281
+
282
+ if not polygon_indices:
283
+ return None
284
+
285
+ geom_id = self._id()
286
+ model_id = self._id()
287
+ model_name = sanitize_filename(name, "mesh", 70)
288
+ base = model_name
289
+ i = 2
290
+ while model_name.lower() in self._used_models:
291
+ model_name = f"{base}_{i}"
292
+ i += 1
293
+ self._used_models.add(model_name.lower())
294
+
295
+ geometry = Node("Geometry", [geom_id, f"{model_name}\x00\x01Geometry", "Mesh"])
296
+ geometry.add("Vertices", Array("d", [value for point in positions for value in point]))
297
+ geometry.add("PolygonVertexIndex", Array("i", polygon_indices))
298
+ geometry.add("GeometryVersion", 124)
299
+
300
+ normal_layer = geometry.child("LayerElementNormal")
301
+ normal_layer.add("Version", 101)
302
+ normal_layer.add("Name", "")
303
+ normal_layer.add("MappingInformationType", "ByPolygonVertex")
304
+ normal_layer.add("ReferenceInformationType", "Direct")
305
+ normal_layer.add("Normals", Array("d", polygon_normals))
306
+
307
+ if mesh.uvs and polygon_uvs:
308
+ uv_layer = geometry.child("LayerElementUV")
309
+ uv_layer.add("Version", 101)
310
+ uv_layer.add("Name", "UVMap")
311
+ uv_layer.add("MappingInformationType", "ByPolygonVertex")
312
+ uv_layer.add("ReferenceInformationType", "IndexToDirect")
313
+ uv_layer.add("UV", Array("d", [value for uv in mesh.uvs for value in uv]))
314
+ uv_layer.add("UVIndex", Array("i", polygon_uvs))
315
+
316
+ if materials:
317
+ mat_layer = geometry.child("LayerElementMaterial")
318
+ mat_layer.add("Version", 101)
319
+ mat_layer.add("Name", "")
320
+ mat_layer.add("MappingInformationType", "ByPolygon")
321
+ mat_layer.add("ReferenceInformationType", "IndexToDirect")
322
+ mat_layer.add("Materials", Array("i", polygon_materials))
323
+
324
+ layer = geometry.child("Layer")
325
+ layer.add("Version", 100)
326
+ layer_types = ["LayerElementNormal"]
327
+ if mesh.uvs and polygon_uvs:
328
+ layer_types.append("LayerElementUV")
329
+ if materials:
330
+ layer_types.append("LayerElementMaterial")
331
+ for layer_type in layer_types:
332
+ item = layer.child("LayerElement")
333
+ item.add("Type", layer_type)
334
+ item.add("TypedIndex", 0)
335
+
336
+ self.objects.append(geometry)
337
+ self._counts["Geometry"] += 1
338
+
339
+ model = Node("Model", [model_id, f"{model_name}\x00\x01Model", "Mesh"])
340
+ model.add("Version", 232)
341
+ model_props = model.child("Properties70")
342
+ model_props.add("P", "Lcl Translation", "Lcl Translation", "", "A", 0.0, 0.0, 0.0)
343
+ model_props.add("P", "Lcl Rotation", "Lcl Rotation", "", "A", 0.0, 0.0, 0.0)
344
+ model_props.add("P", "Lcl Scaling", "Lcl Scaling", "", "A", 1.0, 1.0, 1.0)
345
+ model_props.add("P", "DefaultAttributeIndex", "int", "Integer", "", 0)
346
+ model.add("Culling", "CullingOff")
347
+ self.objects.append(model)
348
+ self._counts["Model"] += 1
349
+
350
+ self._connect("OO", geom_id, model_id)
351
+ self._connect("OO", model_id, 0)
352
+ for material in materials:
353
+ self._connect("OO", self.add_material(material).material_id, model_id)
354
+ return model_name
355
+
356
+ def write(self) -> Path:
357
+ header = Node("FBXHeaderExtension")
358
+ header.add("FBXHeaderVersion", 1003)
359
+ header.add("FBXVersion", FBX_VERSION)
360
+ stamp = header.child("CreationTimeStamp")
361
+ for key, value in (
362
+ ("Version", 1000),
363
+ ("Year", 2026),
364
+ ("Month", 11),
365
+ ("Day", 15),
366
+ ("Hour", 0),
367
+ ("Minute", 0),
368
+ ("Second", 0),
369
+ ("Millisecond", 0),
370
+ ):
371
+ stamp.add(key, value)
372
+ header.add("Creator", "UnityModelRipper")
373
+
374
+ settings = Node("GlobalSettings")
375
+ settings.add("Version", 1000)
376
+ props = settings.child("Properties70")
377
+ for name, value in (
378
+ ("UpAxis", 1),
379
+ ("UpAxisSign", 1),
380
+ ("FrontAxis", 2),
381
+ ("FrontAxisSign", 1),
382
+ ("CoordAxis", 0),
383
+ ("CoordAxisSign", 1),
384
+ ):
385
+ props.add("P", name, "int", "Integer", "", value)
386
+ props.add("P", "UnitScaleFactor", "double", "Number", "", 100.0)
387
+
388
+ documents = Node("Documents")
389
+ documents.add("Count", 1)
390
+ document = documents.child("Document")
391
+ document.props = [1_000_000_000, "Scene", "Scene"]
392
+ doc_props = document.child("Properties70")
393
+ doc_props.add("P", "SourceObject", "object", "", "")
394
+ doc_props.add("P", "ActiveAnimStackName", "KString", "", "", "")
395
+ document.add("RootNode", 0)
396
+
397
+ references = Node("References")
398
+
399
+ definitions = Node("Definitions")
400
+ definitions.add("Version", 100)
401
+ definitions.add("Count", 1 + sum(self._counts.values()))
402
+ global_type = definitions.child("ObjectType")
403
+ global_type.props = ["GlobalSettings"]
404
+ global_type.add("Count", 1)
405
+ for kind in ("Model", "Geometry", "Material", "Texture"):
406
+ count = self._counts[kind]
407
+ if not count:
408
+ continue
409
+ object_type = definitions.child("ObjectType")
410
+ object_type.props = [kind]
411
+ object_type.add("Count", count)
412
+
413
+ objects = Node("Objects")
414
+ objects.children = list(self.objects)
415
+
416
+ connections = Node("Connections")
417
+ connections.children = list(self.connections)
418
+
419
+ takes = Node("Takes")
420
+ takes.add("Current", "")
421
+
422
+ root = [header, settings, documents, references, definitions, objects, connections, takes]
423
+ write_fbx(self.output_file, root)
424
+ log.info("FBX %s (%s)", self.output_file.name, format_size(self.output_file.stat().st_size))
425
+ return self.output_file
426
+
427
+ def export_fbx_assets(
428
+ directory: Path,
429
+ assets: Sequence[MeshAsset],
430
+ textures: TextureStore,
431
+ options: ExportOptions,
432
+ ) -> list[tuple[str, Path]]:
433
+ directory.mkdir(parents=True, exist_ok=True)
434
+ written: list[tuple[str, Path]] = []
435
+ used: set[str] = set()
436
+ for asset in assets:
437
+ stem = sanitize_filename(asset.name, "model")
438
+ candidate = stem
439
+ n = 2
440
+ while candidate.lower() in used:
441
+ candidate = f"{stem}_{n}"
442
+ n += 1
443
+ used.add(candidate.lower())
444
+ try:
445
+ builder = FbxBuilder(directory / f"{candidate}.fbx", textures, options)
446
+ matrix = asset.matrix if asset.matrix != IDENTITY else scale_matrix(asset.scale)
447
+ if builder.add_mesh(asset.mesh, asset.materials, asset.name, matrix) is None:
448
+ continue
449
+ written.append((asset.name, builder.write()))
450
+ except Exception as exc:
451
+ log.warning("FBX export failed for %s: %s: %s", asset.name, type(exc).__name__, exc)
452
+ return written
453
+
454
+ def export_fbx_scene(
455
+ path: Path,
456
+ models: Iterable[RendererModel],
457
+ textures: TextureStore,
458
+ options: ExportOptions,
459
+ scene_name: str = "scene",
460
+ ) -> Path | None:
461
+ builder = FbxBuilder(path, textures, options)
462
+ exported = 0
463
+ for model in models:
464
+ if model.mesh is None:
465
+ continue
466
+ if builder.add_mesh(model.mesh, model.materials, model.path or model.name, model.world) is not None:
467
+ exported += 1
468
+ if not exported:
469
+ log.warning("FBX scene skipped: no geometry")
470
+ return None
471
+ return builder.write()
472
+
473
+ def export_fbx_scene_split(
474
+ directory: Path,
475
+ models: Iterable[RendererModel],
476
+ textures: TextureStore,
477
+ options: ExportOptions,
478
+ ) -> list[tuple[RendererModel, Path]]:
479
+ directory.mkdir(parents=True, exist_ok=True)
480
+ written: list[tuple[RendererModel, Path]] = []
481
+ used: set[str] = set()
482
+ for model in models:
483
+ if model.mesh is None:
484
+ continue
485
+ stem = renderer_stem(model)
486
+ candidate = stem
487
+ n = 2
488
+ while candidate.lower() in used:
489
+ candidate = f"{stem}_{n}"
490
+ n += 1
491
+ used.add(candidate.lower())
492
+ try:
493
+ builder = FbxBuilder(directory / f"{candidate}.fbx", textures, options)
494
+ if builder.add_mesh(model.mesh, model.materials, model.path or model.name, model.world) is None:
495
+ continue
496
+ written.append((model, builder.write()))
497
+ except Exception as exc:
498
+ log.warning("FBX export failed for %s: %s: %s", model.path, type(exc).__name__, exc)
499
+ log.info("FBX scene split into %d file(s)", len(written))
500
+ return written