cozyclay 1.9.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +171 -0
- package/bin/agent/agent-routes.mjs +74 -70
- package/bin/agent/agent-runner.mjs +10 -3
- package/bin/agent/motion-runtime.mjs +32 -260
- package/bin/agent/providers.mjs +46 -3
- package/bin/agent/session-store.mjs +41 -5
- package/bin/agent/studio-prompt.mjs +1 -1
- package/bin/agent/studio-tools.mjs +48 -11
- package/bin/cozyclay.mjs +26 -8
- package/bin/live/cli.mjs +22 -3
- package/bin/mcp-runtime.mjs +35 -20
- package/bin/telemetry-state.mjs +5 -2
- package/bin/update-check.mjs +15 -0
- package/dist/app/index.html +6 -6
- package/dist/assets/analytics-MVZOEW8O.js +1 -0
- package/dist/assets/app-C1sdVbg4.css +1 -0
- package/dist/assets/app-CA55tcI3.js +4876 -0
- package/dist/assets/{demo-B-eg1CT8.js → demo-ByeYp-dY.js} +1 -1
- package/dist/assets/{first-shot-handoff-CGgnvNu8.js → first-shot-handoff-DgT28ZiV.js} +1 -1
- package/dist/assets/{landing-IbRp3FnQ.js → landing-BaXkpFip.js} +1 -1
- package/dist/assets/shot-prompt-CbqWcWYi.css +1 -0
- package/dist/assets/shot-prompt-Yrt99wZx.js +17 -0
- package/dist/assets/{ticket-BgIzOBOf.js → ticket-BcmsnHn5.js} +1 -1
- package/dist/assets/workflow-DRdwoDBT.css +1 -0
- package/dist/assets/workflow-dNPGY9xz.js +179 -0
- package/dist/cozyclay-package.json +1 -1
- package/dist/fonts/IBM-Plex-Sans-OFL.txt +92 -0
- package/dist/fonts/JetBrains-Mono-OFL.txt +93 -0
- package/dist/fonts/README.md +13 -9
- package/dist/fonts/ibm-plex-sans-400-latin.woff2 +0 -0
- package/dist/fonts/ibm-plex-sans-500-latin.woff2 +0 -0
- package/dist/fonts/ibm-plex-sans-600-latin.woff2 +0 -0
- package/dist/fonts/jetbrains-mono-400-latin.woff2 +0 -0
- package/dist/fonts/jetbrains-mono-500-latin.woff2 +0 -0
- package/dist/index.html +7 -7
- package/dist/privacy/index.html +13 -8
- package/dist/sitemap.xml +6 -6
- package/dist/workflow/index.html +5 -5
- package/mcp/LIVE-PROTOCOL.md +1 -1
- package/mcp/live-hub.mjs +35 -93
- package/mcp/mesh-file.mjs +48 -0
- package/mcp/server.mjs +6 -77
- package/mcp/tool-handlers.mjs +224 -377
- package/package.json +2 -1
- package/src/App.jsx +1273 -9075
- package/src/analytics.js +393 -9
- package/src/app-context.js +211 -0
- package/src/app-stage.jsx +25 -24
- package/src/ardy/auto-fix-panel.css +108 -0
- package/src/ardy/collision-blockers.js +9 -3
- package/src/ardy/fix-collisions.js +10 -66
- package/src/ardy/ground.js +4 -4
- package/src/ardy/ik-drag.js +101 -0
- package/src/ardy/ik-key-json.js +43 -0
- package/src/ardy/ik.js +122 -76
- package/src/ardy/physics-panel.css +2 -0
- package/src/ardy/physics-panel.jsx +17 -5
- package/src/ardy/platform-fit-panel.css +64 -0
- package/src/ardy/platform-fit-panel.jsx +40 -0
- package/src/ardy/platform-fit.js +326 -0
- package/src/ardy/playback.js +166 -20
- package/src/ardy/range-pin.js +299 -0
- package/src/ardy/timeline-coordinates.js +26 -0
- package/src/ardy/timeline.css +1199 -0
- package/src/ardy/timeline.jsx +149 -41
- package/src/ardy/waypoints.js +2 -2
- package/src/asset-pane.css +462 -0
- package/src/asset-pane.jsx +461 -232
- package/src/command-bus.js +349 -0
- package/src/commands/ai.js +31 -0
- package/src/commands/cast.js +140 -0
- package/src/commands/elements/character.js +13 -0
- package/src/commands/elements/motion.js +14 -0
- package/src/commands/elements/object.js +22 -0
- package/src/commands/elements/scene.js +16 -0
- package/src/commands/elements/shot.js +9 -0
- package/src/commands/elements/stage.js +11 -0
- package/src/commands/elements.js +155 -0
- package/src/commands/export.js +20 -0
- package/src/commands/index.js +40 -0
- package/src/commands/motion.js +231 -0
- package/src/commands/objects.js +174 -0
- package/src/commands/project.js +53 -0
- package/src/commands/scene.js +81 -0
- package/src/commands/shared.js +19 -0
- package/src/commands/shot.js +103 -0
- package/src/commands/stage.js +17 -0
- package/src/commands/view.js +42 -0
- package/src/document-store.js +144 -0
- package/src/domains/cast.js +1007 -0
- package/src/domains/motion.js +3219 -0
- package/src/domains/objects.js +932 -0
- package/src/domains/scenes.js +817 -0
- package/src/domains/shots.js +404 -0
- package/src/domains/stage.js +93 -0
- package/src/dualview.jsx +113 -57
- package/src/facing-marks.js +3 -0
- package/src/first-success-guide.jsx +14 -14
- package/src/grid-view.js +18 -5
- package/src/hierarchy-model.js +24 -16
- package/src/hierarchy-panel.css +386 -0
- package/src/hierarchy-panel.jsx +150 -21
- package/src/{fal-motion-client.js → i2v-motion-client.js} +13 -13
- package/src/i2v-motion-studio.jsx +180 -0
- package/src/ik-camera.js +3 -0
- package/src/main.jsx +6 -0
- package/src/motion/generation.js +105 -0
- package/src/motion-readiness-ui.jsx +4 -4
- package/src/motion-readiness.js +11 -0
- package/src/motion-trail.js +366 -9
- package/src/object-gizmo.jsx +7 -1
- package/src/otio.js +2 -1
- package/src/panels/CameraPanel.jsx +60 -0
- package/src/panels/CharacterTransformPanel.jsx +48 -0
- package/src/panels/EnvironmentPanel.jsx +40 -0
- package/src/panels/Foldout.jsx +32 -0
- package/src/panels/LightPanel.jsx +24 -0
- package/src/panels/ObjectTransformPanel.jsx +554 -0
- package/src/panels/PosePanel.jsx +97 -0
- package/src/panels/ProjectPanel.jsx +33 -0
- package/src/panels/PromptBlocksPanel.jsx +442 -0
- package/src/panels/PropsPanel.jsx +70 -0
- package/src/panels/ReferenceImageField.jsx +91 -0
- package/src/panels/RigControlPanel.jsx +78 -0
- package/src/panels/RigPanel.jsx +37 -0
- package/src/panels/SubjectBox.jsx +47 -0
- package/src/panels/SubjectsPanel.jsx +39 -0
- package/src/panels/VideoCapturePanel.jsx +180 -0
- package/src/panels/details.css +1171 -0
- package/src/panels/motion.css +197 -0
- package/src/panels/pose.css +39 -0
- package/src/planview.jsx +60 -31
- package/src/posestudio.jsx +59 -4
- package/src/project-browser.css +1073 -0
- package/src/project-browser.jsx +284 -123
- package/src/range-pin-object-transform.js +19 -0
- package/src/range-pin-panel.css +518 -0
- package/src/range-pin-panel.jsx +344 -0
- package/src/result-modal.jsx +5 -5
- package/src/room.jsx +79 -51
- package/src/scene-objects.js +37 -1
- package/src/scenes.js +5 -0
- package/src/semantic-edit.js +2 -0
- package/src/settings-menu.jsx +39 -105
- package/src/shell/BottomDock.jsx +450 -0
- package/src/shell/DetailsSlot.jsx +513 -0
- package/src/shell/LibrarySlot.jsx +86 -0
- package/src/shell/MenuBar.jsx +601 -0
- package/src/shell/OutlinerSlot.jsx +50 -0
- package/src/shell/PreferencesDialog.jsx +538 -0
- package/src/shell/PreferencesSlot.jsx +40 -0
- package/src/shell/StatusBar.jsx +125 -0
- package/src/shell/StudioShell.jsx +92 -0
- package/src/shell/TopBar.jsx +129 -0
- package/src/shell/ViewportToolbar.jsx +656 -0
- package/src/shell/agent-glass.css +296 -0
- package/src/shell/dock.css +93 -0
- package/src/shell/glass-regions.css +985 -0
- package/src/shell/glass.css +687 -0
- package/src/shell/log-store.js +52 -0
- package/src/shell/mode.css +9 -0
- package/src/shell/preferences.css +651 -0
- package/src/shell/shell.css +282 -0
- package/src/shell/studio-shell-context.js +19 -0
- package/src/shell/topbar.css +435 -0
- package/src/shell/viewport.css +451 -0
- package/src/store/authored-intent.js +22 -0
- package/src/store/runtime-adapters.js +92 -0
- package/src/store/scene-stage.js +21 -0
- package/src/store/use-document-store.js +14 -0
- package/src/studio-actions.js +210 -0
- package/src/studio-agent-commands.js +41 -271
- package/src/studio-agent-context.js +39 -10
- package/src/studio-agent-motion.js +122 -373
- package/src/studio-agent-protocol.js +67 -31
- package/src/studio-app-binding.js +379 -0
- package/src/studio-contact-sheet.js +73 -0
- package/src/studio-elements.js +58 -51
- package/src/styles/themes.css +200 -0
- package/src/styles/tokens.css +69 -0
- package/src/styles.css +460 -1742
- package/src/theme.js +44 -0
- package/src/timeline-extent.js +16 -0
- package/src/trail-key-conflicts.js +39 -0
- package/src/trail-pick.js +59 -0
- package/src/ui.jsx +8 -8
- package/src/use-case-question.jsx +66 -0
- package/src/workflow/AgentPanel.jsx +82 -69
- package/src/workflow/agent-client.js +12 -2
- package/src/workflow/agent-panel.css +34 -32
- package/src/workflow/cozy-scene-node.css +2 -0
- package/src/workflow/workflow.css +2 -0
- package/tools/ardy/__pycache__/cclay_gvhmr_worker.cpython-313.pyc +0 -0
- package/tools/ardy/bridge.mjs +164 -146
- package/tools/ardy/visual-qa.mjs +5 -5
- package/tools/bench/EXP3.md +61 -0
- package/tools/bench/cclay_bench_extract_incam.py +125 -0
- package/tools/bench/cclay_bench_extract_obs.py +204 -0
- package/tools/bench/cclay_bench_runner.py +42 -0
- package/tools/bench/cube-contact.mjs +162 -0
- package/tools/bench/exp3.mjs +152 -0
- package/tools/bench/extract-bench-lib.mjs +216 -0
- package/tools/bench/extract-bench.mjs +302 -0
- package/tools/bench/fal-generate.mjs +88 -0
- package/tools/bench/fit/README.md +189 -0
- package/tools/bench/fit/camera.mjs +59 -0
- package/tools/bench/fit/contact.mjs +419 -0
- package/tools/bench/fit/footlock.mjs +234 -0
- package/tools/bench/fit/motion.mjs +85 -0
- package/tools/bench/fit/pin.mjs +27 -0
- package/tools/bench/fit/remote.mjs +105 -0
- package/tools/bench/fit-bench.mjs +126 -0
- package/tools/bench/fit-sanity.mjs +45 -0
- package/tools/bench/metrics.mjs +313 -0
- package/tools/bench/obs/depth.mjs +258 -0
- package/tools/bench/obs/extrinsics.mjs +175 -0
- package/tools/bench/obs/fit_mannequin_betas.py +340 -0
- package/tools/bench/obs/ground.mjs +294 -0
- package/tools/bench/obs/heading.mjs +151 -0
- package/tools/bench/obs/ladder.mjs +555 -0
- package/tools/bench/obs/mannequin-betas.json +124 -0
- package/tools/bench/obs/remote.mjs +83 -0
- package/tools/bench/obs/rest_joints.py +52 -0
- package/tools/bench/obs/ybot-targets.mjs +49 -0
- package/tools/bench/obs-bench.mjs +520 -0
- package/tools/bench/score.mjs +343 -0
- package/tools/bench/summarize.mjs +86 -0
- package/tools/dev/pages/privacy.html +13 -8
- package/tools/gt-render/browser.mjs +159 -0
- package/tools/gt-render/camera-math.mjs +276 -0
- package/tools/gt-render/page.mjs +267 -0
- package/tools/gt-render/render.mjs +514 -0
- package/tools/gt-render/scene-box.mjs +31 -0
- package/tools/gt-render/take-transform.mjs +87 -0
- package/tools/morphgs/assets/gen_truth.py +39 -0
- package/tools/morphgs/assets/mesh_ori_rig.txt +27 -0
- package/tools/morphgs/assets/playback-check.mjs +30 -0
- package/tools/morphgs/demo-gate.sh +26 -0
- package/tools/morphgs/fbx2morphgs.mjs +68 -0
- package/tools/morphgs/morphgs-to-cskel27.mjs +105 -0
- package/tools/morphgs/patches/preprocess_src-none-mode.patch +76 -0
- package/tools/morphgs/setup-on-cluster.sh +126 -0
- package/tools/qa/css-rule-usage.mjs +283 -0
- package/tools/qa/studio-control-count.mjs +70 -32
- package/tools/run-tests.mjs +134 -12
- package/tools/track/DESIGN.md +513 -0
- package/tools/track/backfill-provenance.mjs +116 -0
- package/tools/track/budget.mjs +8 -0
- package/tools/track/check-rig.mjs +209 -0
- package/tools/track/diagnostics.schema.json +60 -0
- package/tools/track/export-rig.mjs +256 -0
- package/tools/track/fallback.mjs +7 -0
- package/tools/track/fk-parity-fixture.mjs +161 -0
- package/tools/track/gate.mjs +349 -0
- package/tools/track/masks.mjs +318 -0
- package/tools/track/metrics.mjs +201 -0
- package/tools/track/publish-obs.mjs +108 -0
- package/tools/track/py/check_env.py +61 -0
- package/tools/track/py/eval_lr.py +229 -0
- package/tools/track/py/lr_viterbi.py +294 -0
- package/tools/track/py/masks.py +405 -0
- package/tools/track/py/objective.py +382 -0
- package/tools/track/py/rig.py +508 -0
- package/tools/track/py/scene.py +326 -0
- package/tools/track/py/test_joint_indices.py +123 -0
- package/tools/track/py/test_lr_viterbi.py +195 -0
- package/tools/track/py/test_masks.py +229 -0
- package/tools/track/py/test_rig.py +288 -0
- package/tools/track/py/test_scene.py +354 -0
- package/tools/track/py/test_track.py +328 -0
- package/tools/track/py/track.py +411 -0
- package/tools/track/remote.mjs +140 -0
- package/tools/track/rig-dump.mjs +227 -0
- package/tools/track/run-box-tests.mjs +14 -0
- package/tools/track/run-box.mjs +168 -0
- package/tools/track/setup-box.sh +59 -0
- package/tools/track/study-2d.mjs +728 -0
- package/dist/assets/analytics-B1hnH66c.js +0 -1
- package/dist/assets/app-BWusbqgO.js +0 -4861
- package/dist/assets/app-qKDo4PBX.css +0 -1
- package/dist/assets/shot-prompt-CHUtw6af.js +0 -17
- package/dist/assets/shot-prompt-C_g2BHVc.css +0 -1
- package/dist/assets/workflow-CVwzMhz2.js +0 -179
- package/dist/assets/workflow-DsudxKHF.css +0 -1
- package/src/fal-motion-studio.jsx +0 -180
- package/src/scene-history.js +0 -129
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Ground-truth renderer (#428): cskel27 motion npz -> GVHMR-ready videos
|
|
4
|
+
* rendered by the real CozyClay Studio from ONE fixed, known camera, with the
|
|
5
|
+
* exact camera and joint ground truth written next to every video.
|
|
6
|
+
*
|
|
7
|
+
* node tools/gt-render/render.mjs --out <dir> [options] <motion.npz ...>
|
|
8
|
+
*
|
|
9
|
+
* Per motion it starts (or reuses, --url) a Vite dev server of this checkout
|
|
10
|
+
* and a headless Chrome, loads the take through `?motion=`, and:
|
|
11
|
+
* 1. pre-pass: scrubs every timeline frame, CPU-skins every drawable vertex
|
|
12
|
+
* of the rig and reduces it (plus the joints) to five support values;
|
|
13
|
+
* 2. solves the closest static camera at the requested azimuth/elevation and
|
|
14
|
+
* integer GVHMR f-mm that keeps every vertex of every frame inside the
|
|
15
|
+
* margin box (camera-math.mjs), identical for all variants;
|
|
16
|
+
* 3. renders every timeline frame at 832x480 through the Studio's export
|
|
17
|
+
* capture (`window.__cozyclay.captureFraming`), encodes H.264 yuv420p
|
|
18
|
+
* 24 fps, and writes camera.json, joints.json and meta.json.
|
|
19
|
+
*
|
|
20
|
+
* Variants: `shaded` (part colours, shaded palette, what GVHMR's palette
|
|
21
|
+
* detector expects), `skin` (part colours off), `hue+N` / `hue-N` (the shaded
|
|
22
|
+
* frames through ffmpeg's `hue=h=N` filter; it rotates the chroma plane of
|
|
23
|
+
* EVERY pixel by the same N degrees, so all hues shift uniformly and neutral
|
|
24
|
+
* greys stay put. It does not reshuffle parts: the palette's relative layout is
|
|
25
|
+
* preserved).
|
|
26
|
+
*
|
|
27
|
+
* Output per motion:
|
|
28
|
+
* <out>/<motion>/plate.png the same framing with the character hidden
|
|
29
|
+
* <out>/<motion>/mask/NNNNNN.png exact per-frame silhouette (gray, 255 = character),
|
|
30
|
+
* the character re-drawn unlit in one colour
|
|
31
|
+
* <out>/<motion>/<variant>/{video.mp4,camera.json,joints.json,meta.json}
|
|
32
|
+
*
|
|
33
|
+
* Scoring renders (#431): `--camera <camera.json>` renders through that exact
|
|
34
|
+
* camera instead of solving one; `--no-video` captures only the silhouette
|
|
35
|
+
* masks and writes <out>/<motion>/{camera.json,joints.json,meta.json,mask/};
|
|
36
|
+
* `--transform` places the take in the scene first (take-transform.mjs, the
|
|
37
|
+
* Studio's sceneCalibration semantics); `--box` also writes contact.json, the
|
|
38
|
+
* per-frame signed distance of the closest skinned vertex to a scene box.
|
|
39
|
+
*/
|
|
40
|
+
import { execFileSync } from "node:child_process";
|
|
41
|
+
import { createHash } from "node:crypto";
|
|
42
|
+
import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
43
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
44
|
+
import { parseArgs } from "node:util";
|
|
45
|
+
import { installSignalCleanup } from "../process-supervisor.mjs";
|
|
46
|
+
import { openStudioClean, startChrome, startVite, terminateAll, waitFor } from "./browser.mjs";
|
|
47
|
+
import { decodeMotionNpz } from "../../src/ardy/npz.js";
|
|
48
|
+
import { writeNpz } from "../ardy/npz.mjs";
|
|
49
|
+
import { boxContactValues, contactFromSigned, parseBox } from "../bench/metrics.mjs";
|
|
50
|
+
import { buildCamera, cameraFromRecord, marginSlopes, mergeSupports, projectPoint, supportArgs, supportValues, translateCamera } from "./camera-math.mjs";
|
|
51
|
+
import { installPageHelpers, MASK_RGB, RIG_JOINTS } from "./page.mjs";
|
|
52
|
+
import { boxCorners, parseSceneBox, sceneBoxRecord } from "./scene-box.mjs";
|
|
53
|
+
import { isIdentityTransform, parseTransform, takeToNpzMembers, transformTake } from "./take-transform.mjs";
|
|
54
|
+
|
|
55
|
+
const ROOT = resolve(dirname(new URL(import.meta.url).pathname), "../..");
|
|
56
|
+
const WIDTH = 832;
|
|
57
|
+
const HEIGHT = 480;
|
|
58
|
+
const FPS = 24;
|
|
59
|
+
const CACHE_DIR = join(ROOT, "node_modules/.cache/gt-render");
|
|
60
|
+
|
|
61
|
+
const USAGE = `usage: node tools/gt-render/render.mjs --out <dir> [options] <motion.npz ...>
|
|
62
|
+
|
|
63
|
+
--out <dir> output root; each motion goes to <dir>/<npz basename>/<variant>/
|
|
64
|
+
--variants <list> comma list of shaded, skin, hue+N, hue-N (default shaded)
|
|
65
|
+
--f-mm <int> GVHMR --f-mm the camera is built for (default 35)
|
|
66
|
+
--azimuth <deg> camera azimuth around the subject; 0 = on +Z looking -Z (default 0)
|
|
67
|
+
--elevation <deg> camera elevation; positive looks down (default 5)
|
|
68
|
+
--margin <frac> fraction of each image side kept clear of the body (default 0.08)
|
|
69
|
+
--crf <int> libx264 CRF (default 12)
|
|
70
|
+
--keep-frames keep the rendered PNG frames in <variant>/frames/
|
|
71
|
+
--url <origin> reuse a running Vite dev server of THIS checkout (default: start one)
|
|
72
|
+
--port <n> Vite port when starting one (default 5191)
|
|
73
|
+
--cdp-port <n> headless Chrome DevTools port (default 9231)
|
|
74
|
+
--camera <file> render through this camera.json (from an earlier render) instead of
|
|
75
|
+
solving one; --f-mm/--azimuth/--elevation/--margin are then unused
|
|
76
|
+
and a joint near or past the edge is reported, not fatal
|
|
77
|
+
--no-video masks + joints only: <dir>/<motion>/{camera.json,joints.json,meta.json,mask/}
|
|
78
|
+
--transform <json> place the take first, Studio sceneCalibration semantics:
|
|
79
|
+
'{"yawDeg":0,"offsetX":0,"offsetY":0,"offsetZ":0,"scale":1}'
|
|
80
|
+
(yaw about the frame-0 anchor, offsets in scene metres)
|
|
81
|
+
--scene-box <json> visible Studio cube: {x,z,rot,sx,sy,sz}; base at floor, sizes in metres
|
|
82
|
+
--export-vertices write vertices.f32 (frame/vertex/xyz, little-endian float32) + vertices.json
|
|
83
|
+
--box <json> '{"min":[x,y,z],"max":[x,y,z]}' scene box; writes <dir>/<motion>/contact.json
|
|
84
|
+
(closest skinned vertex per frame: distance / penetration)
|
|
85
|
+
|
|
86
|
+
writes <dir>/<motion>/{plate.png,mask/NNNNNN.png} and
|
|
87
|
+
<dir>/<motion>/<variant>/{video.mp4,camera.json,joints.json,meta.json}`;
|
|
88
|
+
|
|
89
|
+
function parseOptions(argv) {
|
|
90
|
+
const { values, positionals } = parseArgs({
|
|
91
|
+
args: argv,
|
|
92
|
+
allowPositionals: true,
|
|
93
|
+
options: {
|
|
94
|
+
out: { type: "string" },
|
|
95
|
+
variants: { type: "string", default: "shaded" },
|
|
96
|
+
"f-mm": { type: "string", default: "35" },
|
|
97
|
+
azimuth: { type: "string", default: "0" },
|
|
98
|
+
elevation: { type: "string", default: "5" },
|
|
99
|
+
margin: { type: "string", default: "0.08" },
|
|
100
|
+
crf: { type: "string", default: "12" },
|
|
101
|
+
"keep-frames": { type: "boolean", default: false },
|
|
102
|
+
url: { type: "string" },
|
|
103
|
+
port: { type: "string", default: "5191" },
|
|
104
|
+
"cdp-port": { type: "string", default: "9231" },
|
|
105
|
+
camera: { type: "string" },
|
|
106
|
+
"no-video": { type: "boolean", default: false },
|
|
107
|
+
transform: { type: "string" },
|
|
108
|
+
box: { type: "string" },
|
|
109
|
+
"scene-box": { type: "string" },
|
|
110
|
+
"export-vertices": { type: "boolean", default: false },
|
|
111
|
+
help: { type: "boolean", short: "h", default: false },
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
if (values.help) {
|
|
115
|
+
console.log(USAGE);
|
|
116
|
+
process.exit(0);
|
|
117
|
+
}
|
|
118
|
+
const fail = (message) => {
|
|
119
|
+
console.error(`${message}\n\n${USAGE}`);
|
|
120
|
+
process.exit(2);
|
|
121
|
+
};
|
|
122
|
+
if (!values.out) fail("--out is required");
|
|
123
|
+
if (!positionals.length) fail("at least one motion npz is required");
|
|
124
|
+
const number = (name, integer = false) => {
|
|
125
|
+
const value = Number(values[name]);
|
|
126
|
+
if (!Number.isFinite(value) || (integer && !Number.isInteger(value))) fail(`--${name} must be ${integer ? "an integer" : "a number"}, got ${values[name]}`);
|
|
127
|
+
return value;
|
|
128
|
+
};
|
|
129
|
+
const variants = values.variants.split(",").map((entry) => entry.trim()).filter(Boolean).map((name) => {
|
|
130
|
+
if (name === "shaded" || name === "skin") return { name, kind: name };
|
|
131
|
+
const hue = /^hue([+-]\d+(?:\.\d+)?)$/.exec(name);
|
|
132
|
+
if (hue) return { name, kind: "hue", degrees: Number(hue[1]) };
|
|
133
|
+
return fail(`unknown variant ${name}`);
|
|
134
|
+
});
|
|
135
|
+
if (new Set(variants.map((variant) => variant.name)).size !== variants.length) fail("duplicate variant");
|
|
136
|
+
const motions = positionals.map((file) => resolve(file));
|
|
137
|
+
for (const file of motions) if (!existsSync(file)) fail(`no such motion: ${file}`);
|
|
138
|
+
const names = motions.map((file) => basename(file, ".npz"));
|
|
139
|
+
if (new Set(names).size !== names.length) fail(`two motions share an output name: ${names.join(", ")}`);
|
|
140
|
+
let camera = null;
|
|
141
|
+
if (values.camera) {
|
|
142
|
+
const file = resolve(values.camera);
|
|
143
|
+
if (!existsSync(file)) fail(`no such camera: ${file}`);
|
|
144
|
+
try {
|
|
145
|
+
camera = cameraFromRecord(JSON.parse(readFileSync(file, "utf8")));
|
|
146
|
+
} catch (error) {
|
|
147
|
+
fail(`--camera ${file}: ${error.message}`);
|
|
148
|
+
}
|
|
149
|
+
if (camera.width !== WIDTH || camera.height !== HEIGHT) fail(`--camera is ${camera.width}x${camera.height}; the renderer draws ${WIDTH}x${HEIGHT}`);
|
|
150
|
+
camera.source = file;
|
|
151
|
+
}
|
|
152
|
+
let transform = null;
|
|
153
|
+
if (values.transform) {
|
|
154
|
+
try {
|
|
155
|
+
transform = parseTransform(values.transform);
|
|
156
|
+
} catch (error) {
|
|
157
|
+
fail(`--transform: ${error.message}`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
let box = null;
|
|
161
|
+
if (values.box) {
|
|
162
|
+
try {
|
|
163
|
+
box = parseBox(values.box);
|
|
164
|
+
} catch (error) {
|
|
165
|
+
fail(`--box: ${error.message}`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return {
|
|
169
|
+
camera,
|
|
170
|
+
sceneBox: values["scene-box"] ? parseSceneBox(values["scene-box"]) : null,
|
|
171
|
+
exportVertices: values["export-vertices"],
|
|
172
|
+
noVideo: values["no-video"],
|
|
173
|
+
transform,
|
|
174
|
+
box,
|
|
175
|
+
out: resolve(values.out),
|
|
176
|
+
variants,
|
|
177
|
+
fMm: number("f-mm", true),
|
|
178
|
+
azimuthDeg: number("azimuth"),
|
|
179
|
+
elevationDeg: number("elevation"),
|
|
180
|
+
margin: number("margin"),
|
|
181
|
+
crf: number("crf", true),
|
|
182
|
+
keepFrames: values["keep-frames"],
|
|
183
|
+
url: values.url?.replace(/\/$/, "") ?? null,
|
|
184
|
+
port: number("port", true),
|
|
185
|
+
cdpPort: number("cdp-port", true),
|
|
186
|
+
motions,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const round = (value, digits) => Math.round(value * 10 ** digits) / 10 ** digits;
|
|
191
|
+
const triples = (flat, digits = 6) => Array.from({ length: flat.length / 3 }, (_, i) => [round(flat[i * 3], digits), round(flat[i * 3 + 1], digits), round(flat[i * 3 + 2], digits)]);
|
|
192
|
+
|
|
193
|
+
function toolVersion() {
|
|
194
|
+
const pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
|
|
195
|
+
try {
|
|
196
|
+
const commit = execFileSync("git", ["rev-parse", "--short", "HEAD"], { cwd: ROOT, encoding: "utf8" }).trim();
|
|
197
|
+
const dirty = execFileSync("git", ["status", "--porcelain"], { cwd: ROOT, encoding: "utf8" }).trim() !== "";
|
|
198
|
+
return `${pkg.version}+${commit}${dirty ? "-dirty" : ""}`;
|
|
199
|
+
} catch {
|
|
200
|
+
return pkg.version;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function encode(framesDir, output, { crf, filter }) {
|
|
205
|
+
execFileSync("ffmpeg", [
|
|
206
|
+
"-hide_banner", "-loglevel", "error", "-y",
|
|
207
|
+
"-framerate", String(FPS), "-i", join(framesDir, "%06d.png"),
|
|
208
|
+
...(filter ? ["-vf", filter] : []),
|
|
209
|
+
"-c:v", "libx264", "-preset", "slow", "-crf", String(crf),
|
|
210
|
+
"-pix_fmt", "yuv420p", "-colorspace", "smpte170m", "-color_primaries", "smpte170m", "-color_trc", "smpte170m", "-color_range", "tv",
|
|
211
|
+
"-r", String(FPS), "-movflags", "+faststart", output,
|
|
212
|
+
], { stdio: ["ignore", "inherit", "inherit"] });
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Magenta-on-scene mask captures -> gray PNGs, 255 where the pixel is at
|
|
216
|
+
* least half character (the MSAA edge blends linearly with the scene). */
|
|
217
|
+
function writeMasks(rawDir, maskDir) {
|
|
218
|
+
rmSync(maskDir, { recursive: true, force: true });
|
|
219
|
+
mkdirSync(maskDir, { recursive: true });
|
|
220
|
+
const [r, g, b] = MASK_RGB;
|
|
221
|
+
if (!(r === 255 && g === 0 && b === 255)) throw new Error("writeMasks expects the magenta mask colour");
|
|
222
|
+
const test = "255*gt(r(X,Y)-g(X,Y),127)*gt(b(X,Y)-g(X,Y),127)";
|
|
223
|
+
execFileSync("ffmpeg", [
|
|
224
|
+
"-hide_banner", "-loglevel", "error", "-y",
|
|
225
|
+
"-framerate", String(FPS), "-i", join(rawDir, "%06d.png"),
|
|
226
|
+
"-vf", `format=gbrp,geq=r='${test}':g='${test}':b='${test}',format=gray`,
|
|
227
|
+
"-start_number", "0", join(maskDir, "%06d.png"),
|
|
228
|
+
], { stdio: ["ignore", "inherit", "inherit"] });
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function cameraRecord(camera, shotCam) {
|
|
232
|
+
return {
|
|
233
|
+
width: camera.width,
|
|
234
|
+
height: camera.height,
|
|
235
|
+
fovDeg: camera.fovDeg,
|
|
236
|
+
fx: camera.fx,
|
|
237
|
+
fy: camera.fy,
|
|
238
|
+
cx: camera.cx,
|
|
239
|
+
cy: camera.cy,
|
|
240
|
+
K: [[camera.fx, 0, camera.cx], [0, camera.fy, camera.cy], [0, 0, 1]],
|
|
241
|
+
gvhmrFMm: camera.gvhmrFMm,
|
|
242
|
+
position: camera.position,
|
|
243
|
+
yaw: camera.yaw,
|
|
244
|
+
pitch: camera.pitch,
|
|
245
|
+
rotationOrder: "YXZ",
|
|
246
|
+
azimuthDeg: camera.azimuthDeg,
|
|
247
|
+
elevationDeg: camera.elevationDeg,
|
|
248
|
+
margin: camera.margin,
|
|
249
|
+
bindingAxis: camera.bindingAxis,
|
|
250
|
+
near: shotCam.near,
|
|
251
|
+
far: shotCam.far,
|
|
252
|
+
static: true,
|
|
253
|
+
worldToCamera: camera.worldToCameraCv,
|
|
254
|
+
worldToCameraGl: camera.worldToCameraGl,
|
|
255
|
+
cameraToWorldRotationThree: [camera.cameraToWorldRotation.slice(0, 3), camera.cameraToWorldRotation.slice(3, 6), camera.cameraToWorldRotation.slice(6, 9)],
|
|
256
|
+
convention: {
|
|
257
|
+
world: "CozyClay Studio / Three.js scene: right-handed, +Y up, metres. The character's front is +Z at azimuth 0.",
|
|
258
|
+
worldToCamera: "OpenCV: [X Y Z 1]^T = worldToCamera * [x y z 1]^T, camera x right, y DOWN, z forward (depth).",
|
|
259
|
+
projection: "u = fx * X / Z + cx, v = fy * Y / Z + cy. Square pixels, no distortion, no skew.",
|
|
260
|
+
image: "Pixels continuous from the top-left corner of the top-left pixel: u right, v DOWN; pixel (col,row) covers [col,col+1)x[row,row+1) and its centre is (col+0.5,row+0.5); cx = width/2, cy = height/2.",
|
|
261
|
+
worldToCameraGl: "Three/OpenGL view matrix (camera.matrixWorldInverse): x right, y up, looking down -z.",
|
|
262
|
+
threeCamera: "PerspectiveCamera(fov = fovDeg vertical, aspect = width/height), position, rotation.set(pitch, yaw, 0) with order YXZ (radians); rendered through the Studio export capture.",
|
|
263
|
+
gvhmr: "Run GVHMR with --f-mm gvhmrFMm: f_px = sqrt(W^2 + H^2) / sqrt(24^2 + 36^2) * f_mm equals fx = fy here.",
|
|
264
|
+
},
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
async function main() {
|
|
269
|
+
const options = parseOptions(process.argv.slice(2));
|
|
270
|
+
const children = [];
|
|
271
|
+
const cleanups = [];
|
|
272
|
+
const runCleanups = () => {
|
|
273
|
+
for (const cleanup of cleanups.splice(0)) cleanup();
|
|
274
|
+
};
|
|
275
|
+
const removeSignals = installSignalCleanup(() => children, () => {
|
|
276
|
+
runCleanups();
|
|
277
|
+
process.exit(130);
|
|
278
|
+
});
|
|
279
|
+
const version = toolVersion();
|
|
280
|
+
try {
|
|
281
|
+
const base = options.url ?? await startVite({ root: ROOT, port: options.port, children });
|
|
282
|
+
const cdp = await startChrome({ port: options.cdpPort, children, cleanups });
|
|
283
|
+
mkdirSync(CACHE_DIR, { recursive: true });
|
|
284
|
+
for (const file of options.motions) {
|
|
285
|
+
await renderMotion({ cdp, base, file, options, version });
|
|
286
|
+
}
|
|
287
|
+
cdp.close();
|
|
288
|
+
} finally {
|
|
289
|
+
removeSignals();
|
|
290
|
+
await terminateAll(children);
|
|
291
|
+
runCleanups();
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** The npz the Studio loads: the file itself, or the file with --transform's
|
|
296
|
+
* scale/offsetY/yaw baked in (take-transform.mjs). Either way it is put in
|
|
297
|
+
* the (gitignored) node_modules cache, where Vite can serve it to ?motion=. */
|
|
298
|
+
async function stageTake(file, bytes, transform) {
|
|
299
|
+
if (isIdentityTransform(transform)) {
|
|
300
|
+
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
|
301
|
+
const cached = join(CACHE_DIR, `${sha256.slice(0, 16)}.npz`);
|
|
302
|
+
if (!existsSync(cached)) copyFileSync(file, cached);
|
|
303
|
+
return { sha256, cacheName: `${sha256.slice(0, 16)}.npz`, sceneOffset: { x: 0, y: 0, z: 0 } };
|
|
304
|
+
}
|
|
305
|
+
const decoded = await decodeMotionNpz(new Uint8Array(bytes));
|
|
306
|
+
const { motion, sceneOffset } = transformTake(decoded, transform);
|
|
307
|
+
const staging = join(CACHE_DIR, `.staging-${process.pid}.npz`);
|
|
308
|
+
writeNpz(staging, takeToNpzMembers(motion));
|
|
309
|
+
const sha256 = createHash("sha256").update(readFileSync(staging)).digest("hex");
|
|
310
|
+
const cacheName = `${sha256.slice(0, 16)}.npz`;
|
|
311
|
+
copyFileSync(staging, join(CACHE_DIR, cacheName));
|
|
312
|
+
rmSync(staging, { force: true });
|
|
313
|
+
return { sha256, cacheName, sceneOffset };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
async function renderMotion({ cdp, base, file, options, version }) {
|
|
317
|
+
const started = Date.now();
|
|
318
|
+
const bytes = readFileSync(file);
|
|
319
|
+
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
|
320
|
+
const motionName = basename(file, ".npz");
|
|
321
|
+
const staged = await stageTake(file, bytes, options.transform);
|
|
322
|
+
// The page renders the take where playback anchors it; a scene offset is
|
|
323
|
+
// the camera moved the opposite way, and every reported point is shifted
|
|
324
|
+
// back into the scene by `offset`.
|
|
325
|
+
const offset = staged.sceneOffset;
|
|
326
|
+
const negOffset = { x: -offset.x, y: -offset.y, z: -offset.z };
|
|
327
|
+
const pageBox = options.box ? { min: options.box.min.map((v, i) => v - [offset.x, offset.y, offset.z][i]), max: options.box.max.map((v, i) => v - [offset.x, offset.y, offset.z][i]) } : null;
|
|
328
|
+
const motionUrl = `/node_modules/.cache/gt-render/${staged.cacheName}`;
|
|
329
|
+
const studioUrl = `${base}/app/?motion=${encodeURIComponent(motionUrl)}`;
|
|
330
|
+
const log = (message) => console.log(`[${motionName}] ${message}`);
|
|
331
|
+
|
|
332
|
+
await openStudioClean(cdp, studioUrl);
|
|
333
|
+
await waitFor("studio motion load", () => cdp.evaluate("!!(window.__cozyclay && window.__cozyclay.motion && window.__cozyclay.rigA && typeof window.__cozyclay.captureFraming === 'function')"), { timeoutMs: 180000, intervalMs: 250 });
|
|
334
|
+
await cdp.evaluate(`(${installPageHelpers.toString()})(${supportValues.toString()}, ${JSON.stringify(RIG_JOINTS)}, ${JSON.stringify(MASK_RGB)}, ${boxContactValues.toString()})`);
|
|
335
|
+
const state = await cdp.evaluate("window.__gtRender.state()");
|
|
336
|
+
if (state.motionUrl !== motionUrl) throw new Error(`Studio loaded ${state.motionUrl} instead of ${motionUrl}`);
|
|
337
|
+
if (state.fps !== FPS) throw new Error(`timeline runs at ${state.fps} fps, expected ${FPS}`);
|
|
338
|
+
const frames = state.frameCount;
|
|
339
|
+
log(`loaded ${frames} frames @ ${state.fps} fps, model ${state.characterModel}`);
|
|
340
|
+
const motionDir = join(options.out, motionName);
|
|
341
|
+
mkdirSync(motionDir, { recursive: true });
|
|
342
|
+
if (options.exportVertices) writeFileSync(join(motionDir, "vertices.f32"), "");
|
|
343
|
+
const sceneRecord = options.sceneBox ? { ...sceneBoxRecord(options.sceneBox), studio: await cdp.evaluate(`window.__gtRender.placeBox(${JSON.stringify(options.sceneBox)}, ${JSON.stringify(offset)})`) } : null;
|
|
344
|
+
|
|
345
|
+
// Pre-pass: the camera must see every vertex of every frame (solved
|
|
346
|
+
// camera), and --box needs every vertex anyway.
|
|
347
|
+
const geometry = { width: WIDTH, height: HEIGHT, fMm: options.fMm, azimuthDeg: options.azimuthDeg, elevationDeg: options.elevationDeg, margin: options.margin };
|
|
348
|
+
const givenMargin = options.camera ? (options.camera.margin ?? options.margin) : options.margin;
|
|
349
|
+
const { R, kx, ky } = options.camera
|
|
350
|
+
? { R: options.camera.cameraToWorldRotation, ...marginSlopes(options.camera, givenMargin) }
|
|
351
|
+
: supportArgs(geometry);
|
|
352
|
+
await cdp.evaluate(`window.__gtRender.setOrientation(${JSON.stringify(R)}, ${kx}, ${ky})`);
|
|
353
|
+
const sampleOptions = { vertices: !options.camera, box: pageBox, exportVertices: options.exportVertices };
|
|
354
|
+
const supports = [];
|
|
355
|
+
const prepassJoints = [];
|
|
356
|
+
const contacts = [];
|
|
357
|
+
let vertexCount = 0;
|
|
358
|
+
for (let frame = 0; frame < frames; frame += 1) {
|
|
359
|
+
const sample = await cdp.evaluate(`window.__gtRender.sample(${frame}, ${JSON.stringify(sampleOptions)})`);
|
|
360
|
+
if (sample.support) supports.push(sample.support);
|
|
361
|
+
if (sample.vertices) {
|
|
362
|
+
const points = Buffer.allocUnsafe(sample.vertices.length * 4);
|
|
363
|
+
sample.vertices.forEach((v, i) => points.writeFloatLE(v + [offset.x, offset.y, offset.z][i % 3], i * 4));
|
|
364
|
+
appendFileSync(join(motionDir, "vertices.f32"), points);
|
|
365
|
+
}
|
|
366
|
+
prepassJoints.push(sample.joints);
|
|
367
|
+
if (sample.contact) contacts.push(sample.contact);
|
|
368
|
+
vertexCount = sample.vertexCount;
|
|
369
|
+
}
|
|
370
|
+
if (options.exportVertices) writeFileSync(join(motionDir, "vertices.json"), JSON.stringify({ frames, fps: FPS, vertexCount, file: "vertices.f32", layout: "frame,vertex,xyz; float32 LE; world metres" }));
|
|
371
|
+
if (options.sceneBox && !options.camera) supports.push(supportValues(boxCorners(options.sceneBox).flatMap(p => p.map((v, i) => v - [offset.x, offset.y, offset.z][i])), R, kx, ky));
|
|
372
|
+
// pageCamera renders the anchored take; camera (scene) is what is reported.
|
|
373
|
+
const pageCamera = options.camera ? translateCamera(options.camera, negOffset) : buildCamera({ ...geometry, support: mergeSupports(supports) });
|
|
374
|
+
const camera = options.camera ?? translateCamera(pageCamera, offset);
|
|
375
|
+
const framing = { pos: pageCamera.position, yaw: pageCamera.yaw, pitch: pageCamera.pitch, fovDeg: pageCamera.fovDeg };
|
|
376
|
+
const output = { width: WIDTH, height: HEIGHT };
|
|
377
|
+
log(`camera at (${camera.position.x.toFixed(3)}, ${camera.position.y.toFixed(3)}, ${camera.position.z.toFixed(3)}), fov ${camera.fovDeg.toFixed(4)} deg, f ${camera.fy.toFixed(3)} px, ${options.camera ? `given (${options.camera.source})` : `${camera.bindingAxis}-bound`}, ${vertexCount} vertices/frame`);
|
|
378
|
+
|
|
379
|
+
// Scene joints (page + offset) projected with camera.json. A solved
|
|
380
|
+
// camera guarantees the margin box; a given one only reports it.
|
|
381
|
+
const sceneJoints = prepassJoints.map((joints) => triples(joints, 12).map(([x, y, z]) => [x + offset.x, y + offset.y, z + offset.z]));
|
|
382
|
+
const uv = sceneJoints.map((joints) => joints.map((point) => projectPoint(point, camera)));
|
|
383
|
+
let minMarginPx = Infinity;
|
|
384
|
+
for (const frameUv of uv) {
|
|
385
|
+
for (const [u, v, depth] of frameUv) minMarginPx = Math.min(minMarginPx, depth > 0 ? Math.min(u, v, WIDTH - u, HEIGHT - v) : -Infinity);
|
|
386
|
+
}
|
|
387
|
+
const marginPx = givenMargin * Math.min(WIDTH, HEIGHT);
|
|
388
|
+
if (!options.camera && minMarginPx < marginPx - 1e-6) throw new Error(`a joint projects ${minMarginPx.toFixed(2)} px from the edge, inside the ${marginPx} px margin`);
|
|
389
|
+
if (options.camera && minMarginPx < marginPx - 1e-6) log(`warning: a joint projects ${minMarginPx.toFixed(2)} px from the edge (margin ${marginPx} px); negative = outside the image or behind the camera`);
|
|
390
|
+
|
|
391
|
+
if (!options.noVideo) writeFileSync(join(motionDir, "plate.png"), Buffer.from(await cdp.evaluate(`window.__gtRender.plate(${JSON.stringify(framing)}, ${JSON.stringify(output)})`), "base64"));
|
|
392
|
+
|
|
393
|
+
const wanted = new Set(options.noVideo ? [] : options.variants.map((variant) => variant.name));
|
|
394
|
+
const needsShadedFrames = !options.noVideo && options.variants.some((variant) => variant.kind === "hue");
|
|
395
|
+
const browserPasses = options.noVideo ? [{ name: "mask", partColours: null }] : [
|
|
396
|
+
...(wanted.has("shaded") || needsShadedFrames ? [{ name: "shaded", partColours: true }] : []),
|
|
397
|
+
...(wanted.has("skin") ? [{ name: "skin", partColours: false }] : []),
|
|
398
|
+
];
|
|
399
|
+
const checks = { prepassVsRenderJointMaxM: 0, threeVsCameraJsonMaxPx: 0 };
|
|
400
|
+
const framesDirs = {};
|
|
401
|
+
const passState = {};
|
|
402
|
+
const maskRawDir = join(motionDir, ".mask-raw");
|
|
403
|
+
rmSync(maskRawDir, { recursive: true, force: true });
|
|
404
|
+
mkdirSync(maskRawDir, { recursive: true });
|
|
405
|
+
for (const [passIndex, pass] of browserPasses.entries()) {
|
|
406
|
+
const withMask = passIndex === 0;
|
|
407
|
+
const withColour = pass.partColours !== null;
|
|
408
|
+
if (withColour) passState[pass.name] = await cdp.evaluate(`window.__gtRender.setPartColours(${pass.partColours})`);
|
|
409
|
+
const framesDir = wanted.has(pass.name) ? join(motionDir, pass.name, "frames") : join(motionDir, `.${pass.name}-frames`);
|
|
410
|
+
if (withColour) {
|
|
411
|
+
rmSync(framesDir, { recursive: true, force: true });
|
|
412
|
+
mkdirSync(framesDir, { recursive: true });
|
|
413
|
+
framesDirs[pass.name] = framesDir;
|
|
414
|
+
}
|
|
415
|
+
for (let frame = 0; frame < frames; frame += 1) {
|
|
416
|
+
const captured = await cdp.evaluate(`window.__gtRender.capture(${frame}, ${JSON.stringify(framing)}, ${JSON.stringify(output)}, ${withMask}, ${withColour})`);
|
|
417
|
+
if (withColour) writeFileSync(join(framesDir, `${String(frame).padStart(6, "0")}.png`), Buffer.from(captured.png, "base64"));
|
|
418
|
+
if (withMask) writeFileSync(join(maskRawDir, `${String(frame).padStart(6, "0")}.png`), Buffer.from(captured.mask, "base64"));
|
|
419
|
+
for (let i = 0; i < captured.joints.length; i += 1) {
|
|
420
|
+
checks.prepassVsRenderJointMaxM = Math.max(checks.prepassVsRenderJointMaxM, Math.abs(captured.joints[i] - prepassJoints[frame][i]));
|
|
421
|
+
}
|
|
422
|
+
triples(captured.joints, 12).forEach((point, j) => {
|
|
423
|
+
const [u, v] = projectPoint(point, pageCamera);
|
|
424
|
+
checks.threeVsCameraJsonMaxPx = Math.max(checks.threeVsCameraJsonMaxPx, Math.abs(u - captured.threeUv[j * 2]), Math.abs(v - captured.threeUv[j * 2 + 1]));
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
log(`rendered ${pass.name}: ${frames} frames`);
|
|
428
|
+
}
|
|
429
|
+
writeMasks(maskRawDir, join(motionDir, "mask"));
|
|
430
|
+
rmSync(maskRawDir, { recursive: true, force: true });
|
|
431
|
+
// The pose must not depend on the pass: joints.json is the pre-pass pose.
|
|
432
|
+
if (checks.prepassVsRenderJointMaxM > 1e-6) throw new Error(`rendered pose differs from the pre-pass by ${checks.prepassVsRenderJointMaxM} m`);
|
|
433
|
+
if (checks.threeVsCameraJsonMaxPx > 1e-3) throw new Error(`camera.json projection differs from the Three capture camera by ${checks.threeVsCameraJsonMaxPx} px`);
|
|
434
|
+
|
|
435
|
+
const cameraJson = cameraRecord(camera, passState[browserPasses[0].name]?.shotCam ?? state.shotCam);
|
|
436
|
+
if (options.camera) cameraJson.source = options.camera.source;
|
|
437
|
+
const placement = {
|
|
438
|
+
transform: options.transform ?? null,
|
|
439
|
+
sceneOffset: offset,
|
|
440
|
+
anchor: state.motionAnchor,
|
|
441
|
+
note: "Studio placement: playback anchors the take's frame-0 root XZ on the subject (anchor) with the Character group's yaw. --transform: scale/offsetY/yaw baked into the loaded npz (yaw about the anchor), offsetX/offsetZ applied as the opposite camera move; joints, uv and contact are in the scene frame with the offset included.",
|
|
442
|
+
renderedNpzSha256: staged.sha256,
|
|
443
|
+
};
|
|
444
|
+
const contactJson = options.box ? {
|
|
445
|
+
box: options.box,
|
|
446
|
+
basis: "skinned-vertices",
|
|
447
|
+
vertexCount,
|
|
448
|
+
convention: "signedDistanceM: closest skinned vertex to the box, positive outside, negative inside (depth to the nearest face). minDistanceM = max(0, signed), maxPenetrationM = max(0, -signed). Scene metres, the placement's offset included.",
|
|
449
|
+
frames: contacts.map((contact) => ({ signedDistanceM: round(contact.minSignedDistance, 6), ...Object.fromEntries(Object.entries(contactFromSigned(contact.minSignedDistance)).map(([key, value]) => [key, round(value, 6)])), verticesInside: contact.insideCount })),
|
|
450
|
+
} : null;
|
|
451
|
+
if (contactJson) writeFileSync(join(motionDir, "contact.json"), `${JSON.stringify(contactJson)}\n`);
|
|
452
|
+
const jointsJson = {
|
|
453
|
+
convention: "world: metres in the camera.json world frame; uv: pixels in the camera.json image convention (origin top-left, v down), projected with camera.json; depth: camera-space Z in metres.",
|
|
454
|
+
fps: FPS,
|
|
455
|
+
frames,
|
|
456
|
+
joints: RIG_JOINTS.map(({ bone, cskel27 }) => ({ name: bone.replace(/^mixamorig/, ""), bone, cskel27 })),
|
|
457
|
+
note: "Rig bones of the rendered character (the pose actually drawn). Mixamo Spine/Spine1/Spine2 correspond to cskel27 Spine1/Spine2/Spine3 (src/ardy/playback.js); the Mixamo body is not congruent with cskel27 and playback scales the take's root travel to the rig's leg length, so these are NOT the npz's posed_joints: they differ by centimetres, growing with distance travelled (about 1% of it on walk-then-stop). They are the truth for what the video shows.",
|
|
458
|
+
world: sceneJoints.map((joints) => joints.map((point) => point.map((value) => round(value, 6)))),
|
|
459
|
+
uv: uv.map((frameUv) => frameUv.map(([u, v]) => [round(u, 4), round(v, 4)])),
|
|
460
|
+
depth: uv.map((frameUv) => frameUv.map(([, , z]) => round(z, 6))),
|
|
461
|
+
};
|
|
462
|
+
const shared = {
|
|
463
|
+
tool: "tools/gt-render/render.mjs",
|
|
464
|
+
toolVersion: version,
|
|
465
|
+
createdAt: new Date().toISOString(),
|
|
466
|
+
source: { path: file, sha256, bytes: bytes.length },
|
|
467
|
+
motionName,
|
|
468
|
+
frames,
|
|
469
|
+
fps: FPS,
|
|
470
|
+
placement,
|
|
471
|
+
camera: options.camera ? { source: options.camera.source, given: true } : { given: false },
|
|
472
|
+
video: { file: "video.mp4", width: WIDTH, height: HEIGHT, codec: "h264 (libx264)", pixFmt: "yuv420p", colorspace: "smpte170m, tv range", crf: options.crf },
|
|
473
|
+
characterModel: state.characterModel,
|
|
474
|
+
characterScale: state.characterScale,
|
|
475
|
+
studio: { url: studioUrl, captureHook: "window.__cozyclay.captureFraming" },
|
|
476
|
+
plate: "../plate.png (same camera, character hidden)",
|
|
477
|
+
mask: "../mask/%06d.png (8-bit gray, 255 = character: the frame re-rendered with the character unlit in one colour, >= 50% pixel coverage)",
|
|
478
|
+
checks: {
|
|
479
|
+
...checks,
|
|
480
|
+
minJointEdgeDistancePx: minMarginPx,
|
|
481
|
+
framingVerticesPerFrame: vertexCount,
|
|
482
|
+
},
|
|
483
|
+
};
|
|
484
|
+
if (sceneRecord) writeFileSync(join(motionDir, "scene.json"), `${JSON.stringify(sceneRecord, null, 2)}\n`);
|
|
485
|
+
if (options.noVideo) {
|
|
486
|
+
const { video, plate, ...rest } = shared;
|
|
487
|
+
writeFileSync(join(motionDir, "camera.json"), `${JSON.stringify(cameraJson, null, "\t")}\n`);
|
|
488
|
+
writeFileSync(join(motionDir, "joints.json"), `${JSON.stringify(jointsJson)}\n`);
|
|
489
|
+
writeFileSync(join(motionDir, "meta.json"), `${JSON.stringify({ ...rest, mask: "mask/%06d.png (8-bit gray, 255 = character: the frame re-rendered with the character unlit in one colour, >= 50% pixel coverage)", variant: null, noVideo: true, contact: contactJson ? "contact.json" : null }, null, "\t")}\n`);
|
|
490
|
+
log(`wrote joints + masks (no video)`);
|
|
491
|
+
}
|
|
492
|
+
for (const variant of options.noVideo ? [] : options.variants) {
|
|
493
|
+
const dir = join(motionDir, variant.name);
|
|
494
|
+
mkdirSync(dir, { recursive: true });
|
|
495
|
+
if (sceneRecord) writeFileSync(join(dir, "scene.json"), `${JSON.stringify(sceneRecord, null, 2)}\n`);
|
|
496
|
+
const filter = variant.kind === "hue" ? `hue=h=${variant.degrees}` : null;
|
|
497
|
+
encode(variant.kind === "hue" ? framesDirs.shaded : framesDirs[variant.name], join(dir, "video.mp4"), { crf: options.crf, filter });
|
|
498
|
+
writeFileSync(join(dir, "camera.json"), `${JSON.stringify(cameraJson, null, "\t")}\n`);
|
|
499
|
+
writeFileSync(join(dir, "joints.json"), `${JSON.stringify(jointsJson)}\n`);
|
|
500
|
+
const variantDetail = variant.kind === "hue"
|
|
501
|
+
? { partColours: "shaded", postFilter: filter, note: `ffmpeg hue filter on the shaded frames: rotates every pixel's chroma by ${variant.degrees} degrees, so all hues shift uniformly and greys are unchanged.` }
|
|
502
|
+
: { partColours: variant.kind === "shaded" ? "shaded" : "off", postFilter: null };
|
|
503
|
+
writeFileSync(join(dir, "meta.json"), `${JSON.stringify({ ...shared, variant: variant.name, variantDetail }, null, "\t")}\n`);
|
|
504
|
+
log(`wrote ${variant.name}`);
|
|
505
|
+
}
|
|
506
|
+
if (!options.keepFrames) for (const dir of Object.values(framesDirs)) rmSync(dir, { recursive: true, force: true });
|
|
507
|
+
else if (framesDirs.shaded && !wanted.has("shaded")) rmSync(framesDirs.shaded, { recursive: true, force: true });
|
|
508
|
+
log(`done in ${((Date.now() - started) / 1000).toFixed(1)} s`);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
main().catch((error) => {
|
|
512
|
+
console.error(error?.stack || String(error));
|
|
513
|
+
process.exitCode = 1;
|
|
514
|
+
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { projectPoint } from "./camera-math.mjs";
|
|
2
|
+
import { elementByPath } from "../../src/studio-elements.js";
|
|
3
|
+
|
|
4
|
+
/** Studio cube is 1 m on each axis, origin at the floor/footprint centre. */
|
|
5
|
+
export function parseSceneBox(value) {
|
|
6
|
+
const b = typeof value === "string" ? JSON.parse(value) : value;
|
|
7
|
+
const out = { x: b?.x, z: b?.z, rot: b?.rot ?? 0, sx: b?.sx ?? b?.scaleX, sy: b?.sy ?? b?.scaleY, sz: b?.sz ?? b?.scaleZ };
|
|
8
|
+
if (!Object.values(out).every(Number.isFinite) || ![out.sx, out.sy, out.sz].every(v => v > 0)) throw new Error("scene-box needs finite x,z,rot and positive sx,sy,sz (scaleX/Y/Z also accepted)");
|
|
9
|
+
const size = elementByPath("object.scale"), position = elementByPath("object.position");
|
|
10
|
+
for (const axis of ["x", "y", "z"]) if (out[`s${axis}`] < size.min[axis] || out[`s${axis}`] > size.max[axis]) throw new Error(`scene-box s${axis} must be within Studio's ${size.min[axis]}..${size.max[axis]} m range`);
|
|
11
|
+
for (const axis of ["x", "z"]) if (out[axis] < position.min[axis] || out[axis] > position.max[axis]) throw new Error(`scene-box ${axis} exceeds Studio position bounds`);
|
|
12
|
+
out.rot = ((out.rot + 180) % 360 + 360) % 360 - 180;
|
|
13
|
+
return out;
|
|
14
|
+
}
|
|
15
|
+
export function boxCorners(box) {
|
|
16
|
+
const b = parseSceneBox(box), a = b.rot * Math.PI / 180, c = Math.cos(a), s = Math.sin(a);
|
|
17
|
+
return Array.from({ length: 8 }, (_, i) => {
|
|
18
|
+
const x = (i & 1 ? 1 : -1) * b.sx / 2, z = (i & 4 ? 1 : -1) * b.sz / 2;
|
|
19
|
+
return [b.x + c * x + s * z, i & 2 ? b.sy : 0, b.z - s * x + c * z];
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
export const BOX_EDGES = Array.from({ length: 8 }, (_, i) => [1, 2, 4].filter(bit => !(i & bit)).map(bit => [i, i | bit])).flat();
|
|
23
|
+
export function sceneBoxRecord(box) {
|
|
24
|
+
const b = parseSceneBox(box);
|
|
25
|
+
return { kind: "cube", placement: b, centre: [b.x, b.sy / 2, b.z], halfExtents: [b.sx / 2, b.sy / 2, b.sz / 2], yawDeg: b.rot,
|
|
26
|
+
...(b.rot === 0 ? { min: [b.x - b.sx / 2, 0, b.z - b.sz / 2], max: [b.x + b.sx / 2, b.sy, b.z + b.sz / 2] } : {}),
|
|
27
|
+
corners: boxCorners(b), convention: "World metres, +Y up; yaw degrees about +Y. Cube base at y=0." };
|
|
28
|
+
}
|
|
29
|
+
export function projectBox(box, camera) {
|
|
30
|
+
return boxCorners(box).map(p => projectPoint(p, { ...camera, worldToCameraCv: camera.worldToCameraCv ?? camera.worldToCamera }));
|
|
31
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scene transform of a cskel27 take for the renderer's --transform (#431),
|
|
3
|
+
* with the Studio's sceneCalibration semantics (src/App.jsx loadMotion):
|
|
4
|
+
*
|
|
5
|
+
* scale, offsetY applied to the take's arrays (applyMotionCalibration),
|
|
6
|
+
* exactly as the Studio's playback calibration does;
|
|
7
|
+
* yawDeg rotation about +Y through the take's frame-0 anchor. The
|
|
8
|
+
* Studio puts it on the Character group; here it is baked
|
|
9
|
+
* into the take (joints rotated by applyMotionCalibration,
|
|
10
|
+
* plus the root's local rotation, which that pass leaves
|
|
11
|
+
* alone), which is the same rigid rotation because playback
|
|
12
|
+
* subtracts the frame-0 root XZ before placing the rig;
|
|
13
|
+
* offsetX/offsetZ scene metres added after the anchor. Playback anchors
|
|
14
|
+
* frame 0 on the subject, so an offset baked into the take
|
|
15
|
+
* would be cancelled; the renderer instead moves the camera
|
|
16
|
+
* by the opposite amount (identical character pixels) and
|
|
17
|
+
* adds the offset to every reported joint.
|
|
18
|
+
*/
|
|
19
|
+
import { applyMotionCalibration, normalizeMotionCalibration } from "../../src/ardy/motion-calibration.js";
|
|
20
|
+
|
|
21
|
+
const KEYS = new Set(["scale", "yawDeg", "offsetX", "offsetY", "offsetZ"]);
|
|
22
|
+
|
|
23
|
+
/** Parse and normalise a --transform JSON object; unknown keys are refused. */
|
|
24
|
+
export function parseTransform(value) {
|
|
25
|
+
const raw = typeof value === "string" ? JSON.parse(value) : value;
|
|
26
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("transform must be a JSON object");
|
|
27
|
+
for (const [key, entry] of Object.entries(raw)) {
|
|
28
|
+
if (!KEYS.has(key)) throw new Error(`transform: unknown key ${key} (allowed: ${[...KEYS].join(", ")})`);
|
|
29
|
+
if (!Number.isFinite(Number(entry))) throw new Error(`transform: ${key} must be a finite number`);
|
|
30
|
+
}
|
|
31
|
+
const normalized = normalizeMotionCalibration(raw);
|
|
32
|
+
for (const key of Object.keys(raw)) {
|
|
33
|
+
const given = Number(raw[key]);
|
|
34
|
+
// normalizeMotionCalibration clamps silently; a scorer must not.
|
|
35
|
+
if (key !== "yawDeg" && Math.abs(normalized[key] - given) > 1e-12) throw new Error(`transform: ${key} ${given} is outside the Studio calibration range`);
|
|
36
|
+
}
|
|
37
|
+
return normalized;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function isIdentityTransform(t) {
|
|
41
|
+
return !t || (t.scale === 1 && t.yawDeg === 0 && t.offsetX === 0 && t.offsetY === 0 && t.offsetZ === 0);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Bake scale, offsetY and yaw of `transform` into a decoded take
|
|
46
|
+
* ({ frames, rotMats, rootPos, posedJoints, ... }, src/ardy/npz.js). Returns
|
|
47
|
+
* the new take and the scene offset the caller still has to apply.
|
|
48
|
+
*/
|
|
49
|
+
export function transformTake(motion, transform) {
|
|
50
|
+
const { motion: moved } = applyMotionCalibration(motion, { ...transform, offsetX: 0, offsetZ: 0 });
|
|
51
|
+
const rotMats = Float32Array.from(motion.rotMats);
|
|
52
|
+
if (transform.yawDeg !== 0) {
|
|
53
|
+
const a = (transform.yawDeg * Math.PI) / 180;
|
|
54
|
+
const c = Math.cos(a);
|
|
55
|
+
const s = Math.sin(a);
|
|
56
|
+
// Ry with applyMotionCalibration's sign: x' = c x + s z, z' = -s x + c z.
|
|
57
|
+
const Ry = [c, 0, s, 0, 1, 0, -s, 0, c];
|
|
58
|
+
const stride = rotMats.length / motion.frames;
|
|
59
|
+
for (let f = 0; f < motion.frames; f += 1) {
|
|
60
|
+
const o = f * stride; // joint 0 (Hips) is the root: local == global
|
|
61
|
+
const m = Array.from(rotMats.subarray(o, o + 9));
|
|
62
|
+
for (let r = 0; r < 3; r += 1) {
|
|
63
|
+
for (let col = 0; col < 3; col += 1) {
|
|
64
|
+
rotMats[o + r * 3 + col] = Ry[r * 3] * m[col] + Ry[r * 3 + 1] * m[3 + col] + Ry[r * 3 + 2] * m[6 + col];
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
motion: { ...moved, rotMats, rootPos: Float32Array.from(moved.rootPos), posedJoints: Float32Array.from(moved.posedJoints) },
|
|
71
|
+
sceneOffset: { x: transform.offsetX, y: 0, z: transform.offsetZ },
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The npz members the Studio decoder reads, for tools/ardy/npz.mjs writeNpz. */
|
|
76
|
+
export function takeToNpzMembers(motion) {
|
|
77
|
+
const joints = motion.posedJoints.length / (motion.frames * 3);
|
|
78
|
+
const members = {
|
|
79
|
+
local_rot_mats: { data: Float32Array.from(motion.rotMats), shape: [motion.frames, joints, 3, 3] },
|
|
80
|
+
root_positions: { data: Float32Array.from(motion.rootPos), shape: [motion.frames, 3] },
|
|
81
|
+
posed_joints: { data: Float32Array.from(motion.posedJoints), shape: [motion.frames, joints, 3] },
|
|
82
|
+
fps: { data: Int32Array.of(motion.fps), shape: [] },
|
|
83
|
+
};
|
|
84
|
+
if (motion.personScale !== undefined && motion.personScale !== 1) members.person_scale = { data: Float32Array.of(motion.personScale), shape: [] };
|
|
85
|
+
if (motion.boneScale) members.bone_scale = { data: Float32Array.from(motion.boneScale), shape: [motion.boneScale.length] };
|
|
86
|
+
return members;
|
|
87
|
+
}
|