@margoengine/shader 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 (91) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1771 -3
  4. package/dist/black-hole.d.ts +246 -0
  5. package/dist/black-hole.js +445 -0
  6. package/dist/clock-BLGNexlt.js +52 -0
  7. package/dist/clock.d.ts +42 -0
  8. package/dist/compute-D-BghbXj.js +354 -0
  9. package/dist/compute-texture.d.ts +100 -0
  10. package/dist/compute-texture.js +131 -0
  11. package/dist/compute-volume.d.ts +57 -0
  12. package/dist/compute-volume.js +130 -0
  13. package/dist/compute.d.ts +194 -0
  14. package/dist/control-DvjfV7R0.js +201 -0
  15. package/dist/control.d.ts +93 -0
  16. package/dist/deform.d.ts +111 -0
  17. package/dist/deform.js +89 -0
  18. package/dist/display-BrJM_Qkd.js +5 -0
  19. package/dist/editor-model.d.ts +192 -0
  20. package/dist/editor-pass.d.ts +71 -0
  21. package/dist/editor-pass.js +216 -0
  22. package/dist/editor.d.ts +150 -0
  23. package/dist/editor.js +1071 -0
  24. package/dist/effects.d.ts +150 -0
  25. package/dist/effects.js +87 -0
  26. package/dist/errors-CsQwshHA.js +7 -0
  27. package/dist/glsl/emit.d.ts +43 -0
  28. package/dist/glsl/host.d.ts +55 -0
  29. package/dist/glsl/material.d.ts +173 -0
  30. package/dist/glsl/parser.d.ts +76 -0
  31. package/dist/glsl/preprocess.d.ts +9 -0
  32. package/dist/glsl/presets.d.ts +33 -0
  33. package/dist/glsl/program.d.ts +210 -0
  34. package/dist/glsl/scene.d.ts +9 -0
  35. package/dist/glsl-material.d.ts +82 -0
  36. package/dist/glsl-material.js +288 -0
  37. package/dist/glsl-pass.d.ts +93 -0
  38. package/dist/glsl-pass.js +186 -0
  39. package/dist/glsl.d.ts +94 -0
  40. package/dist/glsl.js +170 -0
  41. package/dist/gpu-DQ5Jmggz.js +31 -0
  42. package/dist/graph.d.ts +82 -0
  43. package/dist/graph.js +365 -0
  44. package/dist/index.d.ts +7 -0
  45. package/dist/index.js +8 -0
  46. package/dist/lighting-Dx8_RsBz.js +77 -0
  47. package/dist/lighting.d.ts +62 -0
  48. package/dist/lighting.js +1 -0
  49. package/dist/material-CU7p-Q8u.js +1184 -0
  50. package/dist/material-REzUrXtu.js +275 -0
  51. package/dist/material.d.ts +74 -0
  52. package/dist/node-DzKv9CF2.js +590 -0
  53. package/dist/node.d.ts +427 -0
  54. package/dist/noise.d.ts +38 -0
  55. package/dist/noise.js +107 -0
  56. package/dist/own-stack-D1XnXrrz.js +11 -0
  57. package/dist/own-stack.d.ts +12 -0
  58. package/dist/pass.d.ts +108 -0
  59. package/dist/pass.js +236 -0
  60. package/dist/post-DC62ZleD.js +113 -0
  61. package/dist/post.d.ts +69 -0
  62. package/dist/preprocess-CWGWlBWQ.js +1195 -0
  63. package/dist/raw-D0W8U3Qa.js +1351 -0
  64. package/dist/raw.d.ts +634 -0
  65. package/dist/raw.js +1 -0
  66. package/dist/readback.d.ts +42 -0
  67. package/dist/readback.js +84 -0
  68. package/dist/scope.d.ts +21 -0
  69. package/dist/serialization.d.ts +11 -0
  70. package/dist/serialization.js +192 -0
  71. package/dist/shadertoy/sound.d.ts +48 -0
  72. package/dist/shadertoy.d.ts +249 -0
  73. package/dist/shadertoy.js +909 -0
  74. package/dist/shared/caster.d.ts +152 -0
  75. package/dist/shared/fog.d.ts +33 -0
  76. package/dist/shared/fractal.d.ts +9 -0
  77. package/dist/shared/msaa.d.ts +25 -0
  78. package/dist/shared/stack.d.ts +22 -0
  79. package/dist/sound-CF_dzP41.js +78 -0
  80. package/dist/storage-format-DWaiSxmq.js +25 -0
  81. package/dist/storage-format.d.ts +7 -0
  82. package/dist/subgroups.d.ts +97 -0
  83. package/dist/subgroups.js +95 -0
  84. package/dist/texture-D6vy0bam.js +62 -0
  85. package/dist/texture-array.d.ts +7 -0
  86. package/dist/texture-array.js +11 -0
  87. package/dist/texture.d.ts +16 -0
  88. package/dist/utils.d.ts +106 -0
  89. package/dist/utils.js +90 -0
  90. package/dist/view-rect-Bm1ac-TK.js +16 -0
  91. package/package.json +151 -6
