@nebula-spatial/studio 0.1.0 → 0.1.2

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 (50) hide show
  1. package/README.md +2 -0
  2. package/dist/assets/openusd_three_loader-DLiqJWUM.js +13769 -0
  3. package/dist/assets/usd-export-worker-BRxTLqer.js +182 -0
  4. package/dist/assets/usd-worker-DekqMsQv.js +1392 -0
  5. package/dist/{builders-BAXRR5o5.js → builders-lydx4-Rh.js} +1 -1
  6. package/dist/core/session-persistence-controller.d.ts +55 -0
  7. package/dist/doc/placement-policy.d.ts +4 -0
  8. package/dist/editor/editor.d.ts +3 -1
  9. package/dist/editor/index.d.ts +2 -0
  10. package/dist/editor/session-persistence.d.ts +54 -0
  11. package/dist/editor.js +727 -490
  12. package/dist/export-evidence-z2Ne7Trf.js +2387 -0
  13. package/dist/generalization.js +2 -2
  14. package/dist/index.d.ts +4 -2
  15. package/dist/index.js +314 -306
  16. package/dist/mjcf-visual-IOy-ucto.js +72 -0
  17. package/dist/mujoco-runtime-BYZnrvbR.js +467 -0
  18. package/dist/persist/indexeddb-store.d.ts +22 -2
  19. package/dist/persist/session.d.ts +22 -0
  20. package/dist/persist/snapshot.d.ts +24 -0
  21. package/dist/{physics-facts-tfQYyNTD.js → physics-facts-D-URIBrt.js} +8 -7
  22. package/dist/{placement-policy-DY_FNRDu.js → placement-policy-C6dV6Tf-.js} +161 -141
  23. package/dist/ports/persistence.d.ts +45 -1
  24. package/dist/project/contracts.d.ts +3 -0
  25. package/dist/remote-asset-resolver-D-UeyDMD.js +311 -0
  26. package/dist/{scene-graph-DBLKAhxa.js → scene-graph-DVOXjMmp.js} +2 -2
  27. package/dist/scene-session-PhoFXFCY.js +22006 -0
  28. package/dist/scene.js +2 -2
  29. package/dist/session-2bp8YOA4.js +963 -0
  30. package/dist/session-B3WbC7Y2.js +296 -0
  31. package/dist/session-B9kEf4xN.js +915 -0
  32. package/dist/session-DYThdzLZ.js +825 -0
  33. package/dist/studio/index.d.ts +5 -0
  34. package/dist/studio/indexeddb-persistence.d.ts +2 -0
  35. package/dist/studio/indexeddb-session-persistence.d.ts +11 -0
  36. package/dist/studio/scene-package-asset-sources.d.ts +14 -0
  37. package/dist/studio.js +1423 -1220
  38. package/dist/urdf-session-CRXL4bHf.js +1230 -0
  39. package/dist/usd-session-CTzInpNy.js +7385 -0
  40. package/dist/version.d.ts +1 -1
  41. package/dist/view/scene-session.d.ts +5 -1
  42. package/dist/wasm-module-DZn2AM1W.js +13 -0
  43. package/dist/xacro-IpPHTMYs.js +76 -0
  44. package/package.json +1 -1
  45. package/dist/asset-source-BExlEcRt.js +0 -444
  46. package/dist/assets/usd-export-worker-BsGubtAE.js +0 -1
  47. package/dist/editorial-BkAFWfbg.js +0 -83
  48. package/dist/export-evidence-B_0zRmb8.js +0 -5027
  49. package/dist/remote-asset-resolver-Cb8cfNmw.js +0 -136
  50. package/dist/scene-session-BV1HnxNh.js +0 -3506
