Repository navigation
Expand file tree
/
Copy pathfcv.py
More file actions
2655 lines (2460 loc) · 120 KB
/
Copy pathfcv.py
File metadata and controls
2655 lines (2460 loc) · 120 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
"""Episode I motion: ``FPK`` packs of ``FCV`` clips -> poses and glTF animations.
The format is read the way the game reads it. The executable keeps its
symbols, and the functions below are the ones this module follows (USA
SLUS_204.69; the names are the executable's own):
* ``FCV2_resetPack`` (0x30d908): the clip header. ``FCV\\0``, u16 format,
u16 frame count, u16 first frame, u16 last frame, s16 frame offset; from
format 2 an attribute stream follows at +0x10 (u32 byte size, then records
of u16 size, u16 type) and the key stream starts after it. A key's u16
time is a fraction of the clip's length: from format 2, seconds = u16 *
frame count / 65535 / 30; below format 2, u16 * (last - first frame) /
65535 / 30 and no frame offset.
* ``FCV2_getPackAttribute``: each skeleton block's part of the key stream
starts with a type-4 record: u16 flags, u16 value mask, and in the 16-byte
form three block indices (translation link, pivot, rotation link). Any
other record type ends the key stream (the routine returns ``defaultAttr``,
flags 0xFFFF, without moving on).
* ``FCV2_getPackValue`` / ``FCV2_getPackVal``: one curve, read each time
``get_fcvpack`` / ``get_fcvpack_fix`` / ``get_fcvpack_flag`` (called from
``JNT_getVal``) finds a mask bit set. u16 key count, u16 flags whose low
nibble is the kind (0 = nothing stored, 1 = one float, 3 = keys; the upper
bits, 0x8000 on many disc curves, are not the kind); a key is u16 type,
u16 time, f32 value, and one tangent (type 4) or two (type 1). Types 1,
2 and 4 are cubic Hermite, 0 linear, 3 a step.
* ``JNT_computeMatrix`` (0x314a38), the routine ``ACT_resetAnimation``
registers for every actor, which samples each body block with
``JNT_getVal`` (0x30f038) and builds its matrix with
``JNT_constructMatrix`` (0x30f938): how the values become matrices. The
value mask's bits 0-2 are translation, 3-5 rotation (about Z, Y, X), 6-8
scale, and 9 marks the root's extra flag value (the game reads it when
bit 7 is set; every disc record sets bits 7 and 9 together). Which of
them a block reads depends on the ``.jnt`` block type: 1 (and 0 among
the body blocks) a node that may take its position or rotation from
another block, 5 a node that does not, and 3 / 2 / 4 the root, links and
end of a chain. A chain whose end names a target block is solved
toward it (two bones by the law of cosines, one bone by aiming); the legs
of the party members are driven this way, two solved chains a frame.
* ``JNT_getStaticVal`` (body blocks) / ``JNT_getStaticVal2`` (the blocks
after them): a block the clip does not reach keeps its ``.jnt``
translation and rotation.
Every clip on the disc is laid out with one curve per set mask bit (a
root record: bits 0-8, then the flag when bit 7 is set, which is how the
game reads it), so every clip can be read without knowing its skeleton.
That is a property of the disc's clips, checked by ``fits``: the game itself
reads only the bits ``JNT_getVal`` consults for the block's type. Posing a
clip needs the ``.jnt`` it was made for. The game does not compare names:
``FCV2_readAttribute`` and ``JNT_readAttribute`` each turn the 8-byte name
field into a key, u32 word 0 * 31 + u32 word 1 (0 when there is no name),
and ``JNT_computeMatrix`` takes the ``JNT_getVal`` path when the two keys are
equal. The kit pairs clips with skeletons by that key (``attribute_key``);
on the USA disc that gives exactly the pairs comparing names would.
* ``EXM_CalcExMotion`` (the hair and cloth blocks from ``JNT_hairID`` to
primary + secondary): simulated a game tick at a time when a clip is baked
(``simulate``); ``pose`` alone leaves them at rest. Wind, the hip sway
and the skirt collision are not followed (skirt chains stay at rest).
Not followed: ``JNT_computeHair`` (only hair_test.c uses it),
``JNT_interpolate`` (blending between two clips), and the move back onto
its parent that ``JNT_constructMatrix`` applies to the root block when the
actor's channel mask has its translation bits clear (``& 7 == 0``, travel
masked off; characters start with 0x1FF, so it does not happen there).
Playback has not been compared with the running game.
"""
from __future__ import annotations
import json
import math
import struct
from dataclasses import dataclass, field
from typing import Optional
FPS = 30.0
# FCV2_setStep(slot->speed) keeps |speed| / 2. The speed starts at 1/30 and
# a type-2 range with bit 7 set would change it; no range on the disc does.
STEP = 1.0 / 60.0
class FcvError(ValueError):
"""Raised for packs, clips or skeletons this module cannot read."""
# ---------------------------------------------------------------------------
# containers
# ---------------------------------------------------------------------------
@dataclass
class Curve:
"""One value of one block. ``kind``: 0 nothing stored (reads as 0.0),
1 a constant, 3 keys. A key is (type, time u16, value, tangent a,
tangent b); ``flags`` is the whole u16 the kind came from."""
kind: int
flags: int
value: float = 0.0
keys: list = field(default_factory=list)
@dataclass
class Channel:
"""A block's record in a clip: the attribute and its curves by mask bit
(0-2 translation, 3-5 rotation, 6-8 scale). A root (inherit, 0x8000)
record's flag value is kept as curve 9: the game reads it when mask bit
7 is set, whatever bit 9 says."""
flags: int
mask: int
translation_link: int
pivot_link: int
rotation_link: int
curves: dict
@dataclass
class Clip:
offset: int
size: int
format: int
frame_count: int
first_frame: int
last_frame: int
frame_offset: int
name: str # the skeleton it was made for ("" = unnamed)
ranges: list # type-2 records: (selector, speed/32, first, last)
channels: list
end_marker: bool
# FCV2_readAttribute's key for the name field: u32 word 0 * 31 + u32
# word 1 of the last type-1 record, 0 when there is none
attribute_key: int = 0
@property
def frames(self) -> int:
return self.last_frame - self.first_frame + 1
@property
def duration(self) -> float:
return (self.last_frame - self.first_frame) / FPS
def key_count(self) -> int:
return sum(len(c.keys) for ch in self.channels for c in ch.curves.values())
def parse_fpk(data: bytes) -> list[int]:
"""Clip offsets of an ``FPK`` pack, one per slot (slots can share a clip)."""
if data[:3] != b"FPK" or len(data) < 0x10:
raise FcvError("not an FPK pack")
count = struct.unpack_from("<I", data, 8)[0]
if count > 4096 or 0x10 + 4 * count > len(data):
raise FcvError("FPK slot table beyond the file")
offs = list(struct.unpack_from("<%dI" % count, data, 0x10))
for o in offs:
if o + 0x10 > len(data):
raise FcvError("FPK slot points beyond the file")
return offs
def _curve(data: bytes, p: int, end: int) -> tuple[Curve, int]:
if p + 4 > end:
raise FcvError("curve header beyond the clip")
n, flags = struct.unpack_from("<HH", data, p)
kind = flags & 0xF
if kind == 1:
if p + 8 > end:
raise FcvError("constant beyond the clip")
return Curve(1, flags, struct.unpack_from("<f", data, p + 4)[0]), p + 8
if kind == 3:
keys = []
p += 4
for _ in range(n):
if p + 8 > end:
raise FcvError("key beyond the clip")
kt, kf = struct.unpack_from("<HH", data, p)
if kt in (0, 2, 3):
keys.append((kt, kf, struct.unpack_from("<f", data, p + 4)[0], 0.0, 0.0))
p += 8
elif kt == 4:
if p + 12 > end:
raise FcvError("key beyond the clip")
v, a = struct.unpack_from("<2f", data, p + 4)
keys.append((kt, kf, v, a, a))
p += 12
elif kt == 1:
if p + 16 > end:
raise FcvError("key beyond the clip")
v, a, b = struct.unpack_from("<3f", data, p + 4)
keys.append((kt, kf, v, a, b))
p += 16
else:
raise FcvError("unknown key type %d at 0x%x" % (kt, p))
if not keys:
raise FcvError("keyed curve with no keys at 0x%x" % p)
return Curve(3, flags, keys[0][2], keys), p
return Curve(0, flags), p + 4
def _attribute_key(raw: bytes) -> int:
"""FCV2_readAttribute / JNT_readAttribute: words[0] * 31 + words[1]."""
w0, w1 = struct.unpack("<II", raw[:8].ljust(8, b"\0"))
return (w0 * 31 + w1) & 0xFFFFFFFF
def parse_clip(data: bytes, offset: int, end: Optional[int] = None,
strict: bool = False) -> Clip:
"""Read the clip at ``offset``. ``end`` is where the next clip (or the
end of the pack) starts; the read fails when it runs past it. The key
stream ends where the game's does: at a 0xFFFF record, or at a record
that is not type 4 (``FCV2_getPackAttribute`` then returns
``defaultAttr``), or when the clip's room runs out. Bytes left after an
end like that are allowed unless ``strict`` (the sweep uses it to check
that every disc clip is read to exactly its last byte)."""
if end is None:
end = len(data)
if data[offset:offset + 4] != b"FCV\0":
raise FcvError("no FCV clip at 0x%x" % offset)
if offset + 0x10 > end:
raise FcvError("FCV header beyond the clip")
fmt, count, first, last, foff = struct.unpack_from("<HHHHh", data, offset + 4)
name, ranges, akey = "", [], 0
if fmt >= 2:
if offset + 0x14 > end:
raise FcvError("attribute stream beyond the clip")
size = struct.unpack_from("<I", data, offset + 0x10)[0]
if size < 4 or offset + 0x10 + size > end:
raise FcvError("attribute stream beyond the clip")
p, stop = offset + 0x14, offset + 0x10 + size
while p + 4 <= stop:
rsize, rtype = struct.unpack_from("<HH", data, p)
if rtype == 0 or rsize < 4 or p + rsize > stop:
break
body = data[p + 4:p + rsize]
if rtype == 1:
name = body[:8].split(b"\0")[0].decode("ascii", "replace")
akey = _attribute_key(body[:8])
elif rtype == 2 and len(body) >= 6:
sel, speed, f0, f1 = struct.unpack_from("<BbHH", body, 0)
ranges.append((sel, speed / 32.0, f0, f1))
p += rsize
p = stop
else:
p = offset + 0x10
channels, end_marker, stopped = [], False, False
while p + 8 <= end:
rsize, rtype = struct.unpack_from("<HH", data, p)
if rtype != 4:
stopped = True # defaultAttr: the stream ends here
break
nxt = p + 4 + rsize
if nxt > end or (rsize >= 10 and p + 14 > end):
raise FcvError("clip at 0x%x: a block record runs past the clip (0x%x)"
% (offset, p))
flags, mask = struct.unpack_from("<HH", data, p + 4)
if flags == 0xFFFF:
end_marker = stopped = True
p = nxt
break
tl = pl = rl = 0
if rsize >= 10:
tl, pl, rl = struct.unpack_from("<HHH", data, p + 8)
curves = {}
p = nxt
if flags & 0x8000:
# JNT_getVal / JNT_getVal2: translation (bits 0-2), rotation (3-5),
# scale (6-8), then get_fcvpack_flag on the mask shifted right by
# 7: one more value when bit 7 is set (kept as curve 9)
for bit in range(9):
if mask & (1 << bit):
curves[bit], p = _curve(data, p, end)
if mask & 0x80:
curves[9], p = _curve(data, p, end)
else:
for bit in range(16):
if mask & (1 << bit):
curves[bit], p = _curve(data, p, end)
channels.append(Channel(flags, mask, tl, pl, rl, curves))
if p > end or (p != end and (strict or not stopped)):
raise FcvError("clip at 0x%x: the key stream stops at 0x%x, the clip at 0x%x"
% (offset, p, end))
return Clip(offset, end - offset, fmt, count, first, last, foff, name, ranges,
channels, end_marker, akey)
def read_pack(data: bytes, strict: bool = False) -> list[tuple[list[int], Clip]]:
"""Every clip of a pack as (slots that point at it, clip), in file order."""
offs = parse_fpk(data)
order = sorted(set(offs))
out = []
for k, o in enumerate(order):
end = order[k + 1] if k + 1 < len(order) else len(data)
out.append(([s for s, x in enumerate(offs) if x == o],
parse_clip(data, o, end, strict)))
return out
# ---------------------------------------------------------------------------
# the skeleton as the motion code sees it
# ---------------------------------------------------------------------------
@dataclass
class Rig:
"""A ``.jnt`` read for posing. The block ranges, as ``JNT_computeMatrix``
walks them: ``[0, hair)`` the body, read from the clip with ``JNT_getVal``;
``[hair, primary + secondary)`` hair and cloth, simulated while the game
runs (``EXM_CalcExMotion``, which reads no record); then ``aprim``
(additional_primary_count) blocks through ``JNT_getVal2``, which go on
reading the clip from the record after the body's; then static blocks
(``JNT_getStaticVal2``) up to the table's end. ``extra`` is
additional_primary + additional_secondary. ``hair`` is ``JNT_hairID``:
``primary``, plus ``secondary`` when the ``.jnt`` has no type-5 attribute
record (the tag's word count is then 0), plus the tag's low half when
its kind is 0x8A."""
name: str
primary: int
secondary: int
extra: int
types: list
parents: list # the block whose matrix this one starts from
translations: list
rotations: list
directions: list # +0x38: its sign picks a chain link's bend
limits: list # None or (min3, flags, max3)
deferred: list # bool: the block has a shape-binding record
hair: int = -1 # JNT_hairID; -1 = primary (rigs built by hand)
aprim: int = -1 # additional_primary_count; -1 = extra
attribute_key: int = 0 # JNT_readAttribute's key for the name (0 = none)
def parse_rig(data: bytes) -> Rig:
if data[:4] != b"JNT\0" or len(data) < 0x20:
raise FcvError("not a jnt file")
version, limit, prim, sec, aprim, asec, asize = struct.unpack_from("<6Hi", data, 4)
if version >= 2 and asize < 4:
raise FcvError("jnt attribute size %d is too small" % asize)
base = 0x10 + asize if version >= 2 else 0x10
name, akey = "", 0
words, tag = 0, 0 # JNT_readAttribute starts from dummyCntFree
if version >= 2:
# JNT_readAttribute: every record up to type 0 or the attribute size;
# the last type-1 record names the skeleton, a type-5 record is the tag
off = 4
while 0x10 + off + 4 <= len(data):
rsize, rtype = struct.unpack_from("<HH", data, 0x10 + off)
if rtype == 1 and 0x10 + off + 12 <= len(data):
name = data[0x14 + off:0x1C + off].split(b"\0")[0].decode("ascii", "replace")
akey = _attribute_key(data[0x14 + off:0x1C + off])
elif rtype == 5 and 0x10 + off + 12 <= len(data):
words, tag = struct.unpack_from("<ii", data, 0x14 + off)
if rtype == 0 or rsize == 0:
break
off += rsize
if off >= asize:
break
if base + 64 * limit > len(data):
raise FcvError("jnt block table beyond the file")
hair = prim + (sec if words == 0 else 0)
if (tag & 0xFFFF0000) == 0x008A0000:
hair += tag & 0xFFFF
rig = Rig(name, prim, sec, aprim + asec, [], [], [], [], [], [], [],
min(hair, limit), aprim, akey)
for i in range(limit):
o = base + 64 * i
t, _fl, lo = struct.unpack_from("<HHi", data, o)
rig.types.append(t)
rig.parents.append(struct.unpack_from("<H", data, o + 0x0E)[0])
rig.translations.append(struct.unpack_from("<3f", data, o + 0x10))
rig.rotations.append(struct.unpack_from("<3f", data, o + 0x20))
rig.directions.append(struct.unpack_from("<f", data, o + 0x38)[0])
lim, deferred = None, False
if lo and 0 < o + lo and o + lo + 4 <= len(data):
h = o + lo
vo, do = struct.unpack_from("<HH", data, h)
deferred = bool(do)
if vo and h + vo + 28 <= len(data):
mn = struct.unpack_from("<3f", data, h + vo)
fl = struct.unpack_from("<H", data, h + vo + 12)[0]
mx = struct.unpack_from("<3f", data, h + vo + 16)
lim = (mn, fl, mx)
rig.limits.append(lim)
rig.deferred.append(deferred)
return rig
# the mask bits each block type reads: JNT_getVal (body blocks) reads type 0
# like type 1, JNT_getVal2 (the blocks after hair and cloth) reads nothing
# for it; the other types read the same in both. A root (inherit) record
# reads bits 0-8 and the flag on bit 7; bit 9, where the disc's clips store
# that flag, is allowed and read by nothing.
_READS = {0: 0x1FF, 1: 0x1FF, 5: 0x1FF, 3: 0x3F, 2: 0x1F8, 4: 0, 6: 0}
_READS_ROOT = 0x3FF
def _ranges(rig: Rig) -> tuple[int, int, int]:
"""(body end, getVal2 start, getVal2 end) as JNT_computeMatrix walks the
blocks on its normal (EXM_CalcExMotion) path."""
n = len(rig.types)
body = min(rig.hair if rig.hair >= 0 else rig.primary, n)
g2 = min(max(body, rig.primary + rig.secondary), n)
aprim = rig.aprim if rig.aprim >= 0 else rig.extra
return body, g2, min(max(g2, rig.primary + rig.secondary + aprim), n)
def _record_fits(typ: int, ch: Channel, in_body: bool) -> bool:
reads = _READS.get(typ)
if reads is None:
return False
if typ == 0 and not in_body:
reads = 0
if ch.flags & 0x8000:
reads = _READS_ROOT
return not ch.mask & ~reads
def fits(rig: Rig, clip: Clip) -> bool:
"""True when the clip's records line up with the skeleton's body blocks:
no more records than blocks, and no body record stores a value
``JNT_getVal`` would not read for that block's type (it would read the
next block's record from the wrong place). A record may store less:
what it leaves out comes from the ``.jnt`` (scale: 1). Records after
the body are read by ``JNT_getVal2`` from the record after the body's
(see ``pose``), which stops at the first that does not line up; they do
not decide whether the clip fits. A clip with no records at all is the
rest pose (``JNT_getStaticVal`` everywhere), and fits."""
if len(clip.channels) > len(rig.types):
return False
body = _ranges(rig)[0]
for i, ch in enumerate(clip.channels[:body]):
if not _record_fits(rig.types[i], ch, True):
return False
return True
# ---------------------------------------------------------------------------
# curves
# ---------------------------------------------------------------------------
def eval_curve(curve: Curve, scale: float, t: float) -> float:
"""``FCV2_getPackVal`` at ``t`` seconds (the frame offset already added)."""
if curve.kind == 1:
return curve.value
if curve.kind != 3:
return 0.0
keys = curve.keys
first = keys[0][1] * scale
if t <= first:
return keys[0][2]
near_prev = near_next = None
near = first
prev = keys[0]
for nxt in keys[1:]:
dist = t - nxt[1] * scale
if dist < STEP:
near = abs(dist)
near_prev, near_next = prev, nxt
break
prev = nxt
if near_prev is None:
return keys[-1][2]
if near < STEP * 0.5:
return near_next[2]
pt, pf, pv = near_prev[0], near_prev[1] * scale, near_prev[2]
# the game reads no value from a step key that ends a segment
nf, nv = near_next[1] * scale, (0.0 if near_next[0] == 3 else near_next[2])
if pt == 3:
return pv
if nf <= pf: # two keys at one time (a damaged clip): nothing to blend
return near_next[2]
if pt == 0:
return pv + (nv - pv) * (t - pf) / (nf - pf)
tan_in = near_next[3] if near_next[0] in (1, 4) else 0.0
tan_out = near_prev[4] if pt == 1 else (near_prev[3] if pt == 4 else 0.0)
inv = 1.0 / (nf - pf)
x = t - pf
x2 = x * x
x3 = x2 * x
a = x2 * inv
b = x3 * inv * inv
c = 3.0 * x2 * inv * inv
e = 2.0 * b * inv
return (pv * (e - c + 1.0) + nv * (c - e)
+ tan_out * (b - a - a + x) + tan_in * (b - a))
# ---------------------------------------------------------------------------
# matrices: rotation (9 floats, row-major, column vectors), scale, position
# ---------------------------------------------------------------------------
_I3 = (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)
def _mm(a, b):
return (a[0] * b[0] + a[1] * b[3] + a[2] * b[6],
a[0] * b[1] + a[1] * b[4] + a[2] * b[7],
a[0] * b[2] + a[1] * b[5] + a[2] * b[8],
a[3] * b[0] + a[4] * b[3] + a[5] * b[6],
a[3] * b[1] + a[4] * b[4] + a[5] * b[7],
a[3] * b[2] + a[4] * b[5] + a[5] * b[8],
a[6] * b[0] + a[7] * b[3] + a[8] * b[6],
a[6] * b[1] + a[7] * b[4] + a[8] * b[7],
a[6] * b[2] + a[7] * b[5] + a[8] * b[8])
def _mv(a, v):
return (a[0] * v[0] + a[1] * v[1] + a[2] * v[2],
a[3] * v[0] + a[4] * v[1] + a[5] * v[2],
a[6] * v[0] + a[7] * v[1] + a[8] * v[2])
def _mtv(a, v):
"""transpose(a) * v"""
return (a[0] * v[0] + a[3] * v[1] + a[6] * v[2],
a[1] * v[0] + a[4] * v[1] + a[7] * v[2],
a[2] * v[0] + a[5] * v[1] + a[8] * v[2])
def _rx(a):
c, s = math.cos(a), math.sin(a)
return (1.0, 0.0, 0.0, 0.0, c, -s, 0.0, s, c)
def _ry(a):
c, s = math.cos(a), math.sin(a)
return (c, 0.0, s, 0.0, 1.0, 0.0, -s, 0.0, c)
def _rz(a):
c, s = math.cos(a), math.sin(a)
return (c, -s, 0.0, s, c, 0.0, 0.0, 0.0, 1.0)
def _rzyx(r):
"""CUR_MATRIX_Rzyx4s: the triple is (about Z, about Y, about X)."""
return _mm(_mm(_rz(r[0]), _ry(r[1])), _rx(r[2]))
def _translate(m, v):
"""CUR_MATRIX_Txyz4s: move along the matrix's own scaled axes."""
r, s, t = m
d = _mv(r, (s[0] * v[0], s[1] * v[1], s[2] * v[2]))
return (r, s, (t[0] + d[0], t[1] + d[1], t[2] + d[2]))
def _rotate(m, rot):
return (_mm(m[0], rot), m[1], m[2])
def _scale(m, v):
s = m[1]
return (m[0], (s[0] * v[0], s[1] * v[1], s[2] * v[2]), m[2])
def _align_x(d):
"""alignXAxis + MATRIX_transpose3: the rotation (about Z, then Y) that
turns the X axis onto ``d``."""
x, y, z = d
rxy = math.hypot(x, y)
ln = math.sqrt(x * x + y * y + z * z)
if ln == 0.0:
return _I3
if rxy == 0.0:
a, b = math.atan2(z / ln, 0.0), 0.0
else:
a, b = math.atan2(z / ln, rxy / ln), math.atan2(-y / rxy, x / rxy)
m = _mm(_ry(a), _rz(b))
return (m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8])
_IDENT = (_I3, (1.0, 1.0, 1.0), (0.0, 0.0, 0.0))
def _bend(root_len, upper, lower):
"""The angle at the chain root for a two-bone reach of ``root_len``."""
a = abs(upper)
den = (a + a) * root_len
cos = (root_len * root_len + a * a - lower * lower) / den if den else 1.0
sin = math.sqrt(max(0.0, 1.0 - cos * cos))
y = sin if upper >= 0.0 else -sin
if cos > 1.0:
cos, y = 1.0, 0.0
elif cos < -1.0:
cos, y = -1.0, 0.0
return math.atan2(y, cos)
def _record_map(rig: Rig, clip: Optional[Clip]) -> dict:
"""{block: record index} for the blocks that take a clip record, as
``JNT_computeMatrix`` hands them out on its normal path: the body blocks
their own record; the ``JNT_getVal2`` blocks the records after the
body's, in order, up to the first that does not line up with the block."""
if clip is None:
return {}
chs = clip.channels
body, g2, g2end = _ranges(rig)
out = {i: i for i in range(min(body, len(chs)))}
if len(chs) >= body:
for k, i in enumerate(range(g2, g2end)):
j = body + k
if j >= len(chs) or not _record_fits(rig.types[i], chs[j], False):
break
out[i] = j
return out
def pose(rig: Rig, clip: Optional[Clip], frame: float, stats: Optional[dict] = None,
driven_only: bool = False) -> list:
"""World matrices of every block at ``frame`` (a frame number, 1/30 s;
``clip.first_frame`` is the clip's start), as (rotation 9-tuple, scale,
position) or None for a block that has no matrix. ``clip`` None gives
the rest pose. ``driven_only`` stops after the last block that takes a
record (the blocks past it only repeat their ``.jnt`` values under moving
parents).
The order is ``JNT_computeMatrix``'s. Body blocks (below ``rig.hair``)
are sampled the way ``JNT_getVal`` does, or take their ``.jnt`` values
(``JNT_getStaticVal``) past the clip's last record, and are built the way
``JNT_constructMatrix`` does. Hair and cloth blocks keep their rest pose
(the game simulates them, see ``simulate``) and read no record. The next
``additional_primary_count`` blocks follow ``JNT_getVal2`` with the
records after the body's, in order (the game's cursor does not move over
the hair records), up to the first record whose values that block's type
would not read (the game reads on out of step there; the kit stops); the
blocks after them are static (``JNT_getStaticVal2``)."""
n = len(rig.types)
world: list = [None] * n
channels = clip.channels if clip is not None else []
body, simulated, g2end = _ranges(rig)
rec_of = _record_map(rig, clip)
last_driven = max(rec_of) if rec_of else -1
one = (1.0, 1.0, 1.0)
# JNT_getVal2's work->channel_scale: a type-1 record without the inherit
# flag writes only the components it stores, and the rest are kept from
# the block before (in the game, from whatever ran before; 1 here)
g2_scale = [1.0, 1.0, 1.0]
if clip is not None:
scale = (clip.frame_count / 65535.0 / FPS if clip.format >= 2
else (clip.last_frame - clip.first_frame) / 65535.0 / FPS)
t = frame / FPS + (clip.frame_offset / FPS if clip.format >= 2 else 0.0)
# JNT_computeMatrix sets block 0 to the unit matrix; when a body record
# carries the inherit flag (0x8000) it builds from block 1 on, so block 0
# stays the unit matrix whatever its record holds
skip_root = any(c.flags & 0x8000 for c in channels[:body])
def start(i):
p = rig.parents[i]
if p == i or p >= n or world[p] is None:
return _IDENT
return world[p]
def read(ch, bit, fallback):
cv = ch.curves
return [eval_curve(cv[bit + k], scale, t) if (bit + k) in cv else fallback[k]
for k in range(3)]
def sample(i, ch):
"""(translation, rotation, scale) as JNT_getVal / JNT_getVal2 leave
them; ch None is JNT_getStaticVal (the .jnt values, unit scale)."""
typ, tr, ro = rig.types[i], rig.translations[i], rig.rotations[i]
if ch is None:
return list(tr), list(ro), list(one)
if ch.flags & 0x8000:
ct, cr, cs = read(ch, 0, tr), read(ch, 3, ro), read(ch, 6, one)
if typ not in (0, 1):
# the rest of the routine runs with an empty mask
ct = list(tr)
if typ in (2, 5):
cr, cs = list(ro), list(one)
elif typ == 3:
cr = list(ro)
elif typ in (0, 1, 5):
ct, cr, cs = read(ch, 0, tr), read(ch, 3, ro), read(ch, 6, one)
elif typ == 3:
ct, cr, cs = read(ch, 0, tr), read(ch, 3, ro), list(one)
elif typ == 2:
ct, cr, cs = list(tr), read(ch, 3, ro), read(ch, 6, one)
else:
ct, cr, cs = list(tr), list(ro), list(one)
if typ == 2 and rig.limits[i]:
mn, fl, mx = rig.limits[i]
for k in range(3):
if (fl >> k) & 1 and cr[k] < mn[k]:
cr[k] = mn[k]
if (fl >> (k + 3)) & 1 and cr[k] > mx[k]:
cr[k] = mx[k]
return ct, cr, cs
sampled: list = [None] * n # JNT_getVal's per-block translation
chain = None
for i in range(n):
typ = rig.types[i]
tr, ro = rig.translations[i], rig.rotations[i]
is_body = i < body
has_rec = i in rec_of
if i > last_driven and driven_only and not (
is_body and chain is not None and not chain["closed"]):
break
if body <= i < simulated or (not has_rec and not is_body) \
or (is_body and not has_rec and typ == 0):
# hair and cloth (EXM_CalcExMotion while the game runs), or a block
# past the clip after them: JNT_getStaticVal2, the .jnt values.
# A body block of type 0 past the clip: JNT_getStaticVal leaves
# whatever its element held, so it gets no matrix here.
if typ in (1, 2, 3, 4, 5):
world[i] = _rotate(_translate(start(i), tr), _rzyx(ro))
continue
ch = channels[rec_of[i]] if has_rec else None
cf = ch.flags if ch is not None else 0
ct, cr, cs = sample(i, ch)
if not is_body and ch is not None:
if cf & 0x8000:
g2_scale = [1.0, 1.0, 1.0] if typ == 5 else list(read(ch, 6, one))
elif typ == 1:
for k in range(3):
if 6 + k in ch.curves:
g2_scale[k] = eval_curve(ch.curves[6 + k], scale, t)
cs = list(g2_scale)
elif typ == 5:
g2_scale = list(cs)
sampled[i] = ct
if i == 0 and skip_root:
world[0] = _IDENT
continue
if typ == 1 or (typ == 0 and is_body):
m = start(i)
if cf & 0xE:
if cf & 4:
if ch.translation_link < i and world[ch.translation_link] is not None:
m = (m[0], m[1], world[ch.translation_link][2])
else:
m = _translate(m, ct)
if cf & 8:
# CUR_MATRIX_SetR copies the three axis rows, scale included
if ch.rotation_link < i and world[ch.rotation_link] is not None:
m = (world[ch.rotation_link][0], world[ch.rotation_link][1], m[2])
else:
m = _scale(_rotate(m, _rzyx(cr)), cs)
else:
m = _rotate(_translate(m, ct), _rzyx(cr))
if is_body: # JNT_constructMatrix scales; JNT_getVal2 does not
m = _scale(m, cs)
if rig.deferred[i]:
if not cf & 4:
m = (m[0], m[1], tuple(ct))
elif ch.translation_link < i:
# JNT_constructMatrix: the linked block's sampled translation;
# JNT_getVal2: this block's own
lt = sampled[ch.translation_link] if is_body else ct
if lt is not None:
m = (m[0], m[1], tuple(lt))
world[i] = m
elif typ == 3:
m = _rotate(_translate(start(i), ct), _rzyx(cr))
world[i] = m
chain = {"base": i, "basis": m, "slots": [None], "length": 0.0, "closed": False}
elif typ == 2:
if chain is None:
raise FcvError("block %d: a chain link before any chain root" % i)
x = ct[0]
chain["length"] += x
if rig.directions[i] >= 0.0:
x = -x
chain["slots"].append({"t": [x, ct[1], ct[2]], "r": cr, "s": cs, "ch": ch})
elif typ == 4:
if chain is None:
raise FcvError("block %d: a chain end before any chain root" % i)
slots, base, basis = chain["slots"], chain["base"], chain["basis"]
chain["closed"] = True
solved = (cf & 0xE) and (cf & 4) and ch.translation_link < i \
and world[ch.translation_link] is not None
if not solved: # forward: each link in turn
cur = basis
for k in range(1, len(slots)):
s = slots[k]
s["t"][0] = abs(s["t"][0])
lch = s["ch"]
if lch is not None and lch.flags & 8:
if lch.rotation_link < i and world[lch.rotation_link] is not None:
cur = _translate(cur, s["t"])
cur = (world[lch.rotation_link][0], world[lch.rotation_link][1],
cur[2])
world[base + k] = cur
else:
cur = _scale(_rotate(_translate(cur, s["t"]), _rzyx(s["r"])), s["s"])
world[base + k] = cur
world[i] = _translate(cur, ct)
else:
target = world[ch.translation_link][2]
slots.append({"t": [ct[0], ct[1], ct[2]]})
count = len(slots)
if stats is not None:
stats["solved_%d" % (count - 1)] = stats.get("solved_%d" % (count - 1), 0) + 1
origin = basis[2]
d = _mtv(basis[0], (target[0] - origin[0], target[1] - origin[1],
target[2] - origin[2]))
if count == 4:
reach = math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2])
basis = _rotate(basis, _align_x(d))
first = slots[1]
fch = first["ch"]
pl = fch.pivot_link if fch is not None else n
if fch is not None and fch.flags & 2 and pl < n and world[pl] is not None:
pv = world[pl][2]
v = _mtv(basis[0], (pv[0] - basis[2][0], pv[1] - basis[2][1],
pv[2] - basis[2][2]))
ln = math.hypot(v[1], v[2])
ang = -math.atan2(-v[2] / ln, v[1] / ln) if ln else 0.0
basis = _scale(_rotate(basis, _rx(ang)), first["s"])
elif is_body:
# JNT_constructMatrix turns the basis by the first link's
# X rotation and scales it (0x310158..0x310168);
# JNT_getVal2 does the same and then reloads the unturned
# basis, so there the turn has no effect
basis = _scale(_rotate(basis, _rx(first["r"][2])), first["s"])
upper, lower = slots[2]["t"][0], slots[3]["t"][0]
cur = _rotate(basis, _rz(_bend(reach, upper, lower)))
world[base + 1] = cur
slots[2]["t"][0] = abs(upper)
knee = _translate(cur, slots[2]["t"])
d = _mtv(knee[0], (target[0] - knee[2][0], target[1] - knee[2][1],
target[2] - knee[2][2]))
cur = _rotate(knee, _align_x(d))
world[base + 2] = cur
world[i] = _translate(cur, slots[3]["t"])
# (a chain the clip scales does not land on its target in
# the game either, so only unscaled ones are measured)
if stats is not None and all(abs(x - 1.0) < 1e-6 for x in basis[1]) \
and abs(abs(upper) - abs(lower)) <= reach <= abs(upper) + abs(lower):
stats["measured"] = stats.get("measured", 0) + 1
stats["worst_miss"] = max(stats.get("worst_miss", 0.0),
math.dist(world[i][2], target))
elif count == 3:
cur = _rotate(basis, _align_x(d))
cur = _scale(_rotate(cur, _rx(slots[1]["r"][2])), slots[1]["s"])
world[base + 1] = cur
world[base + 2] = _translate(cur, slots[2]["t"])
else:
# JNT_constructMatrix / JNT_getVal2 have a general branch
# for longer chains (law-of-cosines bends on the middle
# links); it is not ported: no disc clip solves one, and
# it has quirks no data could check (it never writes the
# first link's matrix and translates by the absolute
# block index's element)
raise FcvError("block %d: a solved chain of %d links (the general "
"solver for more than two links is not ported)"
% (i, count - 2))
elif typ == 5:
m = _translate(start(i), ct)
world[i] = _scale(_rotate(m, _rzyx(cr)), cs)
if is_body and cf & 0x8000 and i >= 4 and world[i] is not None \
and world[i - 1] is not None and world[i - 1][2][1] != 0.0:
# JNT_constructMatrix: the inherit block's height is multiplied by
# (the previous block's .jnt Y + block 0's Y) / the previous block's
# posed Y; block 0 is the unit matrix here
r, s_, p = world[i]
k = (rig.translations[i - 1][1] + (world[0][2][1] if world[0] else 0.0)) \
/ world[i - 1][2][1]
world[i] = (r, s_, (p[0], p[1] * k, p[2]))
return world
# ---------------------------------------------------------------------------
# hair and cloth: EXM_CalcExMotion
# ---------------------------------------------------------------------------
#
# While the game runs, JNT_computeMatrix hands the blocks [JNT_hairID,
# primary + secondary) to EXM_CalcExMotion (exm_1.c) once a tick, with the
# .jnt's own values (not the clip's). A type-3 block starts a chain, rigid
# on its parent; the type-2 links and the type-4 end are queued, and the end
# solves the chain: the first link stays rigid on the root, every later
# joint starts from where it was the tick before, falls by the type's
# gravity, is pulled part of the way toward where the rigid chain would put
# it (less the further down the chain), is put back at its link's length
# from the joint above, and is pushed out of the character's collision
# shapes; then every link is turned to point at the next joint.
# EXM_PresetHair picks, from the .jnt name, a hairpara[] type and flags for
# each chain in turn and one collision table.
#
# Followed here: gravity, the pull, the link length, the floor
# (EX_ANIM_FLAG_NO_GROUND off: 0.07 above the ground under the character),
# EXM_CheckExCollision (spheres, capsules), the bend of
# EX_HAIR_FLAG_ALT_SHAPES and OrientExMotionJoint. Not followed: wind (off
# unless a map turns it on), the hip sway (moved_hair_sway is only set by
# hair_test.c), and EXM_CheckSkirtCollision: a chain of a skirt type
# (EX_HAIR_FLAG_SKIRT) keeps its rest pose.
def _f32(x):
return struct.unpack("<f", struct.pack("<f", x))[0]
# hairpara[]: (gravity, length_response, response xyz, chain_response)
_HAIRPARA = [tuple(_f32(v) if not isinstance(v, tuple) else tuple(_f32(u) for u in v)
for v in row) for row in (
(0.02, 1.0, (0.9, 0.9, 0.9), 0.5), (0.0, 1.0, (1.0, 1.0, 1.0), 100.0),
(0.02, 1.0, (0.9, 0.9, 0.9), 0.5), (0.03, 1.0, (0.7, 0.7, 0.7), 0.6),
(0.02, 1.0, (0.9, 0.9, 0.9), 0.3), (0.01, 0.9, (0.9, 1.0, 0.9), 0.7),
(0.01, 0.9, (0.9, 1.0, 0.9), 1.2), (0.01, 0.9, (0.5, 0.5, 0.5), 2.0),
(0.0, 0.8, (0.5, 0.5, 0.5), 1.0), (0.0, 1.0, (0.8, 0.8, 0.8), 1.7),
(0.03, 1.0, (0.9, 0.9, 0.9), 2.0), (0.05, 1.0, (0.0, 0.0, 0.0), 0.5),
(0.05, 1.0, (0.2, 0.2, 0.2), 0.5), (0.04, 0.9, (0.7, 0.7, 0.7), 0.2),
(0.05, 1.0, (0.5, 0.5, 0.5), 0.1), (0.5, 1.0, (0.9, 0.9, 0.9), 1.0),
(0.01, 0.8, (0.2, 0.2, 0.2), 1.0), (0.0, 0.9, (0.9, 0.9, 0.9), 0.3),
(0.05, 0.8, (0.75, 0.75, 0.75), 0.5), (0.0, 0.8, (0.95, 0.95, 0.95), 2.0),
(0.05, 0.1, (0.0, 0.0, 0.0), 0.5), (0.0, 0.01, (0.0, 0.0, 0.0), 0.5))]
# EX_HAIR_FLAG_* (ExHairTypeSelection.flags)
_ALT, _KIND5, _KIND6, _KIND7, _SKIRT = 0x1, 0x2, 0x8, 0x10, 0x400
# the collision tables: (block, kind, (x, y, z, radius) from the block,
# capsule end (x, y, z, radius)); kinds 1 sphere, 2 capsule, 3 keep inside,
# 4 only for EX_HAIR_FLAG_ALT_SHAPES, 5 only with _KIND5, 6 only with
# _KIND6, 7 only with _KIND7
_Z4 = (0.0, 0.0, 0.0, 0.0)
_HEAD_CAPS = lambda r0, r1, ln: [(51, 2, (0.0, 0.0, 0.0, r0), (ln, 0.0, 0.0, r1)),
(63, 2, (0.0, 0.0, 0.0, r0), (ln, 0.0, 0.0, r1))]
_COL = {
"kosmos": [(48, 1, (0.025, -0.07, 0.0, 0.125), _Z4), (48, 5, (-0.035, -0.1, 0.0, 0.13), _Z4)]
+ _HEAD_CAPS(0.09, 0.07, 0.1)
+ [(39, 4, (0.1, 0.45, 0.0, 0.55), _Z4), (13, 4, (0.1, -0.37, 0.0, 0.5), _Z4)],
"shelley": [(48, 1, (0.03, -0.08, 0.0, 0.08), _Z4),
(51, 2, (-0.02, 0.0, 0.0, 0.1), (0.1, 0.0, 0.0, 0.075)),
(63, 2, (-0.02, 0.0, 0.0, 0.1), (0.1, 0.0, 0.0, 0.075)),
(39, 1, (0.1, 0.01, 0.05, 0.08), _Z4), (39, 1, (0.1, 0.01, -0.05, 0.08), _Z4),
(39, 4, (0.1, 0.52, 0.0, 0.65), _Z4)],
"human": [(48, 1, (0.01, -0.07, 0.0, 0.1), _Z4), (42, 4, (0.05, 0.15, 0.0, 0.3), _Z4)],
"shion": [(48, 1, (0.03, -0.1, 0.0, 0.11), _Z4),
(51, 2, (-0.05, 0.01, 0.01, 0.075), (0.14, -0.01, -0.01, 0.06)),
(45, 4, (0.0, 0.48, 0.0, 0.6), _Z4), (42, 6, (0.0, 0.26, 0.0, 0.4), _Z4)],
"chaos": [(48, 1, (0.01, -0.09, 0.0, 0.115), _Z4)],
"momo": [(48, 1, (0.04, -0.1, 0.0, 0.09), _Z4)] + _HEAD_CAPS(0.09, 0.07, 0.1),
"hyaku": [(48, 1, (0.04, -0.1, 0.0, 0.09), _Z4)] + _HEAD_CAPS(0.08, 0.06, 0.05),
"shitan": [(48, 1, (0.04, -0.05, 0.0, 0.07), _Z4), (42, 4, (-0.1, 0.63, 0.0, 0.8), _Z4),
(42, 1, (0.05, -0.15, 0.0, 0.3), _Z4)],
"elly": [(48, 1, (0.01, -0.08, 0.0, 0.1), _Z4)] + _HEAD_CAPS(0.08, 0.06, 0.08)
+ [(42, 4, (-0.08, 0.3, 0.0, 0.4), _Z4)],
"tonny": [(48, 1, (0.04, -0.1, 0.0, 0.09), _Z4),
(16, 2, (-0.1, 0.0, -0.02, 0.15), (0.4, 0.0, 0.0, 0.14)),
(26, 2, (-0.1, 0.0, 0.02, 0.15), (0.4, 0.0, 0.0, 0.14))],
"albelt": [(48, 1, (0.05, -0.08, 0.0, 0.08), _Z4), (36, 4, (-0.05, 0.2, 0.0, 0.4), _Z4)],
"kebin": [(48, 1, (0.04, -0.06, 0.0, 0.1), _Z4), (48, 3, (0.042, -0.06, 0.0, 0.11), _Z4)],
"kebinh": [(48, 1, (0.015, -0.07, 0.0, 0.1), _Z4)],
"shionch": [(48, 1, (0.01, -0.08, 0.0, 0.1), _Z4), (42, 4, (-0.08, 0.3, 0.0, 0.4), _Z4)],
"helmer": [(55, 6, (0.35, 0.0, -0.22, 0.3), _Z4), (67, 7, (0.35, 0.0, 0.22, 0.3), _Z4)],
"allen": [(48, 1, (0.03, -0.09, 0.0, 0.09), _Z4)],
"abel": [(48, 1, (0.01, -0.07, 0.0, 0.1), _Z4), (42, 4, (0.0, 0.2, 0.0, 0.3), _Z4)],
"mam": [(48, 1, (0.01, -0.07, 0.0, 0.1), _Z4), (42, 4, (0.05, 0.15, 0.0, 0.28), _Z4),
(42, 6, (0.05, -0.15, 0.0, 0.28), _Z4)],
"gaignun": [(48, 6, (0.01, -0.07, 0.0, 0.1), _Z4)],
"off": [(42, 4, (0.05, 0.18, 0.0, 0.3), _Z4)],
"miyuki": [(48, 1, (0.04, -0.1, 0.0, 0.09), _Z4), (39, 4, (0.12, 0.3, 0.0, 0.4), _Z4)],
"robot": [(39, 4, (0.08, -0.2, 0.0, 0.4), _Z4)],
}
_COL["momo1"] = _COL["momo"] + [
(16, 2, (0.0, 0.0, 0.0, 0.13), (0.4, 0.0, 0.0, 0.13)),
(26, 2, (0.0, 0.0, 0.0, 0.13), (0.4, 0.0, 0.0, 0.13)),
(17, 2, (0.0, 0.0, 0.0, 0.1), (0.4, 0.0, 0.0, 0.13)),
(27, 2, (0.0, 0.0, 0.0, 0.1), (0.4, 0.0, 0.0, 0.13))]
_COL["momo4"] = _COL["momo"] + [(39, 4, (0.12, 0.4, 0.0, 0.55), _Z4)]
_COL = {k: [(j, kd, tuple(_f32(x) for x in s), tuple(_f32(x) for x in e))
for j, kd, s, e in v] for k, v in _COL.items()}
_AUTO = "auto" # EX_HAIR_TYPE_AUTO
def exm_preset(name: str):
"""``EXM_PresetHair`` for a ``.jnt`` name: (types, table). ``types`` is
{chain number: (flags, kind)} (a chain it gives nothing gets flags 0,
type 0: the game would read what an earlier skeleton left there), None
(EX_HAIR_TYPE_NONE: every chain type 0, no collision) or "auto"
(GetHairTypeSelection picks per chain); ``table`` a ``_COL`` key."""
if not name:
return None, None
c = lambda k: name[k] if k < len(name) else "\0"
last = ""
for ch in name: # GetLastWord: up to a non-ASCII byte
if ord(ch) >= 0x80:
break
last = ch
fl: dict = {}
kd: dict = {}
def put(idx, flags, kind):
for k in idx:
fl[k], kd[k] = flags, kind
col = None
sk = lambda idx, kind=16: put(idx, _SKIRT, kind)
a, b = c(0), c(1)
if a == "A":
if b == "L":
if c(2) == "B":
col = "albelt"
if last == "H":
put(range(7), _ALT, 18); put([7, 10], 0, 6); put([8, 9], 0, 7)
put([11, 12, 13], 0, 8)
else:
put(range(5), _ALT, 18)
elif c(2) == "L":
col = "allen"
put([0, 1, 2, 6, 7], 0, 10); put([3, 4, 5], 0, 1)
elif b == "N":
if c(4) == "W":
sk([0, 1])
elif c(4) == "D":