@n3rdw1z4rd/core 0.20.0 → 0.22.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 (44) hide show
  1. package/dist/graph/doc.d.ts +141 -0
  2. package/dist/graph/doc.js +173 -0
  3. package/dist/graph/evaluate.d.ts +114 -0
  4. package/dist/graph/evaluate.js +319 -0
  5. package/dist/graph/index.d.ts +9 -0
  6. package/dist/graph/index.js +9 -0
  7. package/dist/graph/node.d.ts +153 -0
  8. package/dist/graph/node.js +94 -0
  9. package/dist/graph/nodes.d.ts +11 -0
  10. package/dist/graph/nodes.js +399 -0
  11. package/dist/graph/script.d.ts +64 -0
  12. package/dist/graph/script.js +111 -0
  13. package/dist/graph/sources.d.ts +11 -0
  14. package/dist/graph/sources.js +263 -0
  15. package/dist/graph/subgraph.d.ts +36 -0
  16. package/dist/graph/subgraph.js +280 -0
  17. package/dist/graph/types.d.ts +56 -0
  18. package/dist/graph/types.js +67 -0
  19. package/dist/graph.cjs +1723 -0
  20. package/dist/graph.d.cts +576 -0
  21. package/dist/index.cjs +53 -52
  22. package/dist/rng-Dhqq7owV.cjs +642 -0
  23. package/dist/{spatial-partition-3d-Ba-VBveM.cjs → spatial-partition-3d-CmSCL87Z.cjs} +19 -660
  24. package/dist/three/adaptive-grid.d.ts +43 -0
  25. package/dist/three/adaptive-grid.js +127 -0
  26. package/dist/three/ecs.d.ts +5 -3
  27. package/dist/three/ecs.js +5 -3
  28. package/dist/three/editor-camera.d.ts +93 -0
  29. package/dist/three/editor-camera.js +174 -0
  30. package/dist/three/index.d.ts +6 -1
  31. package/dist/three/index.js +6 -1
  32. package/dist/three/picking.d.ts +34 -0
  33. package/dist/three/picking.js +59 -0
  34. package/dist/three/schema.d.ts +139 -0
  35. package/dist/three/schema.js +214 -0
  36. package/dist/three/world.d.ts +192 -0
  37. package/dist/three/world.js +363 -0
  38. package/dist/three.cjs +970 -23
  39. package/dist/three.d.cts +497 -5
  40. package/dist/vite.cjs +40 -0
  41. package/dist/vite.d.cts +35 -0
  42. package/dist/vite.d.ts +35 -0
  43. package/dist/vite.js +39 -0
  44. package/package.json +21 -1
