-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathuntoldexplorer.py
More file actions
8385 lines (7336 loc) · 354 KB
/
Copy pathuntoldexplorer.py
File metadata and controls
8385 lines (7336 loc) · 354 KB
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright (C) Untold Engine Studios
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
from __future__ import annotations
import argparse
import hashlib
import json
import math
import os
import shutil
import struct
import sys
import tempfile
from array import array
from dataclasses import dataclass, replace
from pathlib import Path
from typing import Callable, Iterable, Optional
try:
import bpy # type: ignore
import bmesh # type: ignore
from bpy_extras.io_utils import axis_conversion # type: ignore
from mathutils import Matrix, Vector # type: ignore
except ImportError:
bpy = None
bmesh = None
axis_conversion = None
Matrix = None
Vector = None
try:
import numpy as np
_HAS_NUMPY = True
except ImportError:
np = None
_HAS_NUMPY = False
MAGIC = b"UNTOLD\x00\x00"
# Bumped from 1 to 2 when the exporter started multiplying emissive_factor by
# Emission Strength (see extract_material). Readers use this to know whether
# a file's emissiveFactor is trustworthy or a leftover Blender default.
# Bumped to 4 when the material record grew height-map fields (heightTextureIndex,
# heightScale, heightMidlevel) and height-remap fields (heightRemapMin, heightRemapMax) —
# see extract_material's Displacement/Bump detection and write_material_record.
FORMAT_VERSION = 4
FILE_ALIGNMENT = 16
INVALID_INDEX = 0xFFFFFFFF
HEADER_SIZE = 204
CHUNK_ENTRY_SIZE = 40
VERTEX_STRIDE = 32
COMPRESSION_NONE = 0
COMPRESSION_LZ4 = 1
FILE_TYPES = {
"tile": 1,
"lod": 2,
"hlod": 3,
"shared": 4,
"animation": 5,
}
CHUNK_TYPES = {
"string_table": 1,
"entity_table": 2,
"mesh_table": 3,
"material_table": 4,
"texture_table": 5,
"vertex_data": 6,
"index_data": 7,
"skeleton_table": 8,
"skeleton_joint_table": 9,
"skin_table": 10,
"skin_joint_mapping_table": 11,
"animation_clip_table": 12,
"animation_channel_table": 13,
"translation_keyframe_table": 14,
"rotation_keyframe_table": 15,
"joint_index_data": 16,
"joint_weight_data": 17,
"edge_index_data": 18,
"light_table": 19,
"camera_table": 20,
"color_management_table": 21,
"color_grade_lut_table": 22,
"morph_target_table": 23,
"morph_target_data": 24,
"gaussian_asset_table": 25,
"morph_driver_table": 26,
"muscle_table": 27,
}
VERTEX_LAYOUT_PBR_STATIC_V1 = 1
MORPH_ENTRY_SIZE = 16
try:
import numpy as _np_for_morphs
_MORPH_DTYPE = _np_for_morphs.dtype([
("vi", "<u4"),
("px", "<u2"), ("py", "<u2"), ("pz", "<u2"),
("nx", "<u2"), ("ny", "<u2"), ("nz", "<u2"),
])
assert _MORPH_DTYPE.itemsize == MORPH_ENTRY_SIZE
except ImportError:
_MORPH_DTYPE = None
MORPH_FLAG_HAS_NORMAL_DELTAS = 1 << 0
MUSCLE_RECORD_SIZE = 128
MUSCLE_FLAG_HAS_DRIVER = 1 << 0
# Set from --export-shapekeys; shape keys are skipped entirely when False.
EXPORT_SHAPE_KEYS = False
INDEX_TYPE_UINT16 = 1
INDEX_TYPE_UINT32 = 2
LIGHT_TYPE_DIRECTIONAL = 1
LIGHT_TYPE_POINT = 2
LIGHT_TYPE_SPOT = 3
LIGHT_TYPE_AREA = 4
LIGHT_FLAG_CASTS_SHADOW = 1 << 0
LIGHT_FLAG_RADIOMETRIC = 1 << 1
LIGHT_FLAG_CUSTOM_DISTANCE = 1 << 2
ARCHITECTURAL_EDGE_ANGLE_DEGREES = 30.0
ARCHITECTURAL_EDGE_POSITION_EPSILON = 1.0e-5
TEXTURE_FORMAT_UNKNOWN = 0
TEXTURE_FORMAT_RGBA16_FLOAT = 8
TEXTURE_FLAG_SRGB = 1 << 0
TEXTURE_FLAG_NORMAL_MAP = 1 << 1
TEXTURE_FLAG_LUT = 1 << 2
TEXTURE_FLAG_HEIGHT = 1 << 3
TEXTURE_FLAG_EMISSIVE = 1 << 6
TEXTURE_FLAG_OCCLUSION = 1 << 7
TEXTURE_CHANNEL_R = 0
TEXTURE_CHANNEL_G = 1
TEXTURE_CHANNEL_B = 2
TEXTURE_CHANNEL_A = 3
UNTOLD_EXPORT_TEMP_OBJECT_PROP = "_untold_export_temp_object"
# The name of the material a mesh with no material of its own is given. It is one name
# for all of them, and not one made from the object's name: the material is part of what
# tells two models apart (see model_content_signature), so a name taken from the object
# made every copy of a prop with no material a model of its own.
DEFAULT_MATERIAL_NAME = "default_material"
# Material alpha modes, the low two bits of a material record's flags (the engine's
# MaterialAlphaMode).
MATERIAL_ALPHA_MODE_OPAQUE = 0
MATERIAL_ALPHA_MODE_MASK = 1
MATERIAL_ALPHA_MODE_BLEND = 2
# The opacity a fully transmissive, clear surface (Principled Transmission Weight 1 with
# a white base colour) keeps when exported: the engine has no transmission, so glass
# becomes a blended surface this opaque, enough to keep its reflections visible. Tinted
# or frosted glass comes out more opaque, by what its colour and its roughness take from
# what is seen through it, and a metal opaque (see principled_transmittance).
TRANSMISSION_OPACITY = 0.1
# The engine's own parallax depth (the default of its heightScale), for a material with
# no height and for a height whose depth is linked and so has no single value.
DEFAULT_HEIGHT_SCALE = 0.05
# The deepest relief the engine's parallax occlusion mapping can show, as a share of the
# texture's width (the engine's heightScale). Blender leaves a Displacement Scale and a
# Bump Distance at 1, a metre, and what it draws from them under its default "Bump Only"
# displacement is the shading of a bump, not a hollow a metre deep. Carried over as a
# parallax depth, such a value smears the texture across the surface, so a height with
# a scale above this is left out of the export.
MAX_PARALLAX_HEIGHT_SCALE = 0.2
# Samples per channel of the lookup tables that carry RGB Curves and ColorRamp nodes.
CURVE_LUT_SIZE = 256
# Rec. 709 luminance, which Blender uses to turn a colour into a value (a Color output
# linked to a Fac or Alpha input).
LUMINANCE_WEIGHTS = (0.2126, 0.7152, 0.0722)
# Records the name of the source object a temporary export object stands in for:
# each single-material fragment produced by split_blender_objects_by_material(), and
# each mesh made from a curve, surface or text object by convert_curve_objects_to_meshes().
# Multi-model .untoldpack grouping (see group_export_nodes_by_root) uses it to reunite
# the fragments of one object into a single model, and extract_nodes_from_objects uses
# it to parent the source object's children to its stand-in.
UNTOLD_MATERIAL_SPLIT_SOURCE_PROP = "_untold_material_split_source"
# Object types whose evaluated geometry is exported as a mesh when it has faces (a
# curve with a bevel or extrusion, a surface, a text object).
CONVERTIBLE_GEOMETRY_OBJECT_TYPES = {"CURVE", "SURFACE", "FONT"}
ProgressCallback = Callable[[str, int, int, str], None]
class ProgressReporter:
def __init__(self, label: str, total_steps: int, on_progress: Optional[ProgressCallback] = None) -> None:
self.label = label
self.total_steps = max(int(total_steps), 1)
self.completed_steps = 0
self.on_progress = on_progress
def stage(self, stage: str, detail: str = "") -> None:
self._emit(stage, detail, self.completed_steps)
def advance(self, stage: str, detail: str = "", steps: int = 1) -> None:
self.completed_steps = min(self.total_steps, self.completed_steps + max(int(steps), 0))
self._emit(stage, detail, self.completed_steps)
def _emit(self, stage: str, detail: str, completed_steps: int) -> None:
percent = (100.0 * completed_steps) / self.total_steps
suffix = f" - {detail}" if detail else ""
print(
f"[progress] {self.label}: {percent:6.2f}% "
f"({completed_steps}/{self.total_steps}) {stage}{suffix}",
flush=True,
)
if self.on_progress is not None:
self.on_progress(stage, completed_steps, self.total_steps, detail)
def align(value: int, alignment: int) -> int:
remainder = value % alignment
return value if remainder == 0 else value + (alignment - remainder)
def clamp(value: float, minimum: float, maximum: float) -> float:
return max(minimum, min(maximum, value))
def clamp_texture_channel(channel: int) -> int:
channel = int(channel)
if channel in (TEXTURE_CHANNEL_R, TEXTURE_CHANNEL_G, TEXTURE_CHANNEL_B, TEXTURE_CHANNEL_A):
return channel
return TEXTURE_CHANNEL_R
def pack_material_texture_channels(
roughness: int = TEXTURE_CHANNEL_R,
metallic: int = TEXTURE_CHANNEL_R,
) -> int:
return (clamp_texture_channel(roughness) & 0b11) | ((clamp_texture_channel(metallic) & 0b11) << 2)
def texture_channel_from_socket_name(name: str, default: int = TEXTURE_CHANNEL_R) -> int:
normalized = str(name or "").strip().lower().replace(" ", "").replace("_", "")
channel_by_name = {
"r": TEXTURE_CHANNEL_R,
"red": TEXTURE_CHANNEL_R,
"x": TEXTURE_CHANNEL_R,
"g": TEXTURE_CHANNEL_G,
"green": TEXTURE_CHANNEL_G,
"y": TEXTURE_CHANNEL_G,
"b": TEXTURE_CHANNEL_B,
"blue": TEXTURE_CHANNEL_B,
"z": TEXTURE_CHANNEL_B,
"a": TEXTURE_CHANNEL_A,
"alpha": TEXTURE_CHANNEL_A,
"w": TEXTURE_CHANNEL_A,
}
return channel_by_name.get(normalized, default)
def normalize3(vector: tuple[float, float, float], fallback: tuple[float, float, float]) -> tuple[float, float, float]:
x, y, z = vector
length = math.sqrt((x * x) + (y * y) + (z * z))
if length <= 1.0e-8:
return fallback
return (x / length, y / length, z / length)
def _sub3(a: tuple[float, float, float], b: tuple[float, float, float]) -> tuple[float, float, float]:
return (a[0] - b[0], a[1] - b[1], a[2] - b[2])
def _cross3(a: tuple[float, float, float], b: tuple[float, float, float]) -> tuple[float, float, float]:
return (
(a[1] * b[2]) - (a[2] * b[1]),
(a[2] * b[0]) - (a[0] * b[2]),
(a[0] * b[1]) - (a[1] * b[0]),
)
def _dot3(a: tuple[float, float, float], b: tuple[float, float, float]) -> float:
return (a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2])
def build_architectural_edge_indices(
positions: list[tuple[float, float, float]],
indices: list[int],
angle_degrees: float = ARCHITECTURAL_EDGE_ANGLE_DEGREES,
position_epsilon: float = ARCHITECTURAL_EDGE_POSITION_EPSILON,
) -> list[int]:
"""Return boundary and hard-angle edges from an already indexed triangle mesh."""
if len(indices) < 3:
return []
quant_scale = 1.0 / max(position_epsilon, 1.0e-12)
def quantized_position(index: int) -> tuple[int, int, int]:
position = positions[index]
return (
int(round(position[0] * quant_scale)),
int(round(position[1] * quant_scale)),
int(round(position[2] * quant_scale)),
)
cos_threshold = math.cos(math.radians(max(0.0, min(180.0, angle_degrees))))
edge_faces: dict[
tuple[tuple[int, int, int], tuple[int, int, int]],
list[tuple[tuple[float, float, float], tuple[int, int]]],
] = {}
for triangle_start in range(0, len(indices) - 2, 3):
tri = (indices[triangle_start], indices[triangle_start + 1], indices[triangle_start + 2])
if tri[0] >= len(positions) or tri[1] >= len(positions) or tri[2] >= len(positions):
continue
p0 = positions[tri[0]]
p1 = positions[tri[1]]
p2 = positions[tri[2]]
normal = normalize3(_cross3(_sub3(p1, p0), _sub3(p2, p0)), (0.0, 0.0, 0.0))
if normal == (0.0, 0.0, 0.0):
continue
for a, b in ((tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])):
qa = quantized_position(a)
qb = quantized_position(b)
key = (qa, qb) if qa <= qb else (qb, qa)
edge_faces.setdefault(key, []).append((normal, (a, b)))
edge_indices: list[int] = []
for faces in edge_faces.values():
if len(faces) == 1:
edge_indices.extend(faces[0][1])
continue
keep = False
for i in range(len(faces)):
for j in range(i + 1, len(faces)):
if _dot3(faces[i][0], faces[j][0]) <= cos_threshold:
keep = True
break
if keep:
break
if keep:
edge_indices.extend(faces[0][1])
return edge_indices
def pack_index_data(indices: list[int], index_type: int) -> bytes:
writer = BinaryWriter()
for index in indices:
if index_type == INDEX_TYPE_UINT16:
writer.write_u16(index)
else:
writer.write_u32(index)
return writer.data
def pack_snorm10(value: float) -> int:
clamped = clamp(value, -1.0, 1.0)
scaled = int(round(clamped * 511.0))
return scaled & 0x3FF
def pack_snorm2(value: float) -> int:
return (-1 if value < 0.0 else 1) & 0x3
def pack_normal(normal: tuple[float, float, float]) -> int:
nx, ny, nz = normalize3(normal, (0.0, 0.0, 1.0))
return pack_snorm10(nx) | (pack_snorm10(ny) << 10) | (pack_snorm10(nz) << 20)
def pack_tangent(tangent: tuple[float, float, float], handedness: float) -> int:
tx, ty, tz = normalize3(tangent, (1.0, 0.0, 0.0))
return (
pack_snorm10(tx)
| (pack_snorm10(ty) << 10)
| (pack_snorm10(tz) << 20)
| (pack_snorm2(handedness) << 30)
)
def float_to_half_bits(value: float) -> int:
return struct.unpack("<H", struct.pack("<e", value))[0]
def color_to_u8(value: float) -> int:
return int(round(clamp(value, 0.0, 1.0) * 255.0))
if _HAS_NUMPY:
_VERTEX_DTYPE = np.dtype([
("px", np.float32), ("py", np.float32), ("pz", np.float32),
("normal", np.uint32),
("tangent", np.uint32),
("uv0u", np.uint16), ("uv0v", np.uint16),
("uv1u", np.uint16), ("uv1v", np.uint16),
("cr", np.uint8), ("cg", np.uint8), ("cb", np.uint8), ("ca", np.uint8),
])
assert _VERTEX_DTYPE.itemsize == VERTEX_STRIDE, (
f"_VERTEX_DTYPE is {_VERTEX_DTYPE.itemsize} bytes, expected {VERTEX_STRIDE}"
)
def _np_pack_snorm10(values: "np.ndarray") -> "np.ndarray":
clamped = np.clip(values, -1.0, 1.0)
scaled = np.round(clamped * 511.0).astype(np.int32)
return (scaled & 0x3FF).astype(np.uint32)
def _np_pack_normals(normals: "np.ndarray") -> "np.ndarray":
lens = np.linalg.norm(normals, axis=1, keepdims=True)
lens = np.where(lens <= 1.0e-8, 1.0, lens)
n = normals / lens
return (
_np_pack_snorm10(n[:, 0])
| (_np_pack_snorm10(n[:, 1]) << 10)
| (_np_pack_snorm10(n[:, 2]) << 20)
)
def _np_pack_tangents(tangents: "np.ndarray", bitangent_signs: "np.ndarray") -> "np.ndarray":
lens = np.linalg.norm(tangents, axis=1, keepdims=True)
lens = np.where(lens <= 1.0e-8, 1.0, lens)
t = tangents / lens
hw = np.where(bitangent_signs >= 0.0, np.int32(1), np.int32(-1)).astype(np.int32) & np.int32(0x3)
return (
_np_pack_snorm10(t[:, 0])
| (_np_pack_snorm10(t[:, 1]) << 10)
| (_np_pack_snorm10(t[:, 2]) << 20)
| (hw.astype(np.uint32) << 30)
)
else:
_VERTEX_DTYPE = None
_np_pack_normals = None
_np_pack_tangents = None
class BinaryWriter:
def __init__(self) -> None:
self._buffer = bytearray()
@property
def data(self) -> bytes:
return bytes(self._buffer)
@property
def count(self) -> int:
return len(self._buffer)
def align(self, alignment: int) -> None:
target = align(len(self._buffer), alignment)
if target > len(self._buffer):
self._buffer.extend(b"\x00" * (target - len(self._buffer)))
def write_bytes(self, data: bytes) -> None:
self._buffer.extend(data)
def write_u8(self, value: int) -> None:
self._buffer.extend(struct.pack("<B", value))
def write_u16(self, value: int) -> None:
self._buffer.extend(struct.pack("<H", value))
def write_u32(self, value: int) -> None:
self._buffer.extend(struct.pack("<I", value))
def write_u64(self, value: int) -> None:
self._buffer.extend(struct.pack("<Q", value))
def write_f32(self, value: float) -> None:
self._buffer.extend(struct.pack("<f", float(value)))
def write_c_string(self, value: str) -> None:
self._buffer.extend(value.encode("utf-8"))
self._buffer.append(0)
def write_matrix4x4_column_major(self, matrix_rows: list[list[float]]) -> None:
for column in range(4):
for row in range(4):
self.write_f32(matrix_rows[row][column])
class StringTableBuilder:
def __init__(self) -> None:
self._writer = BinaryWriter()
self._offsets: dict[str, int] = {}
def add(self, value: Optional[str]) -> int:
if not value:
return INVALID_INDEX
existing = self._offsets.get(value)
if existing is not None:
return existing
offset = self._writer.count
self._writer.write_c_string(value)
self._offsets[value] = offset
return offset
def string_at(self, offset: int) -> Optional[str]:
for value, existing in self._offsets.items():
if existing == offset:
return value
return None
@property
def data(self) -> bytes:
return self._writer.data
@dataclass(frozen=True)
class AABB:
minimum: tuple[float, float, float]
maximum: tuple[float, float, float]
@dataclass(frozen=True)
class TextureRecord:
name_offset: int
uri_offset: int
texture_format: int = TEXTURE_FORMAT_UNKNOWN
flags: int = 0
width: int = 0
height: int = 0
mip_count: int = 0
@dataclass(frozen=True)
class LightRecord:
entity_id: int
name_offset: int
light_type: int
flags: int
color: tuple[float, float, float]
intensity: float
position: tuple[float, float, float]
radius: float
direction: tuple[float, float, float]
falloff: float
right: tuple[float, float, float]
inner_cone: float
up: tuple[float, float, float]
outer_cone: float
area_size: tuple[float, float]
source_power: float
source_exposure: float
local_transform_rows: list[list[float]]
@dataclass(frozen=True)
class CameraRecord:
entity_id: int
name_offset: int
flags: int
position: tuple[float, float, float]
forward: tuple[float, float, float]
up: tuple[float, float, float]
right: tuple[float, float, float]
fov_y_degrees: float
near_clip: float
far_clip: float
aspect_ratio: float
local_transform_rows: list[list[float]]
@dataclass(frozen=True)
class ColorGradeLUTRecord:
"""An externally-authored .cube LUT, applied as a post-tonemap creative grade.
References a plain .cube file staged next to the export -- no Blender
render/bake, no custom domain. The engine loads the .cube directly (see
CubeLUTLoader) rather than through the native .utex texture pipeline, so
there is no texture_index here.
"""
lut_uri_offset: int
lut_size: int
domain_min: tuple[float, float, float]
domain_max: tuple[float, float, float]
@dataclass(frozen=True)
class MaterialRecord:
name_offset: int
flags: int
base_color_factor: tuple[float, float, float, float]
emissive_factor: tuple[float, float, float]
normal_scale: float
metallic_factor: float
roughness_factor: float
occlusion_strength: float
alpha_cutoff: float
base_color_texture_index: int
normal_texture_index: int = INVALID_INDEX
metallic_texture_index: int = INVALID_INDEX
roughness_texture_index: int = INVALID_INDEX
emissive_texture_index: int = INVALID_INDEX
occlusion_texture_index: int = INVALID_INDEX
height_texture_index: int = INVALID_INDEX
height_scale: float = DEFAULT_HEIGHT_SCALE
height_midlevel: float = 0.5
height_remap_min: float = 0.0
height_remap_max: float = 1.0
roughness_texture_channel: int = TEXTURE_CHANNEL_R
metallic_texture_channel: int = TEXTURE_CHANNEL_R
@dataclass(frozen=True)
class EntityRecord:
entity_id: int
parent_entity_id: int
name_offset: int
first_mesh_record_index: int
mesh_record_count: int
flags: int
local_bounds: AABB
world_bounds: AABB
local_transform_rows: list[list[float]]
@dataclass(frozen=True)
class MeshRecord:
entity_id: int
mesh_name_offset: int
material_index: int
index_type: int
vertex_count: int
index_count: int
vertex_stride_bytes: int
flags: int
vertex_data_offset: int
index_data_offset: int
vertex_data_size_bytes: int
index_data_size_bytes: int
estimated_gpu_bytes: int
edge_index_data_offset: int
edge_index_count: int
local_bounds: AABB
@dataclass(frozen=True)
class SkeletonRecord:
entity_id: int
name_offset: int
first_joint_record_index: int
joint_record_count: int
@dataclass(frozen=True)
class MuscleRecord:
skeleton_entity_id: int
name_offset: int
flags: int
forward_joint_offset: int
forward_tip_joint_offset: int
origin_joint_offset: int
origin_tip_joint_offset: int
origin_fraction: float
origin_offset: tuple[float, float, float]
insertion_joint_offset: int
insertion_tip_joint_offset: int
insertion_fraction: float
insertion_offset: tuple[float, float, float]
belly_radius: float
tendon_radius: float
max_contraction: float
fiber_compliance: float
cross_compliance: float
volume_compliance: float
damping: float
bone_radius: float
skin_influence: float
rings: int
segments: int
driver_joint_offset: int
driver_start_angle: float
driver_full_angle: float
MUSCLE_DEFAULTS: dict[str, float] = {
"maxContraction": 0.25,
"fiberCompliance": 2e-6,
"crossCompliance": 4e-6,
"volumeCompliance": 0.0,
"damping": 6.0,
"boneRadius": 0.0,
"skinInfluence": 0.03,
"rings": 7,
"segments": 8,
}
def load_muscle_rig(path: Path) -> dict:
"""Reads and validates a muscle rig description (`--muscles`).
Schema (angles in degrees, lengths in model units, offsets in the character
frame lateral-left / up / forward):
{
"skeleton": "Armature", # optional skeleton name
"forwardReference": {"from": "LeftFoot", "to": "LeftToeBase"}, # optional
"muscles": [
{"name": "bicepsL",
"origin": {"joint": "LeftArm", "fraction": 0.15, "offset": [0, 0, 0.03], "tip": null},
"insertion": {"joint": "LeftForeArm", "fraction": 0.2, "offset": [0, 0, 0.01]},
"bellyRadius": 0.045, "tendonRadius": 0.012,
"maxContraction": 0.25, "fiberCompliance": 2e-6, "crossCompliance": 4e-6,
"volumeCompliance": 0, "damping": 6, "boneRadius": 0.03, "skinInfluence": 0.03,
"rings": 7, "segments": 8,
"driver": {"joint": "LeftForeArm", "startAngle": 10, "fullAngle": 110}}
]
}
"""
with open(path, "r", encoding="utf-8") as handle:
rig = json.load(handle)
return validate_muscle_rig(rig)
def validate_muscle_rig(rig: object) -> dict:
if not isinstance(rig, dict) or not isinstance(rig.get("muscles"), list) or not rig["muscles"]:
raise RuntimeError("Muscle rig JSON must be an object with a non-empty 'muscles' list")
forward = rig.get("forwardReference")
if forward is not None and (not isinstance(forward, dict) or not forward.get("from") or not forward.get("to")):
raise RuntimeError("Muscle rig 'forwardReference' needs 'from' and 'to' joint names")
for index, muscle in enumerate(rig["muscles"]):
if not isinstance(muscle, dict) or not muscle.get("name"):
raise RuntimeError(f"Muscle #{index} needs a 'name'")
for key in ("origin", "insertion"):
attachment = muscle.get(key)
if not isinstance(attachment, dict) or not attachment.get("joint"):
raise RuntimeError(f"Muscle {muscle['name']}: '{key}' needs a 'joint'")
offset = attachment.get("offset", [0.0, 0.0, 0.0])
if not isinstance(offset, (list, tuple)) or len(offset) != 3:
raise RuntimeError(f"Muscle {muscle['name']}: '{key}.offset' must have three components")
for key in ("bellyRadius", "tendonRadius"):
if float(muscle.get(key, 0.0)) <= 0.0:
raise RuntimeError(f"Muscle {muscle['name']}: '{key}' must be positive")
if int(muscle.get("rings", MUSCLE_DEFAULTS["rings"])) < 2 or int(muscle.get("segments", MUSCLE_DEFAULTS["segments"])) < 3:
raise RuntimeError(f"Muscle {muscle['name']}: needs rings >= 2 and segments >= 3")
driver = muscle.get("driver")
if driver is not None and (not isinstance(driver, dict) or not driver.get("joint")):
raise RuntimeError(f"Muscle {muscle['name']}: 'driver' needs a 'joint'")
return rig
def build_muscle_records(rig: dict, skeletons: list["SkeletonRecord"], string_table: "StringTableBuilder") -> list[MuscleRecord]:
"""Resolves a validated rig against the exported skeletons. The rig's
'skeleton' name selects the target skeleton; the first exported skeleton is
used otherwise."""
if not skeletons:
raise RuntimeError("--muscles requires a rigged (armature) export")
target = skeletons[0]
wanted = rig.get("skeleton")
if wanted:
matches = [
skeleton for skeleton in skeletons
if string_table.string_at(skeleton.name_offset) == wanted
]
if not matches:
raise RuntimeError(f"--muscles: skeleton '{wanted}' not found in the export")
target = matches[0]
forward = rig.get("forwardReference")
forward_joint = string_table.add(forward["from"]) if forward else INVALID_INDEX
forward_tip = string_table.add(forward["to"]) if forward else INVALID_INDEX
def attachment_fields(attachment: dict) -> tuple[int, int, float, tuple[float, float, float]]:
tip = attachment.get("tip")
offset = attachment.get("offset", [0.0, 0.0, 0.0])
return (
string_table.add(str(attachment["joint"])),
string_table.add(str(tip)) if tip else INVALID_INDEX,
float(attachment.get("fraction", 0.5)),
(float(offset[0]), float(offset[1]), float(offset[2])),
)
records: list[MuscleRecord] = []
for muscle in rig["muscles"]:
origin_joint, origin_tip, origin_fraction, origin_offset = attachment_fields(muscle["origin"])
insertion_joint, insertion_tip, insertion_fraction, insertion_offset = attachment_fields(muscle["insertion"])
driver = muscle.get("driver")
flags = MUSCLE_FLAG_HAS_DRIVER if driver else 0
def value(key: str) -> float:
return float(muscle.get(key, MUSCLE_DEFAULTS[key]))
records.append(
MuscleRecord(
skeleton_entity_id=target.entity_id,
name_offset=string_table.add(str(muscle["name"])),
flags=flags,
forward_joint_offset=forward_joint,
forward_tip_joint_offset=forward_tip,
origin_joint_offset=origin_joint,
origin_tip_joint_offset=origin_tip,
origin_fraction=origin_fraction,
origin_offset=origin_offset,
insertion_joint_offset=insertion_joint,
insertion_tip_joint_offset=insertion_tip,
insertion_fraction=insertion_fraction,
insertion_offset=insertion_offset,
belly_radius=float(muscle["bellyRadius"]),
tendon_radius=float(muscle["tendonRadius"]),
max_contraction=value("maxContraction"),
fiber_compliance=value("fiberCompliance"),
cross_compliance=value("crossCompliance"),
volume_compliance=value("volumeCompliance"),
damping=value("damping"),
bone_radius=value("boneRadius"),
skin_influence=value("skinInfluence"),
rings=int(muscle.get("rings", MUSCLE_DEFAULTS["rings"])),
segments=int(muscle.get("segments", MUSCLE_DEFAULTS["segments"])),
driver_joint_offset=string_table.add(str(driver["joint"])) if driver else INVALID_INDEX,
driver_start_angle=math.radians(float(driver.get("startAngle", 0.0))) if driver else 0.0,
driver_full_angle=math.radians(float(driver.get("fullAngle", 90.0))) if driver else 0.0,
)
)
return records
@dataclass(frozen=True)
class SkeletonJointRecord:
parent_joint_index: int
joint_path_offset: int
flags: int
bind_transform_rows: list[list[float]]
rest_transform_rows: list[list[float]]
@dataclass(frozen=True)
class SkinRecord:
entity_id: int
mesh_record_index: int
skeleton_entity_id: int
joint_count: int
first_joint_mapping_index: int
joint_index_data_offset: int
joint_weight_data_offset: int
vertex_count: int
@dataclass(frozen=True)
class SkinJointMappingRecord:
skeleton_joint_index: int
@dataclass(frozen=True)
class AnimationClipRecord:
name_offset: int
duration: float
first_channel_record_index: int
channel_record_count: int
flags: int = 0
@dataclass(frozen=True)
class AnimationChannelRecord:
joint_path_offset: int
first_translation_keyframe_index: int
translation_keyframe_count: int
first_rotation_keyframe_index: int
rotation_keyframe_count: int
flags: int = 0
@dataclass(frozen=True)
class TranslationKeyframeRecord:
time: float
value: tuple[float, float, float]
@dataclass(frozen=True)
class RotationKeyframeRecord:
time: float
value: tuple[float, float, float, float]
@dataclass(frozen=True)
class ExportedTexture:
name: str
uri: str
width: int
height: int
mip_count: int
source_path: Optional[Path] = None
source_image_name: Optional[str] = None
channel: int = TEXTURE_CHANNEL_R
texture_format: int = TEXTURE_FORMAT_UNKNOWN
# Per-pixel colour nodes between the image and the socket it feeds (Invert, Gamma,
# Bright/Contrast, Hue/Saturation/Value, RGB Curves, ColorRamp), in the order they
# apply; staging writes the adjusted image (see adjust_staged_image).
adjustments: tuple["ImageAdjustment", ...] = ()
# The image is sRGB-encoded (its Blender colour space is not data): the adjustments
# run on linear values, as Blender's shader nodes do.
srgb_source: bool = False
@dataclass(frozen=True)
class ImageAdjustment:
"""One per-pixel colour operation of a shader node, applied to linear RGB values
exactly as Blender's node does it.
kind: "invert" (no params), "gamma" (gamma), "bright_contrast" (bright, contrast),
"hue_saturation" (hue, saturation, value), "curves" (three lookup tables of
CURVE_LUT_SIZE samples over [0, 1], for R, G and B) or "ramp" (three tables for
R, G and B, indexed by the luminance of the input).
fac: how much of the result is mixed over the input, for the nodes that have one.
"""
kind: str
params: tuple[float, ...] = ()
fac: float = 1.0
def key(self) -> str:
return hashlib.sha1(repr((self.kind, self.params, self.fac)).encode("utf-8")).hexdigest()[:8]
@dataclass(frozen=True)
class UVTransform:
"""A texture-coordinate scale and offset applied to a mesh's first UV map, read
from the Mapping node in front of a material's image textures."""
scale: tuple[float, float]
offset: tuple[float, float]
def apply(self, uv: tuple[float, float]) -> tuple[float, float]:
return (uv[0] * self.scale[0] + self.offset[0], uv[1] * self.scale[1] + self.offset[1])
@dataclass(frozen=True)
class ExportedMaterial:
name: str
base_color_factor: tuple[float, float, float, float]
emissive_factor: tuple[float, float, float]
normal_scale: float
metallic_factor: float
roughness_factor: float
occlusion_strength: float
alpha_cutoff: float
base_color_texture: Optional[ExportedTexture]
normal_texture: Optional[ExportedTexture] = None
metallic_texture: Optional[ExportedTexture] = None
roughness_texture: Optional[ExportedTexture] = None
emissive_texture: Optional[ExportedTexture] = None
occlusion_texture: Optional[ExportedTexture] = None
height_texture: Optional[ExportedTexture] = None
# Blender's Displacement node Scale is a world-space displacement distance (typically
# a fraction of a meter), while the engine's heightScale is a UV-normalized ray-march
# depth fraction — these are not the same unit and there is no exact conversion without
# knowing the mesh's texel density. This value is carried through as a reasonable
# starting point, not a precise conversion; expect to retune heightScale after import.
height_scale: float = DEFAULT_HEIGHT_SCALE
# Always the neutral default (0.5 = no additional shift) for Displacement-sourced height —
# Blender's Midlevel is NOT copied here. The engine's POM is unidirectional (cannot bulge
# outward past the true polygon surface the way Blender's signed displacement-around-
# Midlevel can), so heightMidlevel is just an additive shift, not a true zero-reference;
# copying Blender's Midlevel into it would not reproduce "neutral gray = no visible depth".
# Blender's Midlevel is used to derive height_remap_max instead — see
# _displacement_remap_max.
height_midlevel: float = 0.5
# Derived from Blender's Displacement Midlevel when present (clamped to (0, 1]): raw values
# at/above this clip to "no depth", values below get contrast-stretched into the full depth
# range. Identity (0.0, 1.0) when no Midlevel is available (e.g. Bump-sourced height).
height_remap_min: float = 0.0
height_remap_max: float = 1.0
roughness_texture_channel: int = TEXTURE_CHANNEL_R
metallic_texture_channel: int = TEXTURE_CHANNEL_R
# MATERIAL_ALPHA_MODE_*: blended when the surface is not fully opaque in Blender.
alpha_mode: int = MATERIAL_ALPHA_MODE_OPAQUE
# A texture feeding the Principled Alpha input that is not the base colour
# texture's own alpha. The engine reads alpha from the base colour texture only,
# so staging writes it into that texture's alpha channel (see compose_alpha_texture).
alpha_texture: Optional[ExportedTexture] = None
@dataclass(frozen=True)
class ValidationTangent:
xyz: tuple[float, float, float]
handedness: float
@dataclass(frozen=True)
class ValidationMesh:
name: str
vertex_count: int
index_count: int
positions: list[tuple[float, float, float]]
normals: list[tuple[float, float, float]]
tangents: list[ValidationTangent]
uv0: list[tuple[float, float]]
indices: list[int]
edge_indices: list[int]
@dataclass(frozen=True)
class ExportedMesh:
entity_name: str
parent_entity_name: Optional[str]
mesh_name: str
local_transform_rows: list[list[float]]
local_bounds: AABB
world_bounds: AABB
vertices: bytes
indices: bytes
edge_indices: bytes
vertex_count: int
index_count: int
edge_index_count: int
index_type: int
material: ExportedMaterial
skin_binding: Optional["ExportedSkinBinding"]