File size: 14,068 Bytes
9b97d00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Minimal pure-Python FBX binary reader for extracting skeleton animation data.

Parses FBX binary format to extract:
- Node hierarchy (skeleton tree)
- Animation curves (rotation, translation per bone)
- Rest pose (bind pose)

Then converts to our BVH-like internal format for further processing.

Reference: https://code.blender.org/2013/08/fbx-binary-file-format-specification/
"""

import struct
import zlib
import numpy as np
from pathlib import Path
from dataclasses import dataclass, field
from typing import Optional, Any


# ============================================================
# FBX Binary Parser
# ============================================================

@dataclass
class FBXNode:
    name: str
    properties: list = field(default_factory=list)
    children: list = field(default_factory=list)

    def find(self, name: str) -> Optional['FBXNode']:
        for c in self.children:
            if c.name == name:
                return c
        return None

    def find_all(self, name: str) -> list['FBXNode']:
        return [c for c in self.children if c.name == name]


def read_fbx(filepath: str | Path) -> FBXNode:
    """Read an FBX binary file and return the root node."""
    with open(filepath, 'rb') as f:
        data = f.read()

    # Check magic
    magic = b'Kaydara FBX Binary  \x00'
    if not data[:len(magic)] == magic:
        raise ValueError("Not a valid FBX binary file")

    # Version
    version = struct.unpack_from('<I', data, 23)[0]

    # Parse nodes
    offset = 27
    root = FBXNode(name='__root__')

    if version >= 7500:
        sentinel_size = 25  # 64-bit offsets
    else:
        sentinel_size = 13  # 32-bit offsets

    while offset < len(data) - sentinel_size:
        node, offset = _read_node(data, offset, version)
        if node is None:
            break
        root.children.append(node)

    return root


def _read_node(data: bytes, offset: int, version: int) -> tuple[Optional[FBXNode], int]:
    """Read a single FBX node."""
    if version >= 7500:
        end_offset = struct.unpack_from('<Q', data, offset)[0]
        num_props = struct.unpack_from('<Q', data, offset + 8)[0]
        props_len = struct.unpack_from('<Q', data, offset + 16)[0]
        name_len = data[offset + 24]
        name = data[offset + 25:offset + 25 + name_len].decode('ascii', errors='replace')
        offset = offset + 25 + name_len
    else:
        end_offset = struct.unpack_from('<I', data, offset)[0]
        num_props = struct.unpack_from('<I', data, offset + 4)[0]
        props_len = struct.unpack_from('<I', data, offset + 8)[0]
        name_len = data[offset + 12]
        name = data[offset + 13:offset + 13 + name_len].decode('ascii', errors='replace')
        offset = offset + 13 + name_len

    if end_offset == 0:
        return None, offset

    # Read properties
    props = []
    props_end = offset + props_len
    for _ in range(num_props):
        prop, offset = _read_property(data, offset)
        props.append(prop)

    node = FBXNode(name=name, properties=props)

    # Read children
    sentinel = b'\x00' * (25 if version >= 7500 else 13)
    while offset < end_offset:
        if data[offset:offset + len(sentinel)] == sentinel:
            offset += len(sentinel)
            break
        child, offset = _read_node(data, offset, version)
        if child is None:
            break
        node.children.append(child)

    offset = max(offset, end_offset)
    return node, offset


def _read_property(data: bytes, offset: int) -> tuple[Any, int]:
    """Read a single FBX property value."""
    type_code = chr(data[offset])
    offset += 1

    if type_code == 'Y':  # int16
        val = struct.unpack_from('<h', data, offset)[0]
        return val, offset + 2
    elif type_code == 'C':  # bool
        val = data[offset] != 0
        return val, offset + 1
    elif type_code == 'I':  # int32
        val = struct.unpack_from('<i', data, offset)[0]
        return val, offset + 4
    elif type_code == 'F':  # float32
        val = struct.unpack_from('<f', data, offset)[0]
        return val, offset + 4
    elif type_code == 'D':  # float64
        val = struct.unpack_from('<d', data, offset)[0]
        return val, offset + 8
    elif type_code == 'L':  # int64
        val = struct.unpack_from('<q', data, offset)[0]
        return val, offset + 8
    elif type_code == 'S':  # string
        length = struct.unpack_from('<I', data, offset)[0]
        val = data[offset + 4:offset + 4 + length].decode('utf-8', errors='replace')
        return val, offset + 4 + length
    elif type_code == 'R':  # raw bytes
        length = struct.unpack_from('<I', data, offset)[0]
        val = data[offset + 4:offset + 4 + length]
        return val, offset + 4 + length
    elif type_code in ('f', 'd', 'l', 'i', 'b'):
        # Array types
        arr_len = struct.unpack_from('<I', data, offset)[0]
        encoding = struct.unpack_from('<I', data, offset + 4)[0]
        comp_len = struct.unpack_from('<I', data, offset + 8)[0]
        offset += 12

        raw = data[offset:offset + comp_len]
        if encoding == 1:
            raw = zlib.decompress(raw)

        dtype_map = {'f': '<f4', 'd': '<f8', 'l': '<i8', 'i': '<i4', 'b': 'bool'}
        arr = np.frombuffer(raw, dtype=dtype_map[type_code])[:arr_len]
        return arr, offset + comp_len
    else:
        raise ValueError(f"Unknown FBX property type: {type_code}")


# ============================================================
# FBX → Skeleton + Animation extraction
# ============================================================

def extract_skeleton_and_animation(fbx_root: FBXNode) -> dict:
    """
    Extract skeleton hierarchy and animation data from parsed FBX.

    Returns dict with:
        - joint_names: list[str]
        - parent_indices: list[int]
        - rest_offsets: [J, 3]
        - rotations: [T, J, 3] Euler degrees
        - root_positions: [T, 3]
        - fps: float
    """
    objects = fbx_root.find('Objects')
    if objects is None:
        raise ValueError("No Objects section in FBX")

    # Find all Model nodes (bones/joints)
    models = {}
    for node in objects.children:
        if node.name == 'Model':
            model_id = node.properties[0] if node.properties else None
            model_name = str(node.properties[1]).split('\x00')[0] if len(node.properties) > 1 else ''
            model_type = str(node.properties[2]) if len(node.properties) > 2 else ''

            if 'LimbNode' in model_type or 'Root' in model_type or 'Null' in model_type:
                # Extract local translation
                local_trans = np.zeros(3)
                props70 = node.find('Properties70')
                if props70:
                    for p in props70.children:
                        if p.name == 'P' and p.properties and str(p.properties[0]) == 'Lcl Translation':
                            local_trans = np.array([
                                float(p.properties[4]),
                                float(p.properties[5]),
                                float(p.properties[6]),
                            ])

                models[model_id] = {
                    'name': model_name,
                    'type': model_type,
                    'translation': local_trans,
                }

    # Find connections to build parent-child hierarchy
    connections = fbx_root.find('Connections')
    parent_map = {}  # child_id → parent_id
    if connections:
        for c in connections.children:
            if c.name == 'C' and c.properties and str(c.properties[0]) == 'OO':
                child_id = c.properties[1]
                parent_id = c.properties[2]
                if child_id in models and parent_id in models:
                    parent_map[child_id] = parent_id

    # Build ordered joint list (BFS from roots)
    roots = [mid for mid in models if mid not in parent_map]
    if not roots:
        raise ValueError("No root bones found")

    joint_names = []
    parent_indices = []
    rest_offsets = []
    id_to_idx = {}

    queue = [(rid, -1) for rid in roots]
    while queue:
        mid, pidx = queue.pop(0)
        idx = len(joint_names)
        id_to_idx[mid] = idx
        joint_names.append(models[mid]['name'])
        parent_indices.append(pidx)
        rest_offsets.append(models[mid]['translation'])

        # Find children
        for child_id, par_id in parent_map.items():
            if par_id == mid:
                queue.append((child_id, idx))

    rest_offsets = np.array(rest_offsets, dtype=np.float32)

    # Extract animation curves
    anim_layers = []
    for node in objects.children:
        if node.name == 'AnimationLayer':
            anim_layers.append(node)

    # Find AnimationCurveNode → Model connections
    anim_curve_nodes = {}
    for node in objects.children:
        if node.name == 'AnimationCurveNode':
            acn_id = node.properties[0] if node.properties else None
            acn_name = str(node.properties[1]).split('\x00')[0] if len(node.properties) > 1 else ''
            anim_curve_nodes[acn_id] = {'name': acn_name, 'curves': {}}

    # Find AnimationCurve data
    anim_curves = {}
    for node in objects.children:
        if node.name == 'AnimationCurve':
            ac_id = node.properties[0] if node.properties else None
            key_time = None
            key_value = None
            for child in node.children:
                if child.name == 'KeyTime' and child.properties:
                    key_time = child.properties[0]
                elif child.name == 'KeyValueFloat' and child.properties:
                    key_value = child.properties[0]
            if key_time is not None and key_value is not None:
                anim_curves[ac_id] = {
                    'times': np.array(key_time, dtype=np.int64),
                    'values': np.array(key_value, dtype=np.float64),
                }

    # Link curves to bones via connections
    # Connection: AnimationCurve → AnimationCurveNode → Model
    acn_to_model = {}  # acn_id → (model_id, property_name)
    ac_to_acn = {}     # ac_id → (acn_id, channel_idx)

    if connections:
        for c in connections.children:
            if c.name == 'C' and len(c.properties) >= 3:
                ctype = str(c.properties[0])
                child_id = c.properties[1]
                parent_id = c.properties[2]

                if ctype == 'OO':
                    if child_id in anim_curve_nodes and parent_id in models:
                        prop_name = anim_curve_nodes[child_id]['name']
                        acn_to_model[child_id] = (parent_id, prop_name)
                    elif child_id in anim_curves and parent_id in anim_curve_nodes:
                        ac_to_acn[child_id] = parent_id
                elif ctype == 'OP':
                    if child_id in anim_curves and parent_id in anim_curve_nodes:
                        channel = str(c.properties[3]) if len(c.properties) > 3 else ''
                        ac_to_acn[child_id] = parent_id
                        anim_curve_nodes[parent_id]['curves'][channel] = child_id

    # Determine frame count and FPS
    all_times = set()
    for ac_id, ac_data in anim_curves.items():
        for t in ac_data['times']:
            all_times.add(int(t))

    if not all_times:
        # No animation, return rest pose
        return {
            'joint_names': joint_names,
            'parent_indices': parent_indices,
            'rest_offsets': rest_offsets,
            'rotations': np.zeros((1, len(joint_names), 3), dtype=np.float32),
            'root_positions': rest_offsets[0:1].copy(),
            'fps': 30.0,
        }

    sorted_times = sorted(all_times)
    fbx_ticks_per_sec = 46186158000  # FBX time unit
    if len(sorted_times) > 1:
        dt = sorted_times[1] - sorted_times[0]
        fps = fbx_ticks_per_sec / dt if dt > 0 else 30.0
    else:
        fps = 30.0

    T = len(sorted_times)
    time_to_frame = {t: i for i, t in enumerate(sorted_times)}

    # Build rotation and position arrays
    J = len(joint_names)
    rotations = np.zeros((T, J, 3), dtype=np.float64)
    positions = np.tile(rest_offsets, (T, 1, 1)).astype(np.float64)

    for acn_id, acn_data in anim_curve_nodes.items():
        if acn_id not in acn_to_model:
            continue
        model_id, prop_name = acn_to_model[acn_id]
        if model_id not in id_to_idx:
            continue
        j = id_to_idx[model_id]

        for channel_key, ac_id in acn_data['curves'].items():
            if ac_id not in anim_curves:
                continue
            ac_data = anim_curves[ac_id]

            # Determine axis
            axis = -1
            ck = channel_key.lower()
            if 'x' in ck or ck == 'd|x':
                axis = 0
            elif 'y' in ck or ck == 'd|y':
                axis = 1
            elif 'z' in ck or ck == 'd|z':
                axis = 2

            if axis < 0:
                continue

            # Fill in values
            for t_val, v_val in zip(ac_data['times'], ac_data['values']):
                t_int = int(t_val)
                if t_int in time_to_frame:
                    f = time_to_frame[t_int]
                    if 'rotation' in prop_name.lower() or 'Lcl Rotation' in prop_name:
                        rotations[f, j, axis] = v_val
                    elif 'translation' in prop_name.lower() or 'Lcl Translation' in prop_name:
                        positions[f, j, axis] = v_val

    root_positions = positions[:, 0, :]

    return {
        'joint_names': joint_names,
        'parent_indices': parent_indices,
        'rest_offsets': rest_offsets,
        'rotations': rotations.astype(np.float32),
        'root_positions': root_positions.astype(np.float32),
        'fps': float(fps),
    }


def fbx_to_bvh_data(filepath: str | Path) -> dict:
    """
    High-level: read FBX file and return data compatible with our BVH pipeline.
    """
    fbx_root = read_fbx(filepath)
    return extract_skeleton_and_animation(fbx_root)