File size: 12,717 Bytes
eff1e50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Unified motion visualization: npz → stick figure video/gif.

Supports all datasets (human + animal, any joint count).
Outputs: MP4 video or GIF for human/VLM review.

Usage:
    # Render single motion
    python scripts/render_motion.py --input data/processed/humanml3d/motions/000001.npz --output results/videos/

    # Batch render dataset
    python scripts/render_motion.py --dataset humanml3d --num 20 --output results/videos/humanml3d/

    # Render with text overlay
    python scripts/render_motion.py --input ... --output ... --show_text --show_skeleton_info
"""

import sys
import os
import argparse
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation, PillowWriter
import matplotlib.patches as mpatches

project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from src.data.skeleton_graph import SkeletonGraph

SIDE_COLORS = {'left': '#e74c3c', 'right': '#3498db', 'center': '#555555'}


def load_motion_and_skeleton(npz_path: Path, dataset_path: Path = None):
    """Load motion data and its skeleton."""
    d = dict(np.load(npz_path, allow_pickle=True))
    T = int(d['num_frames'])

    # Find skeleton
    skel_data = None
    if dataset_path:
        # Try per-species skeleton for Zoo
        species = str(d.get('species', ''))
        if species:
            sp_path = dataset_path / 'skeletons' / f'{species}.npz'
            if sp_path.exists():
                skel_data = dict(np.load(sp_path, allow_pickle=True))
        if skel_data is None:
            main_skel = dataset_path / 'skeleton.npz'
            if main_skel.exists():
                skel_data = dict(np.load(main_skel, allow_pickle=True))

    if skel_data is None:
        # Infer from parent directory
        parent = npz_path.parent.parent
        main_skel = parent / 'skeleton.npz'
        if main_skel.exists():
            skel_data = dict(np.load(main_skel, allow_pickle=True))

    skeleton = SkeletonGraph.from_dict(skel_data) if skel_data else None
    canon = [str(n) for n in skel_data.get('canonical_names', [])] if skel_data else []

    return d, T, skeleton, canon


def render_motion_to_gif(
    npz_path: Path,
    output_path: Path,
    dataset_path: Path = None,
    fps: int = 20,
    show_text: bool = True,
    show_skeleton_info: bool = True,
    figsize: tuple = (10, 8),
    frame_skip: int = 1,
    view_angles: tuple = (25, -60),
):
    """Render a single motion npz to an animated GIF."""
    d, T, skeleton, canon = load_motion_and_skeleton(npz_path, dataset_path)

    joint_positions = d['joint_positions'][:T]  # [T, J, 3]
    J = joint_positions.shape[1]
    parents = skeleton.parent_indices if skeleton else [-1] + [0] * (J - 1)
    side_tags = skeleton.side_tags if skeleton else ['center'] * J

    # Subsample frames
    frames = range(0, T, frame_skip)
    n_frames = len(list(frames))

    # Compute scene bounds (from all frames)
    all_pos = joint_positions.reshape(-1, 3)
    center = all_pos.mean(axis=0)
    span = max(all_pos.max(axis=0) - all_pos.min(axis=0)) / 2 + 0.1

    # Metadata
    texts = str(d.get('texts', ''))
    first_text = texts.split('|||')[0] if texts else ''
    species = str(d.get('species', ''))
    skeleton_id = str(d.get('skeleton_id', ''))
    motion_id = npz_path.stem

    # Create figure
    fig = plt.figure(figsize=figsize)
    ax = fig.add_subplot(111, projection='3d')

    def update(frame_idx):
        ax.clear()
        fi = list(frames)[frame_idx]
        pos = joint_positions[fi]

        # Draw bones
        for j in range(J):
            p = parents[j]
            if p >= 0 and p < J:
                ax.plot3D(
                    [pos[j, 0], pos[p, 0]],
                    [pos[j, 2], pos[p, 2]],
                    [pos[j, 1], pos[p, 1]],
                    color='#bdc3c7', linewidth=2, zorder=1,
                )

        # Draw joints (colored by side)
        for j in range(J):
            color = SIDE_COLORS.get(side_tags[j] if j < len(side_tags) else 'center', '#555')
            ax.scatter3D(
                [pos[j, 0]], [pos[j, 2]], [pos[j, 1]],
                color=color, s=25, zorder=3, edgecolors='black', linewidths=0.3,
            )

        # Draw ground plane
        ground_y = joint_positions[:, :, 1].min() - 0.02
        gx = np.array([center[0] - span, center[0] + span])
        gz = np.array([center[2] - span, center[2] + span])
        gx, gz = np.meshgrid(gx, gz)
        gy = np.full_like(gx, ground_y)
        ax.plot_surface(gx, gz, gy, alpha=0.1, color='green')

        # Draw root trajectory (faded)
        traj = joint_positions[:fi+1, 0, :]
        if len(traj) > 1:
            ax.plot3D(traj[:, 0], traj[:, 2], np.full(len(traj), ground_y),
                     color='blue', alpha=0.3, linewidth=1)

        # Axes
        ax.set_xlim(center[0] - span, center[0] + span)
        ax.set_ylim(center[2] - span, center[2] + span)
        ax.set_zlim(center[1] - span, center[1] + span)
        ax.set_xlabel('X')
        ax.set_ylabel('Z')
        ax.set_zlabel('Y')
        ax.view_init(elev=view_angles[0], azim=view_angles[1])

        # Title
        title_parts = []
        if show_skeleton_info:
            info = f'{skeleton_id}'
            if species:
                info = f'{species}'
            title_parts.append(f'{info} ({J}j)')
        title_parts.append(f'frame {fi}/{T}')
        if show_text and first_text:
            # Truncate text
            txt = first_text[:60] + ('...' if len(first_text) > 60 else '')
            title_parts.append(f'"{txt}"')
        ax.set_title('\n'.join(title_parts), fontsize=9)

    anim = FuncAnimation(fig, update, frames=n_frames, interval=1000 // (fps // frame_skip))

    # Save
    output_path.parent.mkdir(parents=True, exist_ok=True)
    suffix = output_path.suffix.lower()
    if suffix == '.gif':
        anim.save(str(output_path), writer=PillowWriter(fps=fps // frame_skip))
    elif suffix == '.mp4':
        try:
            anim.save(str(output_path), writer='ffmpeg', fps=fps // frame_skip)
        except Exception:
            # Fallback to gif
            gif_path = output_path.with_suffix('.gif')
            anim.save(str(gif_path), writer=PillowWriter(fps=fps // frame_skip))
            output_path = gif_path
    else:
        anim.save(str(output_path), writer=PillowWriter(fps=fps // frame_skip))

    plt.close(fig)
    return output_path


def render_multi_view(
    npz_path: Path,
    output_path: Path,
    dataset_path: Path = None,
    n_frames: int = 8,
):
    """Render a multi-frame overview image (static, for quick review)."""
    d, T, skeleton, canon = load_motion_and_skeleton(npz_path, dataset_path)

    joint_positions = d['joint_positions'][:T]
    J = joint_positions.shape[1]
    parents = skeleton.parent_indices if skeleton else [-1] + [0] * (J - 1)
    side_tags = skeleton.side_tags if skeleton else ['center'] * J

    frame_indices = np.linspace(0, T - 1, n_frames, dtype=int)
    colors = plt.cm.viridis(np.linspace(0, 1, n_frames))

    texts = str(d.get('texts', ''))
    first_text = texts.split('|||')[0][:80] if texts else ''
    species = str(d.get('species', ''))
    skeleton_id = str(d.get('skeleton_id', ''))

    fig = plt.figure(figsize=(16, 6))

    # Left: multi-frame overlay
    ax1 = fig.add_subplot(121, projection='3d')
    for idx, fi in enumerate(frame_indices):
        pos = joint_positions[fi]
        alpha = 0.3 + 0.7 * (idx / max(n_frames - 1, 1))
        for j in range(J):
            p = parents[j]
            if p >= 0 and p < J:
                ax1.plot3D([pos[j, 0], pos[p, 0]], [pos[j, 2], pos[p, 2]],
                          [pos[j, 1], pos[p, 1]], color=colors[idx], alpha=alpha, linewidth=1.5)

    all_pos = joint_positions.reshape(-1, 3)
    mid = all_pos.mean(axis=0)
    sp = max(all_pos.max(axis=0) - all_pos.min(axis=0)) / 2 + 0.1
    ax1.set_xlim(mid[0]-sp, mid[0]+sp); ax1.set_ylim(mid[2]-sp, mid[2]+sp); ax1.set_zlim(mid[1]-sp, mid[1]+sp)
    ax1.set_title(f'{species or skeleton_id} ({J}j, {T} frames)\n{first_text}', fontsize=9)
    ax1.view_init(25, -60)

    # Right: trajectory top view + velocity
    ax2 = fig.add_subplot(222)
    root = d['root_position'][:T]
    ax2.plot(root[:, 0], root[:, 2], 'b-', linewidth=1)
    ax2.plot(root[0, 0], root[0, 2], 'go', ms=6, label='start')
    ax2.plot(root[-1, 0], root[-1, 2], 'ro', ms=6, label='end')
    ax2.set_title('Root trajectory (top)', fontsize=8)
    ax2.set_aspect('equal')
    ax2.legend(fontsize=7)
    ax2.grid(True, alpha=0.3)

    ax3 = fig.add_subplot(224)
    vel = d['velocities'][:T]
    mean_vel = np.linalg.norm(vel, axis=-1).mean(axis=1)
    ax3.plot(mean_vel, 'b-', alpha=0.7, linewidth=1)
    fc = d['foot_contact'][:T]
    if fc.shape[1] >= 4:
        ax3.fill_between(range(T), 0, fc[:, :2].max(axis=1) * mean_vel.max() * 0.3,
                        alpha=0.2, color='red', label='L foot')
        ax3.fill_between(range(T), 0, fc[:, 2:].max(axis=1) * mean_vel.max() * 0.3,
                        alpha=0.2, color='green', label='R foot')
    ax3.set_title('Velocity + foot contact', fontsize=8)
    ax3.legend(fontsize=7)
    ax3.grid(True, alpha=0.3)

    plt.tight_layout()
    output_path.parent.mkdir(parents=True, exist_ok=True)
    plt.savefig(output_path, dpi=120, bbox_inches='tight')
    plt.close()
    return output_path


def batch_render(
    dataset_id: str,
    output_dir: Path,
    num: int = 20,
    mode: str = 'overview',  # 'overview' | 'gif' | 'both'
    frame_skip: int = 2,
):
    """Batch render samples from a dataset."""
    base = project_root / 'data' / 'processed' / dataset_id
    mdir = base / 'motions'
    files = sorted(os.listdir(mdir))

    # Select diverse samples (spread across dataset)
    indices = np.linspace(0, len(files) - 1, min(num, len(files)), dtype=int)
    selected = [files[i] for i in indices]

    output_dir.mkdir(parents=True, exist_ok=True)
    rendered = 0

    for f in selected:
        npz_path = mdir / f
        name = f.replace('.npz', '')

        if mode in ('overview', 'both'):
            out = output_dir / f'{name}_overview.png'
            render_multi_view(npz_path, out, base)
            rendered += 1

        if mode in ('gif', 'both'):
            out = output_dir / f'{name}.gif'
            render_motion_to_gif(npz_path, out, base, frame_skip=frame_skip)
            rendered += 1

    return rendered


def main():
    parser = argparse.ArgumentParser(description='Render motion visualizations')
    parser.add_argument('--input', type=str, help='Single npz file to render')
    parser.add_argument('--dataset', type=str, help='Dataset ID for batch render')
    parser.add_argument('--output', type=str, default='results/videos/', help='Output directory')
    parser.add_argument('--num', type=int, default=20, help='Number of samples for batch')
    parser.add_argument('--mode', choices=['overview', 'gif', 'both'], default='both')
    parser.add_argument('--frame_skip', type=int, default=2, help='Frame skip for GIF (1=all frames)')
    parser.add_argument('--show_text', action='store_true', default=True)
    parser.add_argument('--show_skeleton_info', action='store_true', default=True)
    args = parser.parse_args()

    output = Path(args.output)

    if args.input:
        npz_path = Path(args.input)
        ds_path = npz_path.parent.parent
        print(f'Rendering: {npz_path.name}')

        if args.mode in ('overview', 'both'):
            out = output / f'{npz_path.stem}_overview.png'
            render_multi_view(npz_path, out, ds_path)
            print(f'  Overview: {out}')

        if args.mode in ('gif', 'both'):
            out = output / f'{npz_path.stem}.gif'
            render_motion_to_gif(npz_path, out, ds_path, frame_skip=args.frame_skip)
            print(f'  GIF: {out}')

    elif args.dataset:
        print(f'Batch rendering: {args.dataset} ({args.num} samples, mode={args.mode})')
        n = batch_render(args.dataset, output / args.dataset, args.num, args.mode, args.frame_skip)
        print(f'  Rendered: {n} files → {output / args.dataset}')

    else:
        # Render all datasets
        for ds in ['humanml3d', 'lafan1', '100style', 'bandai_namco', 'cmu_mocap', 'mixamo', 'truebones_zoo']:
            ds_path = project_root / 'data' / 'processed' / ds
            if not ds_path.exists():
                continue
            print(f'Rendering {ds}...')
            n = batch_render(ds, output / ds, min(args.num, 10), args.mode, args.frame_skip)
            print(f'  {n} files')


if __name__ == '__main__':
    main()