> ## Documentation Index
> Fetch the complete documentation index at: https://docs.viggle.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 3D 动作

> 从视频中捕捉 3D 动作或根据文字生成动作，再导出 GLB 或 FBX，用于 Mixamo、MetaHuman 或 Viggle 3D 角色。

JST-2 有两种方式生成 3D 骨骼动画：捕捉视频中人物的动作，或根据文字提示词生成动作。两种方式都会得到一个动作（Motion，`mot_`），可导出为 GLB 或 FBX，并绑定到 Mixamo、MetaHuman 或 Viggle [3D 角色](https://docs.viggle.ai/zh/v1/3d/characters.md)的骨骼上。无需动捕服，就能用它为游戏角色、预演镜头或 splat 角色制作动画。

## 选择来源

以下三种方式都会创建一个动作，但只有前两种会产出 3D 文件。

| 来源 | 调用 | 输出 | 价格 |
| - | - | - | - |
| 人物视频 | `POST /v1/motions`，multipart，`type=glb` | 三种骨骼的 GLB 和 FBX | 源视频每秒 \$0.05，向上取整 |
| 文字提示词 | `POST /v1/motions`，JSON 中带 `text` | 三种骨骼的 GLB 和 FBX | 固定 \$0.10 |
| Viggle 动作模板 | `POST /v1/motions/import` | 用于 [Video Remix](https://docs.viggle.ai/zh/v1/video/video-remix) 的动作，不支持 3D 导出 | 模板每秒 $0.01，最低 $0.01 |

> [!NOTE]
>
> 根据文字生成的动作，或用 `type=glb` 从视频创建的动作，只能用于 3D，无法驱动 Video Remix。如果还想在 Video Remix 中复用视频的动作，请用 `type=all` 创建。

## 参数

### 从视频生成

以 `multipart/form-data` 发送（也支持 JSON 请求体）。

| 参数 | 必填 | 默认值 | 取值 |
| - | - | - | - |
| `motion_video` 或 `motion_video_url` | 是 | | 视频文件或公开 URL。不超过 100 MiB，时长 0.5–600 秒，至少 64×64 且宽高均为偶数 |
| `type` | 3D 必填 | `render` | `glb` 只生成 3D。`all` 还会额外生成一个用于 Video Remix 的 2D 动作 |
| `enable_smoothing` | 否 | `false` | 平滑关节抖动。可能会让突然的动作变得柔和 |
| `target_fps` | 否 | 服务默认值 | 提取出的动画帧率，须大于 0 |
| `render_mp4` | 否 | `false` | `true` 会额外渲染一段动画的 MP4 预览。需要 `type=glb` 或 `all` |
| `name` | 否 | | 用于 `type=all` 的标签。仅 `glb` 的动作读回时名称为空 |

### 从文字生成

以 `application/json` 发送。未知字段会以 `400` 拒绝。

| 参数 | 必填 | 默认值 | 取值 |
| - | - | - | - |
| `text` | 是 | | 要生成的动作，最多 400 字节。写明动作、方向、节奏和身体部位 |
| `duration_seconds` | 否 | `5` | 3–60 |
| `guidance_scale` | 否 | `5` | 0–30。值越高越严格遵循文字 |
| `smooth` | 否 | `true` | 平滑生成的动画 |
| `render_mp4` | 否 | `false` | `true` 会额外渲染一段动画的 MP4 预览 |
| `name` | 否 | | 仅在创建响应中回显 |

所有字段详见 API 参考：[创建动作](https://docs.viggle.ai/zh/v1/api-reference/motions/create-a-motion.md)和[导入动作模板](https://docs.viggle.ai/zh/v1/api-reference/motions/import-a-motion-template.md)。

## 价格

* 从视频生成：`ceil(source seconds) × 5` 积分（source seconds 为源视频秒数）。一段 10.1 秒的视频按 11 秒计费，即 55 积分（\$0.55）。`type=all` 价格相同，因为 2D 动作免费。`enable_smoothing`、`target_fps` 和 `render_mp4` 不影响价格。
* 从文字生成：每次请求 10 积分（\$0.10），与 `duration_seconds` 无关。
* 导入模板：按模板时长每秒 1 积分，不取整，最低 1 积分。一个 7.5 秒的模板需 7.5 积分（\$0.075）。

动作生成失败会退款。

> [!WARNING]
>
> 即使余额不足，从视频捕捉和文生动作的请求也会被接受。动作先是 `queued`，随后以 `failed` 结束，且 `glb.error.code: "INSUFFICIENT_CREDITS"`。导入模板会预先检查余额，余额不足时返回 `402 INSUFFICIENT_CREDITS`。

## 生成、等待并导出

下面的脚本根据文字生成一段 5 秒的动作，每 5 秒轮询一次，然后把 MetaHuman 身体骨骼保存为 GLB。不需要任何输入文件。

```bash cURL theme={null}
#!/usr/bin/env bash
set -euo pipefail
API="https://apis.viggle.ai/v1"
AUTH="Authorization: Bearer $VIGGLE_API_KEY"

motion_id=$(curl -sf -X POST "$API/motions" -H "$AUTH" \
  -H "Content-Type: application/json" \
  -d '{"text":"a person doing a cartwheel","duration_seconds":5}' | jq -r '.id')
echo "created $motion_id"

while true; do
  motion=$(curl -sf "$API/motions/$motion_id" -H "$AUTH")
  case "$(echo "$motion" | jq -r '.status')" in
    ready) break ;;
    failed) echo "failed: $(echo "$motion" | jq -c '.glb.error')" >&2; exit 1 ;;
  esac
  sleep 5
done

exported=$(curl -sf "$API/motions/$motion_id/export?download_type=glb" -H "$AUTH")
url=$(echo "$exported" | jq -r '.metahuman_body_url')
curl -sf -o motion.glb "$url"
echo "saved motion.glb; mixamo rig: $(echo "$exported" | jq -r '.mixamo_url')"
```

```javascript Node.js theme={null}
import { writeFile } from "node:fs/promises";

const API = "https://apis.viggle.ai/v1";
const auth = { Authorization: `Bearer ${process.env.VIGGLE_API_KEY}` };

async function call(path, init = {}) {
  const res = await fetch(`${API}${path}`, { ...init, headers: { ...auth, ...init.headers } });
  const body = await res.json();
  if (!res.ok) throw new Error(`HTTP ${res.status}: ${JSON.stringify(body.error)}`);
  return body;
}

let motion = await call("/motions", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ text: "a person doing a cartwheel", duration_seconds: 5 }),
});
console.log(`created ${motion.id}`);

while (motion.status !== "ready") {
  if (motion.status === "failed") throw new Error(`failed: ${JSON.stringify(motion.glb?.error)}`);
  await new Promise((r) => setTimeout(r, 5000));
  motion = await call(`/motions/${motion.id}`);
}

const exported = await call(`/motions/${motion.id}/export?download_type=glb`);
const file = await fetch(exported.metahuman_body_url);
await writeFile("motion.glb", Buffer.from(await file.arrayBuffer()));
console.log(`saved motion.glb; mixamo rig: ${exported.mixamo_url}`);
```

```python Python theme={null}
import os
import time
import requests

API = "https://apis.viggle.ai/v1"
headers = {"Authorization": f"Bearer {os.environ['VIGGLE_API_KEY']}"}

res = requests.post(
    f"{API}/motions",
    headers=headers,
    json={"text": "a person doing a cartwheel", "duration_seconds": 5},
)
res.raise_for_status()
motion = res.json()
print(f"created {motion['id']}")

while motion["status"] != "ready":
    if motion["status"] == "failed":
        raise RuntimeError(f"failed: {(motion.get('glb') or {}).get('error')}")
    time.sleep(5)
    res = requests.get(f"{API}/motions/{motion['id']}", headers=headers)
    res.raise_for_status()
    motion = res.json()

res = requests.get(
    f"{API}/motions/{motion['id']}/export",
    params={"download_type": "glb"},
    headers=headers,
)
res.raise_for_status()
exported = res.json()
with open("motion.glb", "wb") as f:
    f.write(requests.get(exported["metahuman_body_url"]).content)
print(f"saved motion.glb; mixamo rig: {exported['mixamo_url']}")
```

如果要从视频捕捉动作，只需修改创建请求，轮询和导出步骤不变：

```bash theme={null}
curl -X POST https://apis.viggle.ai/v1/motions \
  -H "Authorization: Bearer $VIGGLE_API_KEY" \
  -F "motion_video_url=https://assets.viggle.ai/pub/www/developers/sample-motion-97bb074a.mp4" \
  -F "type=glb"
```

## 获取结果

轮询 `GET /v1/motions/{motion_id}`，直到 `status` 变为 `ready` 或 `failed`。失败原因在 `glb.error` 中，而不是顶层的 `error`。就绪的动作会列出 `glb.skeletons: ["mixamo", "metahuman"]`。

然后用 `download_type=glb` 或 `fbx` 调用 `GET /v1/motions/{motion_id}/export`。格式对三种骨骼同时生效，三者一并返回：

| 字段 | 骨骼 | 用途 |
| - | - | - |
| `mixamo_url` | Mixamo 骨骼 | 在 Unity、Unreal、Blender 或 Maya 中重定向到你自己的网格上 |
| `metahuman_url` | MetaHuman，441 个关节，含面部 | 用 `joint_set=full` 创建的 Viggle 3D 角色 |
| `metahuman_body_url` | MetaHuman 身体，86 个关节 | 使用默认 `joint_set=body` 的 Viggle 3D 角色 |

如果创建动作时设置了 `render_mp4=true`，无论 `download_type` 取何值，导出都会额外返回 `mp4_url`，即 Mixamo 动画的 MP4 预览。否则 `mp4_url` 为 null。

用 `joint_set=expression`（119 个关节）创建的角色没有对应骨骼；要播放这些动作片段，请用 `body` 或 `full` 创建角色。

两种格式都会预先生成，因此切换 `download_type` 不需要等待。每个链接有效期为 1 小时，每次调用导出接口都会签发新链接。文件属于动作的一部分，在你删除动作（`DELETE /v1/motions/{motion_id}`，返回 `204`，响应体为空）之前一直可用。根据文字或用 `type=glb` 生成的动作，以及任何动作的导出，都只对创建它的 API 密钥可见；其他密钥会收到 `404 MOTION_NOT_FOUND`。轮换该密钥前，请先导出所需内容。根据文字或用 `type=glb` 生成的动作不会出现在 `GET /v1/motions` 中，请保存好它们的 ID。

## 导入动作模板

`POST /v1/motions/import` 会把一个 Viggle 动作模板复制为你名下的动作，可直接用于 Video Remix。模板 ID 可在 [viggle.ai](https://viggle.ai) 上找到：既可以是 Viggle 模板库中的官方模板，也可以是在 Viggle 应用中制作的模板（其 ID 可能以 `3s` 开头，按复制到的原样发送即可）。API 没有列出模板的接口。多人模板会为每个人保留一条轨道，因此在 [Video Remix](https://docs.viggle.ai/zh/v1/video/video-remix) 渲染任务中，可以通过 `character_mapping` 为每个人分别指定角色。

```bash theme={null}
curl -X POST https://apis.viggle.ai/v1/motions/import \
  -H "Authorization: Bearer $VIGGLE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"template_id": "YOUR_TEMPLATE_ID", "name": "Dance loop"}'
```

```json theme={null}
{ "id": "mot_550e8400-e29b-41d4-a716-446655440000", "status": "queued", "progress": 0 }
```

模板不存在时返回 `404`。模板尚未完成人物追踪时返回 `400`。轮询 `GET /v1/motions/{motion_id}` 获取名称和状态。

## 后续步骤

> [card] [3D 角色](https://docs.viggle.ai/zh/v1/3d/characters.md)
>
> 带骨骼的 `.vsplat` 角色，可在其上播放这些动作片段。

> [card] [Unity 快速入门](https://docs.viggle.ai/zh/v1/3d/unity-quickstart.md)
>
> 导入 FBX 并驱动 splat 角色。

> [card] [API 参考](https://docs.viggle.ai/zh/v1/api-reference/motions/export-a-3d-motion.md)
>
> 创建、导入和导出接口的全部字段。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.