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,321 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from PIL import Image
9
+
10
+ from .util import log, object_identity, object_path_id, sanitize_filename, unique_name
11
+
12
+ try:
13
+ from UnityPy.enums import TextureFormat
14
+
15
+ _FORMAT_NAMES = {int(value): value.name for value in TextureFormat}
16
+ except Exception:
17
+ _FORMAT_NAMES = {}
18
+
19
+ def texture_format_name(value: Any) -> str:
20
+ if value is None:
21
+ return ""
22
+ name = getattr(value, "name", None)
23
+ if name:
24
+ return str(name)
25
+ try:
26
+ return _FORMAT_NAMES.get(int(value), str(int(value)))
27
+ except Exception:
28
+ return str(value)
29
+
30
+ try:
31
+ import numpy as _np
32
+ except Exception:
33
+ _np = None
34
+
35
+ NORMAL_FORMATS = {"DXT5", "DXT5Crunched", "BC3"}
36
+ _FLOAT_FORMATS = {
37
+ "RHalf": (1, "<f2"),
38
+ "RGHalf": (2, "<f2"),
39
+ "RGBAHalf": (4, "<f2"),
40
+ "RFloat": (1, "<f4"),
41
+ "RGFloat": (2, "<f4"),
42
+ "RGBAFloat": (4, "<f4"),
43
+ "RGBFloat": (3, "<f4"),
44
+ }
45
+
46
+ @dataclass
47
+ class TextureAsset:
48
+ key: tuple[int, int]
49
+ name: str
50
+ file: Path
51
+ width: int
52
+ height: int
53
+ image: Image.Image | None
54
+ format_name: str = ""
55
+ wrap_u: int = 0
56
+ wrap_v: int = 0
57
+ variant: str = ""
58
+ _png: bytes | None = field(default=None, repr=False)
59
+
60
+ def png_bytes(self) -> bytes:
61
+ if self._png is None:
62
+ if self.image is None:
63
+ self._png = self.file.read_bytes()
64
+ else:
65
+ buffer = io.BytesIO()
66
+ self.image.save(buffer, format="PNG")
67
+ self._png = buffer.getvalue()
68
+ return self._png
69
+
70
+ @property
71
+ def relative_path(self) -> str:
72
+ return f"textures/{self.file.name}"
73
+
74
+ def _get(obj: Any, name: str, default: Any = None) -> Any:
75
+ try:
76
+ return getattr(obj, name, default)
77
+ except Exception:
78
+ return default
79
+
80
+ def _wrap_mode(value: Any) -> int:
81
+ try:
82
+ return int(value)
83
+ except Exception:
84
+ return 0
85
+
86
+ def _unpack_dxt5nm(image: Image.Image) -> Image.Image:
87
+ if _np is None:
88
+ return image.convert("RGB")
89
+ rgba = _np.asarray(image.convert("RGBA"), dtype=_np.float32) / 255.0
90
+ x = rgba[..., 3]
91
+ y = rgba[..., 1]
92
+ z = _np.sqrt(_np.clip(1.0 - x * x - y * y, 0.0, 1.0))
93
+ out = _np.stack([x, y, z], axis=-1)
94
+ return Image.fromarray((_np.clip(out, 0.0, 1.0) * 255.0 + 0.5).astype(_np.uint8), "RGB")
95
+
96
+ def _has_pixel_data(texture: Any) -> bool:
97
+ try:
98
+ inline = getattr(texture, "image_data", b"") or b""
99
+ except Exception:
100
+ inline = b""
101
+ if inline:
102
+ return True
103
+ stream = getattr(texture, "m_StreamData", None)
104
+ if stream is None:
105
+ return False
106
+ try:
107
+ path = str(getattr(stream, "path", "") or "")
108
+ size = int(getattr(stream, "size", 0) or 0)
109
+ except Exception:
110
+ return False
111
+ return bool(path or size)
112
+
113
+ def _decode_float_texture(texture: Any, fmt: str) -> Image.Image:
114
+ if _np is None:
115
+ raise ValueError("numpy is required to decode float textures")
116
+ if fmt not in _FLOAT_FORMATS:
117
+ raise ValueError(f"no fallback decoder for {fmt}")
118
+ channels, dtype = _FLOAT_FORMATS[fmt]
119
+ width = int(getattr(texture, "m_Width", 0) or 0)
120
+ height = int(getattr(texture, "m_Height", 0) or 0)
121
+ if width <= 0 or height <= 0:
122
+ raise ValueError("texture has zero size")
123
+ data = texture.get_image_data()
124
+ itemsize = _np.dtype(dtype).itemsize
125
+ expected = width * height * channels * itemsize
126
+ if len(data) < expected:
127
+ raise ValueError(f"truncated {fmt} texture: {len(data)} < {expected} bytes")
128
+ values = _np.frombuffer(data[:expected], dtype=dtype).reshape(height, width, channels)
129
+ values = _np.flipud(values).astype(_np.float32)
130
+
131
+ rgb = _np.clip(values[..., : min(channels, 3)], 0.0, 1.0)
132
+ rgb = _np.where(rgb <= 0.0031308, rgb * 12.92, 1.055 * _np.power(rgb, 1.0 / 2.4) - 0.055)
133
+ rgb8 = (_np.clip(rgb, 0.0, 1.0) * 255.0 + 0.5).astype(_np.uint8)
134
+
135
+ if channels == 1:
136
+ return Image.fromarray(rgb8[..., 0], "L")
137
+ if channels == 2:
138
+ alpha = (_np.clip(values[..., 1], 0.0, 1.0) * 255.0 + 0.5).astype(_np.uint8)
139
+ return Image.fromarray(_np.stack([rgb8[..., 0], alpha], axis=-1), "LA")
140
+ if channels == 3:
141
+ return Image.fromarray(rgb8, "RGB")
142
+ alpha = (_np.clip(values[..., 3], 0.0, 1.0) * 255.0 + 0.5).astype(_np.uint8)
143
+ rgba = _np.dstack([rgb8, alpha])
144
+ return Image.fromarray(rgba, "RGBA")
145
+
146
+ def _alpha_to_gray(image: Image.Image) -> Image.Image:
147
+ if image.mode in {"RGBA", "LA"}:
148
+ return image.getchannel("A")
149
+ if image.mode == "P":
150
+ return image.convert("RGBA").getchannel("A")
151
+ return image.convert("L")
152
+
153
+ def _ensure_png_mode(image: Image.Image) -> Image.Image:
154
+ if image.mode == "F":
155
+ if _np is None:
156
+ return image.convert("L")
157
+ values = _np.clip(_np.asarray(image, dtype=_np.float32), 0.0, 1.0)
158
+ return Image.fromarray((values * 255.0 + 0.5).astype(_np.uint8), "L")
159
+ if image.mode.startswith("I;16") or image.mode == "I":
160
+ if _np is None:
161
+ return image.convert("L")
162
+ values = _np.clip(_np.asarray(image, dtype=_np.float64) / 257.0, 0.0, 255.0)
163
+ return Image.fromarray(values.astype(_np.uint8), "L")
164
+ if image.mode in {"CMYK", "YCbCr", "HSV"}:
165
+ return image.convert("RGB")
166
+ return image
167
+
168
+ class TextureStore:
169
+
170
+ def __init__(
171
+ self,
172
+ output_dir: Path,
173
+ normal_mode: str = "auto",
174
+ enabled: bool = True,
175
+ base_path: str | Path | None = None,
176
+ retain_images: bool = True,
177
+ ):
178
+ self.output_dir = output_dir
179
+ self.directory = output_dir / "textures"
180
+ self.normal_mode = normal_mode
181
+ self.enabled = enabled
182
+ self.base_path = base_path
183
+ self.retain_images = retain_images
184
+ self._cache: dict[tuple[str, int, str], TextureAsset | None] = {}
185
+ self._used_names: set[str] = set()
186
+ self.assets: list[TextureAsset] = []
187
+ self.errors: list[str] = []
188
+
189
+ def _key(self, obj: Any) -> tuple[str, int]:
190
+ return object_identity(obj, self.base_path)
191
+
192
+ def _decode(self, obj: Any) -> tuple[Image.Image, str, int, int]:
193
+ texture = obj.read()
194
+ fmt = texture_format_name(_get(texture, "m_TextureFormat", None))
195
+ settings = _get(texture, "m_TextureSettings", None)
196
+ wrap_u = _wrap_mode(_get(settings, "m_WrapU", 0))
197
+ wrap_v = _wrap_mode(_get(settings, "m_WrapV", 0))
198
+ try:
199
+ image = texture.image
200
+ except Exception as exc:
201
+ if not _has_pixel_data(texture):
202
+ raise ValueError("no pixel data (runtime-generated or empty stream)") from exc
203
+ if fmt not in _FLOAT_FORMATS:
204
+ raise
205
+ image = _decode_float_texture(texture, fmt)
206
+ image = _ensure_png_mode(image)
207
+ if fmt in {"Alpha8", "A8"}:
208
+ image = _alpha_to_gray(image)
209
+ if image.width == 0 or image.height == 0:
210
+ raise ValueError("texture has zero size")
211
+ return image, fmt, wrap_u, wrap_v
212
+
213
+ def save(self, obj: Any, hint: str = "texture", role: str = "albedo") -> TextureAsset | None:
214
+ if obj is None or not self.enabled:
215
+ return None
216
+ if object_path_id(obj) == 0:
217
+ return None
218
+ if role == "normal" and self.normal_mode == "off":
219
+ return None
220
+
221
+ key = self._key(obj)
222
+ variant = ""
223
+ try:
224
+ texture = obj.read()
225
+ fmt = texture_format_name(_get(texture, "m_TextureFormat", None))
226
+ if role == "normal" and self.normal_mode == "auto" and fmt in NORMAL_FORMATS:
227
+ variant = "n"
228
+ except Exception:
229
+ variant = ""
230
+
231
+ cache_key = (key[0], key[1], variant)
232
+ if cache_key in self._cache:
233
+ return self._cache[cache_key]
234
+
235
+ try:
236
+ image, fmt, wrap_u, wrap_v = self._decode(obj)
237
+ name = _get(texture, "m_Name", "") or hint
238
+ if variant == "n":
239
+ image = _unpack_dxt5nm(image)
240
+ elif role == "normal" and self.normal_mode == "raw":
241
+ image = image.copy()
242
+
243
+ stem = sanitize_filename(name, fallback=sanitize_filename(hint, "texture"))
244
+ if variant:
245
+ stem = f"{stem}_n"
246
+ stem = unique_name(stem, self._used_names, suffix=str(key[1]) if key[1] else "")
247
+ self.directory.mkdir(parents=True, exist_ok=True)
248
+ path = self.directory / f"{stem}.png"
249
+ image.save(path, format="PNG")
250
+
251
+ asset = TextureAsset(
252
+ key=key,
253
+ name=name,
254
+ file=path,
255
+ width=image.width,
256
+ height=image.height,
257
+ image=image if self.retain_images else None,
258
+ format_name=fmt,
259
+ wrap_u=wrap_u,
260
+ wrap_v=wrap_v,
261
+ variant=variant,
262
+ )
263
+ self._cache[cache_key] = asset
264
+ self.assets.append(asset)
265
+ log.debug("texture %s -> %s (%dx%d %s)", name, path.name, image.width, image.height, fmt)
266
+ return asset
267
+ except Exception as exc:
268
+ self._cache[cache_key] = None
269
+ message = f"texture '{hint}' failed: {type(exc).__name__}: {exc}"
270
+ self.errors.append(message)
271
+ log.warning(message)
272
+ return None
273
+
274
+ def save_metallic_roughness(self, obj: Any, hint: str = "material") -> TextureAsset | None:
275
+ if obj is None or not self.enabled:
276
+ return None
277
+ key = self._key(obj)
278
+ cache_key = (key[0], key[1], "mr")
279
+ if cache_key in self._cache:
280
+ return self._cache[cache_key]
281
+ try:
282
+ source = self.save(obj, hint=hint, role="albedo")
283
+ if source is None:
284
+ self._cache[cache_key] = None
285
+ return None
286
+ if source.image is not None:
287
+ rgba = source.image.convert("RGBA")
288
+ else:
289
+ with Image.open(source.file) as handle:
290
+ rgba = handle.convert("RGBA")
291
+ r, _g, _b, a = rgba.split()
292
+ from PIL import ImageChops
293
+
294
+ rough = ImageChops.invert(a)
295
+ out = Image.merge("RGBA", (r, rough, r, Image.new("L", rgba.size, 255)))
296
+ stem = f"{sanitize_filename(hint, 'material')}_mr"
297
+ stem = unique_name(stem, self._used_names, suffix=str(key[1]) if key[1] else "")
298
+ self.directory.mkdir(parents=True, exist_ok=True)
299
+ path = self.directory / f"{stem}.png"
300
+ out.save(path, format="PNG")
301
+ asset = TextureAsset(
302
+ key=key,
303
+ name=f"{hint}_mr",
304
+ file=path,
305
+ width=out.width,
306
+ height=out.height,
307
+ image=out if self.retain_images else None,
308
+ format_name="RGBA32",
309
+ wrap_u=source.wrap_u,
310
+ wrap_v=source.wrap_v,
311
+ variant="mr",
312
+ )
313
+ self._cache[cache_key] = asset
314
+ self.assets.append(asset)
315
+ return asset
316
+ except Exception as exc:
317
+ self._cache[cache_key] = None
318
+ message = f"metallic/roughness repack for '{hint}' failed: {type(exc).__name__}: {exc}"
319
+ self.errors.append(message)
320
+ log.warning(message)
321
+ return None
unityripper/util.py ADDED
@@ -0,0 +1,105 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os
5
+ import re
6
+ import unicodedata
7
+ from pathlib import Path
8
+ from typing import Iterable
9
+
10
+ _INVALID = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
11
+ _SPACES = re.compile(r"\s+")
12
+ _RESERVED = {
13
+ "CON", "PRN", "AUX", "NUL",
14
+ *(f"COM{i}" for i in range(1, 10)),
15
+ *(f"LPT{i}" for i in range(1, 10)),
16
+ }
17
+
18
+ log = logging.getLogger("unityripper")
19
+
20
+ def sanitize_filename(name: str, fallback: str = "unnamed", max_length: int = 100) -> str:
21
+ name = unicodedata.normalize("NFKC", str(name or "")).strip()
22
+ name = _INVALID.sub("_", name)
23
+ name = _SPACES.sub(" ", name).strip(" .")
24
+ if not name:
25
+ name = fallback
26
+ if len(name) > max_length:
27
+ name = name[:max_length].rstrip(" .")
28
+ if not name:
29
+ name = fallback
30
+ if name.split(".")[0].upper() in _RESERVED:
31
+ name = f"_{name}"
32
+ return name
33
+
34
+ def sanitize_node_path(path: str) -> str:
35
+ parts = [sanitize_filename(p, "node", 48) for p in path.split("/") if p]
36
+ return "__".join(parts) if parts else "model"
37
+
38
+ def unique_name(base: str, used: set[str], suffix: str = "") -> str:
39
+ if suffix:
40
+ candidate = f"{base}_{suffix}"
41
+ else:
42
+ candidate = base
43
+ if candidate not in used:
44
+ used.add(candidate)
45
+ return candidate
46
+ i = 2
47
+ while f"{base}_{i}" in used:
48
+ i += 1
49
+ candidate = f"{base}_{i}"
50
+ used.add(candidate)
51
+ return candidate
52
+
53
+ def relative_posix(path: Path, start: Path) -> str:
54
+ return Path(os.path.relpath(path, start)).as_posix()
55
+
56
+ def asset_file_of(obj: object) -> object | None:
57
+ assets_file = getattr(obj, "assets_file", None)
58
+ if assets_file is None:
59
+ assets_file = getattr(obj, "assetsfile", None)
60
+ return assets_file
61
+
62
+ def object_path_id(obj: object) -> int:
63
+ for attribute in ("path_id", "m_PathID"):
64
+ value = getattr(obj, attribute, None)
65
+ if value is None:
66
+ continue
67
+ try:
68
+ return int(value)
69
+ except (TypeError, ValueError):
70
+ continue
71
+ return 0
72
+
73
+ def object_identity(obj: object, base: str | Path | None = None) -> tuple[str, int]:
74
+ assets_file = asset_file_of(obj)
75
+ name = str(getattr(assets_file, "name", "") or "") if assets_file is not None else ""
76
+ if name:
77
+ path = Path(name)
78
+ if not path.is_absolute() and base is not None:
79
+ path = Path(base) / path
80
+ name = os.path.normcase(os.path.normpath(str(path)))
81
+ return name, object_path_id(obj)
82
+
83
+ def format_size(num_bytes: int) -> str:
84
+ value = float(num_bytes)
85
+ for unit in ("B", "KB", "MB", "GB", "TB"):
86
+ if value < 1024.0 or unit == "TB":
87
+ return f"{value:.1f} {unit}" if unit != "B" else f"{int(value)} B"
88
+ value /= 1024.0
89
+ return f"{value:.1f} TB"
90
+
91
+ def plural(count: int, one: str, few: str, many: str) -> str:
92
+ n = abs(count) % 100
93
+ n1 = n % 10
94
+ if 11 <= n <= 19:
95
+ return many
96
+ if n1 == 1:
97
+ return one
98
+ if 2 <= n1 <= 4:
99
+ return few
100
+ return many
101
+
102
+ def walk_files(root: Path) -> Iterable[Path]:
103
+ for dirpath, _dirnames, filenames in os.walk(root):
104
+ for name in filenames:
105
+ yield Path(dirpath) / name
@@ -0,0 +1,10 @@
1
+ Metadata-Version: 2.4
2
+ Name: unityripper
3
+ Version: 1.0.0
4
+ Summary: Model decompiler / ripper for Unity games (Mono and IL2CPP builds)
5
+ License: MIT
6
+ Requires-Python: >=3.10
7
+ Requires-Dist: UnityPy>=1.25.0
8
+ Requires-Dist: Pillow>=10.0.0
9
+ Requires-Dist: numpy>=1.24
10
+ Requires-Dist: texture2ddecoder>=1.0.5
@@ -0,0 +1,19 @@
1
+ unityripper/__init__.py,sha256=J-j-u0itpEFT6irdmWmixQqYMadNl1X91TxUmoiLHMI,22
2
+ unityripper/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
+ unityripper/cli.py,sha256=ll-AQN0er3ozLOGCG0e3uLybwg01drJpS2LnUVWiBCM,24076
4
+ unityripper/discovery.py,sha256=ZzV28vezYDTgc0Sommi_BBmVPvIM7sxZxenx8HzIsx4,5800
5
+ unityripper/materials.py,sha256=bk1MzAKxUAmy3x2vyE1IWWif093kKe3JwQxiK0cf9Bk,8049
6
+ unityripper/mathutil.py,sha256=C84JO9yvdGxD9WQqqoinjf0nAMhzt7OvBz2VEnes6WI,5242
7
+ unityripper/scene.py,sha256=cCpLn4vDQ0B2QRMHon7ICk-QOe9DCG3Xn2l7rRwrfj8,27698
8
+ unityripper/textures.py,sha256=59e7gXZ4PtkEGAtoYl6SZLpSO7h5vkIt62pbYlPq_34,11448
9
+ unityripper/util.py,sha256=0eOCj2jp3KJWItc9eO5E_dGgAoN0o-LCADBUSI2utn0,3182
10
+ unityripper/exporters/__init__.py,sha256=a4T5-zJBMEcI2Epu0fJASGIIK9h8AMxqMRRCl4syRnQ,201
11
+ unityripper/exporters/common.py,sha256=Pt-16f9fpHMDGCLf7jdjgsM0RQTrZWpkzau-Yz6d1NU,3376
12
+ unityripper/exporters/fbx.py,sha256=WcGvzbnQGifxeXTQHo15ep31YHa_l-WP5_9N1VZYuF4,18990
13
+ unityripper/exporters/glb.py,sha256=JQSpjI3sHsMJzMDOTjnubSrNotQhY_iOj4iHVqCCC3A,25786
14
+ unityripper/exporters/obj.py,sha256=CE38EFE0LlWoeTqi0xxhnn5Ik6aJuQJ7v6PHv_d7f6Y,12042
15
+ unityripper-1.0.0.dist-info/METADATA,sha256=SUFUfOphiHeFXNHWFVrHQyVY9EeYpdakpSbP6ClRXyE,305
16
+ unityripper-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
17
+ unityripper-1.0.0.dist-info/entry_points.txt,sha256=BUTmss7NxI_XYDcQVYzpeHXy2k5OTx6RRXRAhiwTOZg,53
18
+ unityripper-1.0.0.dist-info/top_level.txt,sha256=omjGr9Y3h8ekR9FahSbR4D-hTJK-OrmTAR13ogBfvr0,12
19
+ unityripper-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ unityripper = unityripper.cli:main
@@ -0,0 +1 @@
1
+ unityripper