@@ -0,0 +1,263 @@
1
+ //#region src/graph/sources.ts
2
+ /**
3
+ * The built-in nodes as script modules: the same interface and behaviour as the TypeScript
4
+ * definitions in `nodes.ts`, written self-contained so the editor can show a built-in's code
5
+ * and fork it into a custom node. A test compiles each one and checks it matches.
6
+ *
7
+ * @module
8
+ */
9
+ const num = `const num = (v, d = 0) => (typeof v === 'number' && Number.isFinite(v) ? v : d);`;
10
+ /** @category Graph */
11
+ const BUILTIN_SOURCES = {
12
+ "value/number": `export const title = 'Number';
13
+ export const params = { value: { type: 'number', default: 0 } };
14
+ export const outputs = { value: 'number' };
15
+
16
+ ${num}
17
+
18
+ export function run(inputs, { value }) {
19
+ return { value: num(value) };
20
+ }
21
+ `,
22
+ "value/vec2": `export const title = 'Vec2';
23
+ export const inputs = {
24
+ x: { type: 'number', default: 0 },
25
+ y: { type: 'number', default: 0 },
26
+ };
27
+ export const outputs = { vec: 'vec2' };
28
+
29
+ ${num}
30
+
31
+ export function run({ x, y }) {
32
+ return { vec: { x: num(x), y: num(y) } };
33
+ }
34
+ `,
35
+ "value/color": `export const title = 'Color';
36
+ export const params = { color: { type: 'color', default: '#3fd1a4' } };
37
+ export const outputs = { color: 'color' };
38
+
39
+ export function run(inputs, { color }) {
40
+ return { color };
41
+ }
42
+ `,
43
+ "value/text": `export const title = 'Text';
44
+ export const params = { text: { type: 'string', default: '' } };
45
+ export const outputs = { text: 'string' };
46
+
47
+ export function run(inputs, { text }) {
48
+ return { text: String(text ?? '') };
49
+ }
50
+ `,
51
+ "value/time": `export const title = 'Time';
52
+ export const description = 'the animation clock (animates by default)';
53
+ export const animate = true;
54
+ export const params = { speed: { type: 'number', default: 1, step: 0.1 } };
55
+ export const outputs = { time: 'number', dt: 'number', frame: 'number' };
56
+
57
+ ${num}
58
+
59
+ export function run(inputs, { speed }, ctx) {
60
+ return { time: ctx.time * num(speed, 1), dt: ctx.dt * num(speed, 1), frame: ctx.frame };
61
+ }
62
+ `,
63
+ "math/wave": `export const title = 'Wave';
64
+ export const description = 'sin / triangle / square / saw of t';
65
+ export const inputs = {
66
+ t: { type: 'number', default: 0 },
67
+ period: { type: 'number', default: 1 },
68
+ amplitude: { type: 'number', default: 1 },
69
+ };
70
+ export const params = { shape: { type: 'enum', options: ['sine', 'triangle', 'square', 'saw'], default: 'sine' } };
71
+ export const outputs = { value: 'number' };
72
+
73
+ ${num}
74
+
75
+ export function run({ t, period, amplitude }, { shape }) {
76
+ const p = num(t) / (num(period, 1) || 1);
77
+ const f = p - Math.floor(p);
78
+ const waves = {
79
+ sine: Math.sin(p * Math.PI * 2),
80
+ triangle: 1 - 4 * Math.abs(f - 0.5),
81
+ square: f < 0.5 ? 1 : -1,
82
+ saw: f * 2 - 1,
83
+ };
84
+ return { value: (waves[shape] ?? waves.sine) * num(amplitude, 1) };
85
+ }
86
+ `,
87
+ "math/math": `export const title = 'Math';
88
+ export const description = 'a ⊕ b for the chosen operation';
89
+ export const inputs = {
90
+ a: { type: 'number', default: 0 },
91
+ b: { type: 'number', default: 0 },
92
+ };
93
+ export const params = { op: { type: 'enum', options: ['+', '−', '×', '÷', 'min', 'max', 'pow', 'mod'], default: '+' } };
94
+ export const outputs = { result: 'number' };
95
+
96
+ ${num}
97
+
98
+ export function run({ a, b }, { op }) {
99
+ const x = num(a);
100
+ const y = num(b);
101
+ const results = {
102
+ '+': x + y, '−': x - y, '×': x * y, '÷': y === 0 ? 0 : x / y,
103
+ min: Math.min(x, y), max: Math.max(x, y), pow: x ** y, mod: y === 0 ? 0 : ((x % y) + y) % y,
104
+ };
105
+ return { result: results[op] ?? x + y };
106
+ }
107
+ `,
108
+ "math/remap": `export const title = 'Remap';
109
+ export const inputs = {
110
+ value: { type: 'number', default: 0.5 },
111
+ inMin: { type: 'number', default: 0 },
112
+ inMax: { type: 'number', default: 1 },
113
+ outMin: { type: 'number', default: 0 },
114
+ outMax: { type: 'number', default: 100 },
115
+ };
116
+ export const params = { clamp: { type: 'boolean', default: false } };
117
+ export const outputs = { result: 'number' };
118
+
119
+ export function run({ value, inMin, inMax, outMin, outMax }, { clamp }) {
120
+ let t = inMax === inMin ? 0 : (value - inMin) / (inMax - inMin);
121
+ if (clamp) t = Math.min(1, Math.max(0, t));
122
+ return { result: outMin + (outMax - outMin) * t };
123
+ }
124
+ `,
125
+ "vec2/split": `export const title = 'Split Vec2';
126
+ export const inputs = { vec: 'vec2' };
127
+ export const outputs = { x: 'number', y: 'number' };
128
+
129
+ ${num}
130
+
131
+ export function run({ vec }) {
132
+ return { x: num(vec?.x), y: num(vec?.y) };
133
+ }
134
+ `,
135
+ "vec2/offset": `export const title = 'Offset';
136
+ export const description = 'vec + by';
137
+ export const inputs = {
138
+ vec: 'vec2',
139
+ by: { type: 'vec2', default: { x: 0, y: 0 } },
140
+ };
141
+ export const outputs = { vec: 'vec2' };
142
+
143
+ ${num}
144
+
145
+ export function run({ vec, by }) {
146
+ return { vec: { x: num(vec?.x) + num(by?.x), y: num(vec?.y) + num(by?.y) } };
147
+ }
148
+ `,
149
+ "list/range": `export const title = 'Range';
150
+ export const description = 'numbers from start (inclusive) to end (exclusive)';
151
+ export const inputs = {
152
+ start: { type: 'number', default: 0 },
153
+ end: { type: 'number', default: 10 },
154
+ step: { type: 'number', default: 1 },
155
+ };
156
+ export const outputs = { numbers: 'number[]' };
157
+
158
+ ${num}
159
+
160
+ export function run({ start, end, step }) {
161
+ const s = num(step, 1) || 1;
162
+ const numbers = [];
163
+ for (let v = num(start); s > 0 ? v < end : v > end; v += s) {
164
+ numbers.push(v);
165
+ if (numbers.length >= 100000) break;
166
+ }
167
+ return { numbers };
168
+ }
169
+ `,
170
+ "list/grid2d": `export const title = 'Grid';
171
+ export const description = 'points on a grid, centered on \`center\`; stagger shifts every other row by half a cell';
172
+ export const inputs = {
173
+ cols: { type: 'number', default: 5, min: 1, step: 1 },
174
+ rows: { type: 'number', default: 5, min: 1, step: 1 },
175
+ spacing: { type: 'vec2', default: { x: 32, y: 32 } },
176
+ center: { type: 'vec2', default: { x: 0, y: 0 } },
177
+ };
178
+ export const params = { stagger: { type: 'boolean', default: false } };
179
+ export const outputs = { points: 'vec2[]' };
180
+
181
+ ${num}
182
+
183
+ export function run({ cols, rows, spacing, center }, { stagger }) {
184
+ const c = Math.max(0, Math.min(1000, Math.floor(num(cols))));
185
+ const r = Math.max(0, Math.min(1000, Math.floor(num(rows))));
186
+ const sx = num(spacing?.x, 32);
187
+ const sy = num(spacing?.y, 32);
188
+ const points = [];
189
+ for (let j = 0; j < r; j++) {
190
+ const shift = stagger && j % 2 === 1 ? sx / 2 : 0;
191
+ for (let i = 0; i < c; i++) {
192
+ points.push({ x: num(center?.x) + (i - (c - 1) / 2) * sx + shift, y: num(center?.y) + ((r - 1) / 2 - j) * sy });
193
+ }
194
+ }
195
+ return { points };
196
+ }
197
+ `,
198
+ "list/random": `export const title = 'Random';
199
+ export const description = 'seeded random numbers in [min, max)';
200
+ export const inputs = {
201
+ count: { type: 'number', default: 10, min: 0, step: 1 },
202
+ min: { type: 'number', default: 0 },
203
+ max: { type: 'number', default: 1 },
204
+ seed: { type: 'number', default: 1, step: 1 },
205
+ };
206
+ export const outputs = { numbers: 'number[]' };
207
+
208
+ ${num}
209
+
210
+ // the same generator as @n3rdw1z4rd/core's Rng: a 32-bit hash of an incrementing seed
211
+ const hash32 = (n) => {
212
+ n |= 0;
213
+ n ^= n >>> 16;
214
+ n = Math.imul(n, 0x85ebca6b);
215
+ n ^= n >>> 13;
216
+ n = Math.imul(n, 0xc2b2ae35);
217
+ n ^= n >>> 16;
218
+ return n >>> 0;
219
+ };
220
+
221
+ export function run({ count, min, max, seed }) {
222
+ let s = num(seed, 1) | 0;
223
+ const next = () => hash32((s++) | 0) / 0x100000000;
224
+ const n = Math.max(0, Math.min(100000, Math.floor(num(count))));
225
+ return { numbers: Array.from({ length: n }, () => num(min) + next() * (num(max, 1) - num(min))) };
226
+ }
227
+ `,
228
+ "list/count": `export const title = 'Count';
229
+ export const inputs = { list: 'any[]' };
230
+ export const outputs = { count: 'number' };
231
+
232
+ export function run({ list }) {
233
+ return { count: list.length };
234
+ }
235
+ `,
236
+ "list/merge": `export const title = 'Merge';
237
+ export const description = 'joins every list wired in, in order';
238
+ export const inputs = { lists: { type: 'any[]', multi: true, optional: true } };
239
+ export const outputs = { list: 'any[]' };
240
+
241
+ export function run({ lists }) {
242
+ return { list: [...(lists ?? [])] };
243
+ }
244
+ `,
245
+ "list/pick": `export const title = 'Pick';
246
+ export const description = 'every nth item from a list';
247
+ export const inputs = {
248
+ list: 'any[]',
249
+ every: { type: 'number', default: 2, min: 1, step: 1 },
250
+ offset: { type: 'number', default: 0, step: 1 },
251
+ };
252
+ export const outputs = { list: 'any[]' };
253
+
254
+ ${num}
255
+
256
+ export function run({ list, every, offset }) {
257
+ const n = Math.max(1, Math.floor(num(every, 1)));
258
+ return { list: list.filter((_, i) => (i - Math.floor(num(offset))) % n === 0 && i >= num(offset)) };
259
+ }
260
+ `
261
+ };
262
+ //#endregion
263
+ export { BUILTIN_SOURCES };
@@ -0,0 +1,36 @@
1
+ import { NodeRegistry, NodeSpec } from "./node.js";
2
+ import { GraphDoc, GraphNode, SubgraphDef } from "./doc.js";
3
+ //#region src/graph/subgraph.d.ts
4
+ /**
5
+ * Subgraphs: a selection of nodes collapsed into one node type. The inner graph is stored in
6
+ * `doc.subgraphs[type]` with its interface — every wire that crossed the selection's edge
7
+ * became an input or output. A subgraph node evaluates its inner graph (with its own cache per
8
+ * instance), feeding the inner ports from its inputs.
9
+ *
10
+ * @module
11
+ */
12
+ /** The node spec for a subgraph type: runs the inner graph. */
13
+ export declare function subgraphSpec(type: string, def: SubgraphDef, registry: NodeRegistry): NodeSpec;
14
+ /**
15
+ * Registers (or updates) every subgraph type a document defines. Unchanged definitions are
16
+ * left alone (so their nodes keep their caches). Definitions may use each other.
17
+ */
18
+ export declare function registerSubgraphs(doc: GraphDoc, registry: NodeRegistry): void;
19
+ /** A free type name for a subgraph (`subgraph/name`, `subgraph/name-2`, …). */
20
+ export declare function freeSubgraphType(doc: GraphDoc, registry: NodeRegistry, name: string): string;
21
+ /**
22
+ * Collapses nodes into a new subgraph type and puts one node of it in their place, wired to
23
+ * everything they were wired to. Output nodes (like a viewport) can't go into a subgraph.
24
+ */
25
+ export declare function collapseToSubgraph(doc: GraphDoc, registry: NodeRegistry, nodeIds: string[], title?: string): {
26
+ type: string;
27
+ node: GraphNode;
28
+ };
29
+ /**
30
+ * Replaces a subgraph node with a copy of its inner nodes (fresh ids), wired as the
31
+ * subgraph's inputs and outputs were. Returns the new node ids. The type stays defined.
32
+ * `defs`: where the definitions are (default: `doc.subgraphs`; pass the top-level document's
33
+ * when `doc` is itself a subgraph's inner graph).
34
+ */
35
+ export declare function expandSubgraph(doc: GraphDoc, nodeId: string, defs?: Record<string, SubgraphDef> | undefined): string[];
36
+ //#endregion
@@ -0,0 +1,280 @@
1
+ import { getNode, graphId } from "./doc.js";
2
+ import { GraphEvaluator, OUTPUT_LISTS } from "./evaluate.js";
3
+ //#region src/graph/subgraph.ts
4
+ /**
5
+ * Subgraphs: a selection of nodes collapsed into one node type. The inner graph is stored in
6
+ * `doc.subgraphs[type]` with its interface — every wire that crossed the selection's edge
7
+ * became an input or output. A subgraph node evaluates its inner graph (with its own cache per
8
+ * instance), feeding the inner ports from its inputs.
9
+ *
10
+ * @module
11
+ */
12
+ /** The node spec for a subgraph type: runs the inner graph. */
13
+ function subgraphSpec(type, def, registry) {
14
+ const inner = {
15
+ format: "n3rdw1z4rd.graph",
16
+ version: 1,
17
+ nodes: def.nodes,
18
+ links: def.links
19
+ };
20
+ const evaluators = /* @__PURE__ */ new Map();
21
+ let stamp = 0;
22
+ const probe = new GraphEvaluator(registry);
23
+ const targets = [...new Set(def.outputs.map((o) => o.from.node))];
24
+ return {
25
+ type,
26
+ title: def.title,
27
+ category: "subgraph",
28
+ description: `a subgraph of ${def.nodes.length} node${def.nodes.length === 1 ? "" : "s"} (double-click to go inside)`,
29
+ inputs: Object.fromEntries(def.inputs.map((p) => [p.name, {
30
+ type: p.type,
31
+ multi: !!p.multi,
32
+ optional: true
33
+ }])),
34
+ outputs: Object.fromEntries(def.outputs.map((p) => [p.name, p.type])),
35
+ animate: probe.animated(inner, targets).length > 0,
36
+ async run(inputs, _params, ctx) {
37
+ const key = `${ctx.nodeId}#${ctx.index}`;
38
+ let ev = evaluators.get(key);
39
+ if (!ev) evaluators.set(key, ev = new GraphEvaluator(registry));
40
+ const externals = /* @__PURE__ */ new Map();
41
+ for (const p of def.inputs) {
42
+ const v = inputs[p.name];
43
+ if (v === void 0) continue;
44
+ const list = p.type.trim().endsWith("[]");
45
+ for (const to of p.to) {
46
+ const k = `${to.node}:${to.port}`;
47
+ externals.set(k, [...externals.get(k) ?? [], {
48
+ value: v,
49
+ list
50
+ }]);
51
+ }
52
+ }
53
+ const r = await ev.evaluate(inner, {
54
+ targets,
55
+ externals,
56
+ externalsStamp: ++stamp,
57
+ scope: key,
58
+ env: ctx.env,
59
+ frame: {
60
+ time: ctx.time,
61
+ dt: ctx.dt,
62
+ frame: ctx.frame
63
+ }
64
+ });
65
+ const out = {};
66
+ const lists = {};
67
+ for (const o of def.outputs) {
68
+ const res = r.results.get(o.from.node);
69
+ if (!res) throw new Error(`inside: node ${o.from.node} is missing`);
70
+ const node = getNode(inner, o.from.node);
71
+ const name = node?.title ?? registry.get(node?.type ?? "")?.title ?? o.from.node;
72
+ if (res.error) throw new Error(`inside, ${name}: ${res.error}`);
73
+ if (res.disabled) throw new Error(`inside, ${name} is disabled`);
74
+ if (res.blocked) {
75
+ const up = getNode(inner, res.blocked);
76
+ throw new Error(`inside, ${name} is waiting on ${up?.title ?? registry.get(up?.type ?? "")?.title ?? res.blocked}`);
77
+ }
78
+ out[o.name] = res.outputs[o.from.port];
79
+ lists[o.name] = !!res.lists[o.from.port];
80
+ }
81
+ return {
82
+ ...out,
83
+ [OUTPUT_LISTS]: lists
84
+ };
85
+ }
86
+ };
87
+ }
88
+ const registered = /* @__PURE__ */ new Map();
89
+ /**
90
+ * Registers (or updates) every subgraph type a document defines. Unchanged definitions are
91
+ * left alone (so their nodes keep their caches). Definitions may use each other.
92
+ */
93
+ function registerSubgraphs(doc, registry) {
94
+ for (const [type, def] of Object.entries(doc.subgraphs ?? {})) {
95
+ const json = JSON.stringify(def);
96
+ if (registered.get(type) === json && registry.get(type)) continue;
97
+ registered.set(type, json);
98
+ registry.register(subgraphSpec(type, def, registry));
99
+ }
100
+ }
101
+ /** A free type name for a subgraph (`subgraph/name`, `subgraph/name-2`, …). */
102
+ function freeSubgraphType(doc, registry, name) {
103
+ const base = `subgraph/${name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "subgraph"}`;
104
+ let type = base;
105
+ for (let k = 2; registry.get(type) || doc.subgraphs?.[type]; k++) type = `${base}-${k}`;
106
+ return type;
107
+ }
108
+ /**
109
+ * Collapses nodes into a new subgraph type and puts one node of it in their place, wired to
110
+ * everything they were wired to. Output nodes (like a viewport) can't go into a subgraph.
111
+ */
112
+ function collapseToSubgraph(doc, registry, nodeIds, title = "Subgraph") {
113
+ const ids = new Set(nodeIds.filter((id) => {
114
+ const n = getNode(doc, id);
115
+ return n && !registry.get(n.type)?.output;
116
+ }));
117
+ if (!ids.size) throw new Error("select some nodes (output nodes stay outside)");
118
+ const type = freeSubgraphType(doc, registry, title);
119
+ const inside = doc.nodes.filter((n) => ids.has(n.id));
120
+ const internal = doc.links.filter((l) => ids.has(l.from.node) && ids.has(l.to.node));
121
+ const incoming = doc.links.filter((l) => !ids.has(l.from.node) && ids.has(l.to.node));
122
+ const outgoing = doc.links.filter((l) => ids.has(l.from.node) && !ids.has(l.to.node));
123
+ const used = /* @__PURE__ */ new Set();
124
+ const unique = (name) => {
125
+ let n = name;
126
+ for (let k = 2; used.has(n); k++) n = `${name}${k}`;
127
+ used.add(n);
128
+ return n;
129
+ };
130
+ const portOf = (ref, dir) => {
131
+ const def = registry.get(getNode(doc, ref.node).type);
132
+ return (dir === "in" ? def?.inputs : def?.outputs)?.find((p) => p.name === ref.port);
133
+ };
134
+ const inputs = [];
135
+ const inputBySource = /* @__PURE__ */ new Map();
136
+ const outerIn = [];
137
+ for (const l of incoming) {
138
+ const k = `${l.from.node}:${l.from.port}`;
139
+ let input = inputBySource.get(k);
140
+ if (!input) {
141
+ const p = portOf(l.to, "in");
142
+ input = {
143
+ name: unique(l.to.port),
144
+ type: p?.type ?? "any",
145
+ ...p?.multi ? { multi: true } : {},
146
+ to: []
147
+ };
148
+ inputBySource.set(k, input);
149
+ inputs.push(input);
150
+ outerIn.push({
151
+ source: l.from,
152
+ input: input.name
153
+ });
154
+ }
155
+ input.to.push({ ...l.to });
156
+ }
157
+ used.clear();
158
+ const outputs = [];
159
+ const outputBySource = /* @__PURE__ */ new Map();
160
+ for (const l of outgoing) {
161
+ const k = `${l.from.node}:${l.from.port}`;
162
+ if (outputBySource.has(k)) continue;
163
+ const name = unique(l.from.port);
164
+ outputBySource.set(k, name);
165
+ outputs.push({
166
+ name,
167
+ type: portOf(l.from, "out")?.type ?? "any",
168
+ from: { ...l.from }
169
+ });
170
+ }
171
+ let minX = Infinity, minY = Infinity, sumX = 0, sumY = 0;
172
+ for (const n of inside) {
173
+ minX = Math.min(minX, n.pos[0]);
174
+ minY = Math.min(minY, n.pos[1]);
175
+ sumX += n.pos[0];
176
+ sumY += n.pos[1];
177
+ }
178
+ const def = {
179
+ title,
180
+ nodes: inside.map((n) => ({
181
+ ...structuredClone(n),
182
+ pos: [n.pos[0] - minX, n.pos[1] - minY]
183
+ })),
184
+ links: internal.map((l) => structuredClone(l)),
185
+ inputs,
186
+ outputs
187
+ };
188
+ doc.subgraphs = {
189
+ ...doc.subgraphs ?? {},
190
+ [type]: def
191
+ };
192
+ registry.register(subgraphSpec(type, def, registry));
193
+ const node = {
194
+ id: graphId(),
195
+ type,
196
+ pos: [Math.round(sumX / inside.length), Math.round(sumY / inside.length)],
197
+ values: {}
198
+ };
199
+ doc.nodes = doc.nodes.filter((n) => !ids.has(n.id));
200
+ doc.nodes.push(node);
201
+ doc.links = doc.links.filter((l) => !ids.has(l.from.node) && !ids.has(l.to.node));
202
+ for (const { source, input } of outerIn) doc.links.push({
203
+ id: graphId("l"),
204
+ from: { ...source },
205
+ to: {
206
+ node: node.id,
207
+ port: input
208
+ }
209
+ });
210
+ for (const l of outgoing) doc.links.push({
211
+ id: graphId("l"),
212
+ from: {
213
+ node: node.id,
214
+ port: outputBySource.get(`${l.from.node}:${l.from.port}`)
215
+ },
216
+ to: { ...l.to }
217
+ });
218
+ return {
219
+ type,
220
+ node
221
+ };
222
+ }
223
+ /**
224
+ * Replaces a subgraph node with a copy of its inner nodes (fresh ids), wired as the
225
+ * subgraph's inputs and outputs were. Returns the new node ids. The type stays defined.
226
+ * `defs`: where the definitions are (default: `doc.subgraphs`; pass the top-level document's
227
+ * when `doc` is itself a subgraph's inner graph).
228
+ */
229
+ function expandSubgraph(doc, nodeId, defs = doc.subgraphs) {
230
+ const node = getNode(doc, nodeId);
231
+ const def = node && defs?.[node.type];
232
+ if (!node || !def) throw new Error("not a subgraph node");
233
+ const ids = /* @__PURE__ */ new Map();
234
+ for (const n of def.nodes) {
235
+ const id = graphId();
236
+ ids.set(n.id, id);
237
+ doc.nodes.push({
238
+ ...structuredClone(n),
239
+ id,
240
+ pos: [n.pos[0] + node.pos[0], n.pos[1] + node.pos[1]]
241
+ });
242
+ }
243
+ const links = def.links.map((l) => ({
244
+ id: graphId("l"),
245
+ from: {
246
+ node: ids.get(l.from.node),
247
+ port: l.from.port
248
+ },
249
+ to: {
250
+ node: ids.get(l.to.node),
251
+ port: l.to.port
252
+ }
253
+ }));
254
+ for (const l of doc.links) if (l.to.node === nodeId) {
255
+ const input = def.inputs.find((p) => p.name === l.to.port);
256
+ for (const to of input?.to ?? []) links.push({
257
+ id: graphId("l"),
258
+ from: { ...l.from },
259
+ to: {
260
+ node: ids.get(to.node),
261
+ port: to.port
262
+ }
263
+ });
264
+ } else if (l.from.node === nodeId) {
265
+ const output = def.outputs.find((p) => p.name === l.from.port);
266
+ if (output) links.push({
267
+ id: graphId("l"),
268
+ from: {
269
+ node: ids.get(output.from.node),
270
+ port: output.from.port
271
+ },
272
+ to: { ...l.to }
273
+ });
274
+ } else links.push(l);
275
+ doc.links = links;
276
+ doc.nodes = doc.nodes.filter((n) => n.id !== nodeId);
277
+ return [...ids.values()];
278
+ }
279
+ //#endregion
280
+ export { collapseToSubgraph, expandSubgraph, freeSubgraphType, registerSubgraphs, subgraphSpec };
@@ -0,0 +1,56 @@
1
+ //#region src/graph/types.d.ts
2
+ /**
3
+ * Pin types. A type is a name (`number`, `vec2`, `entity`…) with a color for the editor;
4
+ * a trailing `[]` in a port declaration (`vec2[]`) makes the port a **list port** — it takes
5
+ * or produces a whole list instead of one value at a time (see {@link GraphEvaluator}).
6
+ *
7
+ * `any` connects to everything. Other compatibility is declared with `accepts`:
8
+ * `types.define('vec2', '#4ea8de', { accepts: ['number'] })` would let a number plug into a
9
+ * vec2 pin (the node then gets the number as-is — coercion is the node's business).
10
+ *
11
+ * @module
12
+ */
13
+ /** @category Graph */
14
+ export interface PortTypeDef {
15
+ name: string;
16
+ /** pin / wire color in the editor */
17
+ color: string;
18
+ /** other types that may connect into a pin of this type */
19
+ accepts: string[];
20
+ }
21
+ /** A parsed port type: `vec2[]` → `{ base: 'vec2', list: true }`. @category Graph */
22
+ export interface ParsedType {
23
+ base: string;
24
+ list: boolean;
25
+ }
26
+ /** @category Graph */
27
+ export declare function parseType(type: string): ParsedType;
28
+ /**
29
+ * Known pin types and which connect to which.
30
+ *
31
+ * @category Graph
32
+ */
33
+ export declare class TypeRegistry {
34
+ private readonly types;
35
+ constructor();
36
+ define(name: string, color: string, options?: {
37
+ accepts?: string[];
38
+ }): PortTypeDef;
39
+ get(name: string): PortTypeDef | undefined;
40
+ /** The color for a type (unknown types get `any`'s). */
41
+ color(name: string): string;
42
+ /**
43
+ * Whether an output of type `from` may connect to an input of type `to`. List-ness never
44
+ * blocks a connection: one value into a list port becomes a one-item list, and a list
45
+ * into a single-value port broadcasts.
46
+ */
47
+ canConnect(from: string, to: string): boolean;
48
+ all(): PortTypeDef[];
49
+ }
50
+ /**
51
+ * The default pin types (colors match the apparatus palette).
52
+ *
53
+ * @category Graph
54
+ */
55
+ export declare const portTypes: TypeRegistry;
56
+ //#endregion
@@ -0,0 +1,67 @@
1
+ //#region src/graph/types.ts
2
+ /** @category Graph */
3
+ function parseType(type) {
4
+ const t = type.trim();
5
+ return t.endsWith("[]") ? {
6
+ base: t.slice(0, -2).trim(),
7
+ list: true
8
+ } : {
9
+ base: t,
10
+ list: false
11
+ };
12
+ }
13
+ /**
14
+ * Known pin types and which connect to which.
15
+ *
16
+ * @category Graph
17
+ */
18
+ var TypeRegistry = class {
19
+ types = /* @__PURE__ */ new Map();
20
+ constructor() {
21
+ this.define("any", "#9a9a9a");
22
+ }
23
+ define(name, color, options = {}) {
24
+ const def = {
25
+ name,
26
+ color,
27
+ accepts: options.accepts ?? []
28
+ };
29
+ this.types.set(name, def);
30
+ return def;
31
+ }
32
+ get(name) {
33
+ return this.types.get(parseType(name).base);
34
+ }
35
+ /** The color for a type (unknown types get `any`'s). */
36
+ color(name) {
37
+ return (this.get(name) ?? this.types.get("any")).color;
38
+ }
39
+ /**
40
+ * Whether an output of type `from` may connect to an input of type `to`. List-ness never
41
+ * blocks a connection: one value into a list port becomes a one-item list, and a list
42
+ * into a single-value port broadcasts.
43
+ */
44
+ canConnect(from, to) {
45
+ const a = parseType(from).base;
46
+ const b = parseType(to).base;
47
+ if (a === b || a === "any" || b === "any") return true;
48
+ return this.types.get(b)?.accepts.includes(a) ?? false;
49
+ }
50
+ all() {
51
+ return [...this.types.values()];
52
+ }
53
+ };
54
+ /**
55
+ * The default pin types (colors match the apparatus palette).
56
+ *
57
+ * @category Graph
58
+ */
59
+ const portTypes = new TypeRegistry();
60
+ portTypes.define("number", "#3fd1a4");
61
+ portTypes.define("boolean", "#e8554e");
62
+ portTypes.define("string", "#e86fb0");
63
+ portTypes.define("color", "#f2a541");
64
+ portTypes.define("vec2", "#4ea8de");
65
+ portTypes.define("vec3", "#9b6dde");
66
+ //#endregion
67
+ export { TypeRegistry, parseType, portTypes };