@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.
Files changed (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +377 -2
  3. package/dist/animation.d.ts +129 -0
  4. package/dist/animation.js +276 -0
  5. package/dist/batch.d.ts +118 -0
  6. package/dist/batch.js +186 -0
  7. package/dist/bone.d.ts +50 -0
  8. package/dist/bone.js +66 -0
  9. package/dist/camera.d.ts +61 -0
  10. package/dist/camera.js +120 -0
  11. package/dist/cinematics.d.ts +188 -0
  12. package/dist/cinematics.js +165 -0
  13. package/dist/client.d.ts +399 -0
  14. package/dist/client.js +769 -0
  15. package/dist/dforce.d.ts +15 -0
  16. package/dist/dforce.js +36 -0
  17. package/dist/element.d.ts +51 -0
  18. package/dist/element.js +141 -0
  19. package/dist/exceptions.d.ts +124 -0
  20. package/dist/exceptions.js +173 -0
  21. package/dist/geometry.d.ts +81 -0
  22. package/dist/geometry.js +433 -0
  23. package/dist/index.d.ts +50 -0
  24. package/dist/index.js +36 -0
  25. package/dist/light.d.ts +24 -0
  26. package/dist/light.js +40 -0
  27. package/dist/lighting.d.ts +120 -0
  28. package/dist/lighting.js +107 -0
  29. package/dist/material.d.ts +27 -0
  30. package/dist/material.js +63 -0
  31. package/dist/materials.d.ts +107 -0
  32. package/dist/materials.js +165 -0
  33. package/dist/math3.d.ts +204 -0
  34. package/dist/math3.js +502 -0
  35. package/dist/modifier.d.ts +14 -0
  36. package/dist/modifier.js +24 -0
  37. package/dist/morph.d.ts +11 -0
  38. package/dist/morph.js +24 -0
  39. package/dist/node.d.ts +196 -0
  40. package/dist/node.js +447 -0
  41. package/dist/polling.d.ts +24 -0
  42. package/dist/polling.js +50 -0
  43. package/dist/pose.d.ts +82 -0
  44. package/dist/pose.js +295 -0
  45. package/dist/poses.d.ts +54 -0
  46. package/dist/poses.js +40 -0
  47. package/dist/property.d.ts +64 -0
  48. package/dist/property.js +125 -0
  49. package/dist/render.d.ts +242 -0
  50. package/dist/render.js +811 -0
  51. package/dist/renderApi.d.ts +124 -0
  52. package/dist/renderApi.js +235 -0
  53. package/dist/result.d.ts +15 -0
  54. package/dist/result.js +1 -0
  55. package/dist/scene.d.ts +154 -0
  56. package/dist/scene.js +584 -0
  57. package/dist/sceneEvents.d.ts +63 -0
  58. package/dist/sceneEvents.js +102 -0
  59. package/dist/sceneState.d.ts +167 -0
  60. package/dist/sceneState.js +430 -0
  61. package/dist/scriptBuilder.d.ts +41 -0
  62. package/dist/scriptBuilder.js +72 -0
  63. package/dist/shotGeometry.d.ts +49 -0
  64. package/dist/shotGeometry.js +76 -0
  65. package/dist/skeleton.d.ts +120 -0
  66. package/dist/skeleton.js +561 -0
  67. package/dist/timeline.d.ts +24 -0
  68. package/dist/timeline.js +39 -0
  69. package/dist/undo.d.ts +24 -0
  70. package/dist/undo.js +45 -0
  71. package/dist/version.d.ts +31 -0
  72. package/dist/version.js +36 -0
  73. package/dist/viewport.d.ts +58 -0
  74. package/dist/viewport.js +239 -0
  75. package/package.json +52 -4
package/dist/node.js ADDED
@@ -0,0 +1,447 @@
1
+ import { DazDForce } from "./dforce.js";
2
+ import { DazElement } from "./element.js";
3
+ import { NodeNotFoundError, ScriptRuntimeError } from "./exceptions.js";
4
+ import { DazMaterial } from "./material.js";
5
+ import { DazModifier } from "./modifier.js";
6
+ import { DazMorph } from "./morph.js";
7
+ import { DazProperty } from "./property.js";
8
+ import { ScriptBuilder } from "./scriptBuilder.js";
9
+ /**
10
+ * Proxy for a `DzNode` in the active DAZ Studio scene. Provides access to
11
+ * transforms, hierarchy, visibility, materials, modifiers, and geometry.
12
+ * Instances are typically obtained from {@link DazScene} rather than
13
+ * constructed directly. All reads may resolve to `null` if the node no
14
+ * longer exists in the scene.
15
+ *
16
+ * This class is built across two tasks: this file covers transforms,
17
+ * visibility, and hierarchy (Phase 2 Task 3); a later task (Task 6) adds
18
+ * modifiers/materials/fitting methods to this same class.
19
+ */
20
+ export class DazNode extends DazElement {
21
+ identifier;
22
+ constructor(client, identifier, locator) {
23
+ super(client, locator ?? ScriptBuilder.findNodeExpr(identifier));
24
+ this.identifier = identifier;
25
+ }
26
+ /** Wrap `body` in the standard `_node` null-checked IIFE for this node's identifier. */
27
+ nodeScript(body) {
28
+ return ScriptBuilder.nodeBody(this.identifier, body);
29
+ }
30
+ // ---------------------------------------------------------------------
31
+ // Identity
32
+ // ---------------------------------------------------------------------
33
+ /** User-visible display label shown in the Scene panel (read/write). */
34
+ async label() {
35
+ return (await this.client.execute(this.nodeScript("return _node.getLabel();"))).value;
36
+ }
37
+ async setLabel(value) {
38
+ await this.client.execute(this.nodeScript(`_node.setLabel(${ScriptBuilder.escapeString(value)});`));
39
+ }
40
+ /** Internal node name used to look up the node (read-only). */
41
+ async name() {
42
+ return (await this.client.execute(this.nodeScript("return _node.getName();"))).value;
43
+ }
44
+ // ---------------------------------------------------------------------
45
+ // Transforms
46
+ // ---------------------------------------------------------------------
47
+ /** World-space position as `{x, y, z}` (read-only; use {@link setPosition} to change). */
48
+ async position() {
49
+ return (await this.client.execute(this.nodeScript("var p = _node.getWSPos(); return {x: p.x, y: p.y, z: p.z};")))
50
+ .value;
51
+ }
52
+ async setPosition(x, y, z) {
53
+ await this.client.execute(this.nodeScript(`_node.setWSPos(new DzVec3(${ScriptBuilder.serializeArg(x)}, ${ScriptBuilder.serializeArg(y)}, ${ScriptBuilder.serializeArg(z)}));`));
54
+ }
55
+ /** World-space rotation as `{x, y, z, w}` quaternion (read-only; use {@link setRotation} for Euler degrees). */
56
+ async rotation() {
57
+ return (await this.client.execute(this.nodeScript("var r = _node.getWSRot(); return {x: r.x, y: r.y, z: r.z, w: r.w};"))).value;
58
+ }
59
+ /** Uniform scale factor (read-only). */
60
+ async generalScale() {
61
+ return (await this.client.execute(this.nodeScript("return _node.getScaleControl().getValue();"))).value;
62
+ }
63
+ /** Per-axis and uniform scale as `{x, y, z, general}` (read-only; use {@link setScale} to change per-axis values). */
64
+ async scale() {
65
+ return (await this.client.execute(this.nodeScript("return {x: _node.getXScaleControl().getValue(), y: _node.getYScaleControl().getValue(), z: _node.getZScaleControl().getValue(), general: _node.getScaleControl().getValue()};"))).value;
66
+ }
67
+ /** Set per-axis local scale (does not affect the general/uniform scale dial; see {@link generalScale}). */
68
+ async setScale(x, y, z) {
69
+ await this.client.execute(this.nodeScript(`_node.getXScaleControl().setValue(${ScriptBuilder.serializeArg(x)}); _node.getYScaleControl().setValue(${ScriptBuilder.serializeArg(y)}); _node.getZScaleControl().setValue(${ScriptBuilder.serializeArg(z)});`));
70
+ }
71
+ /** Set any combination of local position/rotation(Euler degrees)/scale in one round trip; omitted components are left untouched. */
72
+ async setTransform(opts) {
73
+ const lines = [];
74
+ if (opts.position !== undefined) {
75
+ const [x, y, z] = opts.position;
76
+ lines.push(`_node.setLocalPos(new DzVec3(${ScriptBuilder.serializeArg(x)}, ${ScriptBuilder.serializeArg(y)}, ${ScriptBuilder.serializeArg(z)}));`);
77
+ }
78
+ if (opts.rotation !== undefined) {
79
+ const [x, y, z] = opts.rotation;
80
+ lines.push(`_node.getXRotControl().setValue(${ScriptBuilder.serializeArg(x)}); _node.getYRotControl().setValue(${ScriptBuilder.serializeArg(y)}); _node.getZRotControl().setValue(${ScriptBuilder.serializeArg(z)});`);
81
+ }
82
+ if (opts.scale !== undefined) {
83
+ const [x, y, z] = opts.scale;
84
+ lines.push(`_node.getXScaleControl().setValue(${ScriptBuilder.serializeArg(x)}); _node.getYScaleControl().setValue(${ScriptBuilder.serializeArg(y)}); _node.getZScaleControl().setValue(${ScriptBuilder.serializeArg(z)});`);
85
+ }
86
+ if (lines.length === 0)
87
+ return;
88
+ await this.client.execute(this.nodeScript(lines.join("\n")));
89
+ }
90
+ /** Set the world-space rotation using Euler angles in degrees. */
91
+ async setRotation(x, y, z) {
92
+ await this.client.execute(this.nodeScript(`_node.getXRotControl().setValue(${ScriptBuilder.serializeArg(x)}); _node.getYRotControl().setValue(${ScriptBuilder.serializeArg(y)}); _node.getZRotControl().setValue(${ScriptBuilder.serializeArg(z)});`));
93
+ }
94
+ // ---------------------------------------------------------------------
95
+ // Keyframes
96
+ // ---------------------------------------------------------------------
97
+ /** Write a real position keyframe at timeline `frame` (converted to ticks via `Scene.getTimeStep()`). */
98
+ async setPositionAtFrame(frame, x, y, z) {
99
+ await this.client.execute(this.nodeScript(`var _tm = ${ScriptBuilder.serializeArg(Math.trunc(frame))} * Scene.getTimeStep(); _node.setWSPos(_tm, new DzVec3(${ScriptBuilder.serializeArg(x)}, ${ScriptBuilder.serializeArg(y)}, ${ScriptBuilder.serializeArg(z)}));`));
100
+ }
101
+ /** Write a real Euler rotation keyframe at timeline `frame`. See {@link setPositionAtFrame} for the tick conversion. */
102
+ async setRotationAtFrame(frame, x, y, z) {
103
+ await this.client.execute(this.nodeScript(`var _tm = ${ScriptBuilder.serializeArg(Math.trunc(frame))} * Scene.getTimeStep(); ` +
104
+ `_node.getXRotControl().setDoubleValue(_tm, ${ScriptBuilder.serializeArg(x)}); ` +
105
+ `_node.getYRotControl().setDoubleValue(_tm, ${ScriptBuilder.serializeArg(y)}); ` +
106
+ `_node.getZRotControl().setDoubleValue(_tm, ${ScriptBuilder.serializeArg(z)});`));
107
+ }
108
+ /** Remove all keyframes from this node's X/Y/Z position controls (call before a fresh {@link setPositionAtFrame} curve). */
109
+ async clearPositionKeys() {
110
+ await this.client.execute(this.nodeScript("_node.getXPosControl().deleteAllKeys(); _node.getYPosControl().deleteAllKeys(); _node.getZPosControl().deleteAllKeys();"));
111
+ }
112
+ /** Remove all keyframes from this node's X/Y/Z rotation controls. See {@link clearPositionKeys}. */
113
+ async clearRotationKeys() {
114
+ await this.client.execute(this.nodeScript("_node.getXRotControl().deleteAllKeys(); _node.getYRotControl().deleteAllKeys(); _node.getZRotControl().deleteAllKeys();"));
115
+ }
116
+ // ---------------------------------------------------------------------
117
+ // Local-space transforms
118
+ // ---------------------------------------------------------------------
119
+ /** Local-space position as `{x, y, z}` (read-only). */
120
+ async localPosition() {
121
+ return (await this.client.execute(this.nodeScript("var p = _node.getLocalPos(); return {x: p.x, y: p.y, z: p.z};")))
122
+ .value;
123
+ }
124
+ async setLocalPosition(x, y, z) {
125
+ await this.client.execute(this.nodeScript(`_node.setLocalPos(new DzVec3(${ScriptBuilder.serializeArg(x)}, ${ScriptBuilder.serializeArg(y)}, ${ScriptBuilder.serializeArg(z)}));`));
126
+ }
127
+ /** Local-space rotation as `(x, y, z)` Euler degrees; exact inverse of {@link setLocalRotation}. */
128
+ async localEuler() {
129
+ const result = (await this.client.execute(this.nodeScript("return [_node.getXRotControl().getValue(), _node.getYRotControl().getValue(), _node.getZRotControl().getValue()];"))).value;
130
+ if (result === null)
131
+ return null;
132
+ return [result[0], result[1], result[2]];
133
+ }
134
+ /** Local-space rotation as `{x, y, z, w}` quaternion (read-only). */
135
+ async localRotation() {
136
+ return (await this.client.execute(this.nodeScript("var r = _node.getLocalRot(); return {x: r.x, y: r.y, z: r.z, w: r.w};"))).value;
137
+ }
138
+ async setLocalRotation(x, y, z) {
139
+ await this.client.execute(this.nodeScript(`_node.getXRotControl().setValue(${ScriptBuilder.serializeArg(x)}); _node.getYRotControl().setValue(${ScriptBuilder.serializeArg(y)}); _node.getZRotControl().setValue(${ScriptBuilder.serializeArg(z)});`));
140
+ }
141
+ // ---------------------------------------------------------------------
142
+ // Visibility
143
+ // ---------------------------------------------------------------------
144
+ /** General visibility flag, affecting both viewport and render unless overridden per-channel (read/write). */
145
+ async visible() {
146
+ return (await this.client.execute(this.nodeScript("return _node.isVisible();"))).value;
147
+ }
148
+ async setVisible(value) {
149
+ await this.client.execute(this.nodeScript(`_node.setVisible(${ScriptBuilder.serializeArg(value)});`));
150
+ }
151
+ async isVisibleInRender() {
152
+ return Boolean((await this.client.execute(this.nodeScript("return _node.isVisibleInRender();"))).value);
153
+ }
154
+ async setVisibleInRender(on) {
155
+ await this.client.execute(this.nodeScript(`_node.setVisibleInRender(${ScriptBuilder.serializeArg(on)});`));
156
+ }
157
+ async isVisibleInViewport() {
158
+ return Boolean((await this.client.execute(this.nodeScript("return _node.isVisibleInViewport();"))).value);
159
+ }
160
+ async setVisibleInViewport(on) {
161
+ await this.client.execute(this.nodeScript(`_node.setVisibleInViewport(${ScriptBuilder.serializeArg(on)});`));
162
+ }
163
+ // ---------------------------------------------------------------------
164
+ // Selection / scene state
165
+ // ---------------------------------------------------------------------
166
+ async isSelected() {
167
+ return Boolean((await this.client.execute(this.nodeScript("return _node.isSelected();"))).value);
168
+ }
169
+ async select(on = true) {
170
+ await this.client.execute(this.nodeScript(`_node.select(${ScriptBuilder.serializeArg(on)});`));
171
+ }
172
+ async isInScene() {
173
+ return Boolean((await this.client.execute(this.nodeScript("return _node.isInScene();"))).value);
174
+ }
175
+ /** `true` if this node has no parent (top-level node). */
176
+ async isRoot() {
177
+ return Boolean((await this.client.execute(this.nodeScript("return _node.isRootNode();"))).value);
178
+ }
179
+ // ---------------------------------------------------------------------
180
+ // Hierarchy
181
+ // ---------------------------------------------------------------------
182
+ /** Parent node in the scene hierarchy, or `null` for root nodes. */
183
+ async parent() {
184
+ const name = (await this.client.execute(this.nodeScript("var p = _node.getNodeParent(); return p ? p.getName() : null;"))).value;
185
+ if (name === null)
186
+ return null;
187
+ return new DazNode(this.client, { value: name, kind: "name" });
188
+ }
189
+ /** Direct child nodes. */
190
+ async children() {
191
+ const names = (await this.client.execute(this.nodeScript("var names = []; for (var i = 0; i < _node.getNumNodeChildren(); i++) { names.push(_node.getNodeChild(i).getName()); } return names;"))).value ?? [];
192
+ return names.map((n) => new DazNode(this.client, { value: n, kind: "name" }));
193
+ }
194
+ /** Remove this node from the scene entirely. @returns `true` if found and removed. */
195
+ async delete() {
196
+ return Boolean((await this.client.execute(this.nodeScript("return Scene.removeNode(_node);"))).value);
197
+ }
198
+ /**
199
+ * Move this node to a new position in the scene hierarchy via the
200
+ * `removeNodeChild`/`addNodeChild` pattern.
201
+ * @param preserveWorldTransform When `true` (default), keeps world-space transform, adjusting local transform to compensate.
202
+ */
203
+ async reparent(newParent, opts = {}) {
204
+ const { preserveWorldTransform = true } = opts;
205
+ const parentExpr = ScriptBuilder.findNodeExpr(newParent.identifier);
206
+ const inPlace = ScriptBuilder.serializeArg(preserveWorldTransform);
207
+ const result = (await this.client.execute(this.nodeScript(`
208
+ var _newParent = ${parentExpr};
209
+ if (!_newParent) return "new parent not found";
210
+ var _oldParent = _node.getNodeParent();
211
+ if (_oldParent) _oldParent.removeNodeChild(_node, ${inPlace});
212
+ var _err = _newParent.addNodeChild(_node, ${inPlace});
213
+ var _errNum = _err ? _err.valueOf() : 0;
214
+ return _errNum !== 0 ? ("DzError code " + _errNum) : null;
215
+ `))).value;
216
+ if (result) {
217
+ throw new ScriptRuntimeError(`reparent failed: ${result}`);
218
+ }
219
+ }
220
+ // ---------------------------------------------------------------------
221
+ // Modifiers / Materials / Fitting / Bounding box
222
+ // ---------------------------------------------------------------------
223
+ modifierClassFor(className) {
224
+ if (className === "DzMorph")
225
+ return DazMorph;
226
+ if (className === "DzDForceModifier")
227
+ return DazDForce;
228
+ return DazModifier;
229
+ }
230
+ modifierLocator(modifierName) {
231
+ return (`(function(){` +
232
+ ` var _o = ${this.locator};` +
233
+ ` _o = _o ? _o.getObject() : null;` +
234
+ ` return _o ? _o.findModifier(${ScriptBuilder.escapeString(modifierName)}) : null;` +
235
+ `})()`);
236
+ }
237
+ /** Return all modifiers (morphs, constraints, etc.) on this node, typed via the DzMorph/DzDForceModifier dispatch table. */
238
+ async modifiers() {
239
+ const items = (await this.client.execute(this.nodeScript(`
240
+ var obj = _node.getObject();
241
+ if (!obj) return [];
242
+ var mods = [];
243
+ for (var i = 0; i < obj.getNumModifiers(); i++) {
244
+ var m = obj.getModifier(i);
245
+ mods.push({name: m.getName(), className: m.className()});
246
+ }
247
+ return mods;
248
+ `))).value ?? [];
249
+ return items.map((item) => {
250
+ const Cls = this.modifierClassFor(item.className);
251
+ return new Cls(this.client, this.modifierLocator(item.name));
252
+ });
253
+ }
254
+ /** Find a modifier by internal name. */
255
+ async findModifier(name) {
256
+ const result = (await this.client.execute(this.nodeScript(`
257
+ var obj = _node.getObject();
258
+ if (!obj) return null;
259
+ var m = obj.findModifier(${ScriptBuilder.escapeString(name)});
260
+ return m ? {name: m.getName(), className: m.className()} : null;
261
+ `))).value;
262
+ if (result === null)
263
+ return null;
264
+ const Cls = this.modifierClassFor(result.className);
265
+ return new Cls(this.client, this.modifierLocator(result.name));
266
+ }
267
+ /** Find a modifier by its user-visible label (the name shown in the DAZ UI), matching {@link findModifier}'s internal-name lookup on label instead. */
268
+ async findModifierByLabel(label) {
269
+ const result = (await this.client.execute(this.nodeScript(`
270
+ var obj = _node.getObject();
271
+ if (!obj) return null;
272
+ for (var i = 0; i < obj.getNumModifiers(); i++) {
273
+ var m = obj.getModifier(i);
274
+ if (m.getLabel() === ${ScriptBuilder.escapeString(label)}) {
275
+ return {name: m.getName(), className: m.className()};
276
+ }
277
+ }
278
+ return null;
279
+ `))).value;
280
+ if (result === null)
281
+ return null;
282
+ const Cls = this.modifierClassFor(result.className);
283
+ return new Cls(this.client, this.modifierLocator(result.name));
284
+ }
285
+ materialLocator(materialName) {
286
+ return (`(function(){` +
287
+ ` var _n = ${this.locator};` +
288
+ ` if (!_n) return null;` +
289
+ ` var _o = _n.getObject();` +
290
+ ` if (!_o) return null;` +
291
+ ` var _s = _o.getCurrentShape();` +
292
+ ` return _s ? _s.findMaterial(${ScriptBuilder.escapeString(materialName)}) : null;` +
293
+ `})()`);
294
+ }
295
+ /** Return all surface materials on this node's current shape. */
296
+ async materials() {
297
+ const names = (await this.client.execute(this.nodeScript(`
298
+ var obj = _node.getObject();
299
+ if (!obj) return [];
300
+ var shape = obj.getCurrentShape();
301
+ if (!shape) return [];
302
+ var names = [];
303
+ for (var i = 0; i < shape.getNumMaterials(); i++) {
304
+ names.push(shape.getMaterial(i).getName());
305
+ }
306
+ return names;
307
+ `))).value ?? [];
308
+ return names.map((n) => new DazMaterial(this.client, this.materialLocator(n)));
309
+ }
310
+ /** Find a surface material by name. */
311
+ async findMaterial(name) {
312
+ const result = (await this.client.execute(this.nodeScript(`
313
+ var obj = _node.getObject();
314
+ if (!obj) return null;
315
+ var shape = obj.getCurrentShape();
316
+ if (!shape) return null;
317
+ var m = shape.findMaterial(${ScriptBuilder.escapeString(name)});
318
+ return m ? m.getName() : null;
319
+ `))).value;
320
+ if (result === null)
321
+ return null;
322
+ return new DazMaterial(this.client, this.materialLocator(result));
323
+ }
324
+ /**
325
+ * Find a node-level property by internal name via `DzNode::findProperty` —
326
+ * covers pose controls/FACS dials that are not geometry modifiers and so
327
+ * are invisible to {@link findModifier}.
328
+ */
329
+ async findProperty(name) {
330
+ const locator = `(function(){var _n=${this.locator};return _n ? _n.findProperty(${ScriptBuilder.escapeString(name)}) : null;})()`;
331
+ const exists = (await this.client.execute(ScriptBuilder.iife(`return !!(${locator});`))).value;
332
+ if (!exists)
333
+ return null;
334
+ return DazProperty.fromLocator(this.client, locator);
335
+ }
336
+ /** Like {@link findProperty} but matches `getLabel()` instead of `getName()`. */
337
+ async findPropertyByLabel(label) {
338
+ const locator = `(function(){var _n=${this.locator};return _n ? _n.findPropertyByLabel(${ScriptBuilder.escapeString(label)}) : null;})()`;
339
+ const exists = (await this.client.execute(ScriptBuilder.iife(`return !!(${locator});`))).value;
340
+ if (!exists)
341
+ return null;
342
+ return DazProperty.fromLocator(this.client, locator);
343
+ }
344
+ /** Only the morph modifiers on this node (convenience filter over {@link modifiers}). */
345
+ async morphs() {
346
+ return (await this.modifiers()).filter((m) => m instanceof DazMorph);
347
+ }
348
+ /** Only the dForce simulation modifiers on this node (convenience filter over {@link modifiers}). */
349
+ async dforceModifiers() {
350
+ return (await this.modifiers()).filter((m) => m instanceof DazDForce);
351
+ }
352
+ /** World-space axis-aligned bounding box, or `null` if the node has no geometry. */
353
+ async boundingBox() {
354
+ const script = this.nodeScript("var bb = _node.getWSBoundingBox(); return {min: {x: bb.min.x, y: bb.min.y, z: bb.min.z}, max: {x: bb.max.x, y: bb.max.y, z: bb.max.z}};");
355
+ return (await this.client.execute(script)).value;
356
+ }
357
+ /**
358
+ * Fit this clothing/hair/prop node to a base figure, preferring
359
+ * `setFollowTarget`/`followSkeleton` (conforming items) and falling back
360
+ * to parenting (plain props). @returns which DazScript API was used.
361
+ */
362
+ async fitTo(figure) {
363
+ const figureExpr = ScriptBuilder.findNodeExpr(figure.identifier);
364
+ const result = (await this.client.execute(this.nodeScript(`
365
+ var _figure = ${figureExpr};
366
+ if (!_figure) return null;
367
+ var _method;
368
+ if (typeof _node.setFollowTarget === 'function') {
369
+ _node.setFollowTarget(_figure);
370
+ _method = "setFollowTarget";
371
+ } else if (typeof _node.followSkeleton === 'function') {
372
+ _node.followSkeleton(_figure);
373
+ _method = "followSkeleton";
374
+ } else {
375
+ _figure.addNodeChild(_node, true);
376
+ _method = "addNodeChild";
377
+ }
378
+ return _method;
379
+ `))).value;
380
+ if (result === null) {
381
+ throw new NodeNotFoundError("Could not fit node to figure: one of the nodes was not found.");
382
+ }
383
+ return result;
384
+ }
385
+ /** Remove this node's fitting relationship with its figure (follow-target and/or skeleton parenting). */
386
+ async unfit() {
387
+ const script = this.nodeScript(`
388
+ var _prevFigure = null;
389
+ var _actions = [];
390
+ if (typeof _node.getFollowTarget === 'function') {
391
+ var _ft = _node.getFollowTarget();
392
+ if (_ft) {
393
+ _prevFigure = _ft.getName();
394
+ if (typeof _node.setFollowTarget === 'function') {
395
+ _node.setFollowTarget(null);
396
+ _actions.push("cleared follow target");
397
+ }
398
+ }
399
+ }
400
+ var _parent = _node.getNodeParent();
401
+ if (_parent && _parent.inherits && _parent.inherits("DzSkeleton")) {
402
+ _prevFigure = _prevFigure || _parent.getName();
403
+ _parent.removeNodeChild(_node, true);
404
+ _actions.push("detached from parent");
405
+ }
406
+ return {previous_figure: _prevFigure, actions: _actions};
407
+ `);
408
+ const result = (await this.client.execute(script)).value;
409
+ return { previousFigure: result?.previous_figure ?? null, actions: result?.actions ?? [] };
410
+ }
411
+ /** Every clothing/hair/prop node fitted to this figure (following it, or directly parented to it). */
412
+ async fittedItems() {
413
+ const names = (await this.client.execute(this.nodeScript(`
414
+ var _fitted = [];
415
+ var _numNodes = Scene.getNumNodes();
416
+ for (var i = 0; i < _numNodes; i++) {
417
+ var _n = Scene.getNode(i);
418
+ if (!_n || _n === _node) continue;
419
+ var _isFitted = false;
420
+ if (typeof _n.getFollowTarget === 'function') {
421
+ var _ft = _n.getFollowTarget();
422
+ if (_ft && _ft.elementID === _node.elementID) _isFitted = true;
423
+ }
424
+ if (!_isFitted && typeof _n.getNodeParent === 'function') {
425
+ var _p = _n.getNodeParent();
426
+ if (_p && _p.elementID === _node.elementID) _isFitted = true;
427
+ }
428
+ if (_isFitted) _fitted.push(_n.getName());
429
+ }
430
+ return _fitted;
431
+ `))).value ?? [];
432
+ return names.map((n) => new DazNode(this.client, { value: n, kind: "name" }));
433
+ }
434
+ /** Total vertex count of this node's current geometry, or `null`. */
435
+ async geometryVertexCount() {
436
+ const script = this.nodeScript(`
437
+ var obj = _node.getObject();
438
+ if (!obj) return null;
439
+ var shape = obj.getCurrentShape();
440
+ if (!shape) return null;
441
+ var geo = shape.getGeometry();
442
+ if (!geo) return null;
443
+ return geo.getNumVertices();
444
+ `);
445
+ return (await this.client.execute(script)).value;
446
+ }
447
+ }
@@ -0,0 +1,24 @@
1
+ import type { DazClient } from "./client.js";
2
+ import type { ExecutionResult } from "./result.js";
3
+ /** Options accepted by {@link executeLong}. */
4
+ export interface ExecuteLongOptions {
5
+ /** Maximum total wall-clock milliseconds to wait. Default `120000`. */
6
+ timeoutMs?: number;
7
+ /** Milliseconds to sleep between short polls when the server returns before the long-poll timeout. Default `500`. */
8
+ pollIntervalMs?: number;
9
+ }
10
+ /**
11
+ * Execute a potentially long-running script via the async endpoint with polling.
12
+ *
13
+ * Submits `script` asynchronously, then polls `/requests/:id/result` with
14
+ * long-polling until the script completes or `timeoutMs` is exceeded.
15
+ *
16
+ * `completed_after_cancel_request` and `completed_after_stale` resolve with
17
+ * the kept result. `stale` ends the wait: the server answers it with
18
+ * `success: false`, so it throws even though the script may still finish.
19
+ * `cancel_requested` keeps polling until the script returns.
20
+ *
21
+ * @throws {AsyncExecutionError} If the script fails, the request is cancelled, or it goes `stale`.
22
+ * @throws {DazTimeoutError} If `timeoutMs` is exceeded before the script completes.
23
+ */
24
+ export declare function executeLong(client: DazClient, script: string, args?: unknown, options?: ExecuteLongOptions): Promise<ExecutionResult>;
@@ -0,0 +1,50 @@
1
+ import { AsyncExecutionError, DazTimeoutError } from "./exceptions.js";
2
+ function sleep(ms) {
3
+ return new Promise((resolve) => setTimeout(resolve, ms));
4
+ }
5
+ /**
6
+ * Execute a potentially long-running script via the async endpoint with polling.
7
+ *
8
+ * Submits `script` asynchronously, then polls `/requests/:id/result` with
9
+ * long-polling until the script completes or `timeoutMs` is exceeded.
10
+ *
11
+ * `completed_after_cancel_request` and `completed_after_stale` resolve with
12
+ * the kept result. `stale` ends the wait: the server answers it with
13
+ * `success: false`, so it throws even though the script may still finish.
14
+ * `cancel_requested` keeps polling until the script returns.
15
+ *
16
+ * @throws {AsyncExecutionError} If the script fails, the request is cancelled, or it goes `stale`.
17
+ * @throws {DazTimeoutError} If `timeoutMs` is exceeded before the script completes.
18
+ */
19
+ export async function executeLong(client, script, args, options = {}) {
20
+ const { timeoutMs = 120_000, pollIntervalMs = 500 } = options;
21
+ const requestId = await client.executeAsyncSubmit(script, args);
22
+ const deadline = Date.now() + timeoutMs;
23
+ while (Date.now() < deadline) {
24
+ const waitTimeoutSeconds = Math.min(30, Math.floor((deadline - Date.now()) / 1000) + 1);
25
+ const data = await client.getRequestResult(requestId, true, waitTimeoutSeconds);
26
+ const status = data.status;
27
+ if (data.success !== undefined) {
28
+ if (!data.success) {
29
+ throw new AsyncExecutionError(data.error ?? "Async script failed", requestId);
30
+ }
31
+ return {
32
+ value: data.result ?? null,
33
+ output: data.output ?? [],
34
+ requestId,
35
+ success: true,
36
+ error: "",
37
+ durationMs: data.duration_ms ?? 0,
38
+ };
39
+ }
40
+ if (status === "failed") {
41
+ throw new AsyncExecutionError(data.error ?? "Async script failed", requestId);
42
+ }
43
+ if (status === "cancelled") {
44
+ throw new AsyncExecutionError("Request was cancelled", requestId);
45
+ }
46
+ // cancel_requested is not final: keep polling for the real outcome.
47
+ await sleep(pollIntervalMs);
48
+ }
49
+ throw new DazTimeoutError(`Async execution timed out after ${timeoutMs / 1000}s (requestId=${requestId})`);
50
+ }
package/dist/pose.d.ts ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * A snapshot of a figure's complete pose state. Mirrors dazpy's `_pose.py`.
3
+ */
4
+ import type { RetryOptions } from "./client.js";
5
+ import type { DazSkeleton } from "./skeleton.js";
6
+ /** Plain-object schema matching {@link DazPose.toDict}/{@link DazPose.fromDict} and the pose JSON file format. */
7
+ export interface DazPoseDict {
8
+ figure: string;
9
+ bones: Record<string, [number, number, number]>;
10
+ morphs: Record<string, number>;
11
+ props: Record<string, number>;
12
+ }
13
+ /**
14
+ * A snapshot of a figure's complete pose state.
15
+ *
16
+ * Stores bone rotations (Euler XYZ degrees), geometry morph values, and
17
+ * node-level numeric properties. Sparse by default -- zero values are
18
+ * omitted so the object stays compact for morph-heavy figures.
19
+ *
20
+ * Typical workflow:
21
+ * ```ts
22
+ * const scene = new DazScene();
23
+ * const figure = await scene.findSkeletonByLabel("Genesis 9");
24
+ *
25
+ * const neutral = await DazPose.capture(figure);
26
+ * neutral.save("neutral.json");
27
+ *
28
+ * const smile = DazPose.load("smile.json");
29
+ * await neutral.lerp(smile, 0.5).apply(figure);
30
+ * ```
31
+ */
32
+ export declare class DazPose {
33
+ readonly figure: string;
34
+ readonly bones: Record<string, [number, number, number]>;
35
+ readonly morphs: Record<string, number>;
36
+ readonly props: Record<string, number>;
37
+ constructor(figure: string, bones: Record<string, [number, number, number]>, morphs: Record<string, number>, props: Record<string, number>);
38
+ /**
39
+ * Capture the current pose of `skeleton` in a single HTTP call.
40
+ *
41
+ * Records all non-zero bone rotations, morph values, and node-level
42
+ * numeric properties. Zero values are omitted (sparse storage); they are
43
+ * implied as 0.0 during {@link lerp} and {@link applyFull}.
44
+ *
45
+ * @throws NodeNotFoundError If the skeleton is not found.
46
+ */
47
+ static capture(skeleton: DazSkeleton): Promise<DazPose>;
48
+ /** Load a pose from a JSON file. Accepts files produced by {@link save}. */
49
+ static load(path: string): DazPose;
50
+ /** Write this pose to a JSON file. Parent directories must exist. */
51
+ save(path: string): void;
52
+ /** Return the pose as a plain dict (same schema as the JSON file). */
53
+ toDict(): DazPoseDict;
54
+ static fromDict(data: Partial<DazPoseDict>): DazPose;
55
+ /**
56
+ * Linearly interpolate between this pose and `other`. Missing keys in
57
+ * either pose are treated as zero. The result uses the figure label from
58
+ * `this`. Pure -- no HTTP round-trip.
59
+ *
60
+ * @param t Blend factor. 0.0 = this pose, 1.0 = `other`. Values outside
61
+ * [0, 1] extrapolate.
62
+ */
63
+ lerp(other: DazPose, t: number): DazPose;
64
+ /**
65
+ * Apply this pose to `skeleton` in a single HTTP call.
66
+ *
67
+ * Only channels present in the pose are changed. Bones and morphs not
68
+ * stored in the pose are left at their current values. Use
69
+ * {@link applyFull} when you need a clean, authoritative reset to exactly
70
+ * this pose.
71
+ */
72
+ apply(skeleton: DazSkeleton, opts?: RetryOptions): Promise<void>;
73
+ /**
74
+ * Apply this pose and zero every channel not present in the pose.
75
+ *
76
+ * Unlike {@link apply}, every bone rotation, morph, and node property on
77
+ * the skeleton is explicitly set -- channels absent from the pose are
78
+ * driven to zero. Use this to restore a known baseline cleanly.
79
+ */
80
+ applyFull(skeleton: DazSkeleton, opts?: RetryOptions): Promise<void>;
81
+ toString(): string;
82
+ }