package/dist/editor.js ADDED
@@ -0,0 +1,1071 @@
1
+ import { SURFACE_GRAPH_LIMITS as e, SURFACE_OPERATIONS as t, createGraphMaterial as n, inspectSurfaceGraph as r, serializeSurfaceGraph as i, validateSurfaceGraph as a } from "./graph.js";
2
+ import { MargoError as o } from "@margoengine/math/errors";
3
+ //#region src/editor-model.ts
4
+ var s = Object.freeze([
5
+ {
6
+ op: "position",
7
+ label: "Position",
8
+ group: "Input",
9
+ description: "Object-space position of the surface point (vec3)."
10
+ },
11
+ {
12
+ op: "worldPosition",
13
+ label: "World position",
14
+ group: "Input",
15
+ description: "World-space position (vec3)."
16
+ },
17
+ {
18
+ op: "normal",
19
+ label: "Normal",
20
+ group: "Input",
21
+ description: "Object-space surface normal (vec3)."
22
+ },
23
+ {
24
+ op: "worldNormal",
25
+ label: "World normal",
26
+ group: "Input",
27
+ description: "World-space surface normal (vec3)."
28
+ },
29
+ {
30
+ op: "color",
31
+ label: "Vertex color",
32
+ group: "Input",
33
+ description: "Linear vertex color (vec3)."
34
+ },
35
+ {
36
+ op: "uv",
37
+ label: "UV",
38
+ group: "Input",
39
+ description: "Texture coordinates as (u, v, 0) (vec3)."
40
+ },
41
+ {
42
+ op: "float",
43
+ label: "Number",
44
+ group: "Constant",
45
+ description: "A constant number (f32)."
46
+ },
47
+ {
48
+ op: "vec3",
49
+ label: "Vector",
50
+ group: "Constant",
51
+ description: "A constant vector or linear RGB color (vec3)."
52
+ },
53
+ {
54
+ op: "add",
55
+ label: "Add",
56
+ group: "Math",
57
+ description: "A + B; a number combines with a vector."
58
+ },
59
+ {
60
+ op: "sub",
61
+ label: "Subtract",
62
+ group: "Math",
63
+ description: "A - B."
64
+ },
65
+ {
66
+ op: "mul",
67
+ label: "Multiply",
68
+ group: "Math",
69
+ description: "A * B, per component."
70
+ },
71
+ {
72
+ op: "div",
73
+ label: "Divide",
74
+ group: "Math",
75
+ description: "A / B, per component."
76
+ },
77
+ {
78
+ op: "min",
79
+ label: "Minimum",
80
+ group: "Math",
81
+ description: "The smaller of A and B."
82
+ },
83
+ {
84
+ op: "max",
85
+ label: "Maximum",
86
+ group: "Math",
87
+ description: "The larger of A and B."
88
+ },
89
+ {
90
+ op: "pow",
91
+ label: "Power",
92
+ group: "Math",
93
+ description: "Base raised to Exponent."
94
+ },
95
+ {
96
+ op: "sin",
97
+ label: "Sine",
98
+ group: "Math",
99
+ description: "Sine of the value in radians."
100
+ },
101
+ {
102
+ op: "cos",
103
+ label: "Cosine",
104
+ group: "Math",
105
+ description: "Cosine of the value in radians."
106
+ },
107
+ {
108
+ op: "abs",
109
+ label: "Absolute",
110
+ group: "Math",
111
+ description: "Absolute value."
112
+ },
113
+ {
114
+ op: "floor",
115
+ label: "Floor",
116
+ group: "Shaping",
117
+ description: "Round down to a whole number."
118
+ },
119
+ {
120
+ op: "fract",
121
+ label: "Fraction",
122
+ group: "Shaping",
123
+ description: "The part after the decimal point."
124
+ },
125
+ {
126
+ op: "saturate",
127
+ label: "Saturate",
128
+ group: "Shaping",
129
+ description: "Clamp to the range 0 to 1."
130
+ },
131
+ {
132
+ op: "mix",
133
+ label: "Mix",
134
+ group: "Shaping",
135
+ description: "Blend A to B by Factor (0 gives A, 1 gives B)."
136
+ },
137
+ {
138
+ op: "clamp",
139
+ label: "Clamp",
140
+ group: "Shaping",
141
+ description: "Limit Value to between Min and Max."
142
+ },
143
+ {
144
+ op: "length",
145
+ label: "Length",
146
+ group: "Vector",
147
+ description: "Length of a vector (f32)."
148
+ },
149
+ {
150
+ op: "dot",
151
+ label: "Dot",
152
+ group: "Vector",
153
+ description: "Dot product of two vectors (f32)."
154
+ },
155
+ {
156
+ op: "normalize",
157
+ label: "Normalize",
158
+ group: "Vector",
159
+ description: "Scale a vector to length 1."
160
+ },
161
+ {
162
+ op: "component",
163
+ label: "Component",
164
+ group: "Vector",
165
+ description: "One component (X, Y or Z) of a vector (f32)."
166
+ },
167
+ {
168
+ op: "combine",
169
+ label: "Combine",
170
+ group: "Vector",
171
+ description: "Build a vector from three numbers (vec3)."
172
+ }
173
+ ]), c = {
174
+ add: ["A", "B"],
175
+ sub: ["A", "B"],
176
+ mul: ["A", "B"],
177
+ div: ["A", "B"],
178
+ min: ["A", "B"],
179
+ max: ["A", "B"],
180
+ pow: ["Base", "Exponent"],
181
+ mix: [
182
+ "A",
183
+ "B",
184
+ "Factor"
185
+ ],
186
+ clamp: [
187
+ "Value",
188
+ "Min",
189
+ "Max"
190
+ ],
191
+ dot: ["A", "B"],
192
+ combine: [
193
+ "X",
194
+ "Y",
195
+ "Z"
196
+ ],
197
+ component: ["Vector"],
198
+ length: ["Vector"],
199
+ normalize: ["Vector"]
200
+ }, l = (e, t) => c[e]?.[t] ?? "Value", u = Object.freeze({
201
+ add: [void 0, 0],
202
+ sub: [void 0, 0],
203
+ mul: [void 0, 1],
204
+ div: [void 0, 1],
205
+ min: [void 0, 1],
206
+ max: [void 0, 0],
207
+ pow: [void 0, 1],
208
+ mix: [
209
+ void 0,
210
+ void 0,
211
+ .5
212
+ ],
213
+ clamp: [
214
+ void 0,
215
+ 0,
216
+ 1
217
+ ],
218
+ combine: [
219
+ 0,
220
+ 0,
221
+ 0
222
+ ]
223
+ }), d = Object.freeze([
224
+ {
225
+ slot: "color",
226
+ label: "Color",
227
+ type: "vec3f"
228
+ },
229
+ {
230
+ slot: "roughness",
231
+ label: "Roughness",
232
+ type: "f32"
233
+ },
234
+ {
235
+ slot: "metalness",
236
+ label: "Metalness",
237
+ type: "f32"
238
+ },
239
+ {
240
+ slot: "emissive",
241
+ label: "Emissive",
242
+ type: "vec3f"
243
+ },
244
+ {
245
+ slot: "opacity",
246
+ label: "Opacity",
247
+ type: "f32"
248
+ },
249
+ {
250
+ slot: "normal",
251
+ label: "Normal",
252
+ type: "vec3f"
253
+ }
254
+ ]), f = 176, p = 26, m = 24, h = 6, g = 3, _ = (e) => e === "float" || e === "vec3" || e === "component", v = (e) => Math.max(1, e.inputs.length + +!!_(e.op)), y = (e) => 38 + 24 * v(e), b = 38 + 24 * (d.length + 3), x = (e, t) => [e.x, e.y + 26 + 6 + 24 * (t + .5)], S = (e) => [e.x + 176, e.y + 26 + 6 + 12], C = 240, w = 20, T = 200, E = () => ({
255
+ color: [
256
+ .8,
257
+ .8,
258
+ .8
259
+ ],
260
+ emissive: [
261
+ 0,
262
+ 0,
263
+ 0
264
+ ],
265
+ roughness: .5,
266
+ metalness: 0,
267
+ opacity: 1
268
+ }), D = (e) => typeof e == "number" && Number.isFinite(Math.fround(e)) && Math.abs(e) <= 1e6, O = (e) => e.replace(/-/g, "\\-"), k = class {
269
+ constructor(e, t) {
270
+ this.nodes = [], this.outputs = {}, this.fallback = E(), this.output = {
271
+ x: 0,
272
+ y: 0
273
+ }, this.undoStack = [], this.redoStack = [], this.listeners = /* @__PURE__ */ new Set(), this.depth = 0, this.version = 0, e && (a(e), this.fill(e, t));
274
+ }
275
+ fill(e, t) {
276
+ this.nodes.length = 0;
277
+ for (let n of e.nodes) this.nodes.push({
278
+ id: n.id,
279
+ op: n.op,
280
+ inputs: [...n.inputs],
281
+ ...n.value === void 0 ? {} : { value: Array.isArray(n.value) ? [...n.value] : n.value },
282
+ inline: n.inputs.map(() => void 0),
283
+ x: t?.[n.id]?.[0] ?? NaN,
284
+ y: t?.[n.id]?.[1] ?? NaN
285
+ });
286
+ this.outputs = { ...e.outputs }, this.fallback = structuredClone(e.fallback), this.output = {
287
+ x: t?.output?.[0] ?? NaN,
288
+ y: t?.output?.[1] ?? NaN
289
+ }, (this.nodes.some((e) => Number.isNaN(e.x) || Number.isNaN(e.y)) || Number.isNaN(this.output.x)) && this.arrange(!0);
290
+ }
291
+ node(e) {
292
+ return this.nodes.find((t) => t.id === e);
293
+ }
294
+ get layout() {
295
+ return {
296
+ ...Object.fromEntries(this.nodes.map((e) => [e.id, [e.x, e.y]])),
297
+ output: [this.output.x, this.output.y]
298
+ };
299
+ }
300
+ get canUndo() {
301
+ return this.undoStack.length > 0;
302
+ }
303
+ get canRedo() {
304
+ return this.redoStack.length > 0;
305
+ }
306
+ subscribe(e) {
307
+ return this.listeners.add(e), () => this.listeners.delete(e);
308
+ }
309
+ snapshot() {
310
+ return JSON.stringify({
311
+ nodes: this.nodes,
312
+ outputs: this.outputs,
313
+ fallback: this.fallback,
314
+ output: this.output
315
+ });
316
+ }
317
+ restore(e) {
318
+ let t = JSON.parse(e);
319
+ this.nodes.splice(0, this.nodes.length, ...t.nodes), this.outputs = t.outputs, this.fallback = t.fallback, this.output = t.output;
320
+ }
321
+ emit(e) {
322
+ e === "graph" && this.version++;
323
+ for (let t of [...this.listeners]) t(e);
324
+ }
325
+ checkpoint() {
326
+ this.depth || (this.undoStack.push(this.snapshot()), this.undoStack.length > T && this.undoStack.shift(), this.redoStack.length = 0);
327
+ }
328
+ batch(e) {
329
+ if (this.depth) return e();
330
+ let t = this.snapshot();
331
+ this.checkpoint(), this.depth++;
332
+ try {
333
+ e();
334
+ } catch (e) {
335
+ throw this.restore(t), this.undoStack.pop(), e;
336
+ } finally {
337
+ this.depth--;
338
+ }
339
+ this.snapshot() === t ? this.undoStack.pop() : this.emit("graph");
340
+ }
341
+ change(e) {
342
+ this.batch(e);
343
+ }
344
+ freshId(e) {
345
+ let t = new Set(this.nodes.map((e) => e.id));
346
+ for (let n = 1;; n++) if (!t.has(e + n)) return e + n;
347
+ }
348
+ need(e) {
349
+ let t = this.node(e);
350
+ if (!t) throw RangeError(`There is no node "${e}"; pass the id of a node in this graph`);
351
+ return t;
352
+ }
353
+ dependsOn(e, t, n = /* @__PURE__ */ new Set()) {
354
+ return e === t || !n.has(e) && (n.add(e), (this.node(e)?.inputs ?? []).some((e) => e !== null && this.dependsOn(e, t, n)));
355
+ }
356
+ checkValue(e, t) {
357
+ if (e === "float") {
358
+ if (!D(t)) throw RangeError("A float value must be a finite number within +-1000000; type a smaller number");
359
+ return t;
360
+ }
361
+ if (e === "vec3") {
362
+ if (!Array.isArray(t) || t.length !== 3 || !t.every(D)) throw RangeError("A vec3 value must be three finite numbers within +-1000000; pass [x, y, z]");
363
+ return [
364
+ t[0],
365
+ t[1],
366
+ t[2]
367
+ ];
368
+ }
369
+ if (e === "component") {
370
+ if (!Number.isInteger(t) || t < 0 || t > 2) throw RangeError("A component index must be 0, 1 or 2; pick X, Y or Z");
371
+ return t;
372
+ }
373
+ throw TypeError(`A ${e} node has no value; only float, vec3 and component nodes do`);
374
+ }
375
+ addNode(n, r, i) {
376
+ if (typeof n != "string" || !Object.hasOwn(t, n)) throw RangeError(`"${String(n)}" is not a surface operation; use one of ${Object.keys(t).join(", ")}`);
377
+ if (this.nodes.length >= e.nodes) throw RangeError(`A graph holds at most ${e.nodes} nodes; delete some before adding more`);
378
+ let a = {
379
+ id: "",
380
+ op: n,
381
+ inputs: Array(t[n]).fill(null),
382
+ inline: Array(t[n]).fill(void 0),
383
+ x: r?.[0] ?? 0,
384
+ y: r?.[1] ?? 0
385
+ };
386
+ return _(n) ? a.value = this.checkValue(n, i ?? (n === "vec3" ? [
387
+ 1,
388
+ 1,
389
+ 1
390
+ ] : 0)) : i !== void 0 && this.checkValue(n, i), this.change(() => {
391
+ a.id = this.freshId(n), r || (a.x = a.y = this.nodes.length % 8 * 24), this.nodes.push(a);
392
+ }), a;
393
+ }
394
+ removeNodes(e) {
395
+ let t = new Set(e);
396
+ [...t].some((e) => this.node(e)) && this.change(() => {
397
+ for (let e = this.nodes.length - 1; e >= 0; e--) t.has(this.nodes[e].id) && this.nodes.splice(e, 1);
398
+ for (let e of this.nodes) e.inputs = e.inputs.map((e) => e !== null && t.has(e) ? null : e);
399
+ for (let e of Object.keys(this.outputs)) t.has(this.outputs[e]) && delete this.outputs[e];
400
+ });
401
+ }
402
+ connect(e, t, n) {
403
+ this.need(e);
404
+ let r = this.need(t);
405
+ if (!Number.isInteger(n) || n < 0 || n >= r.inputs.length) throw RangeError(`${t} (${r.op}) has ${r.inputs.length} inputs; pass an input index from 0 to ${r.inputs.length - 1}`);
406
+ if (this.dependsOn(e, t)) throw RangeError(`Wiring ${e} into ${t} would make a loop because ${t} already feeds ${e}; wire from a node that does not depend on ${t}`);
407
+ r.inputs[n] !== e && this.change(() => {
408
+ r.inputs[n] = e;
409
+ });
410
+ }
411
+ connectOutput(e, t) {
412
+ if (this.need(e), !d.some((e) => e.slot === t)) throw RangeError(`"${String(t)}" is not an output slot; use ${d.map((e) => e.slot).join(", ")}`);
413
+ this.outputs[t] !== e && this.change(() => {
414
+ this.outputs[t] = e;
415
+ });
416
+ }
417
+ disconnect(e, t) {
418
+ let n = this.need(e);
419
+ n.inputs[t] != null && this.change(() => {
420
+ n.inputs[t] = null;
421
+ });
422
+ }
423
+ disconnectOutput(e) {
424
+ this.outputs[e] !== void 0 && this.change(() => {
425
+ delete this.outputs[e];
426
+ });
427
+ }
428
+ setValue(e, t) {
429
+ let n = this.need(e), r = this.checkValue(n.op, t);
430
+ JSON.stringify(n.value) !== JSON.stringify(r) && this.change(() => {
431
+ n.value = r;
432
+ });
433
+ }
434
+ setInline(e, t, n) {
435
+ let r = this.need(e);
436
+ if (!u[r.op] || u[r.op][t] === void 0) throw RangeError(`Input ${t + 1} of ${e} (${r.op}) has no default; wire a node to it instead`);
437
+ if (n !== void 0 && !D(n)) throw RangeError("An input constant must be a finite number within +-1000000");
438
+ r.inline[t] !== n && this.change(() => {
439
+ r.inline[t] = n;
440
+ });
441
+ }
442
+ setFallback(e) {
443
+ let t = {
444
+ ...this.fallback,
445
+ ...e
446
+ }, n = (e) => Array.isArray(e) && e.length === 3 && e.every((e) => D(e) && e >= 0);
447
+ if (!n(t.color) || !n(t.emissive) || ![
448
+ t.roughness,
449
+ t.metalness,
450
+ t.opacity
451
+ ].every((e) => D(e) && e >= 0 && e <= 1)) throw RangeError("Fallback needs nonnegative finite RGB for color and emissive and roughness, metalness and opacity from 0 to 1");
452
+ this.change(() => {
453
+ this.fallback = {
454
+ color: [...t.color],
455
+ emissive: [...t.emissive],
456
+ roughness: t.roughness,
457
+ metalness: t.metalness,
458
+ opacity: t.opacity
459
+ };
460
+ });
461
+ }
462
+ move(e, t, n) {
463
+ if (![t, n].every(Number.isFinite)) throw RangeError("Move by finite distances; pass numbers for dx and dy");
464
+ for (let r of e) {
465
+ let e = r === "output" ? this.output : this.node(r);
466
+ e && (e.x += t, e.y += n);
467
+ }
468
+ this.emit("layout");
469
+ }
470
+ duplicate(t) {
471
+ let n = new Set(t), r = this.nodes.filter((e) => n.has(e.id));
472
+ if (!r.length) return [];
473
+ if (this.nodes.length + r.length > e.nodes) throw RangeError(`A graph holds at most ${e.nodes} nodes; delete some before duplicating`);
474
+ let i = /* @__PURE__ */ new Map(), a = new Set(this.nodes.map((e) => e.id));
475
+ for (let e of r) {
476
+ let t = 1;
477
+ for (; a.has(e.op + t);) t++;
478
+ i.set(e.id, e.op + t), a.add(e.op + t);
479
+ }
480
+ return this.change(() => {
481
+ for (let e of r) this.nodes.push({
482
+ ...structuredClone(e),
483
+ id: i.get(e.id),
484
+ inputs: e.inputs.map((e) => e === null ? null : i.get(e) ?? e),
485
+ x: e.x + 24,
486
+ y: e.y + 24
487
+ });
488
+ }), [...i.values()];
489
+ }
490
+ arrange(e = !1) {
491
+ let t = () => {
492
+ let e = /* @__PURE__ */ new Map(), t = (n, r = /* @__PURE__ */ new Set()) => {
493
+ if (e.has(n.id)) return e.get(n.id);
494
+ if (r.has(n.id)) return 0;
495
+ r.add(n.id);
496
+ let i = 1 + Math.max(-1, ...n.inputs.map((e) => e === null || !this.node(e) ? -1 : t(this.node(e), r)));
497
+ return r.delete(n.id), e.set(n.id, i), i;
498
+ };
499
+ this.nodes.forEach((e) => t(e));
500
+ let n = /* @__PURE__ */ new Map();
501
+ for (let t of this.nodes) {
502
+ let r = e.get(t.id), i = n.get(r) ?? 0;
503
+ t.x = r * C, t.y = i, n.set(r, i + y(t) + w);
504
+ }
505
+ this.output.x = (Math.max(-1, ...e.values()) + 1) * C, this.output.y = 0;
506
+ };
507
+ if (e) return t();
508
+ this.change(t);
509
+ }
510
+ undo() {
511
+ let e = this.undoStack.pop();
512
+ return e !== void 0 && (this.redoStack.push(this.snapshot()), this.restore(e), this.emit("graph"), !0);
513
+ }
514
+ redo() {
515
+ let e = this.redoStack.pop();
516
+ return e !== void 0 && (this.undoStack.push(this.snapshot()), this.restore(e), this.emit("graph"), !0);
517
+ }
518
+ load(e, t) {
519
+ a(e), this.change(() => this.fill(e, t));
520
+ }
521
+ raw() {
522
+ let e = [], t = new Set(this.nodes.map((e) => e.id));
523
+ for (let n of this.nodes) {
524
+ let r = n.inputs.map((r, i) => {
525
+ if (r !== null) return r;
526
+ let a = n.inline[i] ?? u[n.op]?.[i];
527
+ if (a === void 0) throw TypeError(`Surface graph is incomplete; connect a node to input ${i + 1} (${l(n.op, i)}) of ${n.id}, or delete ${n.id}`);
528
+ let o = `${n.id.slice(0, 40)}-i${i}`;
529
+ for (; t.has(o);) o += "_";
530
+ return t.add(o), e.push({
531
+ id: o,
532
+ op: "float",
533
+ inputs: [],
534
+ value: a
535
+ }), o;
536
+ });
537
+ e.push({
538
+ id: n.id,
539
+ op: n.op,
540
+ inputs: r,
541
+ ...n.value === void 0 ? {} : { value: n.value }
542
+ });
543
+ }
544
+ return {
545
+ version: 1,
546
+ nodes: e,
547
+ outputs: { ...this.outputs },
548
+ fallback: structuredClone(this.fallback)
549
+ };
550
+ }
551
+ toGraph() {
552
+ return JSON.parse(i(this.raw()));
553
+ }
554
+ toJSON() {
555
+ return i(this.raw());
556
+ }
557
+ status() {
558
+ if (this.cached?.version === this.version) return this.cached.status;
559
+ let e;
560
+ try {
561
+ let t = this.toGraph(), n = r(t).types, i = Object.fromEntries(this.nodes.map((e) => [e.id, n[e.id]])), a = Object.keys(this.outputs);
562
+ e = {
563
+ ok: !0,
564
+ message: a.length ? `Valid graph driving ${a.join(", ")}.` : "Valid graph. Wire a node to an output to change the material.",
565
+ node: null,
566
+ types: i
567
+ };
568
+ } catch (t) {
569
+ let n = t instanceof Error ? t.message : String(t);
570
+ e = {
571
+ ok: !1,
572
+ message: n,
573
+ node: this.nodes.find((e) => RegExp(`(^|[^A-Za-z0-9_-])${O(e.id)}([^A-Za-z0-9_-]|$)`).test(n))?.id ?? null,
574
+ types: {}
575
+ };
576
+ }
577
+ return this.cached = {
578
+ version: this.version,
579
+ status: e
580
+ }, e;
581
+ }
582
+ }, A = "\n:host{display:block;position:relative;min-height:240px;color-scheme:light dark;--bg:#f4f5f7;--grid:#e1e4e9;--panel:#fff;--ink:#1f2328;--muted:#5d636b;--line:#c3c8cf;--accent:#0b6bcb;--bad:#c4281c;--ok:#12805c;--f32:#6c8196;--vec3f:#b8860b;font:12px/1.35 system-ui,sans-serif;color:var(--ink)}\n@media(prefers-color-scheme:dark){:host{--bg:#16181c;--grid:#23262c;--panel:#23272e;--ink:#e6e8eb;--muted:#a0a7b0;--line:#4a515a;--accent:#5aa2f2;--bad:#ff7b72;--ok:#4cc38a;--f32:#8fa6bb;--vec3f:#e0b43c}}\n*{box-sizing:border-box}\n.editor{display:flex;flex-direction:column;height:100%;min-height:inherit;background:var(--bg)}\n.toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:6px;padding:6px 8px;border-bottom:1px solid var(--line);background:var(--panel)}\n.toolbar .status{margin-left:auto;max-width:60%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ok);cursor:default}\n.toolbar .status[data-ok=false]{color:var(--bad);cursor:pointer}\nbutton,input,select{font:inherit;color:inherit}\nbutton{border:1px solid var(--line);background:var(--panel);border-radius:4px;padding:3px 9px;cursor:pointer}\nbutton:disabled{opacity:.45;cursor:default}\nbutton:focus-visible,input:focus-visible,select:focus-visible,.viewport:focus-visible,.node:focus-visible{outline:2px solid var(--accent);outline-offset:1px}\n.viewport{position:relative;flex:1;overflow:hidden;touch-action:none;cursor:grab;background-color:var(--bg);background-image:radial-gradient(var(--grid) 1px,transparent 1px);background-size:24px 24px}\n.viewport[data-panning]{cursor:grabbing}\n.world{position:absolute;left:0;top:0;transform-origin:0 0}\nsvg.wires{position:absolute;left:0;top:0;width:1px;height:1px;overflow:visible;pointer-events:none}\npath.wire{fill:none;stroke:var(--line);stroke-width:2.5;stroke-linecap:round}\npath.wire[data-type=f32]{stroke:var(--f32)}path.wire[data-type=vec3f]{stroke:var(--vec3f)}\npath.wire[data-pending]{stroke:var(--accent);stroke-dasharray:6 4}\n.node{position:absolute;background:var(--panel);border:1px solid var(--line);border-radius:6px;box-shadow:0 1px 3px rgba(0,0,0,.18);user-select:none}\n.node[data-selected]{border-color:var(--accent);box-shadow:0 0 0 2px var(--accent)}\n.node[data-invalid]{border-color:var(--bad);box-shadow:0 0 0 2px var(--bad)}\n.head{height:26px;display:flex;align-items:center;gap:6px;padding:0 10px;border-bottom:1px solid var(--line);cursor:move;font-weight:600;border-radius:6px 6px 0 0}\n.head .id{color:var(--muted);font-weight:400;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n.head .type{margin-left:auto;font-weight:400;color:var(--muted);font-family:ui-monospace,monospace;font-size:11px}\n.rows{padding:6px 0}\n.row{height:24px;display:flex;align-items:center;justify-content:space-between;gap:6px;padding:0 12px}\n.row .label{color:var(--muted)}\n.row input,.row select{width:56px;height:20px;padding:0 3px;border:1px solid var(--line);border-radius:3px;background:var(--bg)}\n.row input.wide{width:100%}\n.row .triple{display:flex;gap:3px;width:100%}.row .triple input{width:0;flex:1}\n.socket{position:absolute;width:12px;height:12px;padding:0;border-radius:50%;border:2px solid var(--line);background:var(--panel)}\n.socket[data-type=f32]{border-color:var(--f32)}.socket[data-type=vec3f]{border-color:var(--vec3f)}\n.socket[data-connected]{background:currentColor}.socket[data-type=f32][data-connected]{background:var(--f32)}.socket[data-type=vec3f][data-connected]{background:var(--vec3f)}\n.socket[data-armed]{outline:2px solid var(--accent)}\n.socket:hover{transform:scale(1.25)}\n.palette{position:absolute;z-index:3;width:260px;max-height:70%;display:flex;flex-direction:column;background:var(--panel);border:1px solid var(--line);border-radius:6px;box-shadow:0 6px 24px rgba(0,0,0,.28)}\n.palette[hidden]{display:none}\n.palette input{margin:6px;padding:4px 6px;border:1px solid var(--line);border-radius:4px;background:var(--bg)}\n.palette ul{list-style:none;margin:0;padding:0 0 6px;overflow:auto}\n.palette li{padding:4px 12px;cursor:pointer}.palette li small{display:block;color:var(--muted)}\n.palette li[aria-selected=true]{background:var(--accent);color:#fff}.palette li[aria-selected=true] small{color:inherit;opacity:.85}\n.code{position:absolute;right:8px;bottom:8px;z-index:2;width:min(460px,60%);max-height:50%;overflow:auto;margin:0;padding:8px;background:var(--panel);border:1px solid var(--line);border-radius:6px;font:11px/1.4 ui-monospace,monospace;white-space:pre;user-select:text}\n.code[hidden]{display:none}\n@media(prefers-reduced-motion:no-preference){.socket{transition:transform .08s}}\n", j = "http://www.w3.org/2000/svg", M = 14, N = class {
583
+ constructor(e, t = {}) {
584
+ this.nodes = /* @__PURE__ */ new Map(), this.selected = /* @__PURE__ */ new Set(), this.graphListeners = /* @__PURE__ */ new Set(), this.changeListeners = /* @__PURE__ */ new Set(), this.pan = {
585
+ x: 24,
586
+ y: 24,
587
+ zoom: 1
588
+ }, this.lastJSON = "", this.matches = [], this.choice = 0, this.addAt = [0, 0], this.flash = "", this.disposed = !1, this.suppressNext = !1, this.presentation = t.presentation ?? {}, this.operations = s.map((e) => this.presentation.operations?.find((t) => t.op === e.op) ?? e), this.slots = this.presentation.outputs ?? d, this.doc = e.ownerDocument, this.readOnly = t.readOnly === !0, this.model = new k(t.graph, t.layout), this.element = this.doc.createElement("div"), this.element.dataset.margoNodeEditor = "", this.root = this.element.attachShadow({ mode: "open" });
589
+ let n = this.make.bind(this), r = n("style");
590
+ r.textContent = A;
591
+ let i = n("div", "toolbar");
592
+ i.setAttribute("role", "toolbar"), i.setAttribute("aria-label", "Graph editor tools");
593
+ let a = (e, t) => {
594
+ let r = n("button");
595
+ return r.type = "button", r.textContent = e, r.title = t, r;
596
+ };
597
+ this.buttons = {
598
+ add: a("Add node", "Add a node (Shift+A)"),
599
+ undo: a("Undo", "Undo (Ctrl+Z)"),
600
+ redo: a("Redo", "Redo (Ctrl+Y)"),
601
+ arrange: a("Arrange", "Lay the nodes out in columns"),
602
+ fit: a("Fit", "Show every node (F)"),
603
+ wgsl: a("WGSL", "Show the generated WGSL")
604
+ }, this.buttons.wgsl.setAttribute("aria-pressed", "false"), this.statusText = n("span", "status"), this.statusText.setAttribute("role", "status"), this.statusText.setAttribute("aria-live", "polite"), i.append(...Object.values(this.buttons), this.statusText), this.viewport = n("div", "viewport"), this.viewport.tabIndex = 0, this.viewport.setAttribute("role", "application"), this.viewport.setAttribute("aria-label", `${this.presentation.title ?? "Surface"} graph canvas. Shift+A adds a node.`), this.world = n("div", "world"), this.wires = this.doc.createElementNS(j, "svg"), this.wires.classList.add("wires"), this.wires.setAttribute("aria-hidden", "true"), this.world.append(this.wires), this.palette = n("div", "palette"), this.palette.hidden = !0, this.palette.setAttribute("role", "dialog"), this.palette.setAttribute("aria-label", "Add a node"), this.search = n("input"), this.search.type = "search", this.search.placeholder = "Search nodes", this.search.setAttribute("aria-label", "Search nodes"), this.list = n("ul"), this.list.setAttribute("role", "listbox"), this.palette.append(this.search, this.list), this.code = n("pre", "code"), this.code.hidden = !0, this.code.tabIndex = 0, this.code.setAttribute("aria-label", "Generated WGSL"), this.viewport.append(this.world, this.palette, this.code);
605
+ let o = n("div", "editor");
606
+ if (o.append(i, this.viewport), this.root.append(r, o), e.append(this.element), this.wire(i), this.unsubscribe = this.model.subscribe((e) => e === "layout" ? this.layoutOnly() : this.render()), t.signal) {
607
+ if (t.signal.aborted) {
608
+ this.dispose();
609
+ return;
610
+ }
611
+ let e = () => this.dispose();
612
+ t.signal.addEventListener("abort", e, { once: !0 }), this.abort = () => t.signal.removeEventListener("abort", e);
613
+ }
614
+ this.render(), this.model.nodes.length ? this.fit() : this.applyPan();
615
+ }
616
+ make(e, t) {
617
+ let n = this.doc.createElement(e);
618
+ return t && (n.className = t), n;
619
+ }
620
+ live() {
621
+ if (this.disposed) throw new o("disposed", "This NodeEditor is disposed; create a new NodeEditor");
622
+ }
623
+ get graph() {
624
+ return this.model.toGraph();
625
+ }
626
+ get status() {
627
+ return this.model.status();
628
+ }
629
+ get selection() {
630
+ return [...this.selected];
631
+ }
632
+ get layout() {
633
+ return this.model.layout;
634
+ }
635
+ onGraph(e) {
636
+ return this.live(), this.graphListeners.add(e), this.model.status().ok && e(this.model.toGraph()), () => this.graphListeners.delete(e);
637
+ }
638
+ onChange(e) {
639
+ return this.live(), this.changeListeners.add(e), () => this.changeListeners.delete(e);
640
+ }
641
+ load(e, t) {
642
+ this.live(), this.selected.clear(), this.model.load(e, t), this.fit();
643
+ }
644
+ select(e) {
645
+ this.live(), this.selected.clear();
646
+ for (let t of e) this.model.node(t) && this.selected.add(t);
647
+ this.paintSelection();
648
+ }
649
+ fit() {
650
+ this.live();
651
+ let e = this.model.output.x, t = this.model.output.y, n = e + 176, r = t + b;
652
+ for (let i of this.model.nodes) e = Math.min(e, i.x), t = Math.min(t, i.y), n = Math.max(n, i.x + 176), r = Math.max(r, i.y + y(i));
653
+ let i = this.viewport.clientWidth || 800, a = this.viewport.clientHeight || 500, o = Math.min(1, Math.max(.25, Math.min((i - 48) / (n - e), (a - 48) / (r - t))));
654
+ this.pan = {
655
+ zoom: o,
656
+ x: (i - (n - e) * o) / 2 - e * o,
657
+ y: (a - (r - t) * o) / 2 - t * o
658
+ }, this.applyPan();
659
+ }
660
+ add(e, t) {
661
+ if (this.live(), this.readOnly) throw new o("state", "This NodeEditor is read-only; create it without readOnly to edit");
662
+ let n = this.model.addNode(e, t);
663
+ return this.selected.clear(), this.selected.add(n.id), this.paintSelection(), n.id;
664
+ }
665
+ dispose() {
666
+ this.disposed || (this.disposed = !0, this.unsubscribe(), this.abort?.(), this.graphListeners.clear(), this.changeListeners.clear(), this.element.remove(), this.nodes.clear());
667
+ }
668
+ [Symbol.dispose ?? Symbol()]() {
669
+ this.dispose();
670
+ }
671
+ applyPan() {
672
+ let { x: e, y: t, zoom: n } = this.pan;
673
+ this.world.style.transform = `translate(${e}px,${t}px) scale(${n})`, this.viewport.style.backgroundPosition = `${e}px ${t}px`, this.viewport.style.backgroundSize = `${24 * n}px ${24 * n}px`;
674
+ }
675
+ point(e) {
676
+ let t = this.viewport.getBoundingClientRect();
677
+ return [(e.clientX - t.left - this.pan.x) / this.pan.zoom, (e.clientY - t.top - this.pan.y) / this.pan.zoom];
678
+ }
679
+ render() {
680
+ if (this.disposed) return;
681
+ let e = this.model, t = e.status();
682
+ for (let t of [...this.selected]) e.node(t) || this.selected.delete(t);
683
+ this.armed && !e.node(this.armed) && (this.armed = void 0);
684
+ let n = this.focusedSocket();
685
+ for (let e of this.nodes.values()) e.remove();
686
+ this.nodes.clear();
687
+ for (let n of e.nodes) this.world.append(this.drawNode(n, t));
688
+ this.world.append(this.drawOutput()), this.drawWires(t), this.paintSelection(), n && this.root.querySelector(n)?.focus({ preventScroll: !0 }), this.buttons.undo.disabled = this.readOnly || !e.canUndo, this.buttons.redo.disabled = this.readOnly || !e.canRedo, this.buttons.add.disabled = this.buttons.arrange.disabled = this.readOnly, this.statusText.textContent = this.flash || t.message, this.statusText.dataset.ok = String(t.ok && !this.flash), this.statusText.title = this.statusText.textContent, this.code.hidden || this.showCode(t), this.flash = "";
689
+ for (let e of [...this.changeListeners]) e(t);
690
+ if (t.ok) {
691
+ let t = e.toJSON();
692
+ if (t !== this.lastJSON) {
693
+ this.lastJSON = t;
694
+ let n = e.toGraph();
695
+ for (let e of [...this.graphListeners]) e(n);
696
+ }
697
+ }
698
+ }
699
+ focusedSocket() {
700
+ let e = this.root.activeElement;
701
+ if (!e?.dataset?.socket) return;
702
+ let t = e.closest("[data-node]")?.dataset.node;
703
+ return e.dataset.slot ? `.socket[data-slot="${e.dataset.slot}"]` : `[data-node="${t}"] .socket[data-socket="${e.dataset.socket}"]${e.dataset.input === void 0 ? "" : `[data-input="${e.dataset.input}"]`}`;
704
+ }
705
+ layoutOnly() {
706
+ for (let e of this.model.nodes) {
707
+ let t = this.nodes.get(e.id);
708
+ t && this.place(t, e.x, e.y);
709
+ }
710
+ let e = this.nodes.get("output");
711
+ e && this.place(e, this.model.output.x, this.model.output.y), this.drawWires(this.model.status());
712
+ }
713
+ place(e, t, n) {
714
+ e.style.left = t + "px", e.style.top = n + "px";
715
+ }
716
+ socket(e, t, n, r, i) {
717
+ let a = this.make("button", "socket");
718
+ return a.type = "button", a.dataset.socket = e, r && (a.dataset.type = r), i && (a.dataset.connected = ""), a.style.top = t - 6 + "px", e === "in" ? a.style.left = "-6px" : a.style.right = "-6px", a.setAttribute("aria-label", n), a;
719
+ }
720
+ field(e, t, n, r = !1) {
721
+ let i = this.make("input", r ? "wide" : "");
722
+ return i.type = "number", i.step = "any", i.value = String(Number(e.toPrecision(7))), i.disabled = this.readOnly, i.setAttribute("aria-label", n), i.addEventListener("change", () => {
723
+ let e = i.valueAsNumber;
724
+ if (Number.isFinite(e)) try {
725
+ t(e);
726
+ } catch (e) {
727
+ this.say(e), this.render();
728
+ }
729
+ else this.render();
730
+ }), i;
731
+ }
732
+ drawNode(e, t) {
733
+ let n = t.types[e.id], r = this.operations.find((t) => t.op === e.op), i = this.make("div", "node");
734
+ i.dataset.node = e.id, i.setAttribute("role", "group"), i.setAttribute("aria-label", `${r.label} node ${e.id}${n ? ", outputs " + n : ""}`), i.style.width = "176px", i.style.height = y(e) + "px", this.place(i, e.x, e.y), !t.ok && t.node === e.id && (i.dataset.invalid = "");
735
+ let a = this.make("div", "head");
736
+ a.dataset.drag = "";
737
+ let o = this.make("span");
738
+ o.textContent = r.label;
739
+ let s = this.make("span", "id");
740
+ s.textContent = e.id;
741
+ let c = this.make("span", "type");
742
+ c.textContent = n ?? "", a.append(o, s, c);
743
+ let d = this.make("div", "rows");
744
+ if (e.inputs.forEach((n, r) => {
745
+ let a = this.make("div", "row"), o = l(e.op, r), s = this.make("span", "label");
746
+ s.textContent = o, a.append(s);
747
+ let c = u[e.op]?.[r];
748
+ n === null && c !== void 0 && a.append(this.field(e.inline[r] ?? c, (t) => this.model.setInline(e.id, r, t), `${e.id} ${o} (default ${c})`)), d.append(a);
749
+ let f = this.socket("in", 32 + 24 * (r + .5), `${e.id} input ${r + 1} ${o}, ${n ? "wired from " + n : "not wired"}`, n ? t.types[n] : void 0, n !== null);
750
+ f.dataset.node = e.id, f.dataset.input = String(r), i.append(f);
751
+ }), e.op === "float" || e.op === "vec3" || e.op === "component") {
752
+ let t = this.make("div", "row");
753
+ if (e.op === "float") t.append(this.field(e.value, (t) => this.model.setValue(e.id, t), `${e.id} value`, !0));
754
+ else if (e.op === "vec3") {
755
+ let n = this.make("div", "triple");
756
+ e.value.forEach((t, r) => n.append(this.field(t, (t) => this.model.setValue(e.id, e.value.map((e, n) => n === r ? t : e)), `${e.id} ${"xyz"[r]}`))), t.append(n);
757
+ } else {
758
+ let n = this.make("select");
759
+ n.disabled = this.readOnly, n.setAttribute("aria-label", `${e.id} component`), [
760
+ "X",
761
+ "Y",
762
+ "Z"
763
+ ].forEach((t, r) => n.append(this.option(t, String(r), r === e.value))), n.addEventListener("change", () => this.model.setValue(e.id, Number(n.value))), t.append(n);
764
+ }
765
+ d.append(t);
766
+ } else e.inputs.length || d.append(this.make("div", "row"));
767
+ i.append(a, d);
768
+ let f = this.socket("out", 44, `${e.id} output${n ? " " + n : ""}`, n, this.usedBy(e.id));
769
+ return f.dataset.node = e.id, this.armed === e.id && (f.dataset.armed = ""), i.append(f), this.nodes.set(e.id, i), i;
770
+ }
771
+ option(e, t, n) {
772
+ let r = this.doc.createElement("option");
773
+ return r.textContent = e, r.value = t, r.selected = n, r;
774
+ }
775
+ usedBy(e) {
776
+ return this.model.nodes.some((t) => t.inputs.includes(e)) || Object.values(this.model.outputs).includes(e);
777
+ }
778
+ drawOutput() {
779
+ let e = this.model, t = this.make("div", "node");
780
+ t.dataset.node = "output", t.setAttribute("role", "group"), t.setAttribute("aria-label", this.presentation.title ?? "Material output"), t.style.width = "176px", t.style.height = b + "px", this.place(t, e.output.x, e.output.y);
781
+ let n = this.make("div", "head");
782
+ n.dataset.drag = "";
783
+ let r = this.make("span");
784
+ r.textContent = this.presentation.title ?? "Material output", n.append(r);
785
+ let i = this.make("div", "rows");
786
+ this.slots.forEach(({ slot: n, label: r, type: a }, o) => {
787
+ let s = this.make("div", "row"), c = this.make("span", "label"), l = e.outputs[n];
788
+ c.textContent = `${r} (${a === "f32" ? "number" : "vec3"})`, s.append(c), i.append(s);
789
+ let u = this.socket("in", 32 + 24 * (o + .5), `Output ${r}, ${l ? "wired from " + l : "not wired"}`, a, l !== void 0);
790
+ u.dataset.slot = n, t.append(u);
791
+ });
792
+ let a = e.fallback, o = (t, n) => {
793
+ let r = this.make("div", "row"), i = this.make("div", "triple");
794
+ return a[n].forEach((r, o) => i.append(this.field(r, (t) => e.setFallback({ [n]: a[n].map((e, n) => n === o ? t : e) }), `Fallback ${t} ${"rgb"[o]}`))), r.append(i), r;
795
+ }, s = this.make("div", "row"), c = this.make("div", "triple");
796
+ return [
797
+ "roughness",
798
+ "metalness",
799
+ "opacity"
800
+ ].forEach((t) => c.append(this.field(a[t], (n) => e.setFallback({ [t]: n }), `Fallback ${t}`))), s.append(c), this.presentation.fallback !== !1 && i.append(o("color", "color"), o("emissive", "emissive"), s), t.append(n, i), this.nodes.set("output", t), t;
801
+ }
802
+ curve(e, t, n, r) {
803
+ let i = Math.max(40, Math.abs(n - e) * .5);
804
+ return `M${e} ${t}C${e + i} ${t} ${n - i} ${r} ${n} ${r}`;
805
+ }
806
+ drawWires(e) {
807
+ this.wires.replaceChildren();
808
+ let t = (e, t, n = !1) => {
809
+ let r = this.doc.createElementNS(j, "path");
810
+ r.setAttribute("class", "wire"), r.setAttribute("d", e), t && r.setAttribute("data-type", t), n && r.setAttribute("data-pending", ""), this.wires.append(r);
811
+ }, n = this.model;
812
+ for (let r of n.nodes) r.inputs.forEach((i, a) => {
813
+ let o = i === null ? void 0 : n.node(i);
814
+ if (!o) return;
815
+ let [s, c] = S(o), [l, u] = x(r, a);
816
+ t(this.curve(s, c, l, u), e.types[o.id]);
817
+ });
818
+ this.slots.forEach(({ slot: r }, i) => {
819
+ let a = n.outputs[r] ? n.node(n.outputs[r]) : void 0;
820
+ if (!a) return;
821
+ let [o, s] = S(a), [c, l] = x(n.output, i);
822
+ t(this.curve(o, s, c, l), e.types[a.id]);
823
+ }), this.pendingWire && t(this.curve(...this.pendingWire), void 0, !0);
824
+ }
825
+ paintSelection() {
826
+ for (let [e, t] of this.nodes) this.selected.has(e) ? t.dataset.selected = "" : delete t.dataset.selected;
827
+ }
828
+ say(e) {
829
+ this.flash = e instanceof Error ? e.message : String(e), this.statusText.textContent = this.flash, this.statusText.dataset.ok = "false", this.statusText.title = this.flash;
830
+ }
831
+ targetAt(e, t) {
832
+ let n = M / this.pan.zoom, r = (r) => Math.hypot(r[0] - e, r[1] - t) <= n;
833
+ for (let e = 0; e < this.slots.length; e++) if (r(x(this.model.output, e))) return { slot: this.slots[e].slot };
834
+ for (let e of this.model.nodes) for (let t = 0; t < e.inputs.length; t++) if (r(x(e, t))) return {
835
+ node: e.id,
836
+ input: t
837
+ };
838
+ }
839
+ connectTo(e, t) {
840
+ "slot" in t ? this.model.connectOutput(e, t.slot) : this.model.connect(e, t.node, t.input);
841
+ }
842
+ sourceOf(e) {
843
+ return "slot" in e ? this.model.outputs[e.slot] : this.model.node(e.node)?.inputs[e.input] ?? void 0;
844
+ }
845
+ socketTarget(e) {
846
+ if (e.dataset.slot) return { slot: e.dataset.slot };
847
+ if (e.dataset.node !== void 0 && e.dataset.input !== void 0) return {
848
+ node: e.dataset.node,
849
+ input: Number(e.dataset.input)
850
+ };
851
+ }
852
+ wire(e) {
853
+ let t = this.viewport;
854
+ e.addEventListener("click", (e) => {
855
+ let t = e.target.closest("button");
856
+ t && !t.disabled && (t === this.buttons.add ? this.openPalette(this.centre()) : t === this.buttons.undo ? this.model.undo() : t === this.buttons.redo ? this.model.redo() : t === this.buttons.arrange ? (this.model.arrange(), this.fit()) : t === this.buttons.fit ? this.fit() : t === this.buttons.wgsl && (this.code.hidden = !this.code.hidden, t.setAttribute("aria-pressed", String(!this.code.hidden)), this.code.hidden || this.showCode(this.model.status())));
857
+ }), this.statusText.addEventListener("click", () => {
858
+ let e = this.model.status();
859
+ !e.ok && e.node && this.model.node(e.node) && this.select([e.node]);
860
+ }), t.addEventListener("pointerdown", (e) => this.down(e)), t.addEventListener("pointermove", (e) => this.moved(e)), t.addEventListener("pointerup", (e) => this.up(e)), t.addEventListener("pointercancel", () => this.cancel()), t.addEventListener("click", (e) => this.clicked(e)), t.addEventListener("dblclick", (e) => {
861
+ let t = e.target;
862
+ this.readOnly || t.closest("[data-node],.palette,.code") || this.openPalette(this.point(e));
863
+ }), t.addEventListener("wheel", (e) => this.wheel(e), { passive: !1 }), t.addEventListener("keydown", (e) => this.key(e)), this.search.addEventListener("input", () => this.filter()), this.search.addEventListener("keydown", (e) => {
864
+ e.stopPropagation(), e.key === "ArrowDown" || e.key === "ArrowUp" ? (e.preventDefault(), this.choice = (this.choice + (e.key === "ArrowDown" ? 1 : -1) + this.matches.length) % Math.max(1, this.matches.length), this.paintChoice()) : e.key === "Enter" ? (e.preventDefault(), this.choose(this.choice)) : e.key === "Escape" && this.closePalette();
865
+ }), this.list.addEventListener("click", (e) => {
866
+ let t = e.target.closest("li");
867
+ t && this.choose(Number(t.dataset.index));
868
+ });
869
+ }
870
+ centre() {
871
+ let e = this.model.nodes.length % 8 * 24;
872
+ return [Math.round(((this.viewport.clientWidth || 800) / 2 - this.pan.x) / this.pan.zoom - 88) + e, Math.round(((this.viewport.clientHeight || 500) / 2 - this.pan.y) / this.pan.zoom - 40) + e];
873
+ }
874
+ down(e) {
875
+ if (e.button !== 0 && e.button !== 1) return;
876
+ let t = e.target;
877
+ if (t.closest(".palette,.code") || t.closest("input,select")) return;
878
+ this.palette.hidden || this.closePalette();
879
+ let n = t.closest("[data-socket]"), r = t.closest("[data-node]");
880
+ if (this.viewport.setPointerCapture?.(e.pointerId), n) {
881
+ let t = n.dataset.socket;
882
+ if (this.readOnly) return;
883
+ if (t === "out") this.gesture = {
884
+ kind: "wire",
885
+ from: n.dataset.node,
886
+ x: e.clientX,
887
+ y: e.clientY,
888
+ moved: !1
889
+ };
890
+ else {
891
+ let t = this.socketTarget(n), r = t && this.sourceOf(t);
892
+ t && r && (this.gesture = {
893
+ kind: "wire",
894
+ from: r,
895
+ detach: t,
896
+ x: e.clientX,
897
+ y: e.clientY,
898
+ moved: !1
899
+ });
900
+ }
901
+ } else if (r && t.closest("[data-drag]")) {
902
+ let t = r.dataset.node;
903
+ t !== "output" && (e.shiftKey ? this.selected.delete(t) || this.selected.add(t) : this.selected.has(t) || (this.selected.clear(), this.selected.add(t))), this.paintSelection(), this.readOnly || (this.gesture = {
904
+ kind: "move",
905
+ ids: t === "output" ? ["output"] : [...this.selected],
906
+ x: e.clientX,
907
+ y: e.clientY,
908
+ moved: !1
909
+ }), this.viewport.focus({ preventScroll: !0 });
910
+ } else r ? (this.selected.clear(), r.dataset.node !== "output" && this.selected.add(r.dataset.node), this.paintSelection()) : (e.shiftKey || (this.selected.clear(), this.paintSelection()), this.gesture = {
911
+ kind: "pan",
912
+ x: e.clientX,
913
+ y: e.clientY,
914
+ moved: !1
915
+ }, this.viewport.dataset.panning = "", this.viewport.focus({ preventScroll: !0 }));
916
+ }
917
+ moved(e) {
918
+ this.lastPoint = this.point(e);
919
+ let t = this.gesture;
920
+ if (t && !(!t.moved && Math.hypot(e.clientX - t.x, e.clientY - t.y) < 4)) {
921
+ if (t.kind === "pan") this.pan.x += e.clientX - t.x, this.pan.y += e.clientY - t.y, t.x = e.clientX, t.y = e.clientY, t.moved = !0, this.applyPan();
922
+ else if (t.kind === "move") {
923
+ t.moved || this.model.checkpoint();
924
+ let n = (e.clientX - t.x) / this.pan.zoom, r = (e.clientY - t.y) / this.pan.zoom;
925
+ t.x = e.clientX, t.y = e.clientY, t.moved = !0, this.model.move(t.ids, n, r);
926
+ } else {
927
+ t.moved = !0;
928
+ let n = this.model.node(t.from);
929
+ if (!n) return;
930
+ let [r, i] = S(n), [a, o] = this.point(e);
931
+ this.pendingWire = [
932
+ r,
933
+ i,
934
+ a,
935
+ o
936
+ ], this.drawWires(this.model.status());
937
+ }
938
+ }
939
+ }
940
+ up(e) {
941
+ let t = this.gesture;
942
+ if (this.gesture = void 0, delete this.viewport.dataset.panning, this.viewport.releasePointerCapture?.(e.pointerId), this.pendingWire = void 0, !t) return;
943
+ if (t.kind === "move" && t.moved) {
944
+ this.suppress();
945
+ return;
946
+ }
947
+ if (t.kind === "pan" && t.moved || t.kind !== "wire") return;
948
+ if (!t.moved) {
949
+ this.drawWires(this.model.status());
950
+ return;
951
+ }
952
+ this.suppress();
953
+ let [n, r] = this.point(e), i = this.targetAt(n, r);
954
+ try {
955
+ this.model.batch(() => {
956
+ t.detach && !(i && JSON.stringify(i) === JSON.stringify(t.detach)) && ("slot" in t.detach ? this.model.disconnectOutput(t.detach.slot) : this.model.disconnect(t.detach.node, t.detach.input)), i && this.connectTo(t.from, i);
957
+ });
958
+ } catch (e) {
959
+ this.say(e);
960
+ }
961
+ this.drawWires(this.model.status());
962
+ }
963
+ cancel() {
964
+ this.gesture = void 0, this.pendingWire = void 0, delete this.viewport.dataset.panning, this.drawWires(this.model.status());
965
+ }
966
+ suppress() {
967
+ this.suppressNext = !0, setTimeout(() => this.suppressNext = !1, 0);
968
+ }
969
+ clicked(e) {
970
+ if (this.suppressNext || this.readOnly) return;
971
+ let t = e.target.closest("[data-socket]");
972
+ if (!t) return;
973
+ if (t.dataset.socket === "out") {
974
+ this.armed = this.armed === t.dataset.node ? void 0 : t.dataset.node, this.render();
975
+ return;
976
+ }
977
+ let n = this.socketTarget(t);
978
+ if (n) {
979
+ if (this.armed) try {
980
+ this.connectTo(this.armed, n), this.armed = void 0;
981
+ } catch (e) {
982
+ this.say(e);
983
+ }
984
+ else if (this.sourceOf(n)) {
985
+ let e = this.sourceOf(n);
986
+ this.model.batch(() => {
987
+ "slot" in n ? this.model.disconnectOutput(n.slot) : this.model.disconnect(n.node, n.input);
988
+ }), this.armed = e, this.render();
989
+ }
990
+ }
991
+ }
992
+ wheel(e) {
993
+ e.preventDefault();
994
+ let t = Math.min(2, Math.max(.25, this.pan.zoom * 1.0015 ** -e.deltaY)), n = this.viewport.getBoundingClientRect(), r = e.clientX - n.left, i = e.clientY - n.top;
995
+ this.pan.x = r - (r - this.pan.x) / this.pan.zoom * t, this.pan.y = i - (i - this.pan.y) / this.pan.zoom * t, this.pan.zoom = t, this.applyPan();
996
+ }
997
+ key(e) {
998
+ let t = e.ctrlKey || e.metaKey, n = e.key.toLowerCase();
999
+ if (e.target.closest?.("input,select")) return;
1000
+ let r = this.readOnly;
1001
+ if (n === "escape") this.armed = void 0, this.cancel(), this.closePalette(), this.render();
1002
+ else if (t && n === "z" && !r) e.preventDefault(), e.shiftKey ? this.model.redo() : this.model.undo();
1003
+ else if (t && n === "y" && !r) e.preventDefault(), this.model.redo();
1004
+ else if (t && n === "a") e.preventDefault(), this.select(this.model.nodes.map((e) => e.id));
1005
+ else if (t && n === "d" && !r) {
1006
+ e.preventDefault();
1007
+ try {
1008
+ let e = this.model.duplicate(this.selected);
1009
+ this.select(e);
1010
+ } catch (e) {
1011
+ this.say(e);
1012
+ }
1013
+ } else if ((n === "delete" || n === "backspace") && !r) {
1014
+ e.preventDefault();
1015
+ let t = e.target.closest?.("[data-socket=in]");
1016
+ if (t) {
1017
+ let e = this.socketTarget(t);
1018
+ e && "slot" in e ? this.model.disconnectOutput(e.slot) : e && this.model.disconnect(e.node, e.input);
1019
+ } else this.model.removeNodes([...this.selected]);
1020
+ } else if (n === "a" && e.shiftKey && !r) e.preventDefault(), this.openPalette(this.lastPoint ?? this.centre());
1021
+ else if (n === "f" && !t) e.preventDefault(), this.fit();
1022
+ else if (n.startsWith("arrow") && this.selected.size && !r) {
1023
+ e.preventDefault();
1024
+ let t = e.shiftKey ? 32 : 8;
1025
+ this.model.checkpoint(), this.model.move(this.selected, n === "arrowleft" ? -t : n === "arrowright" ? t : 0, n === "arrowup" ? -t : n === "arrowdown" ? t : 0);
1026
+ }
1027
+ }
1028
+ openPalette(e) {
1029
+ this.readOnly || (this.addAt = [e[0], e[1]], this.palette.hidden = !1, this.palette.style.left = Math.max(8, Math.min(e[0] * this.pan.zoom + this.pan.x | 0, (this.viewport.clientWidth || 800) - 270)) + "px", this.palette.style.top = Math.max(8, Math.min(e[1] * this.pan.zoom + this.pan.y | 0, (this.viewport.clientHeight || 500) - 280)) + "px", this.search.value = "", this.filter(), this.search.focus());
1030
+ }
1031
+ closePalette() {
1032
+ this.palette.hidden || (this.palette.hidden = !0, this.viewport.focus({ preventScroll: !0 }));
1033
+ }
1034
+ filter() {
1035
+ let e = this.search.value.toLowerCase().split(/\s+/).filter(Boolean);
1036
+ this.matches = this.operations.filter((t) => {
1037
+ let n = `${t.label} ${t.op} ${t.group} ${t.description}`.toLowerCase();
1038
+ return e.every((e) => n.includes(e));
1039
+ }), this.choice = 0, this.list.replaceChildren(...this.matches.map((e, t) => {
1040
+ let n = this.make("li");
1041
+ n.dataset.index = String(t), n.setAttribute("role", "option"), n.textContent = `${e.label} `;
1042
+ let r = this.make("small");
1043
+ return r.textContent = `${e.group}: ${e.description}`, n.append(r), n;
1044
+ })), this.paintChoice();
1045
+ }
1046
+ paintChoice() {
1047
+ [...this.list.children].forEach((e, t) => e.setAttribute("aria-selected", String(t === this.choice))), this.list.children[this.choice]?.scrollIntoView?.({ block: "nearest" });
1048
+ }
1049
+ choose(e) {
1050
+ let t = this.matches[e];
1051
+ if (t) {
1052
+ try {
1053
+ this.add(t.op, [this.addAt[0], this.addAt[1]]);
1054
+ } catch (e) {
1055
+ this.say(e);
1056
+ }
1057
+ this.closePalette();
1058
+ }
1059
+ }
1060
+ showCode(e) {
1061
+ if (!e.ok) this.code.textContent = e.message;
1062
+ else try {
1063
+ let e = this.model.toGraph();
1064
+ this.code.textContent = this.presentation.code?.(e) ?? n(e).fragmentCode;
1065
+ } catch (e) {
1066
+ this.code.textContent = e instanceof Error ? e.message : String(e);
1067
+ }
1068
+ }
1069
+ };
1070
+ //#endregion
1071
+ export { s as EDITOR_OPERATIONS, k as GraphModel, p as HEAD_HEIGHT, u as INPUT_DEFAULTS, f as NODE_WIDTH, N as NodeEditor, g as OUTPUT_EXTRA_ROWS, b as OUTPUT_HEIGHT, d as OUTPUT_SLOTS, m as ROW_HEIGHT, h as ROW_PADDING, l as inputLabel, x as inputSocket, y as nodeHeight, S as outputSocket, v as rowCount };