@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,49 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { TransformControls, type TransformControlsOptions } from '@margoengine/controls/transform';
4
+ import type { Inspector } from './index.js';
5
+ /** Selection gizmo options; all transform controls options retain their defaults. */
6
+ export interface InspectorGizmoOptions extends TransformControlsOptions {
7
+ /** Toolbar parent. Default the inspector's shadow root; null hides the toolbar. */
8
+ parent?: HTMLElement | ShadowRoot | null;
9
+ /** Camera controls disabled during a gizmo drag and restored afterward. Default none. */
10
+ cameraControls?: {
11
+ enabled: boolean;
12
+ };
13
+ /** W/E/R, Q, +/- and Escape shortcuts on the canvas. Default true; the canvas becomes focusable. */
14
+ keyboard?: boolean;
15
+ signal?: AbortSignal;
16
+ }
17
+ /** Inspector selection -> existing transform controls, with one shared undo step per completed drag. */
18
+ export declare class InspectorGizmo {
19
+ readonly engine: EngineKernel;
20
+ readonly inspector: Inspector;
21
+ private readonly options;
22
+ readonly controls: TransformControls;
23
+ readonly element: HTMLFieldSetElement;
24
+ private readonly pluginName;
25
+ private readonly runtime;
26
+ private readonly scene;
27
+ private readonly observer?;
28
+ private readonly stopHistory;
29
+ private readonly stopToolbar;
30
+ private readonly canvas;
31
+ private readonly oldTabIndex;
32
+ private before?;
33
+ private cameraEnabled?;
34
+ private disposed;
35
+ private wasConnected;
36
+ private readonly abort;
37
+ static attach(engine: EngineKernel, inspector: Inspector, options?: InspectorGizmoOptions): InspectorGizmo;
38
+ constructor(engine: EngineKernel, inspector: Inspector, options?: InspectorGizmoOptions);
39
+ private live;
40
+ private pose;
41
+ private apply;
42
+ private readonly begin;
43
+ private readonly end;
44
+ private readonly changed;
45
+ /** Follows selection synchronously (also called before every frame and on tree mutations). */
46
+ sync(): void;
47
+ dispose(): void;
48
+ [Symbol.dispose](): void;
49
+ }
package/dist/gizmo.js ADDED
@@ -0,0 +1,131 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const t=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { t as e } from "./errors-D8rc8kzg.js";
5
+ import { engineRuntime as __margoRuntime, meshRuntime as n } from "@margoengine/core/extension";
6
+ import { TransformControls as r } from "@margoengine/controls/transform";
7
+ //#region src/gizmo.ts
8
+ var i = [
9
+ "x",
10
+ "y",
11
+ "z",
12
+ "qx",
13
+ "qy",
14
+ "qz",
15
+ "qw",
16
+ "sx",
17
+ "sy",
18
+ "sz"
19
+ ], a = 0, o = class o {
20
+ static attach(e, t, n = {}) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
21
+ return new o(e, t, n);
22
+ }
23
+ constructor(n, i, o = {}) {
24
+ if (this.engine = n, this.inspector = i, this.options = o, this.pluginName = `inspector:gizmo:${++a}`, this.disposed = !1, this.wasConnected = !1, this.abort = () => this.dispose(), this.begin = () => {
25
+ let e = this.controls.object;
26
+ e && this.live(e) && (this.before = {
27
+ mesh: e,
28
+ pose: this.pose(e)
29
+ }, this.options.cameraControls && (this.cameraEnabled = this.options.cameraControls.enabled, this.options.cameraControls.enabled = !1));
30
+ }, this.end = () => {
31
+ let e = this.before;
32
+ if (this.before = void 0, this.cameraEnabled !== void 0 && this.options.cameraControls && (this.options.cameraControls.enabled = this.cameraEnabled, this.cameraEnabled = void 0), !e || !this.live(e.mesh)) return;
33
+ let t = this.pose(e.mesh);
34
+ e.pose.every((e, n) => e === t[n]) || (this.inspector.history.record({
35
+ label: `${this.controls.mode} ${e.mesh.name || "entity"}`,
36
+ undo: () => this.apply(e.mesh, e.pose),
37
+ redo: () => this.apply(e.mesh, t)
38
+ }), this.inspector.refresh());
39
+ }, this.changed = () => {
40
+ this.inspector.refresh();
41
+ }, o.signal?.throwIfAborted(), this.runtime = t(n), !this.runtime.sceneOf(i)) throw e("state", "Attach the inspector to this engine before its gizmo");
42
+ this.canvas = n.canvas, this.oldTabIndex = this.canvas.getAttribute?.("tabindex") ?? null;
43
+ let s = o.element ?? this.canvas, c = new Proxy(s, { get: (e, t) => {
44
+ if (t === "addEventListener" || t === "removeEventListener") return (n, r) => e[t](n, r, !0);
45
+ let n = Reflect.get(e, t, e);
46
+ return typeof n == "function" ? n.bind(e) : n;
47
+ } }), l = this.scene = this.runtime.sceneOf(i), u;
48
+ l.use({coreRequirement:/*@__PURE__*/__margoCoreRequirement("0.1.0",import.meta.url),
49
+ name: this.pluginName,
50
+ setup: () => {
51
+ u = r.attach(n, {
52
+ ...o,
53
+ element: c
54
+ });
55
+ },
56
+ onPreUpdate: () => this.sync(),
57
+ dispose: () => this.dispose()
58
+ }), this.controls = u, this.controls.addEventListener("mouseDown", this.begin), this.controls.addEventListener("mouseUp", this.end), this.controls.addEventListener("objectChange", this.changed), this.element = i.element.ownerDocument.createElement("fieldset");
59
+ let d = this.element.ownerDocument.createElement("legend");
60
+ d.textContent = "Transform gizmo", this.element.append(d);
61
+ for (let [e, t] of [
62
+ ["Move", "translate"],
63
+ ["Rotate", "rotate"],
64
+ ["Scale", "scale"]
65
+ ]) {
66
+ let n = this.element.ownerDocument.createElement("button");
67
+ n.textContent = e, n.addEventListener("click", () => this.controls.setMode(t)), this.element.append(n);
68
+ }
69
+ let f = this.element.ownerDocument.createElement("select");
70
+ f.setAttribute("aria-label", "Gizmo space");
71
+ for (let e of ["world", "local"]) {
72
+ let t = f.ownerDocument.createElement("option");
73
+ t.value = e, t.textContent = e, f.append(t);
74
+ }
75
+ f.value = this.controls.space, f.addEventListener("change", () => this.controls.setSpace(f.value)), this.element.append(f);
76
+ let p = () => {
77
+ for (let [e, t] of [
78
+ "translate",
79
+ "rotate",
80
+ "scale"
81
+ ].entries()) this.element.querySelectorAll("button")[e].setAttribute("aria-pressed", String(this.controls.mode === t));
82
+ f.value = this.controls.space;
83
+ };
84
+ this.controls.addEventListener("mode-changed", p), this.controls.addEventListener("space-changed", p), this.stopToolbar = () => {
85
+ this.controls.removeEventListener("mode-changed", p), this.controls.removeEventListener("space-changed", p);
86
+ }, p(), (o.parent === void 0 ? i.root : o.parent)?.append(this.element), o.keyboard !== !1 && (this.canvas.hasAttribute("tabindex") || (this.canvas.tabIndex = 0), this.controls.listenToKeyEvents(this.canvas)), this.stopHistory = i.history.onChange(() => this.sync());
87
+ let m = i.element.ownerDocument.defaultView?.MutationObserver;
88
+ m && (this.observer = new m(() => this.sync()), this.observer.observe(i.root, {
89
+ subtree: !0,
90
+ childList: !0,
91
+ attributes: !0,
92
+ attributeFilter: ["aria-selected"]
93
+ }), this.observer.observe(i.element.parentNode, { childList: !0 })), o.signal?.addEventListener("abort", this.abort, { once: !0 }), this.sync();
94
+ }
95
+ live(e) {
96
+ return !this.runtime.disposed && this.runtime.meshes.get(n(e).id) === n(e);
97
+ }
98
+ pose(e) {
99
+ let { id: t } = n(e), r = this.runtime.store.transforms;
100
+ return i.map((e) => r[e][t]);
101
+ }
102
+ apply(e, t) {
103
+ this.live(e) && (e.setPosition([
104
+ t[0],
105
+ t[1],
106
+ t[2]
107
+ ]).setQuaternion(t.slice(3, 7)).setScale([
108
+ t[7],
109
+ t[8],
110
+ t[9]
111
+ ]), this.inspector.refresh());
112
+ }
113
+ sync() {
114
+ if (this.disposed) return;
115
+ if (this.wasConnected && !this.inspector.element.isConnected) {
116
+ this.dispose();
117
+ return;
118
+ }
119
+ this.wasConnected ||= this.inspector.element.isConnected;
120
+ let e = this.inspector.selected, t = e && this.live(e) ? e : null;
121
+ t !== this.controls.object && (t ? this.controls.attach(t) : this.controls.detach());
122
+ }
123
+ dispose() {
124
+ this.disposed || (this.disposed = !0, this.controls?.object && this.live(this.controls.object) && this.controls.cancelDrag(), this.end(), this.observer?.disconnect(), this.stopHistory?.(), this.stopToolbar?.(), this.options.signal?.removeEventListener("abort", this.abort), this.controls?.removeEventListener("mouseDown", this.begin), this.controls?.removeEventListener("mouseUp", this.end), this.controls?.removeEventListener("objectChange", this.changed), this.controls?.dispose(), this.element?.remove(), this.options.keyboard !== !1 && (this.oldTabIndex === null ? this.canvas.removeAttribute?.("tabindex") : this.canvas.setAttribute?.("tabindex", this.oldTabIndex)), this.scene.removePlugin(this.pluginName));
125
+ }
126
+ [Symbol.dispose]() {
127
+ this.dispose();
128
+ }
129
+ };
130
+ //#endregion
131
+ export { o as InspectorGizmo };
package/dist/gl.d.ts ADDED
@@ -0,0 +1,89 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type EnginePlugin, type FrameGraph } from '@margoengine/core/extension';
4
+ /** A captured native GL draw, including the state and shader sources actually used. */
5
+ export interface GLDrawReport {
6
+ method: string;
7
+ arguments: number[];
8
+ program: number | null;
9
+ framebuffer: number | null;
10
+ vertexArray: number | null;
11
+ viewport: number[];
12
+ depthTest: boolean;
13
+ blend: boolean;
14
+ cullFace: boolean;
15
+ shaders: string[];
16
+ }
17
+ /** One graph pass in one view of the captured frame. */
18
+ export interface GLFramePassReport {
19
+ name: string;
20
+ owner: string;
21
+ order: number;
22
+ view?: string;
23
+ cpuMilliseconds: number;
24
+ gpuMilliseconds: number | null;
25
+ draws: GLDrawReport[];
26
+ }
27
+ /** Plain JSON capture of one preview-backend frame. Null GPU costs mean unsupported or disjoint timing. */
28
+ export interface GLFrameReport {
29
+ backend: 'webgl2';
30
+ gpuTiming: boolean;
31
+ passes: GLFramePassReport[];
32
+ drawCalls: number;
33
+ }
34
+ /** Capture cancellation and maximum GPU readback wait. */
35
+ export interface GLCaptureOptions {
36
+ /** Default true. False waits for the next engine frame. */
37
+ render?: boolean;
38
+ /** Default 5000 ms, positive and finite. */
39
+ timeout?: number;
40
+ signal?: AbortSignal;
41
+ }
42
+ /** Captures an existing preview frame, including already-registered passes. Wrappers are removed after that frame. */
43
+ export declare function captureGLFrame(handle: EngineKernel, options?: GLCaptureOptions): Promise<GLFrameReport>;
44
+ /** WebGL2 overlay panel placement. */
45
+ export interface GLInspectorOptions {
46
+ /** Default document.body; null keeps the controls detached. */
47
+ parent?: HTMLElement | ShadowRoot | null;
48
+ signal?: AbortSignal;
49
+ }
50
+ type Mode = 'wireframe' | 'normals' | 'bounds' | 'lights';
51
+ /** Wireframe, world normals, bounds, light helpers and one-frame capture for the WebGL2 preview backend. */
52
+ export declare class GLInspector implements EnginePlugin {
53
+ readonly engine: EngineKernel;
54
+ private readonly options;
55
+ readonly name: string;
56
+ readonly element: HTMLElement;
57
+ readonly debug: {
58
+ wireframe: boolean;
59
+ normals: boolean;
60
+ bounds: boolean;
61
+ lights: boolean;
62
+ };
63
+ private readonly runtime;
64
+ private readonly helpers;
65
+ private light?;
66
+ private program?;
67
+ private buffer?;
68
+ private vao?;
69
+ private gl?;
70
+ private disposed;
71
+ private readonly inputs;
72
+ private readonly controller;
73
+ private readonly abort;
74
+ private readonly lost;
75
+ /** Installs an independent panel; pass inspector.root as parent to place it beside the scene tree. */
76
+ static attach(engine: EngineKernel, options?: GLInspectorOptions): GLInspector;
77
+ constructor(engine: EngineKernel, options?: GLInspectorOptions);
78
+ setup(): void;
79
+ /** Turns an overlay on or off. */
80
+ setDebug(mode: Mode, enabled: boolean): void;
81
+ /** Captures one frame and shows the native draw state; disposal aborts the operation. */
82
+ capture(options?: GLCaptureOptions): Promise<GLFrameReport>;
83
+ registerPasses(graph: FrameGraph): void;
84
+ private gather;
85
+ private draw;
86
+ dispose(): void;
87
+ [Symbol.dispose](): void;
88
+ }
89
+ export {};
package/dist/gl.js ADDED
@@ -0,0 +1,284 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const a=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { t 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 { t as i } from "./edit-state-Dm3G17js.js";
8
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
9
+ import { BoxHelper as o, LightsHelper as s, VertexNormalsHelper as c } from "@margoengine/lines";
10
+ import { meshWorldMatrix as l } from "@margoengine/math/mesh";
11
+ import { GLStats as u } from "@margoengine/stats/gl";
12
+ //#region src/gl.ts
13
+ var d = /* @__PURE__ */ new WeakSet();
14
+ function f(e) {
15
+ return Object.values(e).find((e) => Array.isArray(e) && e.length > 0 && e.every((e) => typeof e?.execute == "function" && typeof e.name == "string")) ?? [];
16
+ }
17
+ async function p(t, n = {}) {
18
+ let r = a(t), i = r.backend === "webgl2" ? r.canvas.getContext("webgl2") : null, o = n.timeout ?? 5e3;
19
+ if (n.signal?.throwIfAborted(), !i) throw e("unsupported", "Use the WebGL2 preview backend for captureGLFrame");
20
+ if (!Number.isFinite(o) || o <= 0) throw RangeError("Use a positive finite GL capture timeout");
21
+ if (d.has(r)) throw e("state", "Await the current GL capture before starting another");
22
+ d.add(r);
23
+ let s = new u(), c = [], l = [], p = /* @__PURE__ */ new WeakMap(), m = 1, h, g = !1, _ = !1, v = !1, y = (e) => e ? (p.has(e) || p.set(e, m++), p.get(e)) : null, b = () => {
24
+ for (let e of l.splice(0).reverse()) e();
25
+ }, x, S, C = () => {}, w = () => {
26
+ v = !0, C(n.signal?.reason ?? e("disposed", "GL capture cancelled; start a new capture"));
27
+ };
28
+ try {
29
+ s.track(i);
30
+ for (let e of [
31
+ "drawArrays",
32
+ "drawElements",
33
+ "drawRangeElements",
34
+ "drawArraysInstanced",
35
+ "drawElementsInstanced"
36
+ ]) {
37
+ let t = i[e], n = (...n) => {
38
+ if (h) {
39
+ let t = i.getParameter(i.CURRENT_PROGRAM);
40
+ h.draws.push({
41
+ method: e,
42
+ arguments: [...n],
43
+ program: y(t),
44
+ framebuffer: y(i.getParameter(i.DRAW_FRAMEBUFFER_BINDING)),
45
+ vertexArray: y(i.getParameter(i.VERTEX_ARRAY_BINDING)),
46
+ viewport: Array.from(i.getParameter(i.VIEWPORT)),
47
+ depthTest: i.isEnabled(i.DEPTH_TEST),
48
+ blend: i.isEnabled(i.BLEND),
49
+ cullFace: i.isEnabled(i.CULL_FACE),
50
+ shaders: t ? (i.getAttachedShaders(t) ?? []).map((e) => i.getShaderSource(e) ?? "") : []
51
+ });
52
+ }
53
+ return Reflect.apply(t, i, n);
54
+ };
55
+ Object.assign(i, { [e]: n }), l.push(() => {
56
+ i[e] === n && Object.assign(i, { [e]: t });
57
+ });
58
+ }
59
+ let t = new Promise((t, a) => {
60
+ C = a, x = setTimeout(() => a(e("timeout", "GL capture timed out; render a frame or increase timeout")), o), n.signal?.addEventListener("abort", w, { once: !0 });
61
+ let u = () => {
62
+ if (v) return;
63
+ s.endFrame(), b();
64
+ let e = () => {
65
+ if (v) return;
66
+ s.poll();
67
+ let n = i.getExtension("EXT_disjoint_timer_query_webgl2");
68
+ !_ || !s.supported || s.sampleId > 0 || n && i.getParameter(n.GPU_DISJOINT_EXT) ? t() : S = setTimeout(e, 4);
69
+ };
70
+ e();
71
+ }, d = /* @__PURE__ */ new Set([r.frameGraph, ...[...r.scenes].map((e) => e.frameGraph)]);
72
+ for (let e of d) {
73
+ let t = e.execute, n = (n) => {
74
+ if (n.backend !== "webgl2" || v) return t.call(e, n);
75
+ g || (g = !0, _ = s.beginFrame(), queueMicrotask(u));
76
+ let r = [];
77
+ for (let t of f(e)) {
78
+ let e = t.execute, n = (n) => {
79
+ let r = {
80
+ name: t.name,
81
+ owner: t.owner ?? "core",
82
+ order: t.order,
83
+ view: n.view?.id,
84
+ cpuMilliseconds: 0,
85
+ gpuMilliseconds: null,
86
+ draws: []
87
+ };
88
+ c.push(r), h = r;
89
+ let i = performance.now();
90
+ try {
91
+ s.pass(String(c.length - 1), () => e(n));
92
+ } finally {
93
+ r.cpuMilliseconds = performance.now() - i, h = void 0;
94
+ }
95
+ };
96
+ t.execute = n, r.push(() => {
97
+ t.execute === n && (t.execute = e);
98
+ });
99
+ }
100
+ try {
101
+ t.call(e, n);
102
+ } catch (e) {
103
+ throw v = !0, a(e), e;
104
+ } finally {
105
+ r.reverse().forEach((e) => e());
106
+ }
107
+ };
108
+ e.execute = n, l.push(() => {
109
+ e.execute === n && (e.execute = t);
110
+ });
111
+ }
112
+ });
113
+ if (n.render !== !1) try {
114
+ r.render();
115
+ } catch (e) {
116
+ v = !0, C(e);
117
+ }
118
+ await t;
119
+ for (let e of s.passes) c[Number(e.name)] && (c[Number(e.name)].gpuMilliseconds = e.milliseconds);
120
+ return {
121
+ backend: "webgl2",
122
+ gpuTiming: s.sampleId > 0,
123
+ passes: c,
124
+ drawCalls: c.reduce((e, t) => e + t.draws.length, 0)
125
+ };
126
+ } finally {
127
+ v = !0, clearTimeout(x), clearTimeout(S), n.signal?.removeEventListener("abort", w), b(), s.dispose(), d.delete(r);
128
+ }
129
+ }
130
+ var m = "#version 300 es\nprecision highp float;layout(location=0) in vec3 position;uniform mat4 camera;uniform mat4 model;void main(){gl_Position=camera*model*vec4(position,1.0);}", h = "#version 300 es\nprecision highp float;uniform vec3 color;out vec4 outputColor;void main(){outputColor=vec4(color,1.0);}";
131
+ function g(t) {
132
+ let n = t.createProgram();
133
+ if (!n) throw e("failed", "Cannot allocate the GL debug program; restore the context and reattach");
134
+ let r = [];
135
+ try {
136
+ if ([m, h].forEach((i, a) => {
137
+ let o = t.createShader(a === 0 ? t.VERTEX_SHADER : t.FRAGMENT_SHADER);
138
+ if (!o) throw e("failed", "Cannot allocate a GL debug shader; restore the context and reattach");
139
+ if (r.push(o), t.shaderSource(o, i), t.compileShader(o), !t.getShaderParameter(o, t.COMPILE_STATUS)) throw e("failed", `GL debug shader failed: ${t.getShaderInfoLog(o) ?? "unknown compiler error"}; check the driver`);
140
+ t.attachShader(n, o);
141
+ }), t.linkProgram(n), !t.getProgramParameter(n, t.LINK_STATUS)) throw e("failed", `GL debug program failed: ${t.getProgramInfoLog(n) ?? "unknown linker error"}; check the driver`);
142
+ return n;
143
+ } catch (e) {
144
+ throw t.deleteProgram(n), e;
145
+ } finally {
146
+ for (let e of r) t.deleteShader(e);
147
+ }
148
+ }
149
+ var _ = 0, v = class u {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
150
+ static attach(e, t = {}) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
151
+ let n = new u(e, t);
152
+ try {
153
+ return e.use(n), n;
154
+ } catch (e) {
155
+ throw n.dispose(), e;
156
+ }
157
+ }
158
+ constructor(e, t = {}) {
159
+ this.engine = e, this.options = t, this.name = `inspector:gl:${++_}`, this.debug = {
160
+ wireframe: !1,
161
+ normals: !1,
162
+ bounds: !1,
163
+ lights: !1
164
+ }, this.helpers = /* @__PURE__ */ new Map(), this.disposed = !1, this.inputs = /* @__PURE__ */ new Map(), this.controller = new AbortController(), this.abort = () => this.dispose(), this.lost = () => {
165
+ this.program = void 0, this.buffer = void 0, this.vao = void 0;
166
+ }, t.signal?.throwIfAborted(), this.runtime = a(e);
167
+ let n = e.canvas.ownerDocument;
168
+ this.element = n.createElement("fieldset");
169
+ let r = n.createElement("legend");
170
+ r.textContent = "WebGL2 debug", this.element.append(r);
171
+ for (let e of Object.keys(this.debug)) {
172
+ let t = n.createElement("label"), r = n.createElement("input");
173
+ r.type = "checkbox", t.textContent = e, t.append(r), this.element.append(t), r.addEventListener("change", () => this.setDebug(e, r.checked)), this.inputs.set(e, r);
174
+ }
175
+ let i = n.createElement("button"), o = n.createElement("pre");
176
+ i.type = "button", i.textContent = "Capture GL frame", i.addEventListener("click", async () => {
177
+ i.disabled = !0;
178
+ try {
179
+ o.textContent = JSON.stringify(await this.capture(), null, 2);
180
+ } catch (e) {
181
+ o.textContent = String(e);
182
+ } finally {
183
+ i.disabled = !1;
184
+ }
185
+ }), this.element.append(i, o), (t.parent === void 0 ? n.body : t.parent)?.append(this.element), t.signal?.addEventListener("abort", this.abort, { once: !0 }), e.canvas.addEventListener("webglcontextlost", this.lost);
186
+ }
187
+ setup() {
188
+ if (this.gl = this.runtime.backend === "webgl2" ? this.engine.canvas.getContext("webgl2") ?? void 0 : void 0, !this.gl || this.runtime.backend !== "webgl2") throw e("unsupported", "GLInspector requires the WebGL2 preview backend");
189
+ }
190
+ setDebug(t, n) {
191
+ if (this.disposed) throw e("disposed", "Create a new GLInspector after disposal");
192
+ if (!Object.hasOwn(this.debug, t) || typeof n != "boolean") throw TypeError("Use wireframe, normals, bounds or lights and a boolean");
193
+ this.debug[t] = n, this.inputs.get(t).checked = n;
194
+ }
195
+ capture(e = {}) {
196
+ return p(this.engine, {
197
+ ...e,
198
+ signal: e.signal ? AbortSignal.any([e.signal, this.controller.signal]) : this.controller.signal
199
+ });
200
+ }
201
+ registerPasses(e) {
202
+ e.add({
203
+ name: this.name,
204
+ order: 20,
205
+ execute: (e) => {
206
+ e.backend === "webgl2" && this.draw(e);
207
+ }
208
+ });
209
+ }
210
+ gather() {
211
+ let { direction: e, radiance: t } = this.runtime.lighting, n = [];
212
+ e[3] > 0 && n.push({
213
+ direction: [
214
+ -e[0],
215
+ -e[1],
216
+ -e[2]
217
+ ],
218
+ color: [
219
+ t[0],
220
+ t[1],
221
+ t[2]
222
+ ]
223
+ });
224
+ for (let e of this.runtime.plugins.values()) {
225
+ let t = e.list;
226
+ e.name.startsWith("clustered") && Array.isArray(t) ? n.push(...t) : e.name.startsWith("environment:") && "sky" in e && n.push(e);
227
+ }
228
+ return n;
229
+ }
230
+ draw(a) {
231
+ let u = this.gl;
232
+ if (u.isContextLost()) return;
233
+ let d = this.runtime.sceneOf(this) ?? this.runtime.scene, f = [];
234
+ for (let [e, t] of this.helpers) (!d.meshes.has(e.id) || n(e)?.identity !== t.source) && (t.wireframe?.dispose(), t.normals?.dispose(), t.bounds?.dispose(), this.helpers.delete(e));
235
+ for (let e of d.meshes.values()) {
236
+ let s = n(e);
237
+ if (!s || i.has(e) || !r(a, e) || !l(this.runtime, e)) continue;
238
+ let u = this.helpers.get(e);
239
+ u || (u = { source: s.identity }, this.helpers.set(e, u));
240
+ for (let n of [
241
+ "wireframe",
242
+ "normals",
243
+ "bounds"
244
+ ]) if (this.debug[n]) {
245
+ let r = u[n] ??= n === "wireframe" ? t(e) : n === "normals" ? new c(e, {
246
+ size: s.radius * .15,
247
+ color: "#ed6b86"
248
+ }) : new o(e, { color: "#e4ba31" });
249
+ r.update(this.engine) !== !1 && f.push(r);
250
+ }
251
+ }
252
+ if (this.debug.lights && (this.light ??= new s(() => this.gather(), { size: .25 }), this.light.update(), f.push(this.light)), !f.length) return;
253
+ let p = u.getParameter(u.CURRENT_PROGRAM), m = u.getParameter(u.VERTEX_ARRAY_BINDING), h = u.getParameter(u.ARRAY_BUFFER_BINDING), _ = u.getParameter(u.DEPTH_WRITEMASK), v = u.getParameter(u.LINE_WIDTH), y = u.getParameter(u.COLOR_WRITEMASK), b = [
254
+ u.DEPTH_TEST,
255
+ u.BLEND,
256
+ u.CULL_FACE
257
+ ].map((e) => [e, u.isEnabled(e)]);
258
+ try {
259
+ if (!this.program) {
260
+ if (this.program = g(u), this.buffer = u.createBuffer() ?? void 0, this.vao = u.createVertexArray() ?? void 0, !this.buffer || !this.vao) throw e("failed", "Cannot allocate GL debug buffers; free resources and reattach");
261
+ u.bindVertexArray(this.vao), u.bindBuffer(u.ARRAY_BUFFER, this.buffer), u.enableVertexAttribArray(0), u.vertexAttribPointer(0, 3, u.FLOAT, !1, 16, 0);
262
+ }
263
+ u.useProgram(this.program), u.bindVertexArray(this.vao), u.bindBuffer(u.ARRAY_BUFFER, this.buffer), b.forEach(([e]) => u.disable(e)), u.depthMask(!1), u.colorMask(!0, !0, !0, !0), u.lineWidth(1), u.uniformMatrix4fv(u.getUniformLocation(this.program, "camera"), !1, a.camera.matrix);
264
+ for (let e of f) {
265
+ let t = e.attachedMesh ? l(this.runtime, e.attachedMesh) : e.matrix;
266
+ t && (u.uniformMatrix4fv(u.getUniformLocation(this.program, "model"), !1, t), u.uniform3fv(u.getUniformLocation(this.program, "color"), e.material.color), u.bufferData(u.ARRAY_BUFFER, e.points.subarray(0, e.count * 4), u.DYNAMIC_DRAW), u.drawArrays(u.LINES, 0, e.count));
267
+ }
268
+ } finally {
269
+ u.useProgram(p), u.bindVertexArray(m), u.bindBuffer(u.ARRAY_BUFFER, h), u.depthMask(_), u.lineWidth(v), u.colorMask(...y), b.forEach(([e, t]) => t ? u.enable(e) : u.disable(e));
270
+ }
271
+ }
272
+ dispose() {
273
+ if (!this.disposed) {
274
+ this.disposed = !0, this.controller.abort(), this.options.signal?.removeEventListener("abort", this.abort), this.engine.canvas.removeEventListener("webglcontextlost", this.lost);
275
+ for (let e of this.helpers.values()) e.wireframe?.dispose(), e.normals?.dispose(), e.bounds?.dispose();
276
+ this.helpers.clear(), this.light?.dispose(), this.gl && (this.gl.getParameter(this.gl.CURRENT_PROGRAM) === this.program && this.gl.useProgram(null), this.program && this.gl.deleteProgram(this.program), this.vao && this.gl.deleteVertexArray(this.vao), this.buffer && this.gl.deleteBuffer(this.buffer)), this.element.remove(), this.runtime.sceneOf(this)?.removePlugin(this.name);
277
+ }
278
+ }
279
+ [Symbol.dispose]() {
280
+ this.dispose();
281
+ }
282
+ };
283
+ //#endregion
284
+ export { v as GLInspector, p as captureGLFrame };
@@ -0,0 +1,65 @@
1
+ /** One undoable edit: how to take it back and how to do it again. */
2
+ export interface Edit {
3
+ /** Shown to people, e.g. `'Set position.x'`. */
4
+ label: string;
5
+ /** Puts the old value back. */
6
+ undo(): void;
7
+ /** Puts the new value back. */
8
+ redo(): void;
9
+ /**
10
+ * Edits with the same `key` recorded within the history's `coalesceMs` of each other become one: a slider dragged
11
+ * across fifty values undoes in one step. The merged edit keeps the first `undo` and takes the latest `redo`.
12
+ */
13
+ key?: string;
14
+ /** Releases retained resources when this edit leaves both stacks. Called once; never during undo/redo. */
15
+ discard?(): void;
16
+ }
17
+ /**
18
+ * A bounded undo/redo stack. `record` adds an edit that has already happened (it clears the redo side); `undo` and
19
+ * `redo` run the edits and move along. Edits made by `undo`/`redo` themselves are never recorded.
20
+ *
21
+ * ```ts
22
+ * const history = new EditHistory();
23
+ * history.record({ label: 'Move', undo: () => (x = 0), redo: () => (x = 5) });
24
+ * history.undo();
25
+ * ```
26
+ */
27
+ export declare class EditHistory {
28
+ readonly limit: number;
29
+ readonly coalesceMs: number;
30
+ private readonly now;
31
+ private readonly done;
32
+ private readonly undone;
33
+ private last;
34
+ private running;
35
+ private readonly listeners;
36
+ /**
37
+ * @param limit Most edits kept (the oldest are dropped), 1 to 100,000. Default 200.
38
+ * @param coalesceMs Window in milliseconds for merging edits with one `key`, 0 or more. Default 800.
39
+ * @param now Clock in milliseconds. Default `performance.now`.
40
+ */
41
+ constructor(limit?: number, coalesceMs?: number, now?: () => number);
42
+ /** Edits that `undo()` would take back. */
43
+ get undoCount(): number;
44
+ /** Edits that `redo()` would do again. */
45
+ get redoCount(): number;
46
+ /** Label of the edit `undo()` would take back, or undefined. */
47
+ get nextUndo(): string | undefined;
48
+ /** Label of the edit `redo()` would do again, or undefined. */
49
+ get nextRedo(): string | undefined;
50
+ /**
51
+ * Adds an edit that has just been applied and forgets the redo side.
52
+ * @throws TypeError when `edit` lacks a label, `undo` or `redo`; MargoError `'state'` from inside an undo or redo.
53
+ */
54
+ record(edit: Edit): void;
55
+ /** Takes back the latest edit; false when there is none. */
56
+ undo(): boolean;
57
+ /** Does the latest undone edit again; false when there is none. */
58
+ redo(): boolean;
59
+ /** Forgets every edit. */
60
+ clear(): void;
61
+ /** Calls `listener` after every record, undo, redo and clear. Returns a function that removes it. */
62
+ onChange(listener: () => void): () => void;
63
+ private step;
64
+ private changed;
65
+ }