Repository navigation
Expand file tree
/
Copy pathxap.py
More file actions
2019 lines (1855 loc) · 84.7 KB
/
Copy pathxap.py
File metadata and controls
2019 lines (1855 loc) · 84.7 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
"""Episode III motion: `.xap` body clips and `.fap` face clips, decoded and
turned into glTF animations for the `.xhr` skeletons.
Borrowed from the Xenosaga Episode II kit, Xenosaga2PythonExtractor/xap.py
(same author, MIT), 2026-11-21. The container, the block and key
formats, the curve evaluator and the glTF writing are the XS2 ones (same
engine). Changed for Episode III, each point read from SLUS_213.89
(Ghidra output, and the disassembly where noted; gp = 0x5571f0):
* Clip versions 1.4, 1.6 and 1.7 occur (USA Disc 1: 3,751 / 2,231 / 2,514
clips) and all three take the same path: `FUN_00299350` runs the body
player `FUN_00299e98` for an XAC version >= 1.4 and the face player
`FUN_0029ad70` for a FAC version >= 1.4. No clip below 1.4 is on the
discs and Episode III has no player for one: `parse` refuses them.
* The 0x50-byte clip header has eight count / offset pairs, counts at
+0x10..+0x2C, offsets at +0x30..+0x4C: A, B, D, E, visibility, C (as
XS2) and two new ones. +0x28 / +0x48 ("P"): read by `FUN_00299e98` only
when its count is exactly 2 and the skeleton's word +0x60 is not 0; each
entry is 4 bytes the engine skips, then two curves (`FUN_002a48b0`);
the values go to the actor (+0x114, and +0x11C = a skeleton value minus
the second curve). What they mean is not traced: kept in extras. In
1.4 clips a count other than 0 or 2 there is exporter junk (Maya string
fragments) and is ignored. +0x2C / +0x4C ("Q", 1.6 and up, junk in
1.4): no reader found. The bytes are one pair list (i32 n, n x (f32
frame, u32 value)) per set bit of the +0x2C word (the field walk clip of
KOS-MOS has the word 6 and two lists whose value 1 sits at frames 8 and
28, footfall-like). That reading is checked only by the lists tiling
the clip exactly (the sweep); kept in extras.
* One root, not two: the XHR 3.0 run A starts with one 0x40-byte record
(xhr.py), and `FUN_002a3760` reads the first run-A block for it without
a count check, so a body clip needs one run-A block (XS2: two). Block i
>= 1 of run A drives transform i while i < the clip's run-A count.
* Key type 6 (new, 8 bytes): s16 angle at +4 (in = out), s16 value at +6,
both fixed point / 4096 (`FUN_002a2dd0`, `FUN_002a2c08`,
`FUN_002a2cf0`). When a type-6 key ends the curve and is reached first
(time at or past its frame), `FUN_002a2eb0` returns the raw s16 as a
float, NOT divided by 4096 (disassembly at 0x2a3090: `lh` + `cvt.s.w`).
`eval_curve_ref` / `eval_curve` reproduce that; the sweep counts how
often it changes a value (`type-6 last keys, raw != value`).
* Scale (row "S" below) is skipped when all three values are in [0.999,
1.001) for the root and runs A, B, C (gp-0x70d8 / gp-0x70d4) and the face
run D, and only when exactly (1, 1, 1) for run E; the current-scale slot
keeps the keyed value either way.
* Parent-scale compensation (block flags bit 0) is applied for the root
and runs A, B, C and D (face), never for run E (`FUN_00299e98` stores
the bit for run E but does not look up a parent scale there). The slot
lookup `FUN_00299d10` treats the first two transforms as 0x40-byte
records unless skeleton word +0x5C has bit 3 set (no USA skeleton does),
so a child of transform 1 reads transform 1's REST scale (record +0x28),
not its current one; a child of a run-D transform reads record +0x3C.
This module reproduces both.
* Face (`FUN_0029ad70`): run D only, own clock; the keyed translation is
applied only when the rest T is not (0, 0, 0) (as XS2), but the scale
follows the [0.999, 1.001) rule above (XS2: only when the rest S is not
(1, 1, 1)). The rotation limits are clamped after the matrix is built,
so they change nothing (as XS2).
* `FUN_0029c9a8` (taken when actor word +0xE0 is set, likely a blend of
two motions) is not reproduced.
* `sweep` walks a reader (the disc through x3index / disc.Disc) and the
`xap` slot of every MR package (`.sme` under `pac/` and `mg1/`, `.wpn`),
not a dump folder.
Usage (Episode III):
python xap.py --self-test
python cli.py motion --iso D1.iso --path 'pac\\cf\\C3kosmos00.sme' # clip table
python cli.py motion --iso D1.iso --path 'pac\\cf\\C3kosmos00.sme#1' \\
--xhr 'mdl\\chr\\pc\\C3kosmos00.chr' --frame 10 # one pose
python cli.py motion --iso D1.iso --sweep # every clip
python cli.py model --iso D1.iso --path 'mdl\\chr\\pc\\C3kosmos00.chr' \\
--motion 'pac\\cf\\C3kosmos00.sme#1,2' # glTF
The rest of this docstring is the Episode II description; where it says
"two roots", "version 1.2 / 1.3" or "run E from 1.3", read the points
above.
python xap.py --self-test
python xap.py FILE.xap # clip table
python xap.py FILE.xap --xhr FILE.xhr --slot N --frame F
# per-transform pose
python xap.py --sweep DUMPDIR # every file on the disc
Everything below was read from SLUS_208.92 (Ghidra output and, where the
two disagreed, the disassembly) and then checked by walking every clip on
the disc (`--sweep`). Routines are named by address only.
Container (`FUN_00292030` takes the clips)::
+0x00 "XAP " (body) / "FAP " (face) +0x04 f32 1.2 +0x08 u32 n
+0x0C n x u32 clip offsets, ascending, 4-aligned, first = 12 + 4n
A clip runs from its offset to the next distinct offset (or the end of the
file); several slots can share one clip. A clip whose start frame is
greater than its end frame is not taken (`FUN_00292030` tests start <= end):
on the disc these are 16-byte stubs "XAC ", 1.4, 100.0, -100.0.
Clip header ("XAC " body / "FAC " face): +4 f32 version, +8 f32 start frame,
+0xC f32 end frame. The clock runs time += speed * global tick and wraps to
start once time >= end (`FUN_002924a0`). `FUN_002929e0` dispatches on the
version: below 1.4 to `FUN_0028dec0` (body) / `FUN_002900f8` (face), 1.4 to
`FUN_0028f1e0` / `FUN_00290518`. The version tests compare single floats.
version 1.4 (0x50 bytes): count / offset (offsets relative to the clip)
+0x10 / +0x30 run A (the first two blocks are the two roots,
read by FUN_00293e38 without a count check)
+0x14 / +0x34 run B
+0x18 / +0x38 run D (face; only FAC clips drive it)
+0x1C / +0x3C run E (chains; 8-byte block header)
+0x20 / +0x40 visibility list (body only, FUN_00290ec0; junk in FAC)
+0x24 / +0x44 run C
+0x28..+0x2F, +0x48..+0x4F: exporter junk (fragments of Maya strings)
version 1.3 / 1.2 (0x30 bytes, FUN_0028dec0): counts +0x10 A, +0x14 B,
+0x18 D, +0x1C E; offsets +0x20 A, +0x24 B, +0x28 D, +0x2C E.
Run C stays at rest. The run-E block header is 8 bytes from 1.3 on
(FUN_00294338) and 4 bytes below (FUN_002945c8); no clip on the disc
has run-E blocks below 1.3, so the 4-byte case is covered only by
the self-test.
Block i of a run drives transform (run base + i) for i < min(clip count,
xhr count); extra blocks are ignored and missing ones leave the transform at
its `.xhr` rest values (each run pointer is re-read from its own offset
field in FUN_0028f1e0). Transform order is A, B, C, D, E, F as in xhr.py.
Run F is never animated. Which clip the game plays on which skeleton is not
traced, so a clip whose counts differ from the skeleton's may belong to
another model: count_mismatch finds them and add_to_glb flags them.
Block: u16 mask, u16 flags, (run E from 1.3: one f32 the engine copies to
record +0x2C; meaning unknown, kept in extras), then one key list per set
mask bit in bit order: bits 0-2 T.x T.y T.z, 3-5 R.x R.y R.z (radians), 6-8
S.x S.y S.z. Keys replace the rest value. Joint orients are never keyed.
Flags bit 0 sets the record's parent-scale compensation bit
(FUN_002939e8: record +0x44 |= 2); the other flag bits are not read.
Local matrix (row vectors, as xhr.py; built by FUN_0028f1e0)::
L = S * Rx(R.x) Ry(R.y) Rz(R.z) * Rx(JO.x) Ry(JO.y) Rz(JO.z) * invPS * T
with no JO for the roots, and invPS = diag(1/ps) when the compensation bit
is set, ps being the parent's current scale (the slot FUN_0028dd50 finds,
written each frame; FUN_00293330 skips a zero axis, leaving a stale value
there: this module uses 1.0 and counts it). A parent in run F has no slot
(the engine asserts "can not found parent scale" and skips the scale).
World = L * world[parent] (FUN_00290ab8).
Face (FUN_00290518, run D only, its own clock): the same order with JO at
+0x18, except that the translation is applied only when the rest T is not
zero and the scale only when the rest S is not (1,1,1) (then the animated
values are used). The rotation limits are clamped after the matrix is
built, so they change nothing.
Keys (FUN_002935e8, value FUN_00293560, out-angle FUN_00293420, in-angle
FUN_002934c0): u16 header (low 12 bits type, 0x4000 last key, 0x8000 see
below), s16 frame, then
type 0 8 bytes: f32 value (angles 0)
type 1 8 bytes: f32 value (segment always linear)
type 2 12 bytes: f32 angle (in = out), f32 value
type 3 12 bytes: u16 in-angle, u16 out-angle (x 1e-4), f32 value
type 4 asserts "XacKeyType_Hermite"; refused
type 5 16 bytes: f32 in-angle, f32 out-angle, f32 value
Evaluation: t = max(t, first frame); walk the keys; the first k with
frame_k <= t < frame_k+1 picks the segment, a 0x4000 key reached first
returns its own value. The segment is linear (FUN_00295610) for a type-1
key or a 0x8000 key followed by a key whose whole header is 0x0001, else
Hermite (FUN_00295488 -> FUN_00295260 -> FUN_002955c0) with slopes
sin/cos of key k's out-angle and key k+1's in-angle (5729578.0 when the
cosine is 0) over x = frame / 30. Keys are 30 per second.
Visibility list (v1.4 body, FUN_00290ec0 with FUN_00295188 per entry):
per entry i32 n, then n pairs (f32 frame, f32 value). The disassembly of
FUN_00295188 gives: value(t) = the value of the first pair whose frame is
>= t, the walk's "previous frame" starting at 0.0 and the first pair always
taken when nothing later matches; past the last frame, the last value. Bit
i of the output (pointer named pVisible) is set when value == 0.0. Which
mesh part an index means is not traced: this module stores the list and the
per-frame bits in the animation extras and hides nothing.
Not reproduced (see docs/MOTION.md): the chain simulation that runs after
the pose (FUN_00297da0), the visibility bits, the run-time factor
act+0xB0..B8 on transform 1's translation (1.0 unless a script sets it;
unverified), and the real-time rate (curves are 30 per second; the game's
speed x tick is unverified). The calculation is float64; the engine's is
float32.
"""
import json
import math
import os
import struct
import sys
from collections import Counter
import numpy as np
import xhr
__all__ = ["XapError", "Curve", "Block", "Clip", "Xap", "parse",
"eval_curve_ref", "eval_curve", "pose", "animation_tracks",
"driven_runs", "count_mismatch", "add_to_glb", "sweep",
"self_test"]
KEY_SIZE = {0: 8, 1: 8, 2: 12, 3: 12, 5: 16, 6: 8}
FPS = 30.0
STEEP = 5729578.0 # FUN_00295260, cosine 0
F32 = lambda v: float(np.float32(v))
V14, V16 = F32(1.4), F32(1.6)
S_LO, S_HI = F32(0.999), F32(1.001) # gp-0x70d8 / gp-0x70d4 (FUN_00299e98)
RUN_ORDER = "ABCDEF"
class XapError(ValueError):
pass
class Curve(object):
"""One channel's keys, as stored. Arrays: headers (raw u16), types,
frames (int), ain / aout (radians), values (float64), lastvals (the
value FUN_002a2eb0 returns when the key ends the curve and is reached
first: the value, except the raw s16 for a type-6 key)."""
__slots__ = ("offset", "headers", "types", "frames", "ain", "aout",
"values", "lastvals")
def __init__(self, offset, headers, frames, ain, aout, values,
lastvals=None):
self.offset = offset
self.headers = np.asarray(headers, dtype=np.int64)
self.types = self.headers & 0xFFF
self.frames = np.asarray(frames, dtype=np.int64)
self.ain = np.asarray(ain, dtype=np.float64)
self.aout = np.asarray(aout, dtype=np.float64)
self.values = np.asarray(values, dtype=np.float64)
self.lastvals = self.values if lastvals is None else \
np.asarray(lastvals, dtype=np.float64)
def __len__(self):
return len(self.headers)
class Block(object):
__slots__ = ("offset", "mask", "flags", "extra", "curves")
def __init__(self, offset, mask, flags, extra, curves):
self.offset, self.mask, self.flags = offset, mask, flags
self.extra, self.curves = extra, curves # curves: {bit: Curve}
class Clip(object):
def __init__(self, magic, version, start, end, offset, size):
self.magic, self.version = magic, version
self.start, self.end = start, end
self.offset, self.size = offset, size
self.counts = {}
self.runs = {k: [] for k in "ABCDE"}
self.visibility = []
self.padding = 0
self.p_entries = [] # +0x28: (u32 skipped, curve, curve)
self.q_lists = [] # +0x2C: one pair list per set bit
self.q_mask = 0
self.junk = [] # header pairs holding exporter junk
@property
def face(self):
return self.magic == b"FAC "
@property
def e_extra(self):
return [b.extra for b in self.runs["E"] if b.extra is not None]
def frames(self):
return np.arange(int(self.start), int(self.end) + 1)
class Xap(object):
def __init__(self, magic, version, slots, offsets):
self.magic, self.version = magic, version
self.slots, self.offsets = slots, offsets
def clips(self):
"""[(clip, [slots sharing it])] for the non-stub clips."""
seen = {}
for i, c in enumerate(self.slots):
if c is not None:
seen.setdefault(id(c), (c, []))[1].append(i)
return sorted(seen.values(), key=lambda v: v[1][0])
# ------------------------------------------------------------------ parse
def _curve(buf, p, end):
start = p
hs, fr, ai, ao, vs, lv = [], [], [], [], [], []
while True:
if p + 4 > end:
raise XapError("curve at %#x runs past the clip" % start)
h, f = struct.unpack_from("<Hh", buf, p)
ty = h & 0xFFF
if ty not in KEY_SIZE:
raise XapError("key type %d at %#x (the engine knows 0,1,2,3,5,6)"
% (ty, p))
n = KEY_SIZE[ty]
if p + n > end:
raise XapError("curve at %#x runs past the clip" % start)
raw = None
if ty in (0, 1):
v, = struct.unpack_from("<f", buf, p + 4)
a_in = a_out = 0.0
elif ty == 6: # s16 angle, s16 value, / 4096
a, raw = struct.unpack_from("<hh", buf, p + 4)
a_in = a_out = a / 4096.0
v = raw / 4096.0
elif ty == 2:
a, v = struct.unpack_from("<2f", buf, p + 4)
a_in = a_out = a
elif ty == 3:
i_, o_ = struct.unpack_from("<2H", buf, p + 4)
v, = struct.unpack_from("<f", buf, p + 8)
a_in, a_out = i_ * F32(1e-4), o_ * F32(1e-4)
else:
a_in, a_out, v = struct.unpack_from("<3f", buf, p + 4)
hs.append(h)
fr.append(f)
ai.append(a_in)
ao.append(a_out)
vs.append(v)
lv.append(float(raw) if raw is not None else v)
p += n
if h & 0x4000:
return p, Curve(start, hs, fr, ai, ao, vs, lv)
def _block(buf, p, end, extra_f32):
if p + (8 if extra_f32 else 4) > end:
raise XapError("block at %#x runs past the clip" % p)
start = p
mask, flags = struct.unpack_from("<HH", buf, p)
if mask & ~0x1FF:
raise XapError("block at %#x: mask %#x has bits above 8" % (p, mask))
p += 4
extra = None
if extra_f32:
extra, = struct.unpack_from("<f", buf, p)
p += 4
curves = {}
for bit in range(9):
if mask >> bit & 1:
p, curves[bit] = _curve(buf, p, end)
return p, Block(start, mask, flags, extra, curves)
def _pairs(buf, p, end, what):
"""One pair list: i32 n, n x (f32 frame, 4-byte value)."""
if p + 4 > end:
raise XapError("%s runs past the clip" % what)
k, = struct.unpack_from("<i", buf, p)
if not 0 <= k < 100000 or p + 4 + 8 * k > end:
raise XapError("%s entry at %#x: %d pairs" % (what, p, k))
return p + 4 + 8 * k, k
def _clip(buf, o, end, container):
magic = bytes(buf[o:o + 4])
want = b"FAC " if container == b"FAP " else b"XAC "
if end - o < 16:
raise XapError("clip at %#x shorter than its header" % o)
if magic != want:
raise XapError("clip at %#x: magic %r in a %r file"
% (o, magic, container))
version, start, stop = struct.unpack_from("<3f", buf, o + 4)
if not start <= stop:
if end - o != 16:
raise XapError("clip at %#x is not taken (start > end) but has "
"%d bytes" % (o, end - o))
return None
c = Clip(magic, version, start, stop, o, end - o)
if F32(version) < V14:
raise XapError("clip at %#x: version %g (Episode III plays 1.4 and "
"up, FUN_00299350)" % (o, version))
hsize = 0x50
if end - o < hsize:
raise XapError("clip at %#x shorter than its 0x50-byte header" % o)
lay = [("A", 0x10, 0x30), ("B", 0x14, 0x34), ("D", 0x18, 0x38),
("E", 0x1C, 0x3C), ("V", 0x20, 0x40), ("C", 0x24, 0x44),
("P", 0x28, 0x48), ("Q", 0x2C, 0x4C)]
if c.face: # the face path reads run D only
lay = [r for r in lay if r[0] == "D"]
else:
n_p, = struct.unpack_from("<I", buf, o + 0x28)
if n_p not in (0, 2):
if F32(version) >= V16:
raise XapError("clip at %#x: +0x28 count %d (0 or 2 "
"expected from 1.6 on)" % (o, n_p))
lay = [r for r in lay if r[0] != "P"] # 1.4 junk
c.junk.append("P")
if F32(version) < V16:
lay = [r for r in lay if r[0] != "Q"] # 1.4 junk
c.junk.append("Q")
spans = []
for name, co, oo in lay:
n, = struct.unpack_from("<I", buf, o + co)
rel, = struct.unpack_from("<I", buf, o + oo)
c.counts[name] = n
if name == "Q":
c.q_mask = n
n = bin(n).count("1")
if not n:
continue
if n > 100000 or rel < hsize or o + rel > end:
raise XapError("clip at %#x: run %s count %d / offset %#x out "
"of range" % (o, name, n, rel))
p = o + rel
if name in ("V", "Q"):
for _ in range(n):
q, k = _pairs(buf, p, end, "visibility list" if name == "V"
else "+0x2C list")
pairs = struct.unpack_from("<" + "fI" * k if name == "Q"
else "<%df" % (2 * k), buf, p + 4)
(c.visibility if name == "V" else c.q_lists).append(
[(pairs[2 * i], pairs[2 * i + 1]) for i in range(k)])
p = q
elif name == "P":
for _ in range(n):
if p + 4 > end:
raise XapError("+0x28 entry runs past the clip")
head, = struct.unpack_from("<I", buf, p)
p, c1 = _curve(buf, p + 4, end)
p, c2 = _curve(buf, p, end)
c.p_entries.append((head, c1, c2))
else:
extra = name == "E"
for _ in range(n):
p, b = _block(buf, p, end, extra)
c.runs[name].append(b)
spans.append((rel, p - o, name))
if not c.face and c.counts.get("A", 0) < 1:
raise XapError("clip at %#x: run A has no block, the engine reads "
"the root's unconditionally (FUN_002a3760)" % o)
spans.sort()
at = hsize
for s, e, name in spans:
if s != at:
raise XapError("clip at %#x: run %s starts at %#x, expected %#x"
% (o, name, s, at))
at = e
size = end - o
if at != size:
if not (end % 4 == 0 and 0 < size - at <= 3):
raise XapError("clip at %#x: the blocks end at %#x, the clip at "
"%#x" % (o, at, size))
c.padding = size - at
return c
def parse(buf):
buf = bytes(buf)
if len(buf) < 12 or buf[:4] not in (b"XAP ", b"FAP "):
raise XapError("not a .xap / .fap (magic)")
magic = buf[:4]
version, n = struct.unpack_from("<fI", buf, 4)
if abs(version - 1.2) > 1e-6:
raise XapError("container version %g (only 1.2 is known)" % version)
if 12 + 4 * n > len(buf):
raise XapError("offset table runs past the file")
offs = list(struct.unpack_from("<%dI" % n, buf, 12))
if n and offs[0] != 12 + 4 * n:
raise XapError("first clip at %#x, expected %#x" % (offs[0],
12 + 4 * n))
for a, b in zip(offs, offs[1:]):
if b < a:
raise XapError("clip offsets out of order")
for a in offs:
if a % 4 or a >= len(buf):
raise XapError("clip offset %#x misaligned or out of range" % a)
ends = sorted(set(offs)) + [len(buf)]
cache = {}
slots = []
for a in offs:
if a not in cache:
cache[a] = _clip(buf, a, ends[ends.index(a) + 1], magic)
slots.append(cache[a])
return Xap(magic, version, slots, offs)
# ------------------------------------------------------------- evaluation
def _linear(f0, f1, y0, y1, t):
d = float(f1 - f0)
if d == 0.0:
d = 1.0
d = d / FPS
return y0 + (y1 - y0) * (((t - f0) / FPS) / d)
def _hermite(f0, f1, y0, y1, ao, ai, t):
# FUN_00295488: control points (x0, x0 + cos ao, x3 - cos ai, x3) and
# (y0, y0 + sin ao, y3 - sin ai, y3); FUN_00295260 the cubic
x0, x3 = f0 * (1.0 / FPS), f1 * (1.0 / FPS)
x1, y1c = x0 + math.cos(ao), y0 + math.sin(ao)
x2, y2c = x3 - math.cos(ai), y1 - math.sin(ai)
dx01 = x1 - x0
s0 = (y1c - y0) / dx01 if dx01 != 0 else STEEP
dx23 = x3 - x2
s1 = (y1 - y2c) / dx23 if dx23 != 0 else STEEP
L, dy = x3 - x0, y1 - y0
inv = 1.0 / (L * L)
b = (((dy + dy + dy) - L * s0) - L * s0 - L * s1) * inv
a = (((L * s0 + L * s1) - dy) - dy) * inv / L
u = (t - f0) * (1.0 / FPS)
return u * (u * (u * a + b) + s0) + y0
def eval_curve_ref(c, t):
"""Scalar evaluator, a literal transcription of FUN_002935e8 (XS2) /
FUN_002a2eb0 (XS3, with key type 6 and its raw last-key value)."""
hs, fr, vs, lv = c.headers, c.frames, c.values, c.lastvals
tt = float(fr[0])
if tt <= t:
tt = t
found = False
res = 0.0
for k in range(len(hs)):
h = int(hs[k])
if not found:
if h & 0x4000:
res, found = float(lv[k]), True
elif fr[k] <= tt < fr[k + 1]:
found = True
if (h & 0xFFF) == 1 or ((h & 0x8000) and int(hs[k + 1]) == 1):
res = _linear(int(fr[k]), int(fr[k + 1]), float(vs[k]),
float(vs[k + 1]), tt)
else:
res = _hermite(int(fr[k]), int(fr[k + 1]), float(vs[k]),
float(vs[k + 1]), float(c.aout[k]),
float(c.ain[k + 1]), tt)
if h & 0x4000:
return res
raise XapError("curve without a last key")
def _segments(c, tt):
"""Index of the segment each time falls in (-1 = hold the last key)."""
fr = c.frames
n = len(fr)
if n == 1:
return np.full(len(tt), -1)
if np.all(np.diff(fr) > 0):
k = np.searchsorted(fr, tt, side="right") - 1
k[(k < 0) | (k >= n - 1)] = -1
return k
# non-ascending frames: the first k whose [f_k, f_k+1) holds t
m = (fr[None, :-1] <= tt[:, None]) & (tt[:, None] < fr[None, 1:])
k = np.argmax(m, axis=1)
k[~m.any(axis=1)] = -1
return k
def eval_curve(c, frames):
"""Vectorised FUN_002935e8 over an array of times (frames)."""
t = np.asarray(frames, dtype=np.float64).reshape(-1)
tt = np.maximum(t, float(c.frames[0]))
k = _segments(c, tt)
out = np.full(len(tt), c.lastvals[-1])
sel = k >= 0
if not sel.any():
return out
kk = k[sel]
tk = tt[sel]
h0 = c.headers[kk]
h1 = c.headers[kk + 1]
f0 = c.frames[kk].astype(np.float64)
f1 = c.frames[kk + 1].astype(np.float64)
y0, y1 = c.values[kk], c.values[kk + 1]
lin = ((h0 & 0xFFF) == 1) | (((h0 & 0x8000) != 0) & (h1 == 1))
res = np.empty(len(kk))
# linear, FUN_00295610
d = f1 - f0
d = np.where(d == 0.0, 1.0, d) / FPS
res_lin = y0 + (y1 - y0) * (((tk - f0) / FPS) / d)
# Hermite, same arithmetic as _hermite
ao, ai = c.aout[kk], c.ain[kk + 1]
x0, x3 = f0 * (1.0 / FPS), f1 * (1.0 / FPS)
x1, y1c = x0 + np.cos(ao), y0 + np.sin(ao)
x2, y2c = x3 - np.cos(ai), y1 - np.sin(ai)
with np.errstate(divide="ignore", invalid="ignore"):
dx01 = x1 - x0
s0 = np.where(dx01 != 0, (y1c - y0) / np.where(dx01 != 0, dx01, 1),
STEEP)
dx23 = x3 - x2
s1 = np.where(dx23 != 0, (y1 - y2c) / np.where(dx23 != 0, dx23, 1),
STEEP)
L, dy = x3 - x0, y1 - y0
inv = 1.0 / (L * L)
b = (((dy + dy + dy) - L * s0) - L * s0 - L * s1) * inv
a = (((L * s0 + L * s1) - dy) - dy) * inv / L
u = (tk - f0) * (1.0 / FPS)
res_h = u * (u * (u * a + b) + s0) + y0
res = np.where(lin, res_lin, res_h)
out[sel] = res
return out
def visibility_value(pairs, t):
"""FUN_00295188 (from its disassembly): the value an entry gives at
time t, or None when the entry has no pairs (the bit is left as it
was)."""
res = None
prev = 0.0
for i, (f, v) in enumerate(pairs):
if prev < t and t <= f:
res = v
elif i == 0:
res = v
prev = f
if pairs and prev < t:
res = pairs[-1][1]
return res
def visibility_bits(clip, frames):
"""Per frame, the FUN_00290ec0 output word(s) as a Python int: bit i
set when entry i's value is 0.0 (None-valued entries left clear)."""
out = []
for t in frames:
w = 0
for i, e in enumerate(clip.visibility):
v = visibility_value(e, float(t))
if v is not None and v == 0.0:
w |= 1 << i
out.append(w)
return out
# ------------------------------------------------------------------- pose
def _erows(a):
"""(..., 3) Euler angles -> (..., 3, 3) row-vector Rx Ry Rz (as
xhr.euler_rows)."""
a = np.asarray(a, dtype=np.float64)
cx, sx = np.cos(a[..., 0]), np.sin(a[..., 0])
cy, sy = np.cos(a[..., 1]), np.sin(a[..., 1])
cz, sz = np.cos(a[..., 2]), np.sin(a[..., 2])
z, o = np.zeros_like(cx), np.ones_like(cx)
rx = np.stack([o, z, z, z, cx, sx, z, -sx, cx], -1).reshape(a.shape[:-1]
+ (3, 3))
ry = np.stack([cy, z, -sy, z, o, z, sy, z, cy], -1).reshape(a.shape[:-1]
+ (3, 3))
rz = np.stack([cz, sz, z, -sz, cz, z, z, z, o], -1).reshape(a.shape[:-1]
+ (3, 3))
return rx @ ry @ rz
def _run_bases(x):
base, at = {}, 0
for k in RUN_ORDER:
base[k] = at
at += x.counts[k]
return base
def _order(x):
"""Transform indices with every parent before its children."""
done, out = set(), []
def visit(i, depth):
if i in done:
return
if depth > len(x.joints):
raise XapError("parent cycle at transform %d" % i)
p = x.joints[i].parent
if p >= 0:
visit(p, depth + 1)
done.add(i)
out.append(i)
for j in x.joints:
visit(j.index, 0)
return out
def driven_runs(clip):
"""The runs the clip's player reads: run D for a face clip
(FUN_0029ad70), A B C E for a body clip (FUN_00299e98)."""
if clip.face:
return ["D"]
return ["A", "B", "C", "E"]
def count_mismatch(x, clip):
"""{run: (clip blocks, .xhr transforms)} for every run the clip drives
whose block count is not the skeleton's transform count. The engine
takes blocks by index either way, but nothing read so far shows that a
clip with other counts was made for, or is ever played on, this
skeleton (docs/MOTION.md, "Clips whose run counts differ")."""
return {r: (clip.counts.get(r, 0), x.counts[r]) for r in driven_runs(clip)
if clip.counts.get(r, 0) != x.counts[r]}
def mismatch_text(mm):
return " ".join("%s%d/%d" % (r, c, n) for r, (c, n) in sorted(mm.items()))
def _near_one(S):
"""(..., 3) -> (...) True where FUN_00299e98 / FUN_0029ad70 skip the
scale: every component in [0.999, 1.001) (float32 constants)."""
return np.all((S >= S_LO) & (S < S_HI), axis=-1)
def _channels(x, clip, frames):
"""Per transform and frame, the engine's inputs: T, R, S (as applied
to the matrix), S_keyed (the value written to the scale slot), JO,
the compensation flag, and which transforms a block drives."""
frames = np.asarray(frames, dtype=np.float64).reshape(-1)
n, nf = len(x.joints), len(frames)
T = np.empty((n, nf, 3))
R = np.empty((n, nf, 3))
S = np.empty((n, nf, 3))
JO = np.zeros((n, 3))
for j in x.joints:
T[j.index], R[j.index], S[j.index] = j.t, j.r, j.s
JO[j.index] = j.jo
comp = np.zeros(n, dtype=bool)
driven = np.zeros(n, dtype=bool)
base = _run_bases(x)
face = clip.face
for r in driven_runs(clip):
for i, b in enumerate(clip.runs[r][:x.counts[r]]):
ti = base[r] + i
driven[ti] = True
comp[ti] = bool(b.flags & 1) and r != "E"
for bit, cv in b.curves.items():
v = eval_curve(cv, frames)
(T, R, S)[bit // 3][ti, :, bit % 3] = v
S_keyed = S.copy()
kinds = [j.kind for j in x.joints]
for i in range(n):
if kinds[i] in ("A0", "A", "B", "C", "D"):
S[i][_near_one(S[i])] = 1.0
if face:
for i in range(x.counts["D"]):
ti = base["D"] + i
if not np.any(x.joints[ti].t != 0):
T[ti] = 0.0
return dict(T=T, R=R, S=S, S_keyed=S_keyed, JO=JO, comp=comp,
driven=driven, frames=frames, face_play=face)
def parent_scale(x, ch, p):
"""FUN_00299d10: the (nf, 3) scale a child of transform p divides by,
or None (no slot: run F, or p < 0)."""
if p < 0:
return None
kind = x.joints[p].kind
if kind == "F":
return None
if p == 1 and not (getattr(x, "word5c", 0) & 8):
# two 0x40-byte records assumed: record 1 + 0x28 = rest S
return np.broadcast_to(x.joints[1].s, ch["S_keyed"][1].shape)
if kind == "D" and not ch.get("face_play"):
return np.broadcast_to(x.d_slot[p], ch["S_keyed"][p].shape)
return ch["S_keyed"][p]
def _compose(x, ch, stats=None):
"""Row-vector locals and worlds (nf, n, 4, 4) and the column-form
3x3 of each local, plus per-transform compensation bookkeeping."""
T, R, S, JO = ch["T"], ch["R"], ch["S"], ch["JO"]
n, nf = T.shape[:2]
rot = _erows(R) @ _erows(JO)[:, None] # (n, nf, 3, 3)
ps_inv = np.ones((n, nf, 3))
kinds = [j.kind for j in x.joints]
info = [None] * n
for i in range(n):
if not ch["comp"][i]:
continue
p = x.joints[i].parent
if p < 0:
continue
ps = parent_scale(x, ch, p)
if ps is None:
info[i] = "parent in run F"
if stats is not None:
stats["comp_parent_F"] += 1
continue
unit = np.all(ps == 1.0, axis=1) # exactly 1: skipped
zero = ps == 0.0
inv = np.where(zero, 1.0, 1.0 / np.where(zero, 1.0, ps))
inv[unit] = 1.0
ps_inv[i] = inv
if stats is not None:
nonunit = ~unit
if nonunit.any():
stats["comp_nonunit"] += 1
uni = (ps[:, 0] == ps[:, 1]) & (ps[:, 1] == ps[:, 2])
if np.all(uni | ~nonunit):
stats["comp_uniform"] += 1
else:
stats["comp_nonuniform"] += 1
if zero.any():
stats["comp_zero_axis"] += 1
if kinds[p] == "D":
stats["comp_parent_D"] += 1
if p == 1:
stats["comp_parent_t01_rest"] += 1
if x.joints[p].index > i:
stats["comp_parent_later"] += 1
m3 = S[..., :, None] * rot * ps_inv[..., None, :] # S . R . invPS
loc = np.zeros((nf, n, 4, 4))
loc[..., :3, :3] = m3.transpose(1, 0, 2, 3)
loc[..., 3, :3] = T.transpose(1, 0, 2)
loc[..., 3, 3] = 1.0
world = np.zeros_like(loc)
for i in _order(x):
p = x.joints[i].parent
world[:, i] = loc[:, i] if p < 0 else loc[:, i] @ world[:, p]
return loc, world, rot, ps_inv, info
def pose(x, clip, t, face=None):
"""(locals (n,4,4), worlds (n,4,4), trs list) at time t (frames), row
vectors as xhr.py. `face` defaults to the clip's own kind."""
if face is not None and bool(face) != clip.face:
raise XapError("face=%r for a %r clip" % (face, clip.magic))
ch = _channels(x, clip, [t])
loc, world, _, ps_inv, _ = _compose(x, ch)
trs = [dict(t=ch["T"][i, 0].copy(), r=ch["R"][i, 0].copy(),
s=ch["S"][i, 0].copy(), jo=ch["JO"][i].copy(),
comp=bool(ch["comp"][i]), inv_ps=ps_inv[i, 0].copy(),
driven=bool(ch["driven"][i]))
for i in range(len(x.joints))]
return loc[0], world[0], trs
def _quats(m):
"""Vectorised gltf.quat_from_matrix: (..., 3, 3) column-form rotation
-> (..., 4) xyzw, same branches."""
m = np.asarray(m, dtype=np.float64)
sh = m.shape[:-2]
m = m.reshape(-1, 3, 3)
q = np.empty((len(m), 4))
tr = m[:, 0, 0] + m[:, 1, 1] + m[:, 2, 2]
c0 = tr > 0
c1 = ~c0 & (m[:, 0, 0] > m[:, 1, 1]) & (m[:, 0, 0] > m[:, 2, 2])
c2 = ~c0 & ~c1 & (m[:, 1, 1] > m[:, 2, 2])
c3 = ~c0 & ~c1 & ~c2
with np.errstate(invalid="ignore", divide="ignore"):
s = np.sqrt(np.maximum(tr + 1.0, 0)) * 2
q0 = np.stack([(m[:, 2, 1] - m[:, 1, 2]) / s, (m[:, 0, 2] - m[:, 2, 0])
/ s, (m[:, 1, 0] - m[:, 0, 1]) / s, 0.25 * s], -1)
s = np.sqrt(np.maximum(1.0 + m[:, 0, 0] - m[:, 1, 1] - m[:, 2, 2], 0)) * 2
q1 = np.stack([0.25 * s, (m[:, 0, 1] + m[:, 1, 0]) / s, (m[:, 0, 2]
+ m[:, 2, 0]) / s, (m[:, 2, 1] - m[:, 1, 2]) / s], -1)
s = np.sqrt(np.maximum(1.0 + m[:, 1, 1] - m[:, 0, 0] - m[:, 2, 2], 0)) * 2
q2 = np.stack([(m[:, 0, 1] + m[:, 1, 0]) / s, 0.25 * s, (m[:, 1, 2]
+ m[:, 2, 1]) / s, (m[:, 0, 2] - m[:, 2, 0]) / s], -1)
s = np.sqrt(np.maximum(1.0 + m[:, 2, 2] - m[:, 0, 0] - m[:, 1, 1], 0)) * 2
q3 = np.stack([(m[:, 0, 2] + m[:, 2, 0]) / s, (m[:, 1, 2] + m[:, 2, 1])
/ s, 0.25 * s, (m[:, 1, 0] - m[:, 0, 1]) / s], -1)
for c, v in ((c0, q0), (c1, q1), (c2, q2), (c3, q3)):
q[c] = v[c]
q /= np.linalg.norm(q, axis=1, keepdims=True)
return q.reshape(sh + (4,))
def animation_tracks(x, clip, face=None, stats=None):
"""One entry per transform: times (s), translation (k,3), rotation
xyzw (k,4), scale (k,3), shear residual, driven flag. Frames are the
integers int(start)..int(end); time = (f - int(start)) / 30.
glTF TRS is written without decomposing the matrix: the column-form
local is T . (Rrows(R) Rrows(JO))^T . diag(S), so translation = T,
rotation = that orthonormal matrix, scale = S (exact for zero or
negative S). Under compensation with a uniform parent scale k the
scale is S / k; with a non-uniform one the 3x3 diag(1/ps) Q diag(S) is
split by a polar decomposition and the shear left over is reported."""
if face is not None and bool(face) != clip.face:
raise XapError("face=%r for a %r clip" % (face, clip.magic))
frames = clip.frames()
ch = _channels(x, clip, frames)
loc, world, rot, ps_inv, info = _compose(x, ch, stats)
times = (frames - int(clip.start)) / FPS
out = []
for i in range(len(x.joints)):
q_col = rot[i].transpose(0, 2, 1) # (nf, 3, 3)
T = ch["T"][i].copy()
S = ch["S"][i].copy()
resid = 0.0
inv = ps_inv[i]
if np.any(inv != 1.0):
uni = (inv[:, 0] == inv[:, 1]) & (inv[:, 1] == inv[:, 2])
S = np.where(uni[:, None], S * inv[:, :1], S)
nu = ~uni
if nu.any():
M = inv[nu][:, :, None] * q_col[nu] * ch["S"][i][nu][:, None, :]
U, _, Vt = np.linalg.svd(M)
Rp = U @ Vt
neg = np.linalg.det(Rp) < 0
if neg.any():
U[neg, :, 2] *= -1
Rp = U @ Vt
s = np.einsum("nji,nji->ni", Rp, M) # diag(R^T M)
q_col = q_col.copy()
q_col[nu] = Rp
S[nu] = s
resid = float(np.abs(M - Rp * s[:, None, :]).max())
q = _quats(q_col)
for k in range(1, len(q)):
if np.dot(q[k], q[k - 1]) < 0:
q[k] = -q[k]
out.append(dict(times=times, translation=T, rotation=q, scale=S,
shear=resid, driven=bool(ch["driven"][i]),
world=world[:, i]))
return out
# -------------------------------------------------------------------- glb
def _const(v):
return len(v) > 1 and float(np.abs(v - v[0]).max()) < 1e-7
def add_to_glb(glb_bytes, x, sources, matched_only=False):
"""Append one glTF animation per selected non-stub clip.
sources: [(label, Xap, slots or None, face)]. label is the disc path
without chain and extension, with forward slashes, e.g.
"motion/shion00"; slots None = every slot. A clip whose block count in
a run it drives differs from the skeleton's (count_mismatch) is not
known to be made for this skeleton: it is written with the counts in
its name ("motion/gno010#03 [counts A30/55]", clip/xhr) and in its
extras ("run_counts_differ"), or left out when matched_only is true.
Returns (glb bytes, [summary dict per animation, "counts_differ" set
for a flagged one], [{"name", "counts"} per clip left out])."""
import gltf
js, _ = gltf.read_glb(glb_bytes)
nodes = js.get("nodes", [])
sk = [i for i, nd in enumerate(nodes) if nd.get("name") == "skeleton"]
if len(sk) != 1:
raise XapError("the .glb has no skeleton node (mesh written without "
"the .xhr)")
under = {}
stack = list(nodes[sk[0]].get("children", ()))
while stack:
c = stack.pop()
under[nodes[c].get("name")] = c
stack.extend(nodes[c].get("children", ()))
try:
node_of = [under["t%02d" % j.index] for j in x.joints]
except KeyError as e:
raise XapError("the .glb skeleton has no node %s" % e)
base = _run_bases(x)
anims, summary, skipped = [], [], []
for label, xp, slots, face in sources:
want = None if slots is None else set(slots)
for clip, sl in xp.clips():
if want is not None:
sl = [s for s in sl if s in want]
if not sl:
continue
if bool(face) != clip.face:
raise XapError("%s: %s clip given as %s" % (
label, clip.magic.decode().strip(),
"face" if face else "body"))
name = "%s#%s" % (label, ",".join("%02d" % s for s in sl))
mm = count_mismatch(x, clip)
if mm and matched_only:
skipped.append({"name": name, "counts": mm})
continue
if mm:
name += " [counts %s]" % mismatch_text(mm)
stats = Counter()
tracks = animation_tracks(x, clip, stats=stats)
if clip.face:
keyed = range(base["D"], base["D"] + x.counts["D"])
else:
keyed = range(len(x.joints))
dur = (int(clip.end) - int(clip.start)) / FPS
channels = []
for i in keyed:
tr = tracks[i]
for path, vals in (("translation", tr["translation"]),
("rotation", tr["rotation"]),
("scale", tr["scale"])):
if len(vals) == 1 or _const(vals):
tm, vv = tr["times"][:1], vals[:1]
else:
tm, vv = tr["times"], vals
channels.append([node_of[i], path, tm, vv, "LINEAR"])
if dur > 0 and max(float(c[2][-1]) for c in channels) < dur:
# a clip that never moves: give one channel both ends so
# the action keeps the clip's length
c = channels[0]
c[2] = np.array([0.0, dur])
c[3] = np.repeat(c[3][:1], 2, axis=0)
shear = max(t["shear"] for t in tracks)
ex = {"source": label, "slots": sl,
"version": round(float(clip.version), 2),
"start": float(clip.start), "end": float(clip.end),
"fps": 30, "kind": "face" if clip.face else "body",
"counts": {k: v for k, v in clip.counts.items()},
"xhr_counts": dict(x.counts),
"max_shear_residual": shear}
if mm:
ex["run_counts_differ"] = {r: list(v) for r, v in mm.items()}