@bluemoonfoundry/daz-ts 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +377 -2
- package/dist/animation.d.ts +129 -0
- package/dist/animation.js +276 -0
- package/dist/batch.d.ts +118 -0
- package/dist/batch.js +186 -0
- package/dist/bone.d.ts +50 -0
- package/dist/bone.js +66 -0
- package/dist/camera.d.ts +61 -0
- package/dist/camera.js +120 -0
- package/dist/cinematics.d.ts +188 -0
- package/dist/cinematics.js +165 -0
- package/dist/client.d.ts +399 -0
- package/dist/client.js +769 -0
- package/dist/dforce.d.ts +15 -0
- package/dist/dforce.js +36 -0
- package/dist/element.d.ts +51 -0
- package/dist/element.js +141 -0
- package/dist/exceptions.d.ts +124 -0
- package/dist/exceptions.js +173 -0
- package/dist/geometry.d.ts +81 -0
- package/dist/geometry.js +433 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js +36 -0
- package/dist/light.d.ts +24 -0
- package/dist/light.js +40 -0
- package/dist/lighting.d.ts +120 -0
- package/dist/lighting.js +107 -0
- package/dist/material.d.ts +27 -0
- package/dist/material.js +63 -0
- package/dist/materials.d.ts +107 -0
- package/dist/materials.js +165 -0
- package/dist/math3.d.ts +204 -0
- package/dist/math3.js +502 -0
- package/dist/modifier.d.ts +14 -0
- package/dist/modifier.js +24 -0
- package/dist/morph.d.ts +11 -0
- package/dist/morph.js +24 -0
- package/dist/node.d.ts +196 -0
- package/dist/node.js +447 -0
- package/dist/polling.d.ts +24 -0
- package/dist/polling.js +50 -0
- package/dist/pose.d.ts +82 -0
- package/dist/pose.js +295 -0
- package/dist/poses.d.ts +54 -0
- package/dist/poses.js +40 -0
- package/dist/property.d.ts +64 -0
- package/dist/property.js +125 -0
- package/dist/render.d.ts +242 -0
- package/dist/render.js +811 -0
- package/dist/renderApi.d.ts +124 -0
- package/dist/renderApi.js +235 -0
- package/dist/result.d.ts +15 -0
- package/dist/result.js +1 -0
- package/dist/scene.d.ts +154 -0
- package/dist/scene.js +584 -0
- package/dist/sceneEvents.d.ts +63 -0
- package/dist/sceneEvents.js +102 -0
- package/dist/sceneState.d.ts +167 -0
- package/dist/sceneState.js +430 -0
- package/dist/scriptBuilder.d.ts +41 -0
- package/dist/scriptBuilder.js +72 -0
- package/dist/shotGeometry.d.ts +49 -0
- package/dist/shotGeometry.js +76 -0
- package/dist/skeleton.d.ts +120 -0
- package/dist/skeleton.js +561 -0
- package/dist/timeline.d.ts +24 -0
- package/dist/timeline.js +39 -0
- package/dist/undo.d.ts +24 -0
- package/dist/undo.js +45 -0
- package/dist/version.d.ts +31 -0
- package/dist/version.js +36 -0
- package/dist/viewport.d.ts +58 -0
- package/dist/viewport.js +239 -0
- package/package.json +52 -4
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An in-memory pose checkpoint: figure poses plus camera and light placement.
|
|
3
|
+
* Mirrors dazpy's `_scene_state.py`.
|
|
4
|
+
*/
|
|
5
|
+
import { DazBusyError, NodeNotFoundError } from "./exceptions.js";
|
|
6
|
+
import { DazPose } from "./pose.js";
|
|
7
|
+
import { ScriptBuilder } from "./scriptBuilder.js";
|
|
8
|
+
const TRANSFORM_KEYS = ["XTranslate", "YTranslate", "ZTranslate", "XRotate", "YRotate", "ZRotate", "Scale"];
|
|
9
|
+
const LIGHT_EXTRA_KEYS = ["Flux", "Shadow Softness", "Spread Angle"];
|
|
10
|
+
const DEFAULT_VERIFY_TOLERANCE = 0.05;
|
|
11
|
+
const DEFAULT_MAX_VERIFY_RETRIES = 2;
|
|
12
|
+
const FOLLOW_TARGET_RETRY_MAX_WAIT = 30.0;
|
|
13
|
+
function sleep(seconds) {
|
|
14
|
+
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Run `fn`, retrying with backoff on {@link DazBusyError}.
|
|
18
|
+
*
|
|
19
|
+
* `followTarget()`/`fitTo()`/`unfit()` (unlike `DazPose.applyFull()`, which
|
|
20
|
+
* takes its own retry-on-busy options) don't expose retry-on-busy directly,
|
|
21
|
+
* but `apply()`'s follow-target restoration pass makes several of these
|
|
22
|
+
* calls back-to-back per skeleton on top of the pose-restore/verify calls
|
|
23
|
+
* already made for every skeleton in the scene -- under that load a single
|
|
24
|
+
* skeleton's follow-target fix can transiently hit `StudioBusyError` even
|
|
25
|
+
* though the overall restore succeeds for every other skeleton. This
|
|
26
|
+
* mirrors `DazClient`'s internal busy-retry backoff without depending on it.
|
|
27
|
+
*/
|
|
28
|
+
async function retryOnBusy(fn, maxWait = FOLLOW_TARGET_RETRY_MAX_WAIT) {
|
|
29
|
+
const deadline = Date.now() + maxWait * 1000;
|
|
30
|
+
let backoff = 1.0;
|
|
31
|
+
for (;;) {
|
|
32
|
+
try {
|
|
33
|
+
return await fn();
|
|
34
|
+
}
|
|
35
|
+
catch (e) {
|
|
36
|
+
if (!(e instanceof DazBusyError)) {
|
|
37
|
+
throw e;
|
|
38
|
+
}
|
|
39
|
+
const remainingMs = deadline - Date.now();
|
|
40
|
+
if (remainingMs <= 0) {
|
|
41
|
+
throw e;
|
|
42
|
+
}
|
|
43
|
+
await sleep(Math.min(backoff, remainingMs / 1000));
|
|
44
|
+
backoff = Math.min(backoff + 1.0, 5.0);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const ZERO3 = [0, 0, 0];
|
|
49
|
+
/**
|
|
50
|
+
* Return a description of every channel where `actual` does not match
|
|
51
|
+
* `expected` within `tolerance`, or an empty list if they match.
|
|
52
|
+
*
|
|
53
|
+
* Missing keys in either pose are treated as zero, matching {@link DazPose}'s
|
|
54
|
+
* sparse (zero-omitted) storage.
|
|
55
|
+
*/
|
|
56
|
+
function poseMismatches(expected, actual, tolerance) {
|
|
57
|
+
const mismatches = [];
|
|
58
|
+
for (const key of new Set([...Object.keys(expected.bones), ...Object.keys(actual.bones)])) {
|
|
59
|
+
const exp = expected.bones[key] ?? ZERO3;
|
|
60
|
+
const act = actual.bones[key] ?? ZERO3;
|
|
61
|
+
if (exp.some((e, i) => Math.abs(e - act[i]) > tolerance)) {
|
|
62
|
+
mismatches.push(`bone ${key} (expected ${JSON.stringify(exp)}, got ${JSON.stringify(act)})`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
for (const key of new Set([...Object.keys(expected.morphs), ...Object.keys(actual.morphs)])) {
|
|
66
|
+
const expV = expected.morphs[key] ?? 0.0;
|
|
67
|
+
const actV = actual.morphs[key] ?? 0.0;
|
|
68
|
+
if (Math.abs(expV - actV) > tolerance) {
|
|
69
|
+
mismatches.push(`morph ${key} (expected ${expV}, got ${actV})`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
for (const key of new Set([...Object.keys(expected.props), ...Object.keys(actual.props)])) {
|
|
73
|
+
const expV = expected.props[key] ?? 0.0;
|
|
74
|
+
const actV = actual.props[key] ?? 0.0;
|
|
75
|
+
if (Math.abs(expV - actV) > tolerance) {
|
|
76
|
+
mismatches.push(`prop ${key} (expected ${expV}, got ${actV})`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return mismatches;
|
|
80
|
+
}
|
|
81
|
+
// Shared JS snippet: read a property's own dial value rather than getValue()'s
|
|
82
|
+
// post-ERC computed total, for the same reason DazPose/DazProperty.rawValue
|
|
83
|
+
// do -- see DazPose.capture()'s comments for the full explanation.
|
|
84
|
+
const RAW_READ_JS = 'function _raw(p) { return (typeof p.getRawValue === "function") ? p.getRawValue() : p.getValue(); }';
|
|
85
|
+
const RAW_WRITE_JS = 'function _rawSet(p, v) { ' +
|
|
86
|
+
'if (typeof p.setRawValue === "function") { p.setRawValue(v); } else { p.setValue(v); } }';
|
|
87
|
+
/**
|
|
88
|
+
* An in-memory pose checkpoint: figure poses plus camera and light placement.
|
|
89
|
+
*
|
|
90
|
+
* This is not a full scene snapshot. For anything it does not cover, take a
|
|
91
|
+
* full-scene backup with {@link DazScene.saveCopy}, or pass `backupPath` to
|
|
92
|
+
* {@link DazSceneState.capture} to do both at once.
|
|
93
|
+
*
|
|
94
|
+
* Captured, for nodes that exist at capture time:
|
|
95
|
+
*
|
|
96
|
+
* - every skeleton (figure): bone rotations, morph values and the figure
|
|
97
|
+
* node's own numeric properties (see {@link DazPose});
|
|
98
|
+
* - every skeleton's fit-to (follow) target;
|
|
99
|
+
* - every camera: X/Y/Z translate, X/Y/Z rotate and Scale;
|
|
100
|
+
* - every light: the same transform channels, plus Flux, Shadow Softness and
|
|
101
|
+
* Spread Angle.
|
|
102
|
+
*
|
|
103
|
+
* Not captured:
|
|
104
|
+
*
|
|
105
|
+
* - materials and surface properties;
|
|
106
|
+
* - HDRI / environment and render settings;
|
|
107
|
+
* - nodes added or deleted after capture (restore never creates or deletes
|
|
108
|
+
* nodes; missing ones are reported as skipped);
|
|
109
|
+
* - props and any other node that is not a skeleton, camera or light;
|
|
110
|
+
* - bone translations, keyframes / animation, and any other camera or light
|
|
111
|
+
* property (focal length, color, etc.).
|
|
112
|
+
*
|
|
113
|
+
* Everything is captured and restored via each property's raw (pre-ERC) value, so
|
|
114
|
+
* repeated capture/apply cycles are idempotent even for properties driven
|
|
115
|
+
* by `DzERCLink` controllers (e.g. a "Scale" dial fed by dozens of linked
|
|
116
|
+
* morphs) -- see {@link DazPose} for why this matters.
|
|
117
|
+
*
|
|
118
|
+
* Skeletons, cameras, and lights are all keyed by their internal name (not
|
|
119
|
+
* display label), since labels are user-editable and not guaranteed unique.
|
|
120
|
+
*
|
|
121
|
+
* Typical workflow:
|
|
122
|
+
* ```ts
|
|
123
|
+
* const scene = new DazScene();
|
|
124
|
+
* const checkpoint = await DazSceneState.capture(scene);
|
|
125
|
+
* // ...experimental changes
|
|
126
|
+
* await checkpoint.apply(scene);
|
|
127
|
+
* ```
|
|
128
|
+
*/
|
|
129
|
+
export class DazSceneState {
|
|
130
|
+
skeletonPoses;
|
|
131
|
+
cameraTransforms;
|
|
132
|
+
lightTransforms;
|
|
133
|
+
lightExtra;
|
|
134
|
+
/**
|
|
135
|
+
* Each skeleton's conform/fit-to relationship (by target skeleton name,
|
|
136
|
+
* or `null` if unfitted), captured and restored independently of
|
|
137
|
+
* `DazPose`'s generic bones/morphs/props. `DazPose.applyFull()` writes
|
|
138
|
+
* back every property on a skeleton, including the internal "FID_<name>"
|
|
139
|
+
* property DAZ Studio uses to persist a conforming item's fit
|
|
140
|
+
* registration -- rewriting that property (even to the exact value
|
|
141
|
+
* captured) desyncs the live `getFollowTarget()` pointer without raising
|
|
142
|
+
* any error. See daz-script-server-jz0e: a dedicated capture/restore pass
|
|
143
|
+
* via the real `getFollowTarget()`/`setFollowTarget()` API is the only
|
|
144
|
+
* reliable fix.
|
|
145
|
+
*/
|
|
146
|
+
followTargets;
|
|
147
|
+
/**
|
|
148
|
+
* Result of the {@link DazScene.saveCopy} call made by
|
|
149
|
+
* `capture(scene, { backupPath })`, or `null` if no full-scene backup was taken.
|
|
150
|
+
*/
|
|
151
|
+
backup;
|
|
152
|
+
constructor(skeletonPoses, cameraTransforms, lightTransforms, lightExtra, followTargets = {}, backup = null) {
|
|
153
|
+
this.skeletonPoses = skeletonPoses;
|
|
154
|
+
this.cameraTransforms = cameraTransforms;
|
|
155
|
+
this.lightTransforms = lightTransforms;
|
|
156
|
+
this.lightExtra = lightExtra;
|
|
157
|
+
this.followTargets = followTargets;
|
|
158
|
+
this.backup = backup;
|
|
159
|
+
}
|
|
160
|
+
// ── construction ──────────────────────────────────────────────────────
|
|
161
|
+
/** Capture the current state of every skeleton, camera, and light in `scene`. */
|
|
162
|
+
static async capture(scene, opts = {}) {
|
|
163
|
+
const backup = opts.backupPath !== undefined ? await scene.saveCopy(opts.backupPath) : null;
|
|
164
|
+
const client = scene.getClient();
|
|
165
|
+
const skeletonPoses = {};
|
|
166
|
+
const followTargets = {};
|
|
167
|
+
for (const skel of await scene.skeletons()) {
|
|
168
|
+
const name = skel.identifier.value;
|
|
169
|
+
skeletonPoses[name] = await DazPose.capture(skel);
|
|
170
|
+
const target = await skel.followTarget();
|
|
171
|
+
followTargets[name] = target !== null ? target.identifier.value : null;
|
|
172
|
+
}
|
|
173
|
+
const camScript = ScriptBuilder.iife(`
|
|
174
|
+
var _keys = ${JSON.stringify(TRANSFORM_KEYS)};
|
|
175
|
+
${RAW_READ_JS}
|
|
176
|
+
function _captureTransforms(node) {
|
|
177
|
+
var t = {};
|
|
178
|
+
for (var i = 0; i < _keys.length; i++) {
|
|
179
|
+
var p = node.findProperty(_keys[i]);
|
|
180
|
+
if (p) t[_keys[i]] = _raw(p);
|
|
181
|
+
}
|
|
182
|
+
return t;
|
|
183
|
+
}
|
|
184
|
+
var result = {};
|
|
185
|
+
for (var i = 0; i < Scene.getNumCameras(); i++) {
|
|
186
|
+
var c = Scene.getCamera(i);
|
|
187
|
+
result[c.getName()] = _captureTransforms(c);
|
|
188
|
+
}
|
|
189
|
+
return result;
|
|
190
|
+
`);
|
|
191
|
+
const cameraTransforms = (await client.execute(camScript)).value ?? {};
|
|
192
|
+
const lightScript = ScriptBuilder.iife(`
|
|
193
|
+
var _keys = ${JSON.stringify(TRANSFORM_KEYS)};
|
|
194
|
+
var _extraKeys = ${JSON.stringify(LIGHT_EXTRA_KEYS)};
|
|
195
|
+
${RAW_READ_JS}
|
|
196
|
+
function _captureTransforms(node) {
|
|
197
|
+
var t = {};
|
|
198
|
+
for (var i = 0; i < _keys.length; i++) {
|
|
199
|
+
var p = node.findProperty(_keys[i]);
|
|
200
|
+
if (p) t[_keys[i]] = _raw(p);
|
|
201
|
+
}
|
|
202
|
+
return t;
|
|
203
|
+
}
|
|
204
|
+
var transforms = {};
|
|
205
|
+
var extra = {};
|
|
206
|
+
for (var i = 0; i < Scene.getNumLights(); i++) {
|
|
207
|
+
var l = Scene.getLight(i);
|
|
208
|
+
var name = l.getName();
|
|
209
|
+
transforms[name] = _captureTransforms(l);
|
|
210
|
+
var e = {};
|
|
211
|
+
for (var k = 0; k < _extraKeys.length; k++) {
|
|
212
|
+
var p = l.findProperty(_extraKeys[k]);
|
|
213
|
+
if (p) e[_extraKeys[k]] = _raw(p);
|
|
214
|
+
}
|
|
215
|
+
extra[name] = e;
|
|
216
|
+
}
|
|
217
|
+
return {transforms: transforms, extra: extra};
|
|
218
|
+
`);
|
|
219
|
+
const lightResult = (await client.execute(lightScript)).value ?? {};
|
|
220
|
+
return new DazSceneState(skeletonPoses, cameraTransforms, lightResult.transforms ?? {}, lightResult.extra ?? {}, followTargets, backup);
|
|
221
|
+
}
|
|
222
|
+
// ── serialisation ─────────────────────────────────────────────────────
|
|
223
|
+
/** Return this snapshot as a plain, JSON-serialisable dict. */
|
|
224
|
+
toDict() {
|
|
225
|
+
return {
|
|
226
|
+
skeletons: Object.fromEntries(Object.entries(this.skeletonPoses).map(([name, pose]) => [name, pose.toDict()])),
|
|
227
|
+
cameras: this.cameraTransforms,
|
|
228
|
+
lights: { transforms: this.lightTransforms, extra: this.lightExtra },
|
|
229
|
+
follow_targets: this.followTargets,
|
|
230
|
+
backup: this.backup,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
/** Reconstruct a snapshot from {@link toDict}'s output. */
|
|
234
|
+
static fromDict(data) {
|
|
235
|
+
const skeletons = {};
|
|
236
|
+
for (const [name, p] of Object.entries(data.skeletons ?? {})) {
|
|
237
|
+
skeletons[name] = new DazPose(name, p.bones ?? {}, p.morphs ?? {}, p.props ?? {});
|
|
238
|
+
}
|
|
239
|
+
const lights = data.lights ?? { transforms: {}, extra: {} };
|
|
240
|
+
return new DazSceneState(skeletons, data.cameras ?? {}, lights.transforms ?? {}, lights.extra ?? {}, data.follow_targets ?? {}, data.backup ?? null);
|
|
241
|
+
}
|
|
242
|
+
// ── apply ─────────────────────────────────────────────────────────────
|
|
243
|
+
/**
|
|
244
|
+
* Apply this snapshot's skeleton poses, camera transforms, and light
|
|
245
|
+
* properties back onto `scene` in a small, fixed number of HTTP calls.
|
|
246
|
+
*
|
|
247
|
+
* Restore is best effort. A skeleton, camera or light that no longer
|
|
248
|
+
* exists in the scene (deleted or renamed since capture) is skipped and
|
|
249
|
+
* listed in `skipped`, and the rest of the checkpoint is still applied.
|
|
250
|
+
* Nothing is recreated: this restores values, not the scene graph. To get
|
|
251
|
+
* deleted nodes back, reload the full-scene backup taken by
|
|
252
|
+
* `capture(scene, { backupPath })`.
|
|
253
|
+
*
|
|
254
|
+
* Each skeleton restore is independently verified: after
|
|
255
|
+
* `pose.applyFull(skel)` returns, a fresh {@link DazPose.capture} is taken
|
|
256
|
+
* and compared against the checkpoint. This guards against `applyFull()`
|
|
257
|
+
* reporting success for a restore DAZ Studio's single-threaded main loop
|
|
258
|
+
* only partially executed under contention (see dpi-mxq) -- the HTTP call
|
|
259
|
+
* can return normally even though some bone/morph/prop writes never
|
|
260
|
+
* happened. A skeleton whose read-back doesn't match is retried
|
|
261
|
+
* (re-running `applyFull` and re-verifying) up to `maxVerifyRetries`
|
|
262
|
+
* times before being reported in `errors` instead of `restored`, so
|
|
263
|
+
* callers never trust an unverified result.
|
|
264
|
+
*
|
|
265
|
+
* Each skipped node also has a line in `errors`, so a caller that treats
|
|
266
|
+
* any `errors` entry as a failed restore stays safe.
|
|
267
|
+
*/
|
|
268
|
+
async apply(scene, opts = {}) {
|
|
269
|
+
const { maxVerifyRetries = DEFAULT_MAX_VERIFY_RETRIES, verifyTolerance = DEFAULT_VERIFY_TOLERANCE } = opts;
|
|
270
|
+
const client = scene.getClient();
|
|
271
|
+
const restored = [];
|
|
272
|
+
const skipped = [];
|
|
273
|
+
const errors = [];
|
|
274
|
+
const resolvedSkeletons = {};
|
|
275
|
+
const skip = (kind, name, message) => {
|
|
276
|
+
skipped.push({ kind, name, reason: "not_found" });
|
|
277
|
+
errors.push(message);
|
|
278
|
+
};
|
|
279
|
+
for (const [name, pose] of Object.entries(this.skeletonPoses)) {
|
|
280
|
+
let skel;
|
|
281
|
+
try {
|
|
282
|
+
skel = await scene.findSkeleton(name);
|
|
283
|
+
resolvedSkeletons[name] = skel;
|
|
284
|
+
}
|
|
285
|
+
catch (exc) {
|
|
286
|
+
if (exc instanceof NodeNotFoundError) {
|
|
287
|
+
skip("skeleton", name, `Skeleton not found: ${name}`);
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
errors.push(`Failed to look up skeleton ${name}: ${exc instanceof Error ? exc.message : String(exc)}`);
|
|
291
|
+
}
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
let attempt = 0;
|
|
295
|
+
let failed = false;
|
|
296
|
+
let mismatches = [];
|
|
297
|
+
for (;;) {
|
|
298
|
+
try {
|
|
299
|
+
await pose.applyFull(skel);
|
|
300
|
+
}
|
|
301
|
+
catch (exc) {
|
|
302
|
+
errors.push(`Failed to restore skeleton ${name}: ${exc instanceof Error ? exc.message : String(exc)}`);
|
|
303
|
+
failed = true;
|
|
304
|
+
break;
|
|
305
|
+
}
|
|
306
|
+
let actual;
|
|
307
|
+
try {
|
|
308
|
+
actual = await DazPose.capture(skel);
|
|
309
|
+
}
|
|
310
|
+
catch (exc) {
|
|
311
|
+
errors.push(`Failed to verify restore of skeleton ${name}: ${exc instanceof Error ? exc.message : String(exc)}`);
|
|
312
|
+
failed = true;
|
|
313
|
+
break;
|
|
314
|
+
}
|
|
315
|
+
mismatches = poseMismatches(pose, actual, verifyTolerance);
|
|
316
|
+
if (mismatches.length === 0 || attempt >= maxVerifyRetries) {
|
|
317
|
+
break;
|
|
318
|
+
}
|
|
319
|
+
attempt += 1;
|
|
320
|
+
}
|
|
321
|
+
if (failed) {
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
if (mismatches.length > 0) {
|
|
325
|
+
errors.push(`Restore of skeleton ${name} did not verify after ${attempt + 1} attempt(s): ${mismatches.join("; ")}`);
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
restored.push(name);
|
|
329
|
+
}
|
|
330
|
+
// Restore each successfully-restored skeleton's conform/fit-to
|
|
331
|
+
// relationship explicitly via the real getFollowTarget()/
|
|
332
|
+
// setFollowTarget() API -- applyFull() above already wrote back this
|
|
333
|
+
// skeleton's own "FID_*" property as part of its generic props
|
|
334
|
+
// restore, but doing so does not reliably re-resolve the live
|
|
335
|
+
// follow-target pointer (see daz-script-server-jz0e). Only touches
|
|
336
|
+
// skeletons whose current follow-target doesn't already match what was
|
|
337
|
+
// captured, to avoid redundant calls.
|
|
338
|
+
for (const name of restored) {
|
|
339
|
+
const skel = resolvedSkeletons[name];
|
|
340
|
+
const targetName = this.followTargets[name] ?? null;
|
|
341
|
+
try {
|
|
342
|
+
const current = await retryOnBusy(() => skel.followTarget());
|
|
343
|
+
const currentName = current !== null ? current.identifier.value : null;
|
|
344
|
+
if (currentName === targetName) {
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
if (targetName === null) {
|
|
348
|
+
await retryOnBusy(() => skel.unfit());
|
|
349
|
+
}
|
|
350
|
+
else {
|
|
351
|
+
let targetSkel = resolvedSkeletons[targetName];
|
|
352
|
+
if (targetSkel === undefined) {
|
|
353
|
+
try {
|
|
354
|
+
targetSkel = await scene.findSkeleton(targetName);
|
|
355
|
+
}
|
|
356
|
+
catch (exc) {
|
|
357
|
+
if (!(exc instanceof NodeNotFoundError)) {
|
|
358
|
+
throw exc;
|
|
359
|
+
}
|
|
360
|
+
skip("follow_target", name, `Follow-target ${targetName} of skeleton ${name} not found; fit not restored`);
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
const target = targetSkel;
|
|
365
|
+
await retryOnBusy(() => skel.fitTo(target));
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
catch (exc) {
|
|
369
|
+
errors.push(`Failed to restore follow-target for skeleton ${name}: ${exc instanceof Error ? exc.message : String(exc)}`);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
const restoreScript = ScriptBuilder.iife(`
|
|
373
|
+
var _camTransforms = ${JSON.stringify(this.cameraTransforms)};
|
|
374
|
+
var _lightTransforms = ${JSON.stringify(this.lightTransforms)};
|
|
375
|
+
var _lightExtra = ${JSON.stringify(this.lightExtra)};
|
|
376
|
+
${RAW_WRITE_JS}
|
|
377
|
+
function _applyTransforms(node, transforms) {
|
|
378
|
+
for (var key in transforms) {
|
|
379
|
+
var p = node.findProperty(key);
|
|
380
|
+
if (p) _rawSet(p, transforms[key]);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
var restored = [];
|
|
384
|
+
var skipped = [];
|
|
385
|
+
var errors = [];
|
|
386
|
+
|
|
387
|
+
for (var name in _camTransforms) {
|
|
388
|
+
var c = Scene.findNode(name);
|
|
389
|
+
if (!c) {
|
|
390
|
+
skipped.push({kind: "camera", name: name, reason: "not_found"});
|
|
391
|
+
errors.push("Camera not found: " + name);
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
_applyTransforms(c, _camTransforms[name]);
|
|
395
|
+
restored.push(name);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
for (var lname in _lightTransforms) {
|
|
399
|
+
var l = Scene.findNode(lname);
|
|
400
|
+
if (!l) {
|
|
401
|
+
skipped.push({kind: "light", name: lname, reason: "not_found"});
|
|
402
|
+
errors.push("Light not found: " + lname);
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
405
|
+
_applyTransforms(l, _lightTransforms[lname]);
|
|
406
|
+
var extra = _lightExtra[lname] || {};
|
|
407
|
+
for (var ek in extra) {
|
|
408
|
+
var ep = l.findProperty(ek);
|
|
409
|
+
if (ep) _rawSet(ep, extra[ek]);
|
|
410
|
+
}
|
|
411
|
+
restored.push(lname);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
return {restored: restored, skipped: skipped, errors: errors};
|
|
415
|
+
`);
|
|
416
|
+
const nodeResult = (await client.execute(restoreScript, undefined, {
|
|
417
|
+
retryOnBusy: true,
|
|
418
|
+
maxWait: FOLLOW_TARGET_RETRY_MAX_WAIT,
|
|
419
|
+
})).value ?? { restored: [], errors: [] };
|
|
420
|
+
restored.push(...(nodeResult.restored ?? []));
|
|
421
|
+
skipped.push(...(nodeResult.skipped ?? []));
|
|
422
|
+
errors.push(...(nodeResult.errors ?? []));
|
|
423
|
+
return { restored, skipped, errors, complete: errors.length === 0, backup: this.backup };
|
|
424
|
+
}
|
|
425
|
+
// ── dunder ────────────────────────────────────────────────────────────
|
|
426
|
+
toString() {
|
|
427
|
+
return (`DazSceneState(skeletons=${Object.keys(this.skeletonPoses).length}, ` +
|
|
428
|
+
`cameras=${Object.keys(this.cameraTransforms).length}, lights=${Object.keys(this.lightTransforms).length})`);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { NodeIdentifier } from "./node.js";
|
|
2
|
+
/**
|
|
3
|
+
* Helpers for building injection-safe DazScript source strings.
|
|
4
|
+
*
|
|
5
|
+
* Every value interpolated into a generated script MUST go through
|
|
6
|
+
* {@link ScriptBuilder.escapeString} or {@link ScriptBuilder.serializeArg} —
|
|
7
|
+
* never concatenated raw. This is the port's core injection-safety
|
|
8
|
+
* invariant (mirrors dazpy's `json.dumps()`-based escaping).
|
|
9
|
+
*/
|
|
10
|
+
export declare class ScriptBuilder {
|
|
11
|
+
/** Return `value` as a JSON string literal, safe to embed in DazScript source. */
|
|
12
|
+
static escapeString(value: string): string;
|
|
13
|
+
/** Wrap `body` in an immediately-invoked function expression. */
|
|
14
|
+
static iife(body: string): string;
|
|
15
|
+
/**
|
|
16
|
+
* Serialize an arbitrary argument value for embedding in generated
|
|
17
|
+
* DazScript source. Booleans and numbers become bare literals; strings
|
|
18
|
+
* and everything else are JSON-encoded.
|
|
19
|
+
*/
|
|
20
|
+
static serializeArg(value: unknown): string;
|
|
21
|
+
/** DazScript expression that resolves `identifier` via `Scene.findNode`/`.findNodeByLabel`. */
|
|
22
|
+
static findNodeExpr(identifier: NodeIdentifier): string;
|
|
23
|
+
/** Wrap `body` in an IIFE that resolves `identifier` to `_node` and null-guards it. */
|
|
24
|
+
static nodeBody(identifier: NodeIdentifier, body: string): string;
|
|
25
|
+
/** Like {@link nodeBody} but uses a pre-built DazScript locator expression for `_node`. */
|
|
26
|
+
static nodeBodyFromLocator(locator: string, body: string): string;
|
|
27
|
+
/**
|
|
28
|
+
* Return a JS snippet (not wrapped in an IIFE) that finds a skeleton by
|
|
29
|
+
* `identifier` and binds it to `varName`. Embed at the top of a larger
|
|
30
|
+
* body and follow with `if (!<varName>) return null;`.
|
|
31
|
+
*/
|
|
32
|
+
private static skeletonLookupAs;
|
|
33
|
+
/**
|
|
34
|
+
* Return a JS snippet (not wrapped in an IIFE) that finds a skeleton by
|
|
35
|
+
* `identifier` and binds it to `_skel`. Embed at the top of a larger body
|
|
36
|
+
* and follow with `if (!_skel) return null;`.
|
|
37
|
+
*/
|
|
38
|
+
static skeletonLookup(identifier: NodeIdentifier): string;
|
|
39
|
+
/** Like {@link skeletonLookup} but binds the result to `_node` instead of `_skel`, for callers using the shared `_node`-based body convention. */
|
|
40
|
+
static skeletonLookupAsNode(identifier: NodeIdentifier): string;
|
|
41
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for building injection-safe DazScript source strings.
|
|
3
|
+
*
|
|
4
|
+
* Every value interpolated into a generated script MUST go through
|
|
5
|
+
* {@link ScriptBuilder.escapeString} or {@link ScriptBuilder.serializeArg} —
|
|
6
|
+
* never concatenated raw. This is the port's core injection-safety
|
|
7
|
+
* invariant (mirrors dazpy's `json.dumps()`-based escaping).
|
|
8
|
+
*/
|
|
9
|
+
export class ScriptBuilder {
|
|
10
|
+
/** Return `value` as a JSON string literal, safe to embed in DazScript source. */
|
|
11
|
+
static escapeString(value) {
|
|
12
|
+
return JSON.stringify(value);
|
|
13
|
+
}
|
|
14
|
+
/** Wrap `body` in an immediately-invoked function expression. */
|
|
15
|
+
static iife(body) {
|
|
16
|
+
return `(function(){\n${body}\n})()`;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Serialize an arbitrary argument value for embedding in generated
|
|
20
|
+
* DazScript source. Booleans and numbers become bare literals; strings
|
|
21
|
+
* and everything else are JSON-encoded.
|
|
22
|
+
*/
|
|
23
|
+
static serializeArg(value) {
|
|
24
|
+
if (typeof value === "boolean") {
|
|
25
|
+
return value ? "true" : "false";
|
|
26
|
+
}
|
|
27
|
+
if (typeof value === "number") {
|
|
28
|
+
return String(value);
|
|
29
|
+
}
|
|
30
|
+
return JSON.stringify(value);
|
|
31
|
+
}
|
|
32
|
+
/** DazScript expression that resolves `identifier` via `Scene.findNode`/`.findNodeByLabel`. */
|
|
33
|
+
static findNodeExpr(identifier) {
|
|
34
|
+
if (identifier.kind === "label") {
|
|
35
|
+
return `Scene.findNodeByLabel(${ScriptBuilder.escapeString(identifier.value)})`;
|
|
36
|
+
}
|
|
37
|
+
return `Scene.findNode(${ScriptBuilder.escapeString(identifier.value)})`;
|
|
38
|
+
}
|
|
39
|
+
/** Wrap `body` in an IIFE that resolves `identifier` to `_node` and null-guards it. */
|
|
40
|
+
static nodeBody(identifier, body) {
|
|
41
|
+
const expr = ScriptBuilder.findNodeExpr(identifier);
|
|
42
|
+
return ScriptBuilder.iife(`var _node = ${expr};\nif (!_node) return null;\n${body}`);
|
|
43
|
+
}
|
|
44
|
+
/** Like {@link nodeBody} but uses a pre-built DazScript locator expression for `_node`. */
|
|
45
|
+
static nodeBodyFromLocator(locator, body) {
|
|
46
|
+
return ScriptBuilder.iife(`var _node = ${locator};\nif (!_node) return null;\n${body}`);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Return a JS snippet (not wrapped in an IIFE) that finds a skeleton by
|
|
50
|
+
* `identifier` and binds it to `varName`. Embed at the top of a larger
|
|
51
|
+
* body and follow with `if (!<varName>) return null;`.
|
|
52
|
+
*/
|
|
53
|
+
static skeletonLookupAs(identifier, varName) {
|
|
54
|
+
const value = ScriptBuilder.escapeString(identifier.value);
|
|
55
|
+
const match = identifier.kind === "label" ? `_skels[_i].getLabel() === ${value}` : `_skels[_i].getName() === ${value}`;
|
|
56
|
+
return (`var ${varName}=null,_skels=Scene.getSkeletonList();` +
|
|
57
|
+
`for(var _i=0;_i<_skels.length;_i++){` +
|
|
58
|
+
`if(${match}){${varName}=_skels[_i];break;}}`);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Return a JS snippet (not wrapped in an IIFE) that finds a skeleton by
|
|
62
|
+
* `identifier` and binds it to `_skel`. Embed at the top of a larger body
|
|
63
|
+
* and follow with `if (!_skel) return null;`.
|
|
64
|
+
*/
|
|
65
|
+
static skeletonLookup(identifier) {
|
|
66
|
+
return ScriptBuilder.skeletonLookupAs(identifier, "_skel");
|
|
67
|
+
}
|
|
68
|
+
/** Like {@link skeletonLookup} but binds the result to `_node` instead of `_skel`, for callers using the shared `_node`-based body convention. */
|
|
69
|
+
static skeletonLookupAsNode(identifier) {
|
|
70
|
+
return ScriptBuilder.skeletonLookupAs(identifier, "_node");
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure camera/lighting placement math shared by `cinematics.ts` and
|
|
3
|
+
* `lighting.ts`. Mirrors dazpy's `_shot_geometry.py` exactly. No
|
|
4
|
+
* DazScript/HTTP involved.
|
|
5
|
+
*/
|
|
6
|
+
import type { DazNode } from "./node.js";
|
|
7
|
+
import { Vec3 } from "./math3.js";
|
|
8
|
+
/**
|
|
9
|
+
* Return a point `distance` away from `target`, at the given angles.
|
|
10
|
+
*
|
|
11
|
+
* `azimuthDeg=0, elevationDeg=0` sits on the target's `+Z` side. Increasing
|
|
12
|
+
* `azimuthDeg` sweeps from `+Z` toward `+X`. `elevationDeg` tilts the offset
|
|
13
|
+
* up toward `+Y`; at `elevationDeg=90` the result is directly above the
|
|
14
|
+
* target regardless of azimuth.
|
|
15
|
+
*/
|
|
16
|
+
export declare function sphericalOffset(target: Vec3, azimuthDeg: number, elevationDeg: number, distance: number): Vec3;
|
|
17
|
+
/**
|
|
18
|
+
* Return `(x, y, z)` world-space Euler degrees aiming `fromPos` at `toPos`.
|
|
19
|
+
*
|
|
20
|
+
* Suitable for passing directly to `DazNode.setRotation`. A node positioned
|
|
21
|
+
* via {@link sphericalOffset} with `azimuthDeg=0, elevationDeg=0` and aimed
|
|
22
|
+
* with this function at the same target gets rotation `(0, 0, 0)` -- i.e.
|
|
23
|
+
* the unrotated rest pose is defined as facing `-Z`. Roll (`z`) is always
|
|
24
|
+
* `0.0`.
|
|
25
|
+
*
|
|
26
|
+
* The yaw sign was confirmed empirically against a live DAZ Studio session
|
|
27
|
+
* (see beads issue daz-script-server-bu86): a distant light rotated to
|
|
28
|
+
* `y=+90` reports `DazLight.direction()` of `(-1, 0, ~0)`, matching this
|
|
29
|
+
* function's convention.
|
|
30
|
+
*/
|
|
31
|
+
export declare function lookAtEuler(fromPos: Vec3, toPos: Vec3): [number, number, number];
|
|
32
|
+
/**
|
|
33
|
+
* Resolve `target` to a {@link Vec3}, raised by `verticalOffsetCm`.
|
|
34
|
+
*
|
|
35
|
+
* If `target` is already a {@link Vec3}, it is used as-is (before the
|
|
36
|
+
* offset). If it's a `DazNode`, its `position()` is read and converted via
|
|
37
|
+
* `Vec3.fromDict`.
|
|
38
|
+
*
|
|
39
|
+
* `verticalOffsetCm` is added to the resolved Y (DAZ Studio's up axis)
|
|
40
|
+
* component. This exists primarily to compensate for the fact that a
|
|
41
|
+
* figure's `DazNode.position` is generally its root/hip joint, not its
|
|
42
|
+
* center of mass or head -- framing code that wants to aim higher (e.g.
|
|
43
|
+
* chest/head height for a tight shot) passes a positive offset here rather
|
|
44
|
+
* than aiming straight at the hip.
|
|
45
|
+
*
|
|
46
|
+
* @throws Error If `target` is a node and its position is unavailable (e.g.
|
|
47
|
+
* the node no longer exists in the scene).
|
|
48
|
+
*/
|
|
49
|
+
export declare function resolveTarget(target: Vec3 | DazNode, verticalOffsetCm?: number): Promise<Vec3>;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure camera/lighting placement math shared by `cinematics.ts` and
|
|
3
|
+
* `lighting.ts`. Mirrors dazpy's `_shot_geometry.py` exactly. No
|
|
4
|
+
* DazScript/HTTP involved.
|
|
5
|
+
*/
|
|
6
|
+
import { Vec3 } from "./math3.js";
|
|
7
|
+
/**
|
|
8
|
+
* Return a point `distance` away from `target`, at the given angles.
|
|
9
|
+
*
|
|
10
|
+
* `azimuthDeg=0, elevationDeg=0` sits on the target's `+Z` side. Increasing
|
|
11
|
+
* `azimuthDeg` sweeps from `+Z` toward `+X`. `elevationDeg` tilts the offset
|
|
12
|
+
* up toward `+Y`; at `elevationDeg=90` the result is directly above the
|
|
13
|
+
* target regardless of azimuth.
|
|
14
|
+
*/
|
|
15
|
+
export function sphericalOffset(target, azimuthDeg, elevationDeg, distance) {
|
|
16
|
+
const az = (azimuthDeg * Math.PI) / 180;
|
|
17
|
+
const el = (elevationDeg * Math.PI) / 180;
|
|
18
|
+
const horizontal = Math.cos(el);
|
|
19
|
+
const direction = new Vec3(horizontal * Math.sin(az), Math.sin(el), horizontal * Math.cos(az));
|
|
20
|
+
return target.add(direction.mul(distance));
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Return `(x, y, z)` world-space Euler degrees aiming `fromPos` at `toPos`.
|
|
24
|
+
*
|
|
25
|
+
* Suitable for passing directly to `DazNode.setRotation`. A node positioned
|
|
26
|
+
* via {@link sphericalOffset} with `azimuthDeg=0, elevationDeg=0` and aimed
|
|
27
|
+
* with this function at the same target gets rotation `(0, 0, 0)` -- i.e.
|
|
28
|
+
* the unrotated rest pose is defined as facing `-Z`. Roll (`z`) is always
|
|
29
|
+
* `0.0`.
|
|
30
|
+
*
|
|
31
|
+
* The yaw sign was confirmed empirically against a live DAZ Studio session
|
|
32
|
+
* (see beads issue daz-script-server-bu86): a distant light rotated to
|
|
33
|
+
* `y=+90` reports `DazLight.direction()` of `(-1, 0, ~0)`, matching this
|
|
34
|
+
* function's convention.
|
|
35
|
+
*/
|
|
36
|
+
export function lookAtEuler(fromPos, toPos) {
|
|
37
|
+
const direction = toPos.sub(fromPos).normalize();
|
|
38
|
+
const horizontalDist = Math.sqrt(direction.x * direction.x + direction.z * direction.z);
|
|
39
|
+
const pitch = (Math.atan2(direction.y, horizontalDist) * 180) / Math.PI;
|
|
40
|
+
const yaw = horizontalDist < 1e-9 ? 0.0 : (Math.atan2(-direction.x, -direction.z) * 180) / Math.PI;
|
|
41
|
+
return [pitch, yaw, 0.0];
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Resolve `target` to a {@link Vec3}, raised by `verticalOffsetCm`.
|
|
45
|
+
*
|
|
46
|
+
* If `target` is already a {@link Vec3}, it is used as-is (before the
|
|
47
|
+
* offset). If it's a `DazNode`, its `position()` is read and converted via
|
|
48
|
+
* `Vec3.fromDict`.
|
|
49
|
+
*
|
|
50
|
+
* `verticalOffsetCm` is added to the resolved Y (DAZ Studio's up axis)
|
|
51
|
+
* component. This exists primarily to compensate for the fact that a
|
|
52
|
+
* figure's `DazNode.position` is generally its root/hip joint, not its
|
|
53
|
+
* center of mass or head -- framing code that wants to aim higher (e.g.
|
|
54
|
+
* chest/head height for a tight shot) passes a positive offset here rather
|
|
55
|
+
* than aiming straight at the hip.
|
|
56
|
+
*
|
|
57
|
+
* @throws Error If `target` is a node and its position is unavailable (e.g.
|
|
58
|
+
* the node no longer exists in the scene).
|
|
59
|
+
*/
|
|
60
|
+
export async function resolveTarget(target, verticalOffsetCm = 0.0) {
|
|
61
|
+
let base;
|
|
62
|
+
if (target instanceof Vec3) {
|
|
63
|
+
base = target;
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
const position = await target.position();
|
|
67
|
+
if (position === null) {
|
|
68
|
+
throw new Error("resolveTarget: target node has no position (it may not exist in the scene)");
|
|
69
|
+
}
|
|
70
|
+
base = Vec3.fromDict(position);
|
|
71
|
+
}
|
|
72
|
+
if (verticalOffsetCm === 0.0) {
|
|
73
|
+
return base;
|
|
74
|
+
}
|
|
75
|
+
return new Vec3(base.x, base.y + verticalOffsetCm, base.z);
|
|
76
|
+
}
|