@call-me-sensei/angelo 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.
@@ -0,0 +1,176 @@
1
+ // SPDX-FileCopyrightText: 2026 Hyperbond Studio Pte. Ltd.
2
+ // SPDX-License-Identifier: MIT
3
+ //
4
+ // What the SDK changed in one tracked copy since the asset was last as saved, so stopping puts back exactly that, in
5
+ // place, without reloading anything. Before the SDK first changes an object it records how the object was; objects
6
+ // it made are listed to be removed. Restoring touches nothing else: the developer's camera, physics, mixers and
7
+ // everything they added stay as they are.
8
+
9
+ import { Matrix4 } from "three";
10
+
11
+ const LEAF_FIELDS = ["intensity", "distance", "decay", "angle", "penumbra", "width", "height", "fov", "near", "far",
12
+ "zoom", "left", "right", "top", "bottom"];
13
+
14
+ // What "leaf" covers: a light's or camera's settings, morph influences, an instanced mesh's per-instance data.
15
+ function leafState(object) {
16
+ return {
17
+ fields: Object.fromEntries(LEAF_FIELDS.filter((field) => typeof object[field] === "number")
18
+ .map((field) => [field, object[field]])),
19
+ color: object.isLight ? object.color?.clone() : undefined,
20
+ target: object.target?.position?.clone(),
21
+ influences: object.morphTargetInfluences?.slice(),
22
+ instanceMatrix: object.isInstancedMesh ? object.instanceMatrix.array.slice() : undefined,
23
+ instanceColor: object.isInstancedMesh ? object.instanceColor : undefined,
24
+ };
25
+ }
26
+
27
+ function restoreLeaf(object, leaf) {
28
+ Object.assign(object, leaf.fields);
29
+ if (leaf.color) object.color.copy(leaf.color);
30
+ if (leaf.target && object.target) object.target.position.copy(leaf.target);
31
+ if (leaf.influences && object.morphTargetInfluences) {
32
+ object.morphTargetInfluences.splice(0, object.morphTargetInfluences.length, ...leaf.influences);
33
+ }
34
+ if (leaf.instanceMatrix) {
35
+ object.instanceMatrix.array.set(leaf.instanceMatrix);
36
+ object.instanceMatrix.needsUpdate = true;
37
+ object.instanceColor = leaf.instanceColor;
38
+ }
39
+ object.updateProjectionMatrix?.();
40
+ }
41
+
42
+ function snapshot(object, copy, owner) {
43
+ const info = copy.nodes.get(object);
44
+ return {
45
+ parent: object.parent,
46
+ index: object.parent ? object.parent.children.indexOf(object) : -1,
47
+ name: object.name,
48
+ hasUserName: "name" in object.userData,
49
+ userName: object.userData.name,
50
+ position: object.position.clone(),
51
+ quaternion: object.quaternion.clone(),
52
+ scale: object.scale.clone(),
53
+ geometry: object.geometry,
54
+ material: object.material,
55
+ skeleton: object.skeleton,
56
+ boneInverses: object.skeleton?.boneInverses.map((matrix) => matrix.clone()),
57
+ bindMatrix: object.bindMatrix?.clone(),
58
+ bindMode: object.bindMode,
59
+ info: info ? { uid: info.uid, content: { primitives: [...info.content.primitives], camera: info.content.camera,
60
+ light: info.content.light } } : null,
61
+ leaf: leafState(object),
62
+ owner: owner.save(object),
63
+ aspects: new Set(),
64
+ };
65
+ }
66
+
67
+ export const ASPECTS = ["transform", "name", "geometry", "material", "skin", "leaf", "parent", "node"];
68
+
69
+ export class Journal {
70
+ /** @param {{save(object): any, load(object, saved): void}} owner The matcher's own per-object records. */
71
+ constructor(owner) {
72
+ this.owner = owner;
73
+ this.before = new Map(); // Object3D -> how it was
74
+ this.made = new Set(); // Objects the SDK added
75
+ }
76
+
77
+ get empty() {
78
+ return this.before.size === 0 && this.made.size === 0;
79
+ }
80
+
81
+ /** Call before the SDK changes `aspect` (one of ASPECTS) of `object`. */
82
+ touch(object, copy, aspect) {
83
+ if (this.made.has(object)) return;
84
+ let state = this.before.get(object);
85
+ if (!state) {
86
+ state = snapshot(object, copy, this.owner);
87
+ this.before.set(object, state);
88
+ }
89
+ state.aspects.add(aspect);
90
+ }
91
+
92
+ added(object) {
93
+ this.made.add(object);
94
+ }
95
+
96
+ /** The asset is as saved now (a save was shown): forget what came before. */
97
+ reset() {
98
+ this.before.clear();
99
+ this.made.clear();
100
+ }
101
+
102
+ /** What the recorded state still refers to, so it is not disposed while it may come back. */
103
+ resources() {
104
+ const found = [];
105
+ for (const state of this.before.values()) {
106
+ if (state.aspects.has("geometry")) found.push(state.geometry);
107
+ if (state.aspects.has("material")) found.push(state.material);
108
+ if (state.aspects.has("skin")) found.push(state.skeleton);
109
+ }
110
+ return found.filter(Boolean);
111
+ }
112
+
113
+ /** Put the copy back as it was at the last reset. */
114
+ restore(copy) {
115
+ // Objects the SDK made go; anything else under them goes to the nearest object that stays.
116
+ for (const object of this.made) {
117
+ for (const child of [...object.children]) {
118
+ if (this.made.has(child) || this.before.has(child)) continue;
119
+ let target = object.parent;
120
+ while (target && this.made.has(target)) target = target.parent;
121
+ (target ?? copy.root).attach(child);
122
+ }
123
+ }
124
+ for (const object of this.made) {
125
+ object.removeFromParent();
126
+ copy.nodes.delete(object);
127
+ }
128
+ const entries = [...this.before].sort((a, b) => a[1].index - b[1].index);
129
+ for (const [object, state] of entries) {
130
+ const has = (aspect) => state.aspects.has(aspect);
131
+ if (has("name")) {
132
+ object.name = state.name;
133
+ if (state.hasUserName) object.userData.name = state.userName;
134
+ else delete object.userData.name;
135
+ }
136
+ if (has("transform")) {
137
+ object.position.copy(state.position);
138
+ object.quaternion.copy(state.quaternion);
139
+ object.scale.copy(state.scale);
140
+ if (!object.matrixAutoUpdate) object.updateMatrix();
141
+ }
142
+ if (has("geometry") && object.geometry !== state.geometry) {
143
+ object.geometry = state.geometry;
144
+ object.updateMorphTargets?.();
145
+ }
146
+ if (has("material")) object.material = state.material;
147
+ if (has("leaf")) restoreLeaf(object, state.leaf);
148
+ if (has("skin") && state.skeleton) {
149
+ state.skeleton.boneInverses.forEach((matrix, i) => matrix.copy(state.boneInverses[i] ?? new Matrix4()));
150
+ object.bindMode = state.bindMode;
151
+ object.bind(state.skeleton, state.bindMatrix);
152
+ }
153
+ if (has("node")) {
154
+ if (state.info) copy.nodes.set(object, state.info);
155
+ else copy.nodes.delete(object);
156
+ }
157
+ this.owner.load(object, state.owner);
158
+ }
159
+ for (const [object, state] of entries) {
160
+ if (!state.aspects.has("parent")) continue;
161
+ if (!state.parent) {
162
+ object.removeFromParent();
163
+ continue;
164
+ }
165
+ if (object.parent !== state.parent) state.parent.add(object);
166
+ const children = state.parent.children;
167
+ const at = children.indexOf(object);
168
+ const index = Math.min(state.index, children.length - 1);
169
+ if (at !== index) {
170
+ children.splice(at, 1);
171
+ children.splice(index, 0, object);
172
+ }
173
+ }
174
+ this.reset();
175
+ }
176
+ }
@@ -0,0 +1,302 @@
1
+ // SPDX-FileCopyrightText: 2026 Hyperbond Studio Pte. Ltd.
2
+ // SPDX-License-Identifier: MIT
3
+ //
4
+ // Full frames: how a whole parse of an asset updates the copies of it in the developer's scene, by node identity
5
+ // (README, "How updates keep your objects"). Nothing here touches the network or the DOM, so it is tested in Node.
6
+ //
7
+ // - A glTF *node* is known by GLTFLoader's `parser.associations` (its node index). What the loader made under a node
8
+ // for it (the primitives of a multi-primitive mesh, a camera or light beside a mesh) is the node's *content*.
9
+ // Anything else under a node is the developer's.
10
+ // - Matching: by `extras.angelo_uid` (Angelo's per-process node identity) first, using the chain of uids from the
11
+ // asset root only to tell repeated uids apart (the same Blender object instanced under several parents), then by
12
+ // the chain of names from the root for what is left (a first load, a saved file, an Angelo restart).
13
+ // - A matched node keeps its Object3D, and is changed only where Angelo's data differs (update.js): an unchanged node
14
+ // keeps its geometry, material and textures and costs nothing on the GPU. Bones are never replaced.
15
+
16
+ import { describe, isDrawable, kindOf, nameOf } from "./source.js";
17
+ import { Update, contentObjects, developerChildren, emptyContent, materialValues, newJournal, rememberRest, sdkDigest,
18
+ sdkMaterial, sdkMaterialValues, sdkParent } from "./update.js";
19
+
20
+ export { describe, developerChildren };
21
+
22
+ export class Copy {
23
+ constructor(root) {
24
+ this.root = root;
25
+ this.nodes = new Map(); // Object3D -> {uid: string|null, content: {primitives: [], camera, light}}
26
+ this.journal = newJournal(); // What the SDK changed since the asset was last as saved.
27
+ }
28
+ }
29
+
30
+
31
+
32
+ function ownsMaterial(mesh, isLoaderMaterial) {
33
+ const material = mesh.material;
34
+ const all = Array.isArray(material) ? material : [material];
35
+ if (all.length && all.every((item) => item && isLoaderMaterial(item))) {
36
+ sdkMaterial.set(mesh, material);
37
+ sdkMaterialValues.set(mesh, materialValues(material));
38
+ }
39
+ }
40
+
41
+ /** A copy made from a loaded glTF (its own scene, or `root` when it is that scene). */
42
+ export function adoptGltf(gltf, root = gltf.scene) {
43
+ const source = describe(gltf);
44
+ const copy = new Copy(root);
45
+ const associations = gltf.parser?.associations;
46
+ const isLoaderMaterial = (material) => !associations || associations.has(material);
47
+ for (const node of source.nodes) {
48
+ copy.nodes.set(node.object, { uid: node.uid, content: node.content });
49
+ sdkParent.set(node.object, node.object.parent);
50
+ for (const item of [node.object, ...node.content.primitives]) {
51
+ rememberRest(item);
52
+ if (isDrawable(item)) ownsMaterial(item, isLoaderMaterial);
53
+ }
54
+ }
55
+ return copy;
56
+ }
57
+
58
+ /**
59
+ * What the file itself says each loader material is, for comparing Angelo's materials with (update.js): a page
60
+ * often changes a loaded material in place before it calls track() (a colour variant), and that change must not
61
+ * look like Angelo's. GLTFLoader's `loadMaterial` builds a fresh material from the file (sharing its textures).
62
+ */
63
+ export async function rememberFileMaterials(gltf, copy) {
64
+ const parser = gltf.parser;
65
+ if (typeof parser?.loadMaterial !== "function" || !parser.associations) return;
66
+ for (const [object, info] of copy.nodes) {
67
+ for (const item of [object, ...info.content.primitives]) {
68
+ if (!isDrawable(item) || Array.isArray(item.material) || sdkMaterial.get(item) !== item.material) continue;
69
+ const index = parser.associations.get(item.material)?.materials;
70
+ if (index === undefined) continue;
71
+ try {
72
+ // The loader's final step for this mesh (normal-map handedness, vertex colours, points/lines variants),
73
+ // done on a stand-in so the result is what Angelo's frames will hold for an unchanged material.
74
+ const probe = { geometry: item.geometry, material: await parser.loadMaterial(index), isPoints: item.isPoints,
75
+ isLine: item.isLine, isLineSegments: item.isLineSegments, isLineLoop: item.isLineLoop };
76
+ if (typeof parser.assignFinalMaterial === "function") parser.assignFinalMaterial(probe);
77
+ sdkMaterialValues.set(item, probe.material);
78
+ } catch {
79
+ // Keep the copy made at track(): the comparison is then against the material as it was then.
80
+ }
81
+ }
82
+ }
83
+ }
84
+
85
+ /**
86
+ * A copy for `root`, a clone of `template`'s root (Object3D.clone or SkeletonUtils.clone): the two trees are
87
+ * walked side by side, children by position and then by name and kind, so the developer's own children are never
88
+ * taken for nodes.
89
+ */
90
+ export function adoptClone(template, root) {
91
+ const copy = new Copy(root);
92
+ const walk = (from, to) => {
93
+ const taken = new Set();
94
+ from.children.forEach((child, index) => {
95
+ const info = template.nodes.get(child);
96
+ const isContent = !info && template.nodes.has(from)
97
+ && contentObjects(template.nodes.get(from).content).includes(child);
98
+ if (!info && !isContent) return; // The developer's, in the template.
99
+ let match = to.children[index];
100
+ if (!match || taken.has(match) || match.name !== child.name || kindOf(match) !== kindOf(child)) {
101
+ match = to.children.find((item) => !taken.has(item) && item.name === child.name && kindOf(item) === kindOf(child));
102
+ }
103
+ if (!match) return;
104
+ taken.add(match);
105
+ rememberRest(match);
106
+ if (info) {
107
+ copy.nodes.set(match, { uid: info.uid, content: emptyContent(), from: child });
108
+ sdkParent.set(match, to);
109
+ walk(child, match);
110
+ }
111
+ if (isDrawable(child) && isDrawable(match) && sdkMaterial.get(child) === child.material
112
+ && match.material === child.material) {
113
+ sdkMaterial.set(match, match.material);
114
+ sdkMaterialValues.set(match, sdkMaterialValues.get(child) ?? materialValues(match.material));
115
+ }
116
+ });
117
+ };
118
+ walk(template.root, root);
119
+ // Content: the clone's children at the template content's places.
120
+ for (const [object, info] of copy.nodes) {
121
+ const content = template.nodes.get(info.from).content;
122
+ const mapped = (item) => (item ? object.children.find((child) => child.name === item.name
123
+ && kindOf(child) === kindOf(item) && !copy.nodes.has(child)) ?? null : null);
124
+ const used = new Set();
125
+ for (const primitive of content.primitives) {
126
+ const found = object.children.find((child) => !used.has(child) && !copy.nodes.has(child)
127
+ && child.name === primitive.name && kindOf(child) === kindOf(primitive));
128
+ if (found) {
129
+ used.add(found);
130
+ info.content.primitives.push(found);
131
+ }
132
+ }
133
+ info.content.camera = mapped(content.camera);
134
+ info.content.light = mapped(content.light);
135
+ delete info.from;
136
+ }
137
+ return copy;
138
+ }
139
+
140
+
141
+ // Chains: a node's place from the asset root, each step told apart from same-named (or same-uid) siblings.
142
+
143
+ function copyChains(copy) {
144
+ const chains = new Map();
145
+ const visit = (parent, prefixName, prefixUid) => {
146
+ const seenName = new Map();
147
+ const seenUid = new Map();
148
+ for (const child of parent.children) {
149
+ const info = copy.nodes.get(child);
150
+ if (!info) continue;
151
+ const name = nameOf(child);
152
+ const n = seenName.get(name) ?? 0;
153
+ seenName.set(name, n + 1);
154
+ const uid = info.uid ?? "";
155
+ const u = seenUid.get(uid) ?? 0;
156
+ seenUid.set(uid, u + 1);
157
+ const names = `${prefixName}\u0000${name}#${n}`;
158
+ const uids = `${prefixUid}\u0000${uid}#${u}`;
159
+ chains.set(child, { names, uids });
160
+ visit(child, names, uids);
161
+ }
162
+ };
163
+ visit(copy.root, "", "");
164
+ // Nodes the developer moved out of the asset start their own chains where they are.
165
+ for (const [object, info] of copy.nodes) {
166
+ if (!chains.has(object)) {
167
+ const names = `\u0001${nameOf(object)}#0`;
168
+ const uids = `\u0001${info.uid ?? ""}#0`;
169
+ chains.set(object, { names, uids });
170
+ }
171
+ }
172
+ return chains;
173
+ }
174
+
175
+ function groupBy(items, key) {
176
+ const groups = new Map();
177
+ for (const item of items) {
178
+ const value = key(item);
179
+ if (value === null || value === undefined) continue;
180
+ if (!groups.has(value)) groups.set(value, []);
181
+ groups.get(value).push(item);
182
+ }
183
+ return groups;
184
+ }
185
+
186
+ /** Pair the source's nodes with the copy's: Map<source node, Object3D>. */
187
+ export function matchNodes(copy, source) {
188
+ const chains = copyChains(copy);
189
+ const pairs = new Map();
190
+ const used = new Set();
191
+ const pairAll = (sources, objects) => {
192
+ const free = (list) => list.filter((item) => !pairs.has(item) && !used.has(item));
193
+ for (const field of ["uids", "names"]) {
194
+ const byChain = groupBy(free(objects), (object) => chains.get(object)[field]);
195
+ for (const node of free(sources)) {
196
+ const candidates = byChain.get(field === "uids" ? node.uidChain : node.nameChain);
197
+ const object = candidates?.find((item) => !used.has(item));
198
+ if (object) {
199
+ pairs.set(node, object);
200
+ used.add(object);
201
+ }
202
+ }
203
+ }
204
+ const rest = free(objects);
205
+ for (const node of free(sources)) {
206
+ if (!rest.length) break;
207
+ const object = rest.shift();
208
+ pairs.set(node, object);
209
+ used.add(object);
210
+ }
211
+ };
212
+ // 1. By uid: a lone uid on each side pairs whatever moved or was renamed; repeated uids pair by chain, then order.
213
+ const objectsByUid = groupBy([...copy.nodes.keys()], (object) => copy.nodes.get(object).uid);
214
+ for (const [uid, sources] of groupBy(source.nodes, (node) => node.uid)) {
215
+ const objects = objectsByUid.get(uid);
216
+ if (objects) pairAll(sources, objects);
217
+ }
218
+ // 2. By name chain for the rest; nothing pairs by position alone across different names.
219
+ const restObjects = [...copy.nodes.keys()].filter((object) => !used.has(object));
220
+ const byName = groupBy(restObjects, (object) => chains.get(object).names);
221
+ for (const node of source.nodes) {
222
+ if (pairs.has(node)) continue;
223
+ const object = byName.get(node.nameChain)?.find((item) => !used.has(item));
224
+ if (object) {
225
+ pairs.set(node, object);
226
+ used.add(object);
227
+ }
228
+ }
229
+ // 3. Bones are never replaced (an AnimationMixer holds them), but a bone's key holds its name, so a renamed bone
230
+ // arrives with a new key and a new name. Pair what is left of the bones under the same (already paired) parent
231
+ // when exactly one is left on each side.
232
+ const parentObject = (node) => (node.parent ? pairs.get(node.parent) : copy.root);
233
+ const leftBones = groupBy([...copy.nodes.keys()].filter((object) => object.isBone && !used.has(object)),
234
+ (object) => object.parent);
235
+ const newBones = groupBy(source.nodes.filter((node) => node.object.isBone && !pairs.has(node)), parentObject);
236
+ for (const [parent, nodes] of newBones) {
237
+ const objects = leftBones.get(parent);
238
+ if (nodes.length === 1 && objects?.length === 1) {
239
+ pairs.set(nodes[0], objects[0]);
240
+ used.add(objects[0]);
241
+ }
242
+ }
243
+ // 4. A node the developer moved out of the asset has no chain to compare: pair it by its name alone, when that
244
+ // name is unique among what is left on both sides (Blender's object names are unique in a file).
245
+ const leftObjects = groupBy([...copy.nodes.keys()].filter((object) => !used.has(object)), (object) => nameOf(object));
246
+ const leftSources = groupBy(source.nodes.filter((node) => !pairs.has(node)), (node) => node.name);
247
+ for (const [name, nodes] of leftSources) {
248
+ const objects = leftObjects.get(name);
249
+ if (nodes.length === 1 && objects?.length === 1 && chains.get(objects[0]).names.startsWith("\u0001")) {
250
+ pairs.set(nodes[0], objects[0]);
251
+ used.add(objects[0]);
252
+ }
253
+ }
254
+ return pairs;
255
+ }
256
+
257
+ // Updating objects ----------------------------------------------------------------------------------------------
258
+
259
+ /**
260
+ * Update `copy` to `source` (one whole parse, shared by every copy) by diff. `cache` is the page's TextureCache.
261
+ * Returns the report: {renamed, removed, added, replaced, skeletons, changed: Set<Object3D>}.
262
+ */
263
+ export function applySource(copy, source, cache) {
264
+ const update = new Update(copy, copy.journal, cache);
265
+ const pairs = matchNodes(copy, source);
266
+ const kept = new Set(pairs.values());
267
+ const finish = update.removeNodes([...copy.nodes.keys()].filter((object) => !kept.has(object)));
268
+ const objectOf = new Map();
269
+ const unchanged = new Set();
270
+ for (const node of source.nodes) { // Parents before children.
271
+ const parent = node.parent ? objectOf.get(node.parent) : copy.root;
272
+ const object = pairs.get(node);
273
+ if (object && node.digest && sdkDigest.get(object) === node.digest) unchanged.add(node);
274
+ objectOf.set(node, object ? update.updateNode(object, node, parent) : update.addNode(node, parent));
275
+ }
276
+ finish();
277
+ const changed = new Set(source.nodes.filter((node) => !unchanged.has(node)));
278
+ skins(update, source, (bone) => objectOf.get(source.byObject.get(bone)), objectOf, changed);
279
+ return update.report;
280
+ }
281
+
282
+ /** Bind each skinned mesh of the source to this copy's bones; `boneOf` maps a source bone to the copy's object. */
283
+ export function skins(update, source, boneOf, objectOf, only = null) {
284
+ for (const node of source.nodes) {
285
+ if (only && !only.has(node)) continue;
286
+ const object = objectOf.get(node);
287
+ const info = object && update.copy.nodes.get(object);
288
+ if (!info) continue;
289
+ const pairs = [[object, node.object], ...info.content.primitives.map((item, i) => [item, node.content.primitives[i]])];
290
+ for (const [target, from] of pairs) {
291
+ if (!target?.isSkinnedMesh || !from?.isSkinnedMesh || !from.skeleton) continue;
292
+ const bones = from.skeleton.bones.map(boneOf);
293
+ if (bones.some((bone) => !bone)) continue;
294
+ update.skin(target, from, bones);
295
+ }
296
+ }
297
+ }
298
+
299
+ /** Forget every uid (Angelo restarted: its uids start over and mean other objects). */
300
+ export function forgetUids(copy) {
301
+ for (const [object, info] of copy.nodes) if (info.uid !== null) copy.nodes.set(object, { ...info, uid: null });
302
+ }
@@ -0,0 +1,86 @@
1
+ // SPDX-FileCopyrightText: 2026 Hyperbond Studio Pte. Ltd.
2
+ // SPDX-License-Identifier: MIT
3
+ //
4
+ // The page's only UI: a small corner dot for the link's state, and the "Edit <file> in Angelo" chip an Alt-click
5
+ // shows. Plain DOM with inline styles, so nothing depends on the developer's CSS or framework.
6
+
7
+ const COLORS = { off: "#8b8b8b", waiting: "#8b8b8b", live: "#3fb950", linked: "#3fb950", updating: "#d29922",
8
+ lost: "#f85149" };
9
+
10
+ export class Overlay {
11
+ constructor({ showDot }) {
12
+ this.showDot = showDot;
13
+ this.dot = null;
14
+ this.chip = null;
15
+ this.hideChip = this.hideChip.bind(this);
16
+ this.onKey = (event) => {
17
+ if (event.key === "Escape") this.hideChip();
18
+ };
19
+ this.onOutside = (event) => {
20
+ if (this.chip && event.target !== this.chip) this.hideChip();
21
+ };
22
+ }
23
+
24
+ /** state: off | waiting | live | linked | updating | lost; `title` says it in words (hover). */
25
+ setState(state, title) {
26
+ if (!this.showDot || typeof document === "undefined") return;
27
+ if (!this.dot) {
28
+ this.dot = document.createElement("div");
29
+ this.dot.setAttribute("role", "status");
30
+ Object.assign(this.dot.style, {
31
+ position: "fixed", right: "10px", bottom: "10px", width: "10px", height: "10px", borderRadius: "50%",
32
+ zIndex: "2147483646", pointerEvents: "auto", boxShadow: "0 0 0 2px rgba(0,0,0,0.35)", transition:
33
+ "background-color 120ms linear",
34
+ });
35
+ document.body.appendChild(this.dot);
36
+ }
37
+ this.dot.style.backgroundColor = COLORS[state] ?? COLORS.off;
38
+ this.dot.title = title;
39
+ this.dot.setAttribute("aria-label", title);
40
+ this.dot.dataset.state = state;
41
+ }
42
+
43
+ /** Show the chip at a viewport point; `onClick` runs when it is clicked. */
44
+ showChip(x, y, label, onClick) {
45
+ if (typeof document === "undefined") return;
46
+ this.hideChip();
47
+ const chip = document.createElement("button");
48
+ chip.type = "button";
49
+ chip.textContent = label;
50
+ Object.assign(chip.style, {
51
+ position: "fixed", left: `${Math.round(x + 8)}px`, top: `${Math.round(y + 8)}px`, zIndex: "2147483647",
52
+ font: "12px/1.4 system-ui, -apple-system, Segoe UI, sans-serif", color: "#f0f0f0", background: "#1f2328",
53
+ border: "1px solid #3d444d", borderRadius: "6px", padding: "4px 10px", cursor: "pointer",
54
+ boxShadow: "0 4px 12px rgba(0,0,0,0.35)", whiteSpace: "nowrap",
55
+ });
56
+ chip.addEventListener("click", (event) => {
57
+ event.stopPropagation();
58
+ this.hideChip();
59
+ onClick();
60
+ });
61
+ document.body.appendChild(chip);
62
+ this.chip = chip;
63
+ this.chipTimer = setTimeout(this.hideChip, 8000);
64
+ setTimeout(() => {
65
+ if (this.chip !== chip) return;
66
+ document.addEventListener("pointerdown", this.onOutside, true);
67
+ document.addEventListener("keydown", this.onKey, true);
68
+ }, 0);
69
+ }
70
+
71
+ hideChip() {
72
+ clearTimeout(this.chipTimer);
73
+ if (typeof document !== "undefined") {
74
+ document.removeEventListener("pointerdown", this.onOutside, true);
75
+ document.removeEventListener("keydown", this.onKey, true);
76
+ }
77
+ this.chip?.remove();
78
+ this.chip = null;
79
+ }
80
+
81
+ remove() {
82
+ this.hideChip();
83
+ this.dot?.remove();
84
+ this.dot = null;
85
+ }
86
+ }
@@ -0,0 +1,72 @@
1
+ // SPDX-FileCopyrightText: 2026 Hyperbond Studio Pte. Ltd.
2
+ // SPDX-License-Identifier: MIT
3
+ //
4
+ // GPU resources the SDK made (from its own parses), disposed once no tracked copy uses them. What the developer
5
+ // loaded is never disposed here: their own code may still hold it.
6
+
7
+ function texturesOf(material, into) {
8
+ for (const value of Object.values(material)) {
9
+ if (value?.isTexture) into.add(value);
10
+ }
11
+ for (const uniform of Object.values(material.uniforms ?? {})) {
12
+ const value = uniform?.value;
13
+ if (value?.isTexture) into.add(value);
14
+ else if (Array.isArray(value)) for (const item of value) if (item?.isTexture) into.add(item);
15
+ }
16
+ }
17
+
18
+ /** Every geometry, material, texture and skeleton under `roots`. */
19
+ export function resourcesUnder(roots) {
20
+ const found = new Set();
21
+ for (const root of roots) {
22
+ root.traverse((object) => {
23
+ if (object.geometry) found.add(object.geometry);
24
+ if (object.skeleton) found.add(object.skeleton);
25
+ const materials = Array.isArray(object.material) ? object.material : object.material ? [object.material] : [];
26
+ for (const material of materials) {
27
+ found.add(material);
28
+ texturesOf(material, found);
29
+ }
30
+ });
31
+ }
32
+ return found;
33
+ }
34
+
35
+ export class Resources {
36
+ constructor() {
37
+ this.created = new Set();
38
+ }
39
+
40
+ /** Everything a parse made, so it can be disposed when nothing uses it. */
41
+ adopt(root) {
42
+ for (const item of resourcesUnder([root])) this.created.add(item);
43
+ }
44
+
45
+ /** Remember a skeleton the matcher made. */
46
+ add(item) {
47
+ this.created.add(item);
48
+ }
49
+
50
+ /**
51
+ * Dispose what the SDK made that nothing under `roots` uses and that isn't in `keep` (resources a journal may put
52
+ * back). `retain(item)` keeps an item tracked after disposing it (a texture kept for the link, so it is disposed
53
+ * again whenever it goes unused). Returns the set disposed.
54
+ */
55
+ sweep(roots, keep = [], retain = () => false) {
56
+ const used = resourcesUnder(roots);
57
+ for (const item of keep) {
58
+ for (const material of Array.isArray(item) ? item : [item]) {
59
+ used.add(material);
60
+ if (material?.isMaterial) texturesOf(material, used);
61
+ }
62
+ }
63
+ const disposed = new Set();
64
+ for (const item of this.created) {
65
+ if (used.has(item)) continue;
66
+ item.dispose?.(); // Frees GPU memory; a retained texture keeps its picture and uploads again if used.
67
+ disposed.add(item);
68
+ if (!retain(item)) this.created.delete(item);
69
+ }
70
+ return disposed;
71
+ }
72
+ }