@@ -0,0 +1,72 @@
1
+ import { k as v, s as E, b as z } from "./scene-session-PhoFXFCY.js";
2
+ import { Group as q, Euler as G, BoxGeometry as N, SphereGeometry as P, CylinderGeometry as $, CapsuleGeometry as I, PlaneGeometry as X, Mesh as j } from "three";
3
+ function D(f) {
4
+ const y = f.extension.documents, l = new q();
5
+ l.name = f.name;
6
+ try {
7
+ if (y.size !== 1) throw new Error("MJCF 独立预览暂不支持 include");
8
+ const u = [...y.values()][0];
9
+ if (u.querySelector("default, include, attach, replicate, composite, flexcomp, skin, hfield, plugin")) throw new Error("MJCF 独立预览包含尚不支持的继承、组合或扩展语义");
10
+ const a = u.querySelector("compiler");
11
+ if ((a == null ? void 0 : a.getAttribute("coordinate")) === "global" || a != null && a.hasAttribute("eulerseq")) throw new Error("MJCF 独立预览不支持此坐标设置");
12
+ const g = (a == null ? void 0 : a.getAttribute("angle")) === "radian" ? 1 : Math.PI / 180, b = (c, m) => {
13
+ const e = c ? c.trim().split(/\s+/).map(Number) : m;
14
+ if (e.some((s) => !Number.isFinite(s))) throw new Error("MJCF 视觉坐标无效");
15
+ return e;
16
+ }, h = (c, m, e) => {
17
+ const s = b(c, m);
18
+ if (s.length !== e) throw new Error(`MJCF 视觉变换需要 ${e} 个分量`);
19
+ return s;
20
+ }, M = (c, m) => {
21
+ for (const e of c.children) {
22
+ if (!["body", "geom"].includes(e.tagName)) continue;
23
+ if (["class", "childclass", "fromto", "axisangle", "xyaxes", "zaxis"].some((t) => e.hasAttribute(t))) throw new Error("MJCF 独立预览不支持此变换或默认类");
24
+ const s = new q();
25
+ if (s.name = e.getAttribute("name") ?? e.tagName, s.position.fromArray(h(e.getAttribute("pos"), [0, 0, 0], 3)), e.hasAttribute("quat")) {
26
+ const t = h(e.getAttribute("quat"), [1, 0, 0, 0], 4);
27
+ if (Math.hypot(...t) === 0) throw new Error("MJCF 视觉四元数不能为零");
28
+ s.quaternion.set(t[1], t[2], t[3], t[0]).normalize();
29
+ } else {
30
+ const t = h(e.getAttribute("euler"), [0, 0, 0], 3);
31
+ s.quaternion.setFromEuler(new G(t[0] * g, t[1] * g, t[2] * g, "XYZ"));
32
+ }
33
+ if (m.add(s), e.tagName === "body") {
34
+ M(e, s);
35
+ continue;
36
+ }
37
+ const n = e.getAttribute("type") ?? (e.hasAttribute("mesh") ? "mesh" : "sphere"), r = b(e.getAttribute("size"), []);
38
+ if (r.length === 0) throw new Error("MJCF 独立预览缺少可直接解析的几何或材质");
39
+ const F = { box: 3, sphere: 1, cylinder: 2, capsule: 2, plane: 3 }[n];
40
+ if (F && (r.length < F || r.some((t) => n === "plane" ? t < 0 : t <= 0)))
41
+ throw new Error(`MJCF geom ${n} 的尺寸缺失或无效`);
42
+ let i;
43
+ if (n === "box") i = new N(2 * r[0], 2 * r[1], 2 * r[2]);
44
+ else if (n === "sphere") i = new P(r[0]);
45
+ else if (n === "cylinder")
46
+ i = new $(r[0], r[0], 2 * r[1]), i.rotateX(Math.PI / 2);
47
+ else if (n === "capsule")
48
+ i = new I(r[0], 2 * r[1]), i.rotateX(Math.PI / 2);
49
+ else if (n === "plane") i = new X(2 * (r[0] || 5), 2 * (r[1] || 5));
50
+ else throw new Error(`MJCF 独立预览暂不支持 geom ${n}`);
51
+ const p = e.getAttribute("material"), o = [...u.querySelectorAll("asset > material")].find((t) => t.getAttribute("name") === p);
52
+ if (p && !o) throw new Error(`Undefined MJCF material: ${p}`);
53
+ if (o != null && o.hasAttribute("texture") || o != null && o.querySelector("layer")) throw new Error("MJCF textured preview requires the compiled material pipeline");
54
+ const x = h(e.getAttribute("rgba"), [0.5, 0.5, 0.5, 1], 4), J = o && x.every((t, d) => t === [0.5, 0.5, 0.5, 1][d]) ? h(o.getAttribute("rgba"), [1, 1, 1, 1], 4) : x, w = (t, d) => o != null && o.hasAttribute(t) ? b(o.getAttribute(t), [d])[0] : d, S = v({
55
+ color: J,
56
+ roughness: o ? E(w("roughness", -1), w("shininess", 0.5)) : E(),
57
+ metalness: Math.max(0, w("metallic", 0)),
58
+ specular: w("specular", 0.5),
59
+ emission: w("emission", 0)
60
+ }), C = new j(i, S);
61
+ n === "plane" && m === l && (C.userData.excludeFromSimulationFit = !0), s.add(C);
62
+ }
63
+ }, A = u.querySelector("worldbody");
64
+ if (!A) throw new Error("MJCF 缺少 worldbody");
65
+ return M(A, l), l.updateMatrixWorld(!0), l;
66
+ } catch (u) {
67
+ throw z(l), u;
68
+ }
69
+ }
70
+ export {
71
+ D as compileMjcfPreview
72
+ };
@@ -0,0 +1,467 @@
1
+ var S = Object.defineProperty;
2
+ var A = (u, t, e) => t in u ? S(u, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : u[t] = e;
3
+ var p = (u, t, e) => A(u, typeof t != "symbol" ? t + "" : t, e);
4
+ import L from "@mujoco/mujoco";
5
+ import { Quaternion as x, Vector3 as y } from "three";
6
+ import R from "@mujoco/mujoco/mujoco.wasm?url";
7
+ import { i as D } from "./wasm-module-DZn2AM1W.js";
8
+ function B(u) {
9
+ return u ? new URL("mujoco.wasm", u).href : R;
10
+ }
11
+ let C = 0;
12
+ function U(u, t) {
13
+ const e = `/viewer-simulation-${++C}`;
14
+ u.mkdir(e);
15
+ const i = /* @__PURE__ */ new Set([e]), s = /* @__PURE__ */ new Set(), n = (o, r) => {
16
+ const m = o.replaceAll("\\", "/").split("/");
17
+ if (m[0] === "" || m.some((_) => _ === ".." || _.includes(":"))) throw N(`Invalid package path: ${o}`, "E_SIMULATION_PATH");
18
+ const l = m.filter((_) => _ && _ !== ".");
19
+ if (!l.length) throw N("Package path is empty.", "E_SIMULATION_PATH");
20
+ let h = e;
21
+ for (const _ of l.slice(0, -1))
22
+ h += `/${_}`, i.has(h) || (u.mkdir(h), i.add(h));
23
+ const c = `${e}/${l.join("/")}`;
24
+ return u.writeFile(c, r), s.add(c), c;
25
+ }, a = () => {
26
+ for (const o of s) u.unlink(o);
27
+ s.clear();
28
+ for (const o of [...i].reverse()) u.rmdir(o);
29
+ i.clear();
30
+ };
31
+ try {
32
+ for (const [o, r] of t) n(o, r);
33
+ return { writeEntry: (o) => n("__viewer_entry.xml", o), dispose: a };
34
+ } catch (o) {
35
+ throw a(), o;
36
+ }
37
+ }
38
+ function N(u, t) {
39
+ return Object.assign(new Error(u), { code: t });
40
+ }
41
+ function z({
42
+ target: u,
43
+ point: t,
44
+ velocity: e,
45
+ stiffness: i,
46
+ damping: s,
47
+ maxForce: n,
48
+ strength: a
49
+ }) {
50
+ const o = [
51
+ i * (u[0] - t[0]) - s * e[0],
52
+ i * (u[1] - t[1]) - s * e[1],
53
+ i * (u[2] - t[2]) - s * e[2]
54
+ ], r = Math.hypot(o[0], o[1], o[2]), m = n * a;
55
+ if (r > m && r > 0) {
56
+ const l = m / r;
57
+ o[0] *= l, o[1] *= l, o[2] *= l;
58
+ }
59
+ return o;
60
+ }
61
+ const v = 1 / 240, V = 1 / 960, P = 0.25, $ = 0.05, k = 80, Y = 0.7, H = 60, Z = 1e-4, G = 10, J = 3.5, F = 14;
62
+ class et {
63
+ constructor() {
64
+ p(this, "mujoco", null);
65
+ p(this, "model", null);
66
+ p(this, "data", null);
67
+ p(this, "grab", null);
68
+ p(this, "lastGrabForce", [0, 0, 0]);
69
+ p(this, "initialControls", []);
70
+ p(this, "initialJoints", {});
71
+ p(this, "accumulator", 0);
72
+ p(this, "stepTotal", 0);
73
+ p(this, "timestep", v);
74
+ /** Timestep compiled from the physics asset; grabs may temporarily refine it. */
75
+ p(this, "baseTimestep", v);
76
+ /** Authored ground pose, captured before any seating. Re-seats start here. */
77
+ p(this, "initialGround", null);
78
+ /** Ground pose currently in the model; restored verbatim by reset(). */
79
+ p(this, "seatedGround", null);
80
+ p(this, "worldRotation", new x());
81
+ p(this, "topLevelBodies", []);
82
+ p(this, "initialVelocities", []);
83
+ }
84
+ async initialize(t, e = {}) {
85
+ var l;
86
+ const i = e.wasmModule ? await e.wasmModule : void 0;
87
+ this.mujoco ?? (this.mujoco = await L({
88
+ locateFile: (h) => h.endsWith(".wasm") ? B(e.baseUrl) : h,
89
+ ...i ? {
90
+ instantiateWasm(h, c) {
91
+ return D(i, h, c);
92
+ }
93
+ } : {}
94
+ }));
95
+ const s = U(this.mujoco.FS, t.files);
96
+ let n = null, a = null, o = null, r = null, m = v;
97
+ try {
98
+ if (n = this.mujoco.MjModel.from_xml_path(s.writeEntry(t.xml)), m = n.opt.timestep, !Number.isFinite(m) || m <= 0)
99
+ throw new Error(`Invalid MuJoCo timestep: ${m}`);
100
+ for (const c of t.massOverrides ?? []) {
101
+ const _ = this.mujoco.mj_name2id(n, this.mujoco.mjtObj.mjOBJ_BODY.value, c.body);
102
+ if (_ <= 0 || !Number.isFinite(c.mass) || c.mass <= 0 || !(n.body_mass[_] > 0)) throw new Error(`Invalid mass override: ${c.body}`);
103
+ const f = c.mass / n.body_mass[_];
104
+ n.body_mass[_] = c.mass;
105
+ for (let j = 0; j < 3; j++) n.body_inertia[_ * 3 + j] *= f;
106
+ }
107
+ a = new this.mujoco.MjData(n), (l = t.massOverrides) != null && l.length && this.mujoco.mj_setConst(n, a), this.applyCenterOfMassOverrides(n, t.centerOfMassOverrides), this.worldRotation.identity(), this.applyInitialJoints(n, a, t.initialJoints), this.applyInitialControls(a, t.initialControls), this.applyInitialVelocities(n, a, t.initialVelocities), this.mujoco.mj_forward(n, a);
108
+ const h = this.mujoco.mj_name2id(n, this.mujoco.mjtObj.mjOBJ_GEOM.value, "__viewer_default_ground__");
109
+ o = h < 0 ? null : { id: h, height: n.geom_pos[h * 3 + 2], sameFrame: n.geom_sameframe[h] }, r = this.seatDefaultGround(n, a);
110
+ } catch (h) {
111
+ throw a == null || a.delete(), n == null || n.delete(), M(h, "E_MUJOCO_INITIALIZE");
112
+ } finally {
113
+ s.dispose();
114
+ }
115
+ this.disposeModel(), this.model = n, this.data = a, this.initialControls = t.initialControls ?? [], this.initialJoints = t.initialJoints ?? {}, this.initialVelocities = t.initialVelocities ?? [], this.accumulator = 0, this.stepTotal = 0, this.baseTimestep = m, this.timestep = m, this.initialGround = o, this.seatedGround = r, this.topLevelBodies = this.captureTopLevelBodies(n);
116
+ }
117
+ get defaultGroundHeight() {
118
+ if (!this.mujoco || !this.model) return;
119
+ const t = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_GEOM.value, "__viewer_default_ground__");
120
+ return t < 0 ? void 0 : this.model.geom_pos[t * 3 + 2];
121
+ }
122
+ get stepCount() {
123
+ return this.stepTotal;
124
+ }
125
+ /** Pin the viewer-owned floor to a world-frame height, overriding auto-seating. */
126
+ setDefaultGroundHeight(t) {
127
+ if (!Number.isFinite(t) || !this.mujoco || !this.model || !this.data) return !1;
128
+ const e = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_GEOM.value, "__viewer_default_ground__");
129
+ return e < 0 || this.model.geom_bodyid[e] !== 0 || this.model.geom_type[e] !== this.mujoco.mjtGeom.mjGEOM_PLANE.value ? !1 : (this.model.geom_pos[e * 3 + 2] = t, this.model.geom_sameframe[e] = 0, this.seatedGround = { id: e, height: t, sameFrame: 0 }, this.mujoco.mj_forward(this.model, this.data), !0);
130
+ }
131
+ /**
132
+ * Re-orients the compiled physics to the given authored up axis by rotating
133
+ * every top-level body about the world origin. Gravity stays -Z and the
134
+ * viewer ground stays the authored horizontal plane, so a cup that was
135
+ * standing now genuinely topples and settles on its side — the alternative,
136
+ * rotating only the rendered scene graph, would leave the visuals and the
137
+ * simulation in different frames.
138
+ *
139
+ * The full current state (free-joint positions, orientations and velocities)
140
+ * is rotated by the same delta, so a paused or running simulation is carried
141
+ * over instead of being re-seeded.
142
+ */
143
+ setWorldRotation(t) {
144
+ var n;
145
+ if (!this.mujoco || !this.model || !this.data) return;
146
+ const e = this.model, i = this.data;
147
+ if (t.equals(this.worldRotation)) return;
148
+ const s = t.clone().multiply(this.worldRotation.clone().invert());
149
+ this.rotateReferenceFrames(this.topLevelBodies, t), this.rotateState(this.topLevelBodies, e, i, s), this.worldRotation.copy(t), this.mujoco.mj_forward(e, i), this.seatedGround = this.seatDefaultGround(e, i, (n = this.initialGround) == null ? void 0 : n.height), this.accumulator = 0;
150
+ }
151
+ captureTopLevelBodies(t) {
152
+ const e = this.mujoco, i = [];
153
+ for (let s = 1; s < t.nbody; s++) {
154
+ if (t.body_parentid[s] !== 0) continue;
155
+ const n = t.body_jntadr[s], a = t.body_jntnum[s] === 1 && n >= 0 && t.jnt_type[n] === e.mjtJoint.mjJNT_FREE.value ? n : -1, o = s * 3, r = s * 4;
156
+ i.push({
157
+ id: s,
158
+ position: new y(t.body_pos[o], t.body_pos[o + 1], t.body_pos[o + 2]),
159
+ quaternion: new x(t.body_quat[r + 1], t.body_quat[r + 2], t.body_quat[r + 3], t.body_quat[r]),
160
+ freeJoint: a
161
+ });
162
+ }
163
+ return i;
164
+ }
165
+ /** Writes the rotated reference pose, which reset() and fixed bases follow. */
166
+ rotateReferenceFrames(t, e) {
167
+ const i = this.model;
168
+ for (const s of t) {
169
+ const n = s.position.clone().applyQuaternion(e), a = e.clone().multiply(s.quaternion), o = s.id * 3, r = s.id * 4;
170
+ if (i.body_pos[o] = n.x, i.body_pos[o + 1] = n.y, i.body_pos[o + 2] = n.z, i.body_quat[r] = a.w, i.body_quat[r + 1] = a.x, i.body_quat[r + 2] = a.y, i.body_quat[r + 3] = a.z, i.body_sameframe[s.id] && (i.body_sameframe[s.id] = 0), s.freeJoint < 0) continue;
171
+ const m = i.jnt_qposadr[s.freeJoint];
172
+ i.qpos0[m] = n.x, i.qpos0[m + 1] = n.y, i.qpos0[m + 2] = n.z, i.qpos0[m + 3] = a.w, i.qpos0[m + 4] = a.x, i.qpos0[m + 5] = a.y, i.qpos0[m + 6] = a.z;
173
+ }
174
+ }
175
+ /** Rotates the live free-joint state so the simulation keeps its progress. */
176
+ rotateState(t, e, i, s) {
177
+ for (const n of t) {
178
+ if (n.freeJoint < 0) continue;
179
+ const a = e.jnt_qposadr[n.freeJoint], o = e.jnt_dofadr[n.freeJoint], r = new y(i.qpos[a], i.qpos[a + 1], i.qpos[a + 2]).applyQuaternion(s);
180
+ i.qpos[a] = r.x, i.qpos[a + 1] = r.y, i.qpos[a + 2] = r.z;
181
+ const m = new x(i.qpos[a + 4], i.qpos[a + 5], i.qpos[a + 6], i.qpos[a + 3]).premultiply(s);
182
+ i.qpos[a + 3] = m.w, i.qpos[a + 4] = m.x, i.qpos[a + 5] = m.y, i.qpos[a + 6] = m.z;
183
+ const l = new y(i.qvel[o], i.qvel[o + 1], i.qvel[o + 2]).applyQuaternion(s);
184
+ i.qvel[o] = l.x, i.qvel[o + 1] = l.y, i.qvel[o + 2] = l.z;
185
+ const h = new y(i.qvel[o + 3], i.qvel[o + 4], i.qvel[o + 5]).applyQuaternion(s);
186
+ i.qvel[o + 3] = h.x, i.qvel[o + 4] = h.y, i.qvel[o + 5] = h.z;
187
+ }
188
+ }
189
+ /** Lower only the viewer-owned plane, never authored bodies or authored floors.
190
+ * Run after forward kinematics, not during stepping (the floor must not follow falling bodies).
191
+ * `baseHeight` re-seats from a stable reference; omitting it lowers from the current pose.
192
+ */
193
+ seatDefaultGround(t, e, i) {
194
+ const s = this.mujoco, n = s.mj_name2id(t, s.mjtObj.mjOBJ_GEOM.value, "__viewer_default_ground__");
195
+ if (n < 0 || t.geom_bodyid[n] !== 0 || t.geom_type[n] !== s.mjtGeom.mjGEOM_PLANE.value) return null;
196
+ let a = i ?? t.geom_pos[n * 3 + 2];
197
+ for (let o = 0; o < t.ngeom; o++) {
198
+ if (o === n || t.geom_type[o] === s.mjtGeom.mjGEOM_PLANE.value || !(t.geom_contype[o] & t.geom_conaffinity[n]) && !(t.geom_conaffinity[o] & t.geom_contype[n])) continue;
199
+ const r = this.geomBottom(t, e, o), m = Math.max(1e-3, t.geom_margin[o] + t.geom_margin[n]);
200
+ Number.isFinite(r) && r < a && (a = Math.min(a, r - m));
201
+ }
202
+ return a !== t.geom_pos[n * 3 + 2] && (t.geom_pos[n * 3 + 2] = a, t.geom_sameframe[n] = 0, s.mj_forward(t, e)), { id: n, height: a, sameFrame: t.geom_sameframe[n] };
203
+ }
204
+ /**
205
+ * Resolve the lowest world-space point directly from MuJoCo's primitive
206
+ * parameters. Rotating a mesh's local AABB into world space is conservative:
207
+ * for a long, rotated shape it can sit far below the actual geometry. Use the
208
+ * compiled vertices for mesh-backed geoms so the ground reflects the real
209
+ * lowest point rather than the corners of its local bounding box.
210
+ */
211
+ geomBottom(t, e, i) {
212
+ const s = this.mujoco, n = e.geom_xpos[i * 3 + 2], a = i * 3, o = i * 9, r = t.geom_type[i], m = Math.abs(t.geom_size[a]), l = Math.abs(t.geom_size[a + 1]), h = Math.abs(t.geom_size[a + 2]);
213
+ if (r === s.mjtGeom.mjGEOM_SPHERE.value)
214
+ return n - m;
215
+ if (r === s.mjtGeom.mjGEOM_CAPSULE.value)
216
+ return n - m - Math.abs(e.geom_xmat[o + 8]) * l;
217
+ if (r === s.mjtGeom.mjGEOM_CYLINDER.value) {
218
+ const d = e.geom_xmat[o + 8];
219
+ return n - Math.abs(d) * l - Math.sqrt(Math.max(0, 1 - d * d)) * m;
220
+ }
221
+ if (r === s.mjtGeom.mjGEOM_ELLIPSOID.value)
222
+ return n - Math.hypot(
223
+ e.geom_xmat[o + 2] * m,
224
+ e.geom_xmat[o + 5] * l,
225
+ e.geom_xmat[o + 8] * h
226
+ );
227
+ if (r === s.mjtGeom.mjGEOM_BOX.value)
228
+ return n - Math.abs(e.geom_xmat[o + 2]) * m - Math.abs(e.geom_xmat[o + 5]) * l - Math.abs(e.geom_xmat[o + 8]) * h;
229
+ if (r === s.mjtGeom.mjGEOM_MESH.value || r === s.mjtGeom.mjGEOM_SDF.value) {
230
+ const d = t.geom_dataid[i];
231
+ if (d < 0 || d >= t.nmesh) return Number.POSITIVE_INFINITY;
232
+ const E = t.mesh_vertadr[d], T = t.mesh_vertnum[d];
233
+ if (!Number.isInteger(E) || !Number.isInteger(T) || E < 0 || T <= 0 || E + T > t.nmeshvert)
234
+ return Number.POSITIVE_INFINITY;
235
+ let I = Number.POSITIVE_INFINITY;
236
+ for (let O = E; O < E + T; O++) {
237
+ const w = O * 3, q = n + e.geom_xmat[o + 6] * t.mesh_vert[w] + e.geom_xmat[o + 7] * t.mesh_vert[w + 1] + e.geom_xmat[o + 8] * t.mesh_vert[w + 2];
238
+ Number.isFinite(q) && q < I && (I = q);
239
+ }
240
+ return I;
241
+ }
242
+ const c = i * 6, _ = t.geom_aabb[c + 3], f = t.geom_aabb[c + 4], j = t.geom_aabb[c + 5];
243
+ if (![_, f, j].every((d) => Number.isFinite(d) && d >= 0))
244
+ return Number.POSITIVE_INFINITY;
245
+ const b = n + e.geom_xmat[o + 6] * t.geom_aabb[c] + e.geom_xmat[o + 7] * t.geom_aabb[c + 1] + e.geom_xmat[o + 8] * t.geom_aabb[c + 2], g = Math.abs(e.geom_xmat[o + 6]) * _ + Math.abs(e.geom_xmat[o + 7]) * f + Math.abs(e.geom_xmat[o + 8]) * j;
246
+ return b - g;
247
+ }
248
+ beginGrab({
249
+ bodyId: t,
250
+ localPoint: e,
251
+ target: i,
252
+ stiffness: s,
253
+ damping: n,
254
+ maxForce: a,
255
+ dampingRatio: o = Y,
256
+ maxTargetSpeed: r = J,
257
+ targetResponse: m = F
258
+ }) {
259
+ var j, b, g;
260
+ const l = Math.max(((j = this.model) == null ? void 0 : j.body_mass[t]) ?? 1, 1e-6);
261
+ if ((b = this.data) != null && b.body_awake && (this.data.body_awake[t] = 1), (g = this.data) != null && g.tree_awake && this.model) {
262
+ const d = this.model.body_rootid[t] ?? t;
263
+ this.data.tree_awake[d] = 1;
264
+ }
265
+ const h = s ?? k, c = n ?? 2 * Math.sqrt(h * l) * o, _ = a ?? Math.max(Z, l * H);
266
+ this.setTimestep(this.grabTimestep(t, e, l, h));
267
+ const f = [i[0], i[1], i[2]];
268
+ this.grab = {
269
+ bodyId: t,
270
+ localPoint: [e[0], e[1], e[2]],
271
+ target: [...f],
272
+ requestedTarget: f,
273
+ stiffness: h,
274
+ damping: c,
275
+ maxForce: _,
276
+ strength: 1,
277
+ maxTargetSpeed: r,
278
+ targetResponse: m
279
+ };
280
+ }
281
+ updateGrabTarget(t) {
282
+ this.grab && (this.grab.requestedTarget = [t[0], t[1], t[2]]);
283
+ }
284
+ updateGrabStrength(t) {
285
+ this.grab && (this.grab.strength = t);
286
+ }
287
+ applyGrabForce() {
288
+ if (!this.grab || !this.model || !this.data || !this.mujoco) return;
289
+ const { bodyId: t, localPoint: e, target: i, stiffness: s, damping: n, maxForce: a, strength: o } = this.grab, r = this.data.xmat.subarray(t * 9, t * 9 + 9), m = this.data.xpos.subarray(t * 3, t * 3 + 3), l = [
290
+ m[0] + r[0] * e[0] + r[1] * e[1] + r[2] * e[2],
291
+ m[1] + r[3] * e[0] + r[4] * e[1] + r[5] * e[2],
292
+ m[2] + r[6] * e[0] + r[7] * e[1] + r[8] * e[2]
293
+ ], h = this.data.cvel.subarray(t * 6, t * 6 + 6), c = this.data.xipos.subarray(t * 3, t * 3 + 3), _ = [
294
+ l[0] - c[0],
295
+ l[1] - c[1],
296
+ l[2] - c[2]
297
+ ], f = [
298
+ h[3] + h[1] * _[2] - h[2] * _[1],
299
+ h[4] + h[2] * _[0] - h[0] * _[2],
300
+ h[5] + h[0] * _[1] - h[1] * _[0]
301
+ ], j = z({ target: i, point: l, velocity: f, stiffness: s, damping: n, maxForce: a, strength: o });
302
+ this.lastGrabForce = [...j], this.data.qfrc_applied.fill(0);
303
+ const b = Math.min(
304
+ Math.max(this.model.body_inertia[t * 3], 1e-9),
305
+ Math.max(this.model.body_inertia[t * 3 + 1], 1e-9),
306
+ Math.max(this.model.body_inertia[t * 3 + 2], 1e-9)
307
+ ), g = [
308
+ -b * G * h[0],
309
+ -b * G * h[1],
310
+ -b * G * h[2]
311
+ ];
312
+ this.mujoco.mj_applyFT(
313
+ this.model,
314
+ this.data,
315
+ j,
316
+ g,
317
+ l,
318
+ t,
319
+ this.data.qfrc_applied
320
+ );
321
+ }
322
+ endGrab() {
323
+ this.data && this.data.qfrc_applied.fill(0), this.lastGrabForce = [0, 0, 0], this.grab = null, this.setTimestep(this.baseTimestep);
324
+ }
325
+ step(t) {
326
+ if (!this.mujoco || !this.model || !this.data || t <= 0) return !1;
327
+ this.accumulator += Math.min(t, $);
328
+ let e = !1;
329
+ for (; this.accumulator >= this.timestep; )
330
+ this.updateGrabTargetForStep(), this.applyGrabForce(), this.mujoco.mj_step(this.model, this.data), this.stepTotal += 1, this.accumulator -= this.timestep, e = !0;
331
+ return e;
332
+ }
333
+ updateGrabTargetForStep() {
334
+ const t = this.grab;
335
+ if (!t) return;
336
+ const e = t.requestedTarget ?? t.target, i = (t.maxTargetSpeed ?? J) * Math.max(1, Math.sqrt(t.strength)), s = t.targetResponse ?? F, n = 1 - Math.exp(-s * this.timestep), a = i * this.timestep;
337
+ for (let o = 0; o < 3; o++) {
338
+ const r = e[o] - t.target[o], m = Math.sign(r) * Math.min(Math.abs(r) * n, a);
339
+ t.target[o] += m;
340
+ }
341
+ }
342
+ setJointValues(t) {
343
+ if (!(!this.mujoco || !this.model || !this.data)) {
344
+ for (const [e, i] of Object.entries(t)) {
345
+ const s = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_JOINT.value, e);
346
+ if (s < 0 || !Number.isFinite(i)) continue;
347
+ const n = this.model.jnt_type[s], a = this.mujoco.mjtJoint.mjJNT_HINGE.value, o = this.mujoco.mjtJoint.mjJNT_SLIDE.value;
348
+ n !== a && n !== o || (this.data.qpos[this.model.jnt_qposadr[s]] = i);
349
+ }
350
+ this.mujoco.mj_forward(this.model, this.data), this.seatDefaultGround(this.model, this.data), this.accumulator = 0;
351
+ }
352
+ }
353
+ getJointValues(t) {
354
+ const e = {};
355
+ if (!this.mujoco || !this.model || !this.data) return e;
356
+ for (const i of t) {
357
+ const s = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_JOINT.value, i);
358
+ if (s < 0) continue;
359
+ const n = this.model.jnt_type[s], a = this.mujoco.mjtJoint.mjJNT_HINGE.value, o = this.mujoco.mjtJoint.mjJNT_SLIDE.value;
360
+ (n === a || n === o) && (e[i] = this.data.qpos[this.model.jnt_qposadr[s]]);
361
+ }
362
+ return e;
363
+ }
364
+ reset() {
365
+ if (!(!this.mujoco || !this.model || !this.data)) {
366
+ if (this.endGrab(), this.seatedGround) {
367
+ const { id: t, height: e, sameFrame: i } = this.seatedGround;
368
+ this.model.geom_pos[t * 3 + 2] = e, this.model.geom_sameframe[t] = i;
369
+ }
370
+ this.mujoco.mj_resetData(this.model, this.data), this.applyInitialJoints(this.model, this.data, this.initialJoints), this.applyInitialControls(this.data, this.initialControls), this.applyInitialVelocities(this.model, this.data, this.initialVelocities), this.mujoco.mj_forward(this.model, this.data), this.accumulator = 0, this.stepTotal = 0;
371
+ }
372
+ }
373
+ /**
374
+ * Runs an exact number of fixed-size steps for a deterministic probe. The
375
+ * compiled timestep is restored afterwards so the interactive runtime keeps
376
+ * its authored cadence.
377
+ */
378
+ advanceFixed(t, e) {
379
+ if (!this.mujoco || !this.model || !this.data || !Number.isFinite(t) || t <= 0 || !Number.isInteger(e) || e <= 0) return !1;
380
+ const i = this.timestep;
381
+ try {
382
+ this.setTimestep(t);
383
+ for (let s = 0; s < e; s += 1)
384
+ this.mujoco.mj_step(this.model, this.data), this.stepTotal += 1;
385
+ return this.accumulator = 0, !0;
386
+ } finally {
387
+ this.setTimestep(this.grab ? i : this.baseTimestep);
388
+ }
389
+ }
390
+ dispose() {
391
+ this.disposeModel(), this.mujoco = null;
392
+ }
393
+ applyInitialControls(t, e) {
394
+ if (e != null && e.length) {
395
+ if (e.length !== t.ctrl.length) throw M(new Error(`Initial control count ${e.length} does not match MuJoCo actuator count ${t.ctrl.length}.`), "E_MUJOCO_INITIALIZE");
396
+ t.ctrl.set(e);
397
+ }
398
+ }
399
+ applyCenterOfMassOverrides(t, e) {
400
+ for (const i of e ?? []) {
401
+ const s = this.mujoco.mj_name2id(
402
+ t,
403
+ this.mujoco.mjtObj.mjOBJ_BODY.value,
404
+ i.body
405
+ );
406
+ if (s <= 0 || i.position.length !== 3 || !i.position.every(Number.isFinite))
407
+ throw M(
408
+ new Error(`Invalid center-of-mass override: ${i.body}`),
409
+ "E_MUJOCO_INITIALIZE"
410
+ );
411
+ t.body_ipos.set(i.position, s * 3);
412
+ }
413
+ }
414
+ /**
415
+ * A point force on a light body can excite a much higher rotational
416
+ * frequency than its translational mass suggests. Refine physics only while
417
+ * that body is grabbed instead of adding global damping to hide the error.
418
+ */
419
+ grabTimestep(t, e, i, s) {
420
+ if (!this.model || !this.data) return v;
421
+ const n = Math.min(
422
+ Math.max(this.model.body_inertia[t * 3], 1e-9),
423
+ Math.max(this.model.body_inertia[t * 3 + 1], 1e-9),
424
+ Math.max(this.model.body_inertia[t * 3 + 2], 1e-9)
425
+ ), a = this.data.xpos.subarray(t * 3, t * 3 + 3), o = this.data.xipos.subarray(t * 3, t * 3 + 3), r = this.data.xmat.subarray(t * 9, t * 9 + 9), m = [
426
+ a[0] + r[0] * e[0] + r[1] * e[1] + r[2] * e[2],
427
+ a[1] + r[3] * e[0] + r[4] * e[1] + r[5] * e[2],
428
+ a[2] + r[6] * e[0] + r[7] * e[1] + r[8] * e[2]
429
+ ], l = (m[0] - o[0]) ** 2 + (m[1] - o[1]) ** 2 + (m[2] - o[2]) ** 2, h = Math.sqrt(s * (1 / i + l / n)), c = P / Math.max(h, 1e-9);
430
+ return Math.min(this.baseTimestep, Math.max(V, c));
431
+ }
432
+ setTimestep(t) {
433
+ var e;
434
+ this.timestep = t, (e = this.model) != null && e.opt && (this.model.opt.timestep = t);
435
+ }
436
+ applyInitialJoints(t, e, i = {}) {
437
+ const s = this.mujoco;
438
+ for (const [n, a] of Object.entries(i)) {
439
+ const o = s.mj_name2id(t, s.mjtObj.mjOBJ_JOINT.value, n);
440
+ if (o < 0 || !Number.isFinite(a) || ![s.mjtJoint.mjJNT_HINGE.value, s.mjtJoint.mjJNT_SLIDE.value].includes(t.jnt_type[o])) throw M(new Error("Initial pose requires a known scalar joint: " + n), "E_INITIAL_POSE_JOINT_INVALID");
441
+ e.qpos[t.jnt_qposadr[o]] = a;
442
+ }
443
+ }
444
+ applyInitialVelocities(t, e, i) {
445
+ for (const s of i ?? []) {
446
+ if (s.velocity.length !== 6 || !s.velocity.every(Number.isFinite))
447
+ throw M(new Error(`Invalid free-body initial velocity: ${s.body}`), "E_MUJOCO_INITIALIZE");
448
+ if (s.velocity.every((l) => Math.abs(l) <= 1e-12)) continue;
449
+ const n = this.mujoco.mj_name2id(t, this.mujoco.mjtObj.mjOBJ_BODY.value, s.body), a = n >= 0 ? t.body_jntadr[n] : -1;
450
+ if (a < 0 || t.jnt_type[a] !== this.mujoco.mjtJoint.mjJNT_FREE.value)
451
+ throw M(new Error(`Invalid free-body initial velocity: ${s.body}`), "E_MUJOCO_INITIALIZE");
452
+ const { worldRotation: o } = this, r = new y(s.velocity[0], s.velocity[1], s.velocity[2]).applyQuaternion(o), m = new y(s.velocity[3], s.velocity[4], s.velocity[5]).applyQuaternion(o);
453
+ e.qvel.set([r.x, r.y, r.z, m.x, m.y, m.z], t.jnt_dofadr[a]);
454
+ }
455
+ }
456
+ disposeModel() {
457
+ var t, e;
458
+ this.endGrab(), (t = this.data) == null || t.delete(), (e = this.model) == null || e.delete(), this.data = null, this.model = null, this.initialGround = null, this.seatedGround = null, this.topLevelBodies = [], this.initialControls = [], this.initialJoints = {}, this.initialVelocities = [], this.accumulator = 0, this.stepTotal = 0, this.baseTimestep = v, this.timestep = v;
459
+ }
460
+ }
461
+ function M(u, t) {
462
+ const e = u instanceof Error ? u : new Error(String(u));
463
+ return Object.assign(e, { code: t });
464
+ }
465
+ export {
466
+ et as MujocoRuntime
467
+ };
@@ -4,17 +4,19 @@
4
4
  * implement the same boundaries as a remote asset platform.
