@margoengine/inspector 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 (49) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +623 -3
  4. package/dist/animation.d.ts +53 -0
  5. package/dist/animation.js +234 -0
  6. package/dist/color-D6qetPCJ.js +10 -0
  7. package/dist/color.d.ts +4 -0
  8. package/dist/debug-geometry-D61TEkP9.js +61 -0
  9. package/dist/debug-geometry.d.ts +15 -0
  10. package/dist/edit-state-Dm3G17js.js +4 -0
  11. package/dist/edit-state.d.ts +3 -0
  12. package/dist/edit.d.ts +105 -0
  13. package/dist/edit.js +379 -0
  14. package/dist/errors-D8rc8kzg.js +7 -0
  15. package/dist/frame-panel.d.ts +16 -0
  16. package/dist/frame.d.ts +264 -0
  17. package/dist/frame.js +881 -0
  18. package/dist/gizmo.d.ts +49 -0
  19. package/dist/gizmo.js +131 -0
  20. package/dist/gl.d.ts +89 -0
  21. package/dist/gl.js +284 -0
  22. package/dist/history.d.ts +65 -0
  23. package/dist/history.js +66 -0
  24. package/dist/index.d.ts +122 -0
  25. package/dist/index.js +490 -0
  26. package/dist/mesh-debug.d.ts +115 -0
  27. package/dist/mesh-debug.js +501 -0
  28. package/dist/mesh-source-BSQA_1GQ.js +31 -0
  29. package/dist/packages.d.ts +98 -0
  30. package/dist/packages.js +337 -0
  31. package/dist/remote-relay.d.ts +25 -0
  32. package/dist/remote-relay.js +64 -0
  33. package/dist/remote.d.ts +175 -0
  34. package/dist/remote.js +349 -0
  35. package/dist/resources.d.ts +30 -0
  36. package/dist/resources.js +42 -0
  37. package/dist/shaders.d.ts +122 -0
  38. package/dist/shaders.js +285 -0
  39. package/dist/snapshot.d.ts +47 -0
  40. package/dist/snapshot.js +90 -0
  41. package/dist/textures.d.ts +127 -0
  42. package/dist/textures.js +380 -0
  43. package/dist/tools.d.ts +101 -0
  44. package/dist/tools.js +220 -0
  45. package/dist/tweak.d.ts +86 -0
  46. package/dist/tweak.js +291 -0
  47. package/dist/view-rect-CTC0iGjf.js +23 -0
  48. package/dist/visibility-7_j5J9Nv.js +7 -0
  49. package/package.json +149 -6
