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.
- unityripper/__init__.py +1 -0
- unityripper/__main__.py +3 -0
- unityripper/cli.py +591 -0
- unityripper/discovery.py +165 -0
- unityripper/exporters/__init__.py +5 -0
- unityripper/exporters/common.py +95 -0
- unityripper/exporters/fbx.py +500 -0
- unityripper/exporters/glb.py +654 -0
- unityripper/exporters/obj.py +293 -0
- unityripper/materials.py +230 -0
- unityripper/mathutil.py +133 -0
- unityripper/scene.py +720 -0
- unityripper/textures.py +321 -0
- unityripper/util.py +105 -0
- unityripper-1.0.0.dist-info/METADATA +10 -0
- unityripper-1.0.0.dist-info/RECORD +19 -0
- unityripper-1.0.0.dist-info/WHEEL +5 -0
- unityripper-1.0.0.dist-info/entry_points.txt +2 -0
- unityripper-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,654 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import struct
|
|
6
|
+
import sys
|
|
7
|
+
from array import array
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Iterable, Sequence
|
|
10
|
+
|
|
11
|
+
from ..materials import MaterialData, TextureBinding
|
|
12
|
+
from ..mathutil import Mat4, IDENTITY, mat4_to_gltf, transform_normal, transform_point
|
|
13
|
+
from ..scene import MeshAsset, MeshData, RendererModel
|
|
14
|
+
from ..textures import TextureAsset, TextureStore
|
|
15
|
+
from ..util import asset_file_of, format_size, log, object_path_id, sanitize_filename
|
|
16
|
+
from .common import (
|
|
17
|
+
ExportOptions,
|
|
18
|
+
compute_normals,
|
|
19
|
+
flatten_triangles,
|
|
20
|
+
material_key,
|
|
21
|
+
usable_normals,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
MAGIC = 0x46546C67
|
|
25
|
+
CHUNK_JSON = 0x4E4F534A
|
|
26
|
+
CHUNK_BIN = 0x004E4942
|
|
27
|
+
ARRAY_BUFFER = 34962
|
|
28
|
+
ELEMENT_ARRAY_BUFFER = 34963
|
|
29
|
+
|
|
30
|
+
def _f32(values: Iterable[float]) -> bytes:
|
|
31
|
+
data = array("f", (float(v) for v in values))
|
|
32
|
+
if sys.byteorder != "little":
|
|
33
|
+
data.byteswap()
|
|
34
|
+
return data.tobytes()
|
|
35
|
+
|
|
36
|
+
def _u32(values: Iterable[int]) -> bytes:
|
|
37
|
+
data = array("I", (int(v) for v in values))
|
|
38
|
+
if sys.byteorder != "little":
|
|
39
|
+
data.byteswap()
|
|
40
|
+
return data.tobytes()
|
|
41
|
+
|
|
42
|
+
def _u16(values: Iterable[int]) -> bytes:
|
|
43
|
+
data = array("H", (int(v) for v in values))
|
|
44
|
+
if sys.byteorder != "little":
|
|
45
|
+
data.byteswap()
|
|
46
|
+
return data.tobytes()
|
|
47
|
+
|
|
48
|
+
def _u8(values: Iterable[int]) -> bytes:
|
|
49
|
+
return bytes(max(0, min(255, int(v))) for v in values)
|
|
50
|
+
|
|
51
|
+
def _finite(value: float) -> float:
|
|
52
|
+
return float(value) if math.isfinite(float(value)) else 0.0
|
|
53
|
+
|
|
54
|
+
WRAP_MODES = {0: 10497, 1: 33071, 2: 33648, 3: 33648}
|
|
55
|
+
|
|
56
|
+
class GlbWriter:
|
|
57
|
+
def __init__(self, textures: TextureStore, options: ExportOptions):
|
|
58
|
+
self.textures = textures
|
|
59
|
+
self.options = options
|
|
60
|
+
self.bin = bytearray()
|
|
61
|
+
self.views: list[dict[str, Any]] = []
|
|
62
|
+
self.accessors: list[dict[str, Any]] = []
|
|
63
|
+
self.meshes: list[dict[str, Any]] = []
|
|
64
|
+
self.materials: list[dict[str, Any]] = []
|
|
65
|
+
self.textures_json: list[dict[str, Any]] = []
|
|
66
|
+
self.images: list[dict[str, Any]] = []
|
|
67
|
+
self.samplers: list[dict[str, Any]] = []
|
|
68
|
+
self.nodes: list[dict[str, Any]] = []
|
|
69
|
+
self.skins: list[dict[str, Any]] = []
|
|
70
|
+
self.extensions_used: set[str] = set()
|
|
71
|
+
self._image_cache: dict[Path, int] = {}
|
|
72
|
+
self._sampler_cache: dict[tuple[int, int], int] = {}
|
|
73
|
+
self._texture_cache: dict[tuple[int, int], int] = {}
|
|
74
|
+
self._material_cache: dict[tuple, int] = {}
|
|
75
|
+
self._mesh_cache: dict[tuple, int] = {}
|
|
76
|
+
self._material_names: set[str] = set()
|
|
77
|
+
self._mesh_names: set[str] = set()
|
|
78
|
+
|
|
79
|
+
def _add_view(self, data: bytes, target: int | None = None) -> int:
|
|
80
|
+
while len(self.bin) % 4:
|
|
81
|
+
self.bin.append(0)
|
|
82
|
+
offset = len(self.bin)
|
|
83
|
+
self.bin.extend(data)
|
|
84
|
+
view: dict[str, Any] = {"buffer": 0, "byteOffset": offset, "byteLength": len(data)}
|
|
85
|
+
if target is not None:
|
|
86
|
+
view["target"] = target
|
|
87
|
+
self.views.append(view)
|
|
88
|
+
return len(self.views) - 1
|
|
89
|
+
|
|
90
|
+
def _add_accessor(
|
|
91
|
+
self,
|
|
92
|
+
data: bytes,
|
|
93
|
+
component_type: int,
|
|
94
|
+
count: int,
|
|
95
|
+
type_: str,
|
|
96
|
+
target: int | None,
|
|
97
|
+
minimum: Sequence[float] | None = None,
|
|
98
|
+
maximum: Sequence[float] | None = None,
|
|
99
|
+
normalized: bool = False,
|
|
100
|
+
no_view: bool = False,
|
|
101
|
+
) -> int:
|
|
102
|
+
accessor: dict[str, Any] = {
|
|
103
|
+
"componentType": component_type,
|
|
104
|
+
"count": count,
|
|
105
|
+
"type": type_,
|
|
106
|
+
}
|
|
107
|
+
if not no_view:
|
|
108
|
+
accessor["bufferView"] = self._add_view(data, target)
|
|
109
|
+
if minimum is not None:
|
|
110
|
+
accessor["min"] = [round(float(v), 6) for v in minimum]
|
|
111
|
+
if maximum is not None:
|
|
112
|
+
accessor["max"] = [round(float(v), 6) for v in maximum]
|
|
113
|
+
if normalized:
|
|
114
|
+
accessor["normalized"] = True
|
|
115
|
+
self.accessors.append(accessor)
|
|
116
|
+
return len(self.accessors) - 1
|
|
117
|
+
|
|
118
|
+
def _add_image(self, asset: TextureAsset) -> tuple[int, int]:
|
|
119
|
+
image_index = self._image_cache.get(asset.file)
|
|
120
|
+
if image_index is None:
|
|
121
|
+
view = self._add_view(asset.png_bytes())
|
|
122
|
+
self.images.append(
|
|
123
|
+
{"bufferView": view, "mimeType": "image/png", "name": asset.name or asset.file.stem}
|
|
124
|
+
)
|
|
125
|
+
image_index = len(self.images) - 1
|
|
126
|
+
self._image_cache[asset.file] = image_index
|
|
127
|
+
|
|
128
|
+
sampler_key = (asset.wrap_u, asset.wrap_v)
|
|
129
|
+
sampler_index = self._sampler_cache.get(sampler_key)
|
|
130
|
+
if sampler_index is None:
|
|
131
|
+
sampler = {
|
|
132
|
+
"magFilter": 9729,
|
|
133
|
+
"minFilter": 9987,
|
|
134
|
+
"wrapS": WRAP_MODES.get(asset.wrap_u, 10497),
|
|
135
|
+
"wrapT": WRAP_MODES.get(asset.wrap_v, 10497),
|
|
136
|
+
}
|
|
137
|
+
self.samplers.append(sampler)
|
|
138
|
+
sampler_index = len(self.samplers) - 1
|
|
139
|
+
self._sampler_cache[sampler_key] = sampler_index
|
|
140
|
+
|
|
141
|
+
texture_key = (image_index, sampler_index)
|
|
142
|
+
texture_index = self._texture_cache.get(texture_key)
|
|
143
|
+
if texture_index is None:
|
|
144
|
+
self.textures_json.append(
|
|
145
|
+
{"sampler": sampler_index, "source": image_index, "name": asset.name or asset.file.stem}
|
|
146
|
+
)
|
|
147
|
+
texture_index = len(self.textures_json) - 1
|
|
148
|
+
self._texture_cache[texture_key] = texture_index
|
|
149
|
+
return texture_index, sampler_index
|
|
150
|
+
|
|
151
|
+
def _texture_info(self, binding: TextureBinding | None, hint: str, role: str) -> dict[str, Any] | None:
|
|
152
|
+
if binding is None or binding.texture is None or not self.textures.enabled:
|
|
153
|
+
return None
|
|
154
|
+
asset = self.textures.save(binding.texture, hint=hint, role=role)
|
|
155
|
+
if asset is None:
|
|
156
|
+
return None
|
|
157
|
+
index, _ = self._add_image(asset)
|
|
158
|
+
info: dict[str, Any] = {"index": index, "texCoord": 0}
|
|
159
|
+
scale = binding.scale
|
|
160
|
+
offset = binding.offset
|
|
161
|
+
if scale != (1.0, 1.0) or offset != (0.0, 0.0):
|
|
162
|
+
self.extensions_used.add("KHR_texture_transform")
|
|
163
|
+
info["extensions"] = {
|
|
164
|
+
"KHR_texture_transform": {
|
|
165
|
+
"offset": [round(offset[0], 6), round(1.0 - offset[1] - scale[1], 6)],
|
|
166
|
+
"scale": [round(scale[0], 6), round(scale[1], 6)],
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return info
|
|
170
|
+
|
|
171
|
+
def _unique_material_name(self, material: MaterialData) -> str:
|
|
172
|
+
from ..util import sanitize_filename
|
|
173
|
+
|
|
174
|
+
base = sanitize_filename(material.name or "material", "material", 64)
|
|
175
|
+
name = base
|
|
176
|
+
i = 2
|
|
177
|
+
while name in self._material_names:
|
|
178
|
+
name = f"{base}_{i}"
|
|
179
|
+
i += 1
|
|
180
|
+
self._material_names.add(name)
|
|
181
|
+
return name
|
|
182
|
+
|
|
183
|
+
def add_material(self, material: MaterialData) -> int:
|
|
184
|
+
key = material_key(material)
|
|
185
|
+
cached = self._material_cache.get(key)
|
|
186
|
+
if cached is not None:
|
|
187
|
+
return cached
|
|
188
|
+
|
|
189
|
+
name = self._unique_material_name(material)
|
|
190
|
+
pbr: dict[str, Any] = {
|
|
191
|
+
"baseColorFactor": [round(max(0.0, min(1.0, float(c))), 6) for c in material.base_color],
|
|
192
|
+
}
|
|
193
|
+
albedo = self._texture_info(material.albedo, f"{name}_albedo", "albedo")
|
|
194
|
+
if albedo is not None:
|
|
195
|
+
pbr["baseColorTexture"] = albedo
|
|
196
|
+
|
|
197
|
+
if material.metallic_map is not None and self.options.mr_mode != "off" and self.textures.enabled:
|
|
198
|
+
asset = self.textures.save_metallic_roughness(
|
|
199
|
+
material.metallic_map.texture, hint=name
|
|
200
|
+
)
|
|
201
|
+
if asset is not None:
|
|
202
|
+
index, _ = self._add_image(asset)
|
|
203
|
+
pbr["metallicRoughnessTexture"] = {"index": index, "texCoord": 0}
|
|
204
|
+
pbr["metallicFactor"] = 1.0
|
|
205
|
+
pbr["roughnessFactor"] = 1.0
|
|
206
|
+
else:
|
|
207
|
+
pbr["metallicFactor"] = material.metallic
|
|
208
|
+
pbr["roughnessFactor"] = material.roughness
|
|
209
|
+
else:
|
|
210
|
+
pbr["metallicFactor"] = round(material.metallic, 6)
|
|
211
|
+
pbr["roughnessFactor"] = round(material.roughness, 6)
|
|
212
|
+
|
|
213
|
+
result: dict[str, Any] = {"name": name, "pbrMetallicRoughness": pbr}
|
|
214
|
+
if material.alpha_mode != "OPAQUE":
|
|
215
|
+
result["alphaMode"] = material.alpha_mode
|
|
216
|
+
if material.alpha_mode == "MASK":
|
|
217
|
+
result["alphaCutoff"] = round(material.alpha_cutoff, 6)
|
|
218
|
+
if material.double_sided:
|
|
219
|
+
result["doubleSided"] = True
|
|
220
|
+
if material.unlit:
|
|
221
|
+
self.extensions_used.add("KHR_materials_unlit")
|
|
222
|
+
result.setdefault("extensions", {})["KHR_materials_unlit"] = {}
|
|
223
|
+
|
|
224
|
+
normal = self._texture_info(material.normal, f"{name}_normal", "normal")
|
|
225
|
+
if normal is not None:
|
|
226
|
+
bump = material.floats.get("_BumpScale", 1.0)
|
|
227
|
+
normal["scale"] = round(float(bump), 6)
|
|
228
|
+
result["normalTexture"] = normal
|
|
229
|
+
|
|
230
|
+
occlusion = self._texture_info(material.occlusion, f"{name}_occlusion", "albedo")
|
|
231
|
+
if occlusion is not None:
|
|
232
|
+
strength = material.floats.get("_OcclusionStrength", 1.0)
|
|
233
|
+
occlusion["strength"] = round(float(strength), 6)
|
|
234
|
+
result["occlusionTexture"] = occlusion
|
|
235
|
+
|
|
236
|
+
emission_info = self._texture_info(material.emission_map, f"{name}_emission", "albedo")
|
|
237
|
+
if emission_info is not None:
|
|
238
|
+
result["emissiveTexture"] = emission_info
|
|
239
|
+
emission = [max(0.0, min(1.0, float(c))) for c in material.emission_color]
|
|
240
|
+
if max(emission) > 0.001:
|
|
241
|
+
peak = max(emission)
|
|
242
|
+
if peak > 1.0:
|
|
243
|
+
emission = [c / peak for c in emission]
|
|
244
|
+
self.extensions_used.add("KHR_materials_emissive_strength")
|
|
245
|
+
result.setdefault("extensions", {})["KHR_materials_emissive_strength"] = {
|
|
246
|
+
"emissiveStrength": round(peak, 6)
|
|
247
|
+
}
|
|
248
|
+
result["emissiveFactor"] = [round(c, 6) for c in emission]
|
|
249
|
+
|
|
250
|
+
self.materials.append(result)
|
|
251
|
+
index = len(self.materials) - 1
|
|
252
|
+
self._material_cache[key] = index
|
|
253
|
+
return index
|
|
254
|
+
|
|
255
|
+
def _add_attribute(
|
|
256
|
+
self, values: Iterable[float], count: int, type_: str, target: int, minmax: bool = False
|
|
257
|
+
) -> int:
|
|
258
|
+
flat = [float(v) for v in values]
|
|
259
|
+
components = int(type_[-1]) if type_.startswith("VEC") else 1
|
|
260
|
+
minimum = maximum = None
|
|
261
|
+
if minmax:
|
|
262
|
+
minimum = [min(flat[i::components]) for i in range(components)]
|
|
263
|
+
maximum = [max(flat[i::components]) for i in range(components)]
|
|
264
|
+
return self._add_accessor(_f32(flat), 5126, count, type_, target, minimum, maximum)
|
|
265
|
+
|
|
266
|
+
def add_mesh(
|
|
267
|
+
self,
|
|
268
|
+
mesh: MeshData,
|
|
269
|
+
materials: Sequence[MaterialData],
|
|
270
|
+
name: str,
|
|
271
|
+
*,
|
|
272
|
+
skin: bool = False,
|
|
273
|
+
bone_count: int = 0,
|
|
274
|
+
) -> int | None:
|
|
275
|
+
key = (
|
|
276
|
+
mesh.key,
|
|
277
|
+
tuple(material_key(m) for m in materials),
|
|
278
|
+
bool(skin),
|
|
279
|
+
)
|
|
280
|
+
cached = self._mesh_cache.get(key)
|
|
281
|
+
if cached is not None:
|
|
282
|
+
return cached
|
|
283
|
+
|
|
284
|
+
if not mesh.vertices or mesh.triangle_count == 0:
|
|
285
|
+
return None
|
|
286
|
+
|
|
287
|
+
uv_flipped = [(uv[0], 1.0 - uv[1]) for uv in mesh.uvs] if mesh.uvs else None
|
|
288
|
+
attributes: dict[str, int] = {}
|
|
289
|
+
attributes["POSITION"] = self._add_attribute(
|
|
290
|
+
(c for v in mesh.vertices for c in v), len(mesh.vertices), "VEC3", ARRAY_BUFFER, minmax=True
|
|
291
|
+
)
|
|
292
|
+
normals = usable_normals(mesh)
|
|
293
|
+
if normals is None:
|
|
294
|
+
normals = compute_normals(mesh.vertices, flatten_triangles(mesh))
|
|
295
|
+
attributes["NORMAL"] = self._add_attribute(
|
|
296
|
+
(c for n in normals for c in n), len(normals), "VEC3", ARRAY_BUFFER
|
|
297
|
+
)
|
|
298
|
+
if uv_flipped:
|
|
299
|
+
attributes["TEXCOORD_0"] = self._add_attribute(
|
|
300
|
+
(c for uv in uv_flipped for c in uv), len(uv_flipped), "VEC2", ARRAY_BUFFER
|
|
301
|
+
)
|
|
302
|
+
if mesh.colors:
|
|
303
|
+
attributes["COLOR_0"] = self._add_attribute(
|
|
304
|
+
(c for col in mesh.colors for c in col), len(mesh.colors), "VEC4", ARRAY_BUFFER
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
if skin and mesh.joints and mesh.weights and bone_count > 0:
|
|
308
|
+
joint_values: list[int] = []
|
|
309
|
+
weight_values: list[float] = []
|
|
310
|
+
valid = True
|
|
311
|
+
for j, w in zip(mesh.joints, mesh.weights):
|
|
312
|
+
if any((int(x) < 0 or int(x) >= bone_count) for x in j):
|
|
313
|
+
valid = False
|
|
314
|
+
break
|
|
315
|
+
total = sum(max(0.0, float(x)) for x in w)
|
|
316
|
+
if total <= 0.0:
|
|
317
|
+
total = 1.0
|
|
318
|
+
joint_values.extend(int(x) for x in j)
|
|
319
|
+
weight_values.extend(max(0.0, float(x)) / total for x in w)
|
|
320
|
+
if valid:
|
|
321
|
+
max_joint = max(joint_values) if joint_values else 0
|
|
322
|
+
if max_joint < 256:
|
|
323
|
+
jdata = _u8(joint_values)
|
|
324
|
+
jtype = 5121
|
|
325
|
+
else:
|
|
326
|
+
jdata = _u16(joint_values)
|
|
327
|
+
jtype = 5123
|
|
328
|
+
attributes["JOINTS_0"] = self._add_accessor(
|
|
329
|
+
jdata, jtype, len(mesh.joints), "VEC4", ARRAY_BUFFER
|
|
330
|
+
)
|
|
331
|
+
attributes["WEIGHTS_0"] = self._add_accessor(
|
|
332
|
+
_f32(weight_values), 5126, len(mesh.joints), "VEC4", ARRAY_BUFFER
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
primitives: list[dict[str, Any]] = []
|
|
336
|
+
for sub_index, tris in enumerate(mesh.triangles):
|
|
337
|
+
if not tris:
|
|
338
|
+
continue
|
|
339
|
+
indices = [index for tri in tris for index in tri]
|
|
340
|
+
if max(indices) >= len(mesh.vertices):
|
|
341
|
+
continue
|
|
342
|
+
if len(mesh.vertices) <= 65535:
|
|
343
|
+
index_data = _u16(indices)
|
|
344
|
+
component = 5123
|
|
345
|
+
else:
|
|
346
|
+
index_data = _u32(indices)
|
|
347
|
+
component = 5125
|
|
348
|
+
index_accessor = self._add_accessor(
|
|
349
|
+
index_data, component, len(indices), "SCALAR", ELEMENT_ARRAY_BUFFER
|
|
350
|
+
)
|
|
351
|
+
material = materials[min(sub_index, len(materials) - 1)] if materials else None
|
|
352
|
+
primitive: dict[str, Any] = {
|
|
353
|
+
"attributes": attributes,
|
|
354
|
+
"indices": index_accessor,
|
|
355
|
+
"mode": 4,
|
|
356
|
+
}
|
|
357
|
+
if material is not None:
|
|
358
|
+
primitive["material"] = self.add_material(material)
|
|
359
|
+
primitives.append(primitive)
|
|
360
|
+
|
|
361
|
+
if not primitives:
|
|
362
|
+
return None
|
|
363
|
+
|
|
364
|
+
base = sanitize_filename(name, "mesh", 80)
|
|
365
|
+
unique = base
|
|
366
|
+
i = 2
|
|
367
|
+
while unique in self._mesh_names:
|
|
368
|
+
unique = f"{base}_{i}"
|
|
369
|
+
i += 1
|
|
370
|
+
self._mesh_names.add(unique)
|
|
371
|
+
self.meshes.append({"name": unique, "primitives": primitives})
|
|
372
|
+
index = len(self.meshes) - 1
|
|
373
|
+
self._mesh_cache[key] = index
|
|
374
|
+
return index
|
|
375
|
+
|
|
376
|
+
def add_node(
|
|
377
|
+
self,
|
|
378
|
+
name: str,
|
|
379
|
+
*,
|
|
380
|
+
translation: Sequence[float] | None = None,
|
|
381
|
+
rotation: Sequence[float] | None = None,
|
|
382
|
+
scale: Sequence[float] | None = None,
|
|
383
|
+
matrix: Mat4 | None = None,
|
|
384
|
+
mesh: int | None = None,
|
|
385
|
+
skin: int | None = None,
|
|
386
|
+
children: Sequence[int] | None = None,
|
|
387
|
+
) -> int:
|
|
388
|
+
node: dict[str, Any] = {"name": name}
|
|
389
|
+
if matrix is not None:
|
|
390
|
+
node["matrix"] = [round(_finite(v), 6) for v in mat4_to_gltf(matrix)]
|
|
391
|
+
if translation is not None:
|
|
392
|
+
node["translation"] = [round(_finite(v), 6) for v in translation]
|
|
393
|
+
if rotation is not None:
|
|
394
|
+
q = [round(_finite(v), 6) for v in rotation]
|
|
395
|
+
length = math.sqrt(sum(v * v for v in q))
|
|
396
|
+
if length > 1e-9:
|
|
397
|
+
q = [v / length for v in q]
|
|
398
|
+
else:
|
|
399
|
+
q = [0.0, 0.0, 0.0, 1.0]
|
|
400
|
+
node["rotation"] = q
|
|
401
|
+
if scale is not None:
|
|
402
|
+
node["scale"] = [round(_finite(v), 6) for v in scale]
|
|
403
|
+
if mesh is not None:
|
|
404
|
+
node["mesh"] = mesh
|
|
405
|
+
if skin is not None:
|
|
406
|
+
node["skin"] = skin
|
|
407
|
+
if children:
|
|
408
|
+
node["children"] = list(children)
|
|
409
|
+
self.nodes.append(node)
|
|
410
|
+
return len(self.nodes) - 1
|
|
411
|
+
|
|
412
|
+
def add_skin(self, joints: Sequence[int], bindposes: Sequence[Mat4]) -> int:
|
|
413
|
+
flat: list[float] = []
|
|
414
|
+
for matrix in bindposes:
|
|
415
|
+
flat.extend(mat4_to_gltf(matrix))
|
|
416
|
+
accessor = self._add_accessor(_f32(flat), 5126, len(bindposes), "MAT4", None)
|
|
417
|
+
self.skins.append({"joints": list(joints), "inverseBindMatrices": accessor})
|
|
418
|
+
return len(self.skins) - 1
|
|
419
|
+
|
|
420
|
+
def finish(self, path: Path, scene_name: str, roots: Sequence[int]) -> Path:
|
|
421
|
+
while len(self.bin) % 4:
|
|
422
|
+
self.bin.append(0)
|
|
423
|
+
document: dict[str, Any] = {
|
|
424
|
+
"asset": {"version": "2.0", "generator": "UnityModelRipper"},
|
|
425
|
+
"scene": 0,
|
|
426
|
+
"scenes": [{"name": scene_name, "nodes": list(roots)}],
|
|
427
|
+
"nodes": self.nodes,
|
|
428
|
+
}
|
|
429
|
+
if self.meshes:
|
|
430
|
+
document["meshes"] = self.meshes
|
|
431
|
+
if self.materials:
|
|
432
|
+
document["materials"] = self.materials
|
|
433
|
+
if self.textures_json:
|
|
434
|
+
document["textures"] = self.textures_json
|
|
435
|
+
if self.images:
|
|
436
|
+
document["images"] = self.images
|
|
437
|
+
if self.samplers:
|
|
438
|
+
document["samplers"] = self.samplers
|
|
439
|
+
if self.skins:
|
|
440
|
+
document["skins"] = self.skins
|
|
441
|
+
if self.accessors:
|
|
442
|
+
document["accessors"] = self.accessors
|
|
443
|
+
if self.views:
|
|
444
|
+
document["bufferViews"] = self.views
|
|
445
|
+
if self.bin:
|
|
446
|
+
document["buffers"] = [{"byteLength": len(self.bin)}]
|
|
447
|
+
if self.extensions_used:
|
|
448
|
+
document["extensionsUsed"] = sorted(self.extensions_used)
|
|
449
|
+
|
|
450
|
+
json_bytes = json.dumps(document, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
|
451
|
+
while len(json_bytes) % 4:
|
|
452
|
+
json_bytes += b" "
|
|
453
|
+
|
|
454
|
+
total = 12 + 8 + len(json_bytes) + (8 + len(self.bin) if self.bin else 0)
|
|
455
|
+
out = bytearray()
|
|
456
|
+
out.extend(struct.pack("<III", MAGIC, 2, total))
|
|
457
|
+
out.extend(struct.pack("<II", len(json_bytes), CHUNK_JSON))
|
|
458
|
+
out.extend(json_bytes)
|
|
459
|
+
if self.bin:
|
|
460
|
+
out.extend(struct.pack("<II", len(self.bin), CHUNK_BIN))
|
|
461
|
+
out.extend(self.bin)
|
|
462
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
463
|
+
path.write_bytes(out)
|
|
464
|
+
log.info("GLB %s (%s, %d mesh(es), %d material(s))", path.name, format_size(len(out)), len(self.meshes), len(self.materials))
|
|
465
|
+
return path
|
|
466
|
+
|
|
467
|
+
def _root_scale(options: ExportOptions) -> list[float] | None:
|
|
468
|
+
scale = float(options.scale)
|
|
469
|
+
values = [-scale, scale, scale] if options.mirror_x else [scale, scale, scale]
|
|
470
|
+
if values == [1.0, 1.0, 1.0]:
|
|
471
|
+
return None
|
|
472
|
+
return values
|
|
473
|
+
|
|
474
|
+
def _add_asset_node(writer: GlbWriter, asset: MeshAsset, mesh_index: int) -> int:
|
|
475
|
+
if asset.matrix != IDENTITY:
|
|
476
|
+
return writer.add_node(asset.name, mesh=mesh_index, matrix=asset.matrix)
|
|
477
|
+
scale = (asset.scale, asset.scale, asset.scale) if asset.scale != 1.0 else None
|
|
478
|
+
return writer.add_node(asset.name, mesh=mesh_index, scale=scale)
|
|
479
|
+
|
|
480
|
+
def export_glb_assets(path: Path, assets: Sequence[MeshAsset], textures: TextureStore, options: ExportOptions) -> Path | None:
|
|
481
|
+
writer = GlbWriter(textures, options)
|
|
482
|
+
roots: list[int] = []
|
|
483
|
+
for asset in assets:
|
|
484
|
+
mesh_index = writer.add_mesh(asset.mesh, asset.materials, asset.name)
|
|
485
|
+
if mesh_index is None:
|
|
486
|
+
continue
|
|
487
|
+
roots.append(_add_asset_node(writer, asset, mesh_index))
|
|
488
|
+
if not roots:
|
|
489
|
+
return None
|
|
490
|
+
root_scale = _root_scale(options)
|
|
491
|
+
if root_scale is not None:
|
|
492
|
+
root = writer.add_node("UnityRoot", scale=root_scale, children=roots)
|
|
493
|
+
roots = [root]
|
|
494
|
+
return writer.finish(path, "models", roots)
|
|
495
|
+
|
|
496
|
+
def export_glb_assets_split(
|
|
497
|
+
directory: Path,
|
|
498
|
+
assets: Sequence[MeshAsset],
|
|
499
|
+
textures: TextureStore,
|
|
500
|
+
options: ExportOptions,
|
|
501
|
+
) -> list[tuple[str, Path]]:
|
|
502
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
503
|
+
written: list[tuple[str, Path]] = []
|
|
504
|
+
used: set[str] = set()
|
|
505
|
+
for asset in assets:
|
|
506
|
+
stem = sanitize_filename(asset.name, "model")
|
|
507
|
+
candidate = stem
|
|
508
|
+
n = 2
|
|
509
|
+
while candidate.lower() in used:
|
|
510
|
+
candidate = f"{stem}_{n}"
|
|
511
|
+
n += 1
|
|
512
|
+
used.add(candidate.lower())
|
|
513
|
+
try:
|
|
514
|
+
writer = GlbWriter(textures, options)
|
|
515
|
+
mesh_index = writer.add_mesh(asset.mesh, asset.materials, asset.name)
|
|
516
|
+
if mesh_index is None:
|
|
517
|
+
continue
|
|
518
|
+
roots = [_add_asset_node(writer, asset, mesh_index)]
|
|
519
|
+
root_scale = _root_scale(options)
|
|
520
|
+
if root_scale is not None:
|
|
521
|
+
roots = [writer.add_node("UnityRoot", scale=root_scale, children=roots)]
|
|
522
|
+
written.append((asset.name, writer.finish(directory / f"{candidate}.glb", asset.name, roots)))
|
|
523
|
+
except Exception as exc:
|
|
524
|
+
log.warning("GLB export failed for %s: %s: %s", asset.name, type(exc).__name__, exc)
|
|
525
|
+
return written
|
|
526
|
+
|
|
527
|
+
class _SceneNodes:
|
|
528
|
+
|
|
529
|
+
def __init__(self, writer: GlbWriter):
|
|
530
|
+
self.writer = writer
|
|
531
|
+
self.by_transform: dict[tuple[int, int], int] = {}
|
|
532
|
+
self.roots: list[int] = []
|
|
533
|
+
|
|
534
|
+
@staticmethod
|
|
535
|
+
def _key(transform: Any) -> tuple[int, int]:
|
|
536
|
+
reader = getattr(transform, "object_reader", None)
|
|
537
|
+
if reader is not None:
|
|
538
|
+
return (id(asset_file_of(reader)), object_path_id(reader))
|
|
539
|
+
return (id(asset_file_of(transform)), object_path_id(transform))
|
|
540
|
+
|
|
541
|
+
@staticmethod
|
|
542
|
+
def _vec(value: Any, size: int) -> tuple[float, ...]:
|
|
543
|
+
try:
|
|
544
|
+
if size == 3:
|
|
545
|
+
return (float(value.x), float(value.y), float(value.z))
|
|
546
|
+
return (float(value.x), float(value.y), float(value.z), float(value.w))
|
|
547
|
+
except Exception:
|
|
548
|
+
return tuple(1.0 if size == 4 and i == 3 else 0.0 for i in range(size))
|
|
549
|
+
|
|
550
|
+
def ensure(self, transform: Any, depth: int = 0) -> int | None:
|
|
551
|
+
if transform is None or depth > 512:
|
|
552
|
+
return None
|
|
553
|
+
if not hasattr(transform, "m_LocalScale") and hasattr(transform, "read"):
|
|
554
|
+
try:
|
|
555
|
+
transform = transform.read()
|
|
556
|
+
except Exception:
|
|
557
|
+
return None
|
|
558
|
+
key = self._key(transform)
|
|
559
|
+
if key in self.by_transform:
|
|
560
|
+
return self.by_transform[key]
|
|
561
|
+
|
|
562
|
+
gameobject = None
|
|
563
|
+
father_ptr = getattr(transform, "m_Father", None)
|
|
564
|
+
try:
|
|
565
|
+
if father_ptr is not None and getattr(father_ptr, "m_PathID", 0):
|
|
566
|
+
gameobject_ptr = getattr(transform, "m_GameObject", None)
|
|
567
|
+
else:
|
|
568
|
+
gameobject_ptr = getattr(transform, "m_GameObject", None)
|
|
569
|
+
gameobject = gameobject_ptr.read() if gameobject_ptr is not None and getattr(gameobject_ptr, "m_PathID", 0) else None
|
|
570
|
+
except Exception:
|
|
571
|
+
gameobject = None
|
|
572
|
+
name = str(getattr(gameobject, "m_Name", "") or "node") if gameobject is not None else "node"
|
|
573
|
+
|
|
574
|
+
index = self.writer.add_node(
|
|
575
|
+
name,
|
|
576
|
+
translation=self._vec(getattr(transform, "m_LocalPosition", None), 3),
|
|
577
|
+
rotation=self._vec(getattr(transform, "m_LocalRotation", None), 4),
|
|
578
|
+
scale=self._vec(getattr(transform, "m_LocalScale", None), 3),
|
|
579
|
+
)
|
|
580
|
+
self.by_transform[key] = index
|
|
581
|
+
|
|
582
|
+
father = None
|
|
583
|
+
if father_ptr is not None and getattr(father_ptr, "m_PathID", 0):
|
|
584
|
+
try:
|
|
585
|
+
father = father_ptr.read()
|
|
586
|
+
except Exception:
|
|
587
|
+
father = None
|
|
588
|
+
father_index = self.ensure(father, depth + 1) if father is not None else None
|
|
589
|
+
if father_index is None:
|
|
590
|
+
self.roots.append(index)
|
|
591
|
+
else:
|
|
592
|
+
children = self.writer.nodes[father_index].setdefault("children", [])
|
|
593
|
+
children.append(index)
|
|
594
|
+
return index
|
|
595
|
+
|
|
596
|
+
def export_glb_scene(
|
|
597
|
+
path: Path,
|
|
598
|
+
models: Sequence[RendererModel],
|
|
599
|
+
textures: TextureStore,
|
|
600
|
+
options: ExportOptions,
|
|
601
|
+
scene_name: str = "scene",
|
|
602
|
+
) -> Path | None:
|
|
603
|
+
writer = GlbWriter(textures, options)
|
|
604
|
+
graph = _SceneNodes(writer)
|
|
605
|
+
attached = 0
|
|
606
|
+
|
|
607
|
+
for model in models:
|
|
608
|
+
if model.mesh is None:
|
|
609
|
+
continue
|
|
610
|
+
transform = getattr(model.gameobject, "m_Transform", None)
|
|
611
|
+
node_index = graph.ensure(transform) if transform is not None else None
|
|
612
|
+
if node_index is None:
|
|
613
|
+
continue
|
|
614
|
+
|
|
615
|
+
skin_index: int | None = None
|
|
616
|
+
if model.is_skinned and model.bones and model.bindposes and model.mesh.joints and model.mesh.weights:
|
|
617
|
+
joints: list[int] = []
|
|
618
|
+
valid = True
|
|
619
|
+
for bone in model.bones:
|
|
620
|
+
joint_node = graph.ensure(bone)
|
|
621
|
+
if joint_node is None:
|
|
622
|
+
valid = False
|
|
623
|
+
break
|
|
624
|
+
joints.append(joint_node)
|
|
625
|
+
if valid and len(joints) == len(model.bindposes):
|
|
626
|
+
skin_index = writer.add_skin(joints, model.bindposes)
|
|
627
|
+
|
|
628
|
+
mesh_index = writer.add_mesh(
|
|
629
|
+
model.mesh,
|
|
630
|
+
model.materials,
|
|
631
|
+
model.path or model.name,
|
|
632
|
+
skin=skin_index is not None,
|
|
633
|
+
bone_count=len(model.bones),
|
|
634
|
+
)
|
|
635
|
+
if mesh_index is None:
|
|
636
|
+
continue
|
|
637
|
+
|
|
638
|
+
target = node_index
|
|
639
|
+
if "mesh" in writer.nodes[target]:
|
|
640
|
+
target = writer.add_node(f"{model.name}_mesh")
|
|
641
|
+
writer.nodes[node_index].setdefault("children", []).append(target)
|
|
642
|
+
writer.nodes[target]["mesh"] = mesh_index
|
|
643
|
+
if skin_index is not None:
|
|
644
|
+
writer.nodes[target]["skin"] = skin_index
|
|
645
|
+
attached += 1
|
|
646
|
+
|
|
647
|
+
if not attached:
|
|
648
|
+
return None
|
|
649
|
+
|
|
650
|
+
roots = list(graph.roots)
|
|
651
|
+
root_scale = _root_scale(options)
|
|
652
|
+
if root_scale is not None:
|
|
653
|
+
roots = [writer.add_node("UnityRoot", scale=root_scale, children=roots)]
|
|
654
|
+
return writer.finish(path, scene_name, roots)
|