5
5
  */
6
6
  import { type ContentAddressedResource } from './content-addressed';
7
- import type { StudioStateSnapshot } from './snapshot';
7
+ import type { StudioSessionSnapshot, StudioStateSnapshot } from './snapshot';
8
8
  import type { StudioAssetResourceLocator } from '../doc/schema';
9
9
  export interface IndexedDbStudioStoreOptions {
10
10
  readonly dbName?: string;
11
11
  readonly indexedDB?: IDBFactory;
12
12
  }
13
13
  export declare const INDEXED_DB_STUDIO_NAME = "sim-studio.indexeddb";
14
- export declare const INDEXED_DB_STUDIO_VERSION = 3;
14
+ export declare const INDEXED_DB_STUDIO_VERSION = 4;
15
15
  export declare const INDEXED_DB_DOCUMENT_STORE = "documents";
16
16
  export declare const INDEXED_DB_RESOURCE_STORE = "resources";
17
17
  export declare const INDEXED_DB_SOURCE_STORE = "asset-sources";
18
+ export declare const INDEXED_DB_SESSION_STORE = "sessions";
19
+ declare const SESSION_FORMAT = "sim-studio.indexeddb-session@1";
18
20
  export declare const INDEXED_DB_STORE_ERROR: {
19
21
  readonly unavailable: "INDEXED_DB_STORE_UNAVAILABLE";
20
22
  readonly openFailed: "INDEXED_DB_STORE_OPEN_FAILED";
@@ -28,6 +30,21 @@ export declare class IndexedDbStoreError extends Error {
28
30
  readonly cause?: unknown;
29
31
  constructor(code: string, message: string, cause?: unknown);
30
32
  }
33
+ export interface IndexedDbSessionRecord {
34
+ readonly format: typeof SESSION_FORMAT;
35
+ readonly schemaVersion: 1;
36
+ readonly snapshot: StudioSessionSnapshot;
37
+ readonly revision: string;
38
+ readonly etag: string;
39
+ readonly savedAt: string;
40
+ }
41
+ export type IndexedDbSessionCommitResult = {
42
+ readonly status: 'saved';
43
+ readonly record: IndexedDbSessionRecord;
44
+ } | {
45
+ readonly status: 'conflict';
46
+ readonly current: IndexedDbSessionRecord;
47
+ };
31
48
  export interface IndexedDbAssetSourceFile {
32
49
  readonly locator: StudioAssetResourceLocator;
33
50
  readonly mediaType?: string;
@@ -59,6 +76,8 @@ export declare class IndexedDbStudioStore {
59
76
  constructor(options?: IndexedDbStudioStoreOptions);
60
77
  load(): Promise<StudioStateSnapshot | null>;
61
78
  save(snapshot: StudioStateSnapshot): Promise<void>;
79
+ loadSessionRecord(): Promise<IndexedDbSessionRecord | null>;
80
+ commitSessionRecord(record: IndexedDbSessionRecord, expectedRevision: string | null): Promise<IndexedDbSessionCommitResult>;
62
81
  loadResources(hashes: readonly string[]): Promise<readonly ContentAddressedResource[]>;
63
82
  saveResources(resources: readonly ContentAddressedResource[]): Promise<void>;
64
83
  loadAssetSource(revisionId: string): Promise<IndexedDbAssetSourceRecord | null>;
@@ -67,3 +86,4 @@ export declare class IndexedDbStudioStore {
67
86
  close(): void;
68
87
  private open;
69
88
  }
89
+ export {};
@@ -0,0 +1,22 @@
1
+ import type { AssetCatalogV3, ResourceManifestV2 } from '../project/contracts';
2
+ import type { StudioAssetClosureRef, StudioSessionSnapshot } from './snapshot';
3
+ export declare const STUDIO_SESSION_ERROR: {
4
+ readonly invalidSnapshot: "STUDIO_SESSION_INVALID_SNAPSHOT";
5
+ readonly documentHashMismatch: "STUDIO_SESSION_DOCUMENT_HASH_MISMATCH";
6
+ readonly unsupportedFormat: "STUDIO_SESSION_UNSUPPORTED_FORMAT";
7
+ };
8
+ export declare class StudioSessionSnapshotError extends Error {
9
+ readonly code: string;
10
+ constructor(code: string, message: string);
11
+ }
12
+ /**
13
+ * Validates the document and editorial halves as one recoverable session.
14
+ * Adapters should call this before persisting and after loading untrusted data.
15
+ */
16
+ export declare function assertStudioSessionSnapshot(snapshot: StudioSessionSnapshot): void;
17
+ export declare function studioSessionSnapshotDigest(snapshot: StudioSessionSnapshot): string;
18
+ export declare function createStudioAssetClosureRef(input: {
19
+ readonly closureId: string;
20
+ readonly assetCatalog: AssetCatalogV3;
21
+ readonly resourceManifest: ResourceManifestV2;
22
+ }): StudioAssetClosureRef;
@@ -1,5 +1,29 @@
1
+ import type { EditorialStateV1 } from '../project/contracts';
2
+ export declare const STUDIO_SESSION_SNAPSHOT_FORMAT: "sim-studio.session@1";
1
3
  /** Scene state shared by browser-local and remote persistence adapters. */
2
4
  export interface StudioStateSnapshot {
3
5
  readonly documentText: string;
4
6
  readonly documentHash: string;
5
7
  }
8
+ /**
9
+ * Stable reference to an immutable asset catalog/resource closure.
10
+ * Resource bytes and source-provider state stay outside the scene snapshot.
11
+ */
12
+ export interface StudioAssetClosureRef {
13
+ readonly closureId: string;
14
+ readonly catalogDigest: string;
15
+ readonly manifestDigest: string;
16
+ }
17
+ /**
18
+ * Complete editor recovery state. The document must be opened before the
19
+ * editorial state is applied because selection and node states reference the
20
+ * document graph.
21
+ */
22
+ export interface StudioSessionSnapshot {
23
+ readonly format: typeof STUDIO_SESSION_SNAPSHOT_FORMAT;
24
+ readonly schemaVersion: 1;
25
+ readonly documentText: string;
26
+ readonly documentHash: string;
27
+ readonly editorial: EditorialStateV1;
28
+ readonly assetClosure: StudioAssetClosureRef | null;
29
+ }