@@ -0,0 +1,66 @@
1
+ import { MargoError as e } from "@margoengine/math/errors";
2
+ //#region src/history.ts
3
+ var t = class {
4
+ constructor(e = 200, t = 800, n = () => performance.now()) {
5
+ if (this.limit = e, this.coalesceMs = t, this.now = n, this.done = [], this.undone = [], this.last = -Infinity, this.running = !1, this.listeners = /* @__PURE__ */ new Set(), !Number.isInteger(e) || e < 1 || e > 1e5) throw RangeError("History limit must be an integer from 1 to 100000; pass a whole number in range");
6
+ if (!Number.isFinite(t) || t < 0) throw RangeError("History coalesceMs must be 0 or more; pass a number of milliseconds");
7
+ }
8
+ get undoCount() {
9
+ return this.done.length;
10
+ }
11
+ get redoCount() {
12
+ return this.undone.length;
13
+ }
14
+ get nextUndo() {
15
+ return this.done.at(-1)?.label;
16
+ }
17
+ get nextRedo() {
18
+ return this.undone.at(-1)?.label;
19
+ }
20
+ record(t) {
21
+ if (!t || typeof t.label != "string" || typeof t.undo != "function" || typeof t.redo != "function" || t.discard !== void 0 && typeof t.discard != "function") throw TypeError("History edit needs a label, undo, redo and optional discard function; pass callable actions");
22
+ if (this.running) throw new e("state", "History is replaying an edit; record edits outside undo and redo");
23
+ let n = this.now(), r = this.done.at(-1);
24
+ t.key !== void 0 && !t.discard && !r?.discard && r?.key === t.key && !this.undone.length && n - this.last <= this.coalesceMs ? this.done[this.done.length - 1] = {
25
+ label: t.label,
26
+ key: t.key,
27
+ undo: r.undo,
28
+ redo: t.redo
29
+ } : (this.done.push(t), this.done.length > this.limit && this.done.shift()?.discard?.()), this.last = n;
30
+ let i = this.undone.splice(0);
31
+ for (let e of i) e.discard?.();
32
+ this.changed();
33
+ }
34
+ undo() {
35
+ return this.step(this.done, this.undone, "undo");
36
+ }
37
+ redo() {
38
+ return this.step(this.undone, this.done, "redo");
39
+ }
40
+ clear() {
41
+ let e = [...this.done.splice(0), ...this.undone.splice(0)];
42
+ for (let t of e) t.discard?.();
43
+ this.last = -Infinity, this.changed();
44
+ }
45
+ onChange(e) {
46
+ if (typeof e != "function") throw TypeError("History onChange needs a function; pass a listener");
47
+ return this.listeners.add(e), () => void this.listeners.delete(e);
48
+ }
49
+ step(t, n, r) {
50
+ if (this.running) throw new e("state", "History is replaying an edit; call undo and redo outside edits");
51
+ let i = t.at(-1);
52
+ if (!i) return !1;
53
+ this.running = !0;
54
+ try {
55
+ i[r]();
56
+ } finally {
57
+ this.running = !1;
58
+ }
59
+ return t.pop(), n.push(i), this.last = -Infinity, this.changed(), !0;
60
+ }
61
+ changed() {
62
+ for (let e of [...this.listeners]) e();
63
+ }
64
+ };
65
+ //#endregion
66
+ export { t as EditHistory };
@@ -0,0 +1,122 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel, Mesh as MeshHandle } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin, type FrameGraph, type Mesh } from '@margoengine/core/extension';
4
+ import { EditHistory } from './history.js';
5
+ import { type RestoreResult, type SceneSnapshot } from './snapshot.js';
6
+ import { type EngineResources } from './resources.js';
7
+ export { EditHistory, type Edit } from './history.js';
8
+ export { snapshotMeshes, restoreSnapshot, parseSnapshot, type MeshSnapshot, type SceneSnapshot, type RestoreResult, } from './snapshot.js';
9
+ export { describeEngine, type EngineResources } from './resources.js';
10
+ /** Options of the Inspector: the parent element for its panel and the effect options it edits. */
11
+ export interface InspectorOptions {
12
+ parent?: HTMLElement;
13
+ /** Mutable options of an attached PostProcessing/Tonemap effect. */
14
+ effects?: {
15
+ exposure?: number;
16
+ bloom?: number;
17
+ };
18
+ /**
19
+ * Click an object in the canvas to select it (a click, not a drag: a move of more than 4 px is left to the camera
20
+ * controls). Default true.
21
+ */
22
+ pick?: boolean;
23
+ /** Most edits the undo history keeps, 1 to 100,000. Default 200. */
24
+ historyLimit?: number;
25
+ /** Tree label of an entity without a name, such as the component that made it. Default `Entity <id>`. */
26
+ label?: (mesh: Mesh) => string | undefined;
27
+ }
28
+ type Mode = 'wireframe' | 'normals' | 'bounds' | 'lights';
29
+ /**
30
+ * A DOM panel with a scene tree, frame statistics and debug overlays (wireframe, normals, bounds, lights). Install it as an engine plugin; dispose it to remove the panel.
31
+ */
32
+ export declare class Inspector implements EnginePlugin {
33
+ readonly name = "inspector";
34
+ readonly element: HTMLDivElement;
35
+ readonly root: ShadowRoot;
36
+ readonly debug: {
37
+ wireframe: boolean;
38
+ normals: boolean;
39
+ bounds: boolean;
40
+ lights: boolean;
41
+ };
42
+ private engine?;
43
+ private selection;
44
+ private readonly lines;
45
+ private readonly helpers;
46
+ private lightLines?;
47
+ /** Core's sun as a directional light shape (direction it travels, colour), and the lights gathered each frame. */
48
+ private readonly sun;
49
+ private readonly sceneLights;
50
+ private readonly collapsed;
51
+ private readonly items;
52
+ private readonly inputs;
53
+ private readonly tree;
54
+ private readonly effects?;
55
+ private signature;
56
+ private disposed;
57
+ private readonly timer;
58
+ /** Every edit made in the panel, undoable with `undo()` / Ctrl+Z. */
59
+ readonly history: EditHistory;
60
+ private readonly pickEnabled;
61
+ private readonly label?;
62
+ private query;
63
+ private shader;
64
+ private pickCount;
65
+ private stopPicking?;
66
+ private readonly buttons;
67
+ private readonly details;
68
+ private readonly outputs;
69
+ constructor({ parent, effects, pick, historyLimit, label }?: InspectorOptions);
70
+ static attach(engine: EngineKernel, options?: InspectorOptions): Inspector;
71
+ get selected(): MeshHandle | null;
72
+ select(handle: MeshHandle | null): void;
73
+ private choose;
74
+ /**
75
+ * Applies a change to the selected mesh and records it for undo. Changes with one `key` made within 800 ms of each
76
+ * other (a slider drag) undo as one step. A value the engine rejects throws before anything is recorded.
77
+ */
78
+ private commit;
79
+ /** Takes back the latest edit made in the panel; false when there is none. */
80
+ undo(): boolean;
81
+ /** Does the latest undone edit again; false when there is none. */
82
+ redo(): boolean;
83
+ private alive;
84
+ /**
85
+ * The scene as plain JSON (names, visibility, transforms, core PBR material values) for the inspector's scene. Save
86
+ * it with `JSON.stringify` and give it to `restore` later; the panel's Save button downloads it.
87
+ * @throws MargoError `'state'` when the inspector is not attached, `'disposed'` after `dispose()`.
88
+ */
89
+ snapshot(): SceneSnapshot;
90
+ /**
91
+ * Puts a snapshot's values back on the meshes with the same ids, as one undoable edit. The snapshot is checked first,
92
+ * so a bad one changes nothing.
93
+ * @throws TypeError / RangeError for a malformed snapshot, MargoError `'state'` when not attached.
94
+ */
95
+ restore(snapshot: unknown): RestoreResult;
96
+ /** Counts of what the engine draws (meshes, geometries, materials, triangles) and its plugins. */
97
+ resources(): EngineResources;
98
+ /** The scene's WGSL from the latest WebGPU frame, or an empty string before one has drawn. */
99
+ get shaderSource(): string;
100
+ private download;
101
+ private say;
102
+ /** Runs a panel action; a failure shows in the status line instead of escaping from an event handler. */
103
+ private report;
104
+ private shortcut;
105
+ private watchPicks;
106
+ setDebug(mode: Mode, enabled: boolean): void;
107
+ setup(engine: Engine): void;
108
+ registerPasses(graph: FrameGraph): void;
109
+ /** The meshes of the scene this inspector is attached to (the default scene unless attached with `scene.use`). */
110
+ private meshes;
111
+ private syncDebug;
112
+ private gatherLights;
113
+ private input;
114
+ private liveSelection;
115
+ private edit;
116
+ refresh(): void;
117
+ private toggle;
118
+ private keydown;
119
+ onDeviceRestored(engine: Engine): void;
120
+ dispose(): void;
121
+ [Symbol.dispose]: () => void;
122
+ }
package/dist/index.js ADDED
@@ -0,0 +1,490 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const d=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { n as e } from "./errors-D8rc8kzg.js";
5
+ import { n as t, t as n } from "./debug-geometry-D61TEkP9.js";
6
+ import { n as r } from "./view-rect-CTC0iGjf.js";
7
+ import { EditHistory as i } from "./history.js";
8
+ import { t as a } from "./edit-state-Dm3G17js.js";
9
+ import { t as o } from "./color-D6qetPCJ.js";
10
+ import { parseSnapshot as s, restoreSnapshot as c, snapshotMeshes as l } from "./snapshot.js";
11
+ import { describeEngine as u } from "./resources.js";
12
+ import { engineRuntime as __margoRuntime, meshRuntime as f } from "@margoengine/core/extension";
13
+ import { BoxHelper as p, LightsHelper as m, Lines as h, VertexNormalsHelper as g } from "@margoengine/lines";
14
+ import { meshWorldMatrix as _ } from "@margoengine/math/mesh";
15
+ //#region src/index.ts
16
+ var v = "\n:host{position:fixed;right:12px;top:12px;width:280px;max-width:calc(100vw - 24px);max-height:calc(100dvh - 24px);z-index:10001;display:block;color:#202226;font:12px/1.4 system-ui;letter-spacing:0}\n@media(max-width:560px){:host{top:150px;max-height:calc(100dvh - 162px)}section{max-height:calc(100dvh - 162px)!important}}\n*{box-sizing:border-box}section{background:#fafbfc;border:1px solid #b9bec7;border-radius:4px;max-height:calc(100dvh - 24px);overflow:auto}\nh2{font-size:14px;margin:0;padding:10px 12px;border-bottom:1px solid #d5d9df}fieldset{border:0;border-bottom:1px solid #d5d9df;padding:10px 12px;margin:0}legend{padding:6px 0 0;font-weight:600}\nlabel{display:flex;align-items:center;justify-content:space-between;gap:8px;min-height:28px}input{max-width:100%;min-width:0;font:inherit}input[type=number]{width:72px}input[type=text]{width:156px}input[type=range]{width:132px;accent-color:#087e67}input[type=checkbox]{accent-color:#087e67}\nbutton{font:inherit;border:0;background:none;color:inherit;cursor:pointer}button:focus-visible,[role=treeitem]:focus-visible{outline:2px solid #087e67;outline-offset:-2px}\n[role=tree]{max-height:220px;overflow:auto;padding:6px 0}.row{display:flex;align-items:center;min-height:28px;padding-right:8px}.row button{flex:none;width:24px;height:24px;padding:0}.name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n[aria-selected=true]>.row{background:#d6eee7;color:#084f40}.muted{opacity:.55}[role=group]{padding-left:12px}.axes{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px}.axes label{display:block}.axes input{width:100%}input:disabled{opacity:.5}\nfieldset.bar{display:flex;flex-wrap:wrap;gap:6px;align-items:center}fieldset.bar button{border:1px solid #b9bec7;border-radius:3px;padding:3px 9px;background:#fff}button:disabled{opacity:.45;cursor:default}input[type=color]{width:48px;height:24px;padding:0}input[data-search]{flex:1 1 100%;width:auto}.status{flex:1 1 100%;min-height:1.4em;color:#555}details{border-bottom:1px solid #d5d9df;padding:6px 12px}summary{cursor:pointer;font-weight:600}pre{margin:6px 0 0;max-height:240px;overflow:auto;white-space:pre-wrap;font:11px/1.35 ui-monospace,monospace;user-select:text}\n", y = class s {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
17
+ constructor({ parent: e = document.body, effects: t, pick: n = !0, historyLimit: r = 200, label: a } = {}) {
18
+ if (this.name = "inspector", this.debug = {
19
+ wireframe: !1,
20
+ normals: !1,
21
+ bounds: !1,
22
+ lights: !1
23
+ }, this.selection = null, this.lines = new h({ name: "inspector:lines" }), this.helpers = /* @__PURE__ */ new Map(), this.sun = {
24
+ direction: [
25
+ 0,
26
+ -1,
27
+ 0
28
+ ],
29
+ color: [
30
+ 1,
31
+ 1,
32
+ 1
33
+ ]
34
+ }, this.sceneLights = [], this.collapsed = /* @__PURE__ */ new Set(), this.items = /* @__PURE__ */ new Map(), this.inputs = /* @__PURE__ */ new Map(), this.signature = "", this.disposed = !1, this.query = "", this.shader = "", this.pickCount = 0, this.buttons = /* @__PURE__ */ new Map(), this.details = /* @__PURE__ */ new Map(), this.outputs = /* @__PURE__ */ new Map(), this.label = a, typeof n != "boolean") throw TypeError("Inspector pick must be true or false; pass a boolean");
35
+ this.history = new i(r), this.pickEnabled = n, this.effects = t;
36
+ let s = e.ownerDocument;
37
+ this.element = s.createElement("div"), this.element.dataset.margoInspector = "", this.root = this.element.attachShadow({ mode: "open" });
38
+ let c = s.createElement("style");
39
+ c.textContent = v;
40
+ let l = s.createElement("section"), u = s.createElement("h2");
41
+ u.textContent = "Inspector", l.append(u), this.root.append(c, l);
42
+ let d = s.createElement("fieldset"), f = s.createElement("input"), p = s.createElement("input"), m = s.createElement("div");
43
+ d.className = "bar", f.type = "file", f.accept = "application/json,.json", f.hidden = !0, f.setAttribute("aria-label", "Load scene file"), f.addEventListener("change", () => {
44
+ let e = f.files?.[0];
45
+ f.value = "", e && e.text().then((e) => this.report(() => this.restore(JSON.parse(e)))).catch((e) => this.say(String(e)));
46
+ });
47
+ for (let [e, t, n] of [
48
+ [
49
+ "undo",
50
+ "Undo",
51
+ () => this.undo()
52
+ ],
53
+ [
54
+ "redo",
55
+ "Redo",
56
+ () => this.redo()
57
+ ],
58
+ [
59
+ "save",
60
+ "Save",
61
+ () => this.download()
62
+ ],
63
+ [
64
+ "load",
65
+ "Load",
66
+ () => f.click()
67
+ ]
68
+ ]) {
69
+ let r = s.createElement("button");
70
+ r.type = "button", r.textContent = t, r.dataset.action = e, r.addEventListener("click", () => this.report(n)), this.buttons.set(e, r), d.append(r);
71
+ }
72
+ p.type = "text", p.placeholder = "Search entities", p.setAttribute("aria-label", "Search entities"), p.dataset.search = "", p.addEventListener("input", () => {
73
+ this.query = p.value.trim().toLowerCase(), this.signature = "", this.refresh();
74
+ }), m.setAttribute("role", "status"), m.className = "status", this.outputs.set("status", m), d.append(f, p, m), l.append(d), this.element.addEventListener("keydown", (e) => this.shortcut(e)), this.history.onChange(() => this.refresh());
75
+ let g = s.createElement("fieldset");
76
+ for (let [e, t] of [
77
+ ["wireframe", "Wireframe"],
78
+ ["normals", "Vertex normals"],
79
+ ["bounds", "AABB bounds"],
80
+ ["lights", "Light helpers"]
81
+ ]) {
82
+ let n = this.input(g, e, t, "checkbox");
83
+ n.addEventListener("change", () => this.setDebug(e, n.checked));
84
+ }
85
+ l.append(g), this.tree = s.createElement("div"), this.tree.setAttribute("role", "tree"), this.tree.setAttribute("aria-label", "Scene entities"), l.append(this.tree), this.tree.addEventListener("keydown", (e) => this.keydown(e));
86
+ let _ = s.createElement("fieldset"), y = s.createElement("legend");
87
+ y.textContent = "Entity", _.append(y);
88
+ let b = this.input(_, "name", "Name", "text");
89
+ b.addEventListener("change", () => {
90
+ this.liveSelection() && (this.commit("Rename", "name", (e) => e.name, (e, t) => e.name = t, b.value), this.refresh());
91
+ });
92
+ let x = this.input(_, "visible", "Visible", "checkbox");
93
+ x.addEventListener("change", () => {
94
+ this.liveSelection() && this.commit("Set visible", "visible", (e) => e.visible, (e, t) => e.visible = t, x.checked);
95
+ });
96
+ for (let e of [
97
+ "position",
98
+ "rotation",
99
+ "scale"
100
+ ]) {
101
+ let t = s.createElement("div");
102
+ t.textContent = e[0].toUpperCase() + e.slice(1), _.append(t);
103
+ let n = s.createElement("div");
104
+ n.className = "axes", _.append(n);
105
+ for (let t of [
106
+ "x",
107
+ "y",
108
+ "z"
109
+ ]) {
110
+ let r = this.input(n, `${e}.${t}`, t.toUpperCase(), "number");
111
+ r.step = "0.01", r.setAttribute("aria-label", `${e} ${t}`), r.addEventListener("change", () => this.edit(r, () => {
112
+ this.liveSelection() && this.commit(`Set ${e} ${t}`, `${e}.${t}`, (n) => n[e][t], (n, r) => n[e][t] = r, r.valueAsNumber);
113
+ }));
114
+ }
115
+ }
116
+ for (let [e, t, n, r] of [[
117
+ "roughness",
118
+ "Roughness",
119
+ 4,
120
+ .045
121
+ ], [
122
+ "metallic",
123
+ "Metallic",
124
+ 5,
125
+ 0
126
+ ]]) {
127
+ let i = this.input(_, e, t, "range");
128
+ i.min = String(r), i.max = "1", i.step = "0.005", i.value = e === "roughness" ? "0.5" : "0", i.addEventListener("input", () => this.edit(i, () => {
129
+ let t = i.valueAsNumber;
130
+ if (!Number.isFinite(t) || t < r || t > 1) throw RangeError("Invalid material value; pass a finite number in the control range");
131
+ this.liveSelection() && this.commit(`Set ${e}`, e, (e) => e.material.data[n], (e, t) => e.material.data[n] = t, t);
132
+ }));
133
+ }
134
+ let S = this.input(_, "color", "Colour", "color");
135
+ S.addEventListener("input", () => this.edit(S, () => {
136
+ this.liveSelection() && this.commit("Set colour", "color", (e) => o(e.material.data), (e, t) => e.material.set({ color: t }), S.value);
137
+ }));
138
+ let C = this.input(_, "doubleSided", "Double sided", "checkbox");
139
+ C.addEventListener("change", () => this.edit(C, () => {
140
+ this.liveSelection() && this.commit("Set double sided", "doubleSided", (e) => !!e.material.data[6], (e, t) => e.material.set({ doubleSided: t }), C.checked);
141
+ })), l.append(_);
142
+ let w = s.createElement("fieldset"), T = s.createElement("legend");
143
+ T.textContent = "Effects", w.append(T);
144
+ for (let [e, t, n, r] of [[
145
+ "exposure",
146
+ "Exposure",
147
+ -10,
148
+ 10
149
+ ], [
150
+ "bloom",
151
+ "Bloom",
152
+ 0,
153
+ 4
154
+ ]]) {
155
+ let i = this.input(w, e, t, "range");
156
+ i.min = String(n), i.max = String(r), i.step = "0.05", i.value = String(this.effects?.[e] ?? 0), i.addEventListener("input", () => this.edit(i, () => {
157
+ let t = i.valueAsNumber;
158
+ if (!Number.isFinite(t) || t < n || t > r) throw RangeError("Invalid effect value; pass a finite, non-negative number");
159
+ let a = this.effects;
160
+ if (a) {
161
+ let n = a[e] ?? 0;
162
+ a[e] = t, this.history.record({
163
+ label: `Set ${e}`,
164
+ key: `effect.${e}`,
165
+ undo: () => a[e] = n,
166
+ redo: () => a[e] = t
167
+ });
168
+ }
169
+ }));
170
+ }
171
+ l.append(w);
172
+ for (let [e, t] of [["resources", "Resources"], ["shader", "Scene shader (WGSL)"]]) {
173
+ let n = s.createElement("details"), r = s.createElement("summary"), i = s.createElement("pre");
174
+ n.dataset.section = e, r.textContent = t, i.dataset.output = e, n.append(r, i), n.addEventListener("toggle", () => this.refresh()), this.details.set(e, n), this.outputs.set(e, i), l.append(n);
175
+ }
176
+ e.append(this.element), this.refresh(), this.timer = setInterval(() => this.refresh(), 250);
177
+ }
178
+ static attach(e, t = {}) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
179
+ let n = new s(t);
180
+ try {
181
+ return d(e).use(n), n;
182
+ } catch (e) {
183
+ throw n.dispose(), e;
184
+ }
185
+ }
186
+ get selected() {
187
+ return this.selection;
188
+ }
189
+ select(t) {
190
+ if (this.disposed || !this.engine) throw e("state", "Inspector is not attached; install it on an engine first");
191
+ let n = t ? f(t) : null;
192
+ if (n && (n.check(), n.engine !== this.engine)) throw TypeError("Mesh belongs to another engine; select a mesh created by this engine");
193
+ this.choose(n);
194
+ }
195
+ choose(e) {
196
+ if (this.selection = e, e) for (let t = this.engine.store.parents[e.id]; t !== -1; t = this.engine.store.parents[t]) this.collapsed.delete(this.engine.meshes.get(t));
197
+ this.signature = "", this.refresh();
198
+ }
199
+ commit(e, t, n, r, i) {
200
+ let a = this.selection, o = n(a), s = this.engine;
201
+ r(a, i);
202
+ let c = () => s.meshes.get(a.id) === a;
203
+ this.history.record({
204
+ label: e,
205
+ key: `${a.id}.${t}`,
206
+ undo: () => c() && r(a, o),
207
+ redo: () => c() && r(a, i)
208
+ });
209
+ }
210
+ undo() {
211
+ return this.alive(), this.history.undo();
212
+ }
213
+ redo() {
214
+ return this.alive(), this.history.redo();
215
+ }
216
+ alive() {
217
+ if (this.disposed) throw e("disposed", "Inspector is disposed; create a new Inspector");
218
+ }
219
+ snapshot() {
220
+ if (this.alive(), !this.engine) throw e("state", "Inspector is not attached; install it on an engine first");
221
+ return l(this.engine, this.meshes());
222
+ }
223
+ restore(t) {
224
+ this.alive();
225
+ let n = this.engine;
226
+ if (!n) throw e("state", "Inspector is not attached; install it on an engine first");
227
+ let r = l(n, this.meshes()), i = c(n, t), a = l(n, this.meshes());
228
+ return this.history.record({
229
+ label: "Load scene",
230
+ undo: () => void c(n, r),
231
+ redo: () => void c(n, a)
232
+ }), this.signature = "", this.say(`Loaded ${i.applied} entities` + (i.missing.length ? `, ${i.missing.length} not in this scene` : "")), i;
233
+ }
234
+ resources() {
235
+ if (this.alive(), !this.engine) throw e("state", "Inspector is not attached; install it on an engine first");
236
+ return u(this.engine, this.meshes());
237
+ }
238
+ get shaderSource() {
239
+ return this.shader;
240
+ }
241
+ download() {
242
+ let e = this.element.ownerDocument, t = URL.createObjectURL(new Blob([JSON.stringify(this.snapshot(), null, 2)], { type: "application/json" })), n = e.createElement("a");
243
+ n.href = t, n.download = "scene.json", n.click(), URL.revokeObjectURL(t);
244
+ }
245
+ say(e) {
246
+ let t = this.outputs.get("status");
247
+ t && (t.textContent = e);
248
+ }
249
+ report(e) {
250
+ try {
251
+ e();
252
+ } catch (e) {
253
+ this.say(e instanceof Error ? e.message : String(e));
254
+ }
255
+ }
256
+ shortcut(e) {
257
+ if (!(e.ctrlKey || e.metaKey) || e.altKey) return;
258
+ let t = e.target, n = t.tagName === "INPUT" && [
259
+ "text",
260
+ "number",
261
+ "search"
262
+ ].includes(t.type), r = e.key.toLowerCase();
263
+ if (!(n || this.disposed)) {
264
+ if (r === "z" && !e.shiftKey) this.report(() => this.undo());
265
+ else if (r === "z" && e.shiftKey || r === "y") this.report(() => this.redo());
266
+ else return;
267
+ e.preventDefault();
268
+ }
269
+ }
270
+ watchPicks(e) {
271
+ let t = e.canvas;
272
+ if (typeof t?.addEventListener != "function" || typeof t.getBoundingClientRect != "function") return () => {};
273
+ let n, r = (e) => {
274
+ n = e.button === 0 ? {
275
+ x: e.clientX,
276
+ y: e.clientY
277
+ } : void 0;
278
+ }, i = (r) => {
279
+ let i = n;
280
+ if (n = void 0, !i || r.defaultPrevented || Math.hypot(r.clientX - i.x, r.clientY - i.y) > 4) return;
281
+ let a = t.getBoundingClientRect(), o = ++this.pickCount;
282
+ e.pick(r.clientX - a.left, r.clientY - a.top).then((t) => {
283
+ o === this.pickCount && !this.disposed && this.engine === e && this.choose(t);
284
+ }).catch((t) => {
285
+ !this.disposed && !e.disposed && reportError(t);
286
+ });
287
+ };
288
+ return t.addEventListener("pointerdown", r), t.addEventListener("pointerup", i), () => {
289
+ t.removeEventListener("pointerdown", r), t.removeEventListener("pointerup", i);
290
+ };
291
+ }
292
+ setDebug(t, n) {
293
+ if (this.disposed) throw e("disposed", "Inspector is disposed; create a new Inspector");
294
+ if (!Object.hasOwn(this.debug, t) || typeof n != "boolean") throw TypeError("Invalid debug mode; use wireframe, normals, bounds or lights");
295
+ if (n && this.engine?.backend !== "webgpu") throw e("unsupported", "Debug rendering requires WebGPU; use a browser that supports it");
296
+ this.debug[t] = n, this.inputs.get(t).checked = n;
297
+ }
298
+ setup(t) {
299
+ if (this.disposed || this.engine) throw e("attached", "Inspector is disposed or already attached; create a new Inspector for this engine");
300
+ this.engine = t, this.pickEnabled && (this.stopPicking = this.watchPicks(t)), t.backend === "webgpu" && this.lines.setup(t), this.refresh();
301
+ }
302
+ registerPasses(e) {
303
+ e.add({
304
+ name: "inspector:sync",
305
+ order: 19,
306
+ execute: (e) => {
307
+ e.backend === "webgpu" && typeof e.shader == "string" && (this.shader = e.shader), this.syncDebug(e);
308
+ }
309
+ }), this.lines.registerPasses(e);
310
+ }
311
+ *meshes() {
312
+ let e = this.engine;
313
+ for (let t of (e.sceneOf(this) ?? e.scene).meshes.values()) a.has(t) || (yield t);
314
+ }
315
+ syncDebug(e) {
316
+ let i = this.engine;
317
+ if (this.debug.lights && !this.lightLines && i.backend === "webgpu" && (this.lightLines = this.lines.add(new m(() => this.gatherLights(), {
318
+ onTop: !0,
319
+ size: .25
320
+ }))), this.lightLines && (this.lightLines.visible = this.debug.lights), this.helpers.size || this.debug.wireframe || this.debug.normals || this.debug.bounds) {
321
+ for (let [e, t] of this.helpers) (i.meshes.get(e.id) !== e || n(e)?.identity !== t.geometry) && (t.wireframe?.dispose(), t.normals?.dispose(), t.bounds?.dispose(), this.helpers.delete(e));
322
+ if (i.backend === "webgpu") for (let a of this.meshes()) {
323
+ let o = n(a);
324
+ if (!o) continue;
325
+ let s = this.helpers.get(a);
326
+ if (!s && (this.debug.wireframe || this.debug.normals || this.debug.bounds) && (s = { geometry: o.identity }, this.helpers.set(a, s)), s) for (let n of [
327
+ "wireframe",
328
+ "normals",
329
+ "bounds"
330
+ ]) this.debug[n] && !s[n] && (s[n] = this.lines.add(n === "wireframe" ? t(a) : n === "normals" ? new g(a, {
331
+ size: o.radius * .15,
332
+ color: "#ed6b86",
333
+ onTop: !0
334
+ }) : new p(a, {
335
+ color: "#e4ba31",
336
+ onTop: !0
337
+ }))), s[n] && (s[n].visible = this.debug[n] && r(e, a) && (o.pbr ? _(i, a) !== null : !!i.store.visible[a.id]));
338
+ }
339
+ }
340
+ }
341
+ gatherLights() {
342
+ let e = this.engine, t = this.sceneLights, { direction: n, radiance: r } = e.lighting;
343
+ if (t.length = 0, n[3] > 0) {
344
+ for (let e = 0; e < 3; e++) this.sun.direction[e] = -n[e], this.sun.color[e] = r[e];
345
+ t.push(this.sun);
346
+ }
347
+ for (let n of e.plugins.values()) {
348
+ let e = n.list;
349
+ if (n.name.startsWith("clustered") && Array.isArray(e)) for (let n of e) t.push(n);
350
+ else n.name.startsWith("environment:") && "sky" in n && t.push(n);
351
+ }
352
+ return t;
353
+ }
354
+ input(e, t, n, r) {
355
+ let i = this.element.ownerDocument, a = i.createElement("label"), o = i.createElement("span"), s = i.createElement("input");
356
+ return o.textContent = n, s.type = r, s.dataset.property = t, a.append(o, s), e.append(a), this.inputs.set(t, s), s;
357
+ }
358
+ liveSelection() {
359
+ return !!this.selection && !a.has(this.selection) && this.engine?.meshes.get(this.selection.id) === this.selection;
360
+ }
361
+ edit(e, t) {
362
+ try {
363
+ t(), e.setCustomValidity("");
364
+ } catch (t) {
365
+ e.setCustomValidity(String(t));
366
+ }
367
+ this.refresh();
368
+ }
369
+ refresh() {
370
+ if (this.disposed) return;
371
+ let e = this.engine;
372
+ this.selection && !this.liveSelection() && (this.selection = null);
373
+ let t = "", n = !1;
374
+ if (e && !e.disposed) for (let r of this.meshes()) t += JSON.stringify([
375
+ r.id,
376
+ r.name,
377
+ e.store.parents[r.id],
378
+ r.visible,
379
+ r === this.selection,
380
+ this.collapsed.has(r)
381
+ ]), this.items.has(r) || (n = !0);
382
+ if (t !== this.signature || n) {
383
+ let n = this.tree.contains(this.root.activeElement);
384
+ this.signature = t, this.tree.replaceChildren(), this.items.clear();
385
+ for (let t of [...this.collapsed]) e?.meshes.get(t.id) !== t && this.collapsed.delete(t);
386
+ if (e) {
387
+ let t = /* @__PURE__ */ new Map(), n = this.element.ownerDocument;
388
+ for (let e of this.meshes()) {
389
+ let r = n.createElement("div"), i = n.createElement("div"), a = n.createElement("span"), o = n.createElement("div");
390
+ r.setAttribute("role", "treeitem"), r.setAttribute("aria-selected", String(e === this.selection)), r.tabIndex = e === this.selection ? 0 : -1, r.dataset.entity = String(e.id), i.className = "row", a.className = "name", a.textContent = e.name || this.label?.(e) || `Entity ${e.id}`, e.visible || a.classList.add("muted"), i.addEventListener("click", () => {
391
+ this.select(e), this.items.get(e)?.focus();
392
+ }), o.setAttribute("role", "group"), o.hidden = this.collapsed.has(e), i.append(a), r.append(i, o), t.set(e.id, o), this.items.set(e, r);
393
+ }
394
+ for (let [n, r] of this.items) {
395
+ let i = e.store.parents[n.id];
396
+ (t.get(i) ?? this.tree).append(r);
397
+ }
398
+ for (let [e, r] of this.items) {
399
+ let i = t.get(e.id);
400
+ if (i.childElementCount) {
401
+ let t = n.createElement("button");
402
+ t.type = "button", t.tabIndex = -1, t.textContent = this.collapsed.has(e) ? "+" : "-", t.setAttribute("aria-label", `Toggle ${e.name || "entity"} children`), r.setAttribute("aria-expanded", String(!i.hidden)), t.addEventListener("click", (t) => {
403
+ t.stopPropagation(), this.toggle(e);
404
+ }), r.firstElementChild.prepend(t);
405
+ }
406
+ }
407
+ if (this.query) {
408
+ let t = /* @__PURE__ */ new Set();
409
+ for (let n of this.items.keys()) if ((n.name || `Entity ${n.id}`).toLowerCase().includes(this.query)) for (let r = n; r && !t.has(r); r = e.meshes.get(e.store.parents[r.id])) t.add(r);
410
+ for (let [e, n] of this.items) n.hidden = !t.has(e);
411
+ }
412
+ let r = this.tree.querySelector("[role=treeitem]:not([hidden])");
413
+ r && !this.selection && (r.tabIndex = 0);
414
+ }
415
+ n && (this.selection ? this.items.get(this.selection) : this.tree.querySelector("[role=treeitem]"))?.focus();
416
+ }
417
+ for (let [t, n] of this.inputs) {
418
+ if (t in this.debug) {
419
+ n.disabled = e?.backend !== "webgpu";
420
+ continue;
421
+ }
422
+ let r = t === "exposure" || t === "bloom";
423
+ if (n.disabled = r ? !this.effects || !(t in this.effects) : !this.liveSelection(), !(this.root.activeElement === n || n.disabled)) {
424
+ if (r) n.value = String(this.effects[t] ?? 0);
425
+ else if (t === "name") n.value = this.selection.name;
426
+ else if (t === "visible") n.checked = this.selection.visible;
427
+ else if (t === "color") n.value = o(this.selection.material.data);
428
+ else if (t === "doubleSided") n.checked = !!this.selection.material.data[6];
429
+ else if (t === "roughness" || t === "metallic") n.value = String(this.selection.material.data[t === "roughness" ? 4 : 5]);
430
+ else {
431
+ let [e, r] = t.split(".");
432
+ n.value = String(this.selection[e][r]);
433
+ }
434
+ }
435
+ }
436
+ let r = this.buttons.get("undo"), i = this.buttons.get("redo");
437
+ if (r.disabled = !this.history.undoCount, i.disabled = !this.history.redoCount, r.title = this.history.nextUndo ? `Undo: ${this.history.nextUndo}` : "Nothing to undo", i.title = this.history.nextRedo ? `Redo: ${this.history.nextRedo}` : "Nothing to redo", this.buttons.get("save").disabled = this.buttons.get("load").disabled = !e || e.disposed, e && !e.disposed) {
438
+ if (this.details.get("resources").open) {
439
+ let t = u(e, this.meshes());
440
+ this.outputs.get("resources").textContent = `${t.backend} ${t.canvas.width} x ${t.canvas.height}\n${t.meshes} meshes (${t.visibleMeshes} visible)\n${t.geometries} geometries, ${t.vertices} vertices\n${t.materials} materials, ${t.triangles} triangles drawn\nPlugins: ${t.plugins.join(", ") || "none"}`;
441
+ }
442
+ this.details.get("shader").open && (this.outputs.get("shader").textContent = this.shader || (e.backend === "webgpu" ? "Waiting for the first frame." : "WGSL shows on WebGPU only."));
443
+ }
444
+ }
445
+ toggle(e) {
446
+ this.collapsed.has(e) ? this.collapsed.delete(e) : this.collapsed.add(e), this.refresh(), this.items.get(e)?.focus();
447
+ }
448
+ keydown(e) {
449
+ let t = e.target.closest("[role=treeitem]");
450
+ if (!t || !this.engine) return;
451
+ let n = this.engine.meshes.get(Number(t.dataset.entity)), r = [...this.tree.querySelectorAll("[role=treeitem]")].filter((e) => !e.closest("[hidden]")), i;
452
+ switch (e.key) {
453
+ case "ArrowDown":
454
+ i = r[Math.min(r.length - 1, r.indexOf(t) + 1)];
455
+ break;
456
+ case "ArrowUp":
457
+ i = r[Math.max(0, r.indexOf(t) - 1)];
458
+ break;
459
+ case "Home":
460
+ i = r[0];
461
+ break;
462
+ case "End":
463
+ i = r.at(-1);
464
+ break;
465
+ case "ArrowRight":
466
+ t.hasAttribute("aria-expanded") && (this.collapsed.has(n) ? this.toggle(n) : i = t.querySelector("[role=group]>[role=treeitem]") ?? void 0);
467
+ break;
468
+ case "ArrowLeft":
469
+ t.getAttribute("aria-expanded") === "true" ? this.toggle(n) : i = t.parentElement?.closest("[role=treeitem]") ?? void 0;
470
+ break;
471
+ case "Enter":
472
+ case " ":
473
+ this.select(n);
474
+ break;
475
+ default: return;
476
+ }
477
+ e.preventDefault(), e.stopPropagation(), i && (this.select(this.engine.meshes.get(Number(i.dataset.entity))), this.items.get(this.selection)?.focus());
478
+ }
479
+ onDeviceRestored(e) {
480
+ this.lines.onDeviceRestored(e);
481
+ }
482
+ dispose() {
483
+ this.disposed || (this.disposed = !0, this.engine?.sceneOf(this)?.removePlugin(this.name), this.engine = void 0, clearInterval(this.timer), this.stopPicking?.(), this.stopPicking = void 0, this.history.clear(), this.shader = "", this.lines.clear(), this.lines.dispose(), this.helpers.clear(), this.lightLines = void 0, this.items.clear(), this.collapsed.clear(), this.selection = null, this.element.remove());
484
+ }
485
+ [Symbol.dispose ?? Symbol()]() {
486
+ this.dispose();
487
+ }
488
+ };
489
+ //#endregion
490
+ export { i as EditHistory, y as Inspector, u as describeEngine, s as parseSnapshot, c as restoreSnapshot, l as snapshotMeshes };