@n3rdw1z4rd/core 0.21.0 → 0.23.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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @n3rdw1z4rd/core
2
2
 
3
- A personal, browser-facing TypeScript toolkit consolidated out of several game/graphics side projects: math helpers and a deterministic, seedable RNG, an event emitter (TODO: emitter replaced), two ECS flavors, procedural generation (pathfinding, dungeon layout), a "particle life" simulation in 2D and 3D, raw WebGL helpers, and a set of Three.js helpers (camera rigs, voxel meshing, texture atlases, procedural meshes).
3
+ A personal, browser-facing TypeScript toolkit consolidated out of several game/graphics side projects: math helpers and a deterministic, seedable RNG, event helpers, an event-based input system with action maps, two ECS flavors, procedural generation (pathfinding, dungeon layout), a "particle life" simulation in 2D and 3D, raw WebGL helpers, a node graph format and evaluator (`core/graph`), and a set of Three.js helpers (`core/three`: a scene `World` with component schemas, editor camera and picking, camera rigs, voxel meshing, texture atlases, procedural meshes).
4
4
 
5
5
  Nothing here is trying to be a general-purpose framework - it's the shared plumbing that kept getting copy-pasted between projects, pulled into one place so it only has to be fixed once.
6
6
 
@@ -32,7 +32,7 @@ This package ships ESM and CJS builds plus `.d.ts` types (built with `tsdown`).
32
32
 
33
33
  ### Browser vs. Node
34
34
 
35
- The data and logic modules load and run anywhere, including Node (the tests run there): math, `Random`/`Rng`, `Vector`, `Rectangle`, `Map2D`/`Map3D`/`Tilemap`, `findPath` (A*), the dungeon generator, `ECS`, the event helpers (`Emitter`, `Observable`, `Signal`, `EventQueue`, `Disposable`), `Color` and color palettes, the spatial partitions and the particle simulations.
35
+ The data and logic modules load and run anywhere, including Node (the tests run there): math, `Random`/`Rng`, `Vector`, `Rectangle`, `Map2D`/`Map3D`/`Tilemap`, `findPath` (A*), the dungeon generator, `ECS`, the event helpers (`Emitter`, `Observable`, `Signal`, `EventQueue`, `Disposable`), `Color` and color palettes, the spatial partitions, the particle simulations, and all of `@n3rdw1z4rd/core/graph` (in a page, a worker or Node).
36
36
 
37
37
  These need a browser when used (importing them is still safe anywhere): `CanvasRenderer`, `ParticleRenderer`, `WebGlRenderer` and the WebGL helpers, `Input`, `InputActionMap`, `WorkerInterface`, `Clock.start()`, `Color.fromName()` and `GetUrlParams()`, plus anything in `@n3rdw1z4rd/core/three` that renders or loads textures.
38
38
 
@@ -98,12 +98,67 @@ const move = controls.getVector("move_left", "move_right", "move_forward", "move
98
98
 
99
99
  Keyboard, mouse and pen, touch gestures, gamepads (each its own device for local multiplayer) and WebXR controllers (`controls.attachXR(session)`) all feed the same actions. `repeat` keeps a held action pressing again like a held key in a text field (`{ repeat: true }`; the `ui_*` directions repeat by default), `controls.gestures.events` says where the last frame's taps and swipes happened, `controls.actions.toJSON()` / `load()` save rebinds, and `controls.captureBinding()` waits for the next input for rebinding menus.
100
100
 
101
- Three.js helpers come from the `three` subpath:
101
+ ## Three.js helpers (`@n3rdw1z4rd/core/three`)
102
+
103
+ A scene `World` for editors and games: entities are three.js `Object3D`s (tracked by their `uuid`, so ids stay stable), components are declared with schemas, and the whole scene saves and loads as JSON.
104
+
105
+ ```ts
106
+ import { World, component, field, defineComponent } from "@n3rdw1z4rd/core/three";
107
+
108
+ @component("RigidBody")
109
+ class RigidBody {
110
+ @field({ type: "enum", options: ["dynamic", "fixed"] }) kind = "dynamic";
111
+ @field({ min: 0, step: 0.1 }) mass = 1;
112
+ }
113
+
114
+ // or as plain data (no decorators: works in workers and user scripts)
115
+ const Health = defineComponent("Health", { value: { type: "number", default: 100, min: 0 } });
116
+
117
+ const world = new World();
118
+ const ball = world.create("ball"); // an Object3D; parent it to build a hierarchy
119
+ world.addComponent(ball, RigidBody, { mass: 2 });
120
+ world.query(RigidBody); // entities with a RigidBody
121
+ const saved = world.serialize(); // JSON-safe; world.load(saved) restores it
122
+ ```
123
+
124
+ Schemas are what let an editor work with components it has never seen: an inspector, a serializer or graph nodes can be generated from them. Class components use standard (TC39) decorators; until browsers run them natively, the `decorators()` Vite plugin from `@n3rdw1z4rd/core/vite` lowers them.
125
+
126
+ For editors: `EditorCamera` (orthographic or perspective; pan, zoom-at-cursor, orbit, fit, with `zoom` in screen px per world unit), `AdaptiveGrid` (a grid that keeps its spacing readable at any zoom), `pickEntity(world, camera, x, y)` (the entity under a screen point) and `Renderer` (a `WebGLRenderer` that uses the device pixel ratio and can size itself to its parent). Also: `CameraRig`, voxel meshing, texture atlases, `AsteroidMesh`, `CubeSphereGeometry`, a starfield and a 3D particle system.
127
+
128
+ ## Node graphs (`@n3rdw1z4rd/core/graph`)
129
+
130
+ A graph document format, typed pins, node types (built-in or written as scripts) and a lazy, memoized evaluator. It has no DOM, so it runs in a page, a worker or Node.
102
131
 
103
132
  ```ts
104
- import { CameraRig } from "@n3rdw1z4rd/core/three";
133
+ import { createGraph, createNodeRegistry, addNode, connect, GraphEvaluator } from "@n3rdw1z4rd/core/graph";
134
+
135
+ const nodes = createNodeRegistry(); // the built-ins: values, math, lists, ...
136
+ const graph = createGraph(); // { format: "n3rdw1z4rd.graph", nodes, links, ... }
137
+ const grid = addNode(graph, nodes.get("list/grid2d")!, [0, 0], { cols: 3, rows: 2 });
138
+ const count = addNode(graph, nodes.get("list/count")!, [240, 0]);
139
+ connect(graph, nodes, { node: grid.id, port: "points" }, { node: count.id, port: "list" });
140
+
141
+ const { results } = await new GraphEvaluator(nodes).evaluate(graph);
142
+ results.get(count.id)!.outputs.count; // 6
105
143
  ```
106
144
 
145
+ - **Pins are typed** (`number`, `vec2`, `color`, `string`, `boolean`, `any`, your own via `portTypes.define()`), and `T[]` is a list. A list wired into a single-value input **broadcasts**: the node runs once per item (several lists pair up; the longest wins). A `multi` input takes any number of wires.
146
+ - **Evaluation is lazy and local**: only what the output nodes need is evaluated, results are memoized between evaluations, and a node that throws gets an error without stopping the rest. A multi input leaves out a source that failed; downstream nodes are marked `skipped`. Nodes can be `disabled`, and `animate` nodes re-run every frame (`evaluate(graph, { frame })`).
147
+ - **Nodes can be scripts.** A node type is an ES module with its interface and a `run()`; `compileNodeScript(type, source)` turns it into a node type, and every built-in carries an equivalent `source`, so an editor can show any node's code and let you fork it:
148
+
149
+ ```js
150
+ export const title = 'Double';
151
+ export const inputs = { value: { type: 'number', default: 1 } };
152
+ export const outputs = { value: 'number' };
153
+ export function run({ value }, params, ctx) { return { value: value * 2 }; }
154
+ ```
155
+
156
+ A host can also declare its own **module kinds** (`compileNodeScript(type, source, { kinds })`): a module that exports hooks instead of `run` (say, an `update(self, dt)` the host calls every frame) becomes a node with a `run` the host provides, typically one that outputs the node's params and source for the host to run later. apparatus's behaviours (`setup` / `step` / `enter` / `exit` on a physics body) are one.
157
+ - **Subgraphs**: `collapseToSubgraph(graph, nodes, ids, title)` turns a selection into a reusable node type (the wires crossing the selection become its pins); `expandSubgraph()` undoes it, and `registerSubgraphs()` restores the types from a saved document.
158
+ - **Documents** are plain JSON (`normalizeGraph()` checks and fills in one you've loaded): nodes, links, groups, subgraph definitions and embedded scripts.
159
+
160
+ [apparatus](https://github.com/n3rdw1z4rd/apparatus) is built on it: a node graph editor where the graph is a 2D physics scene.
161
+
107
162
  The optional stylesheet (reset + dark defaults) is shipped as plain CSS:
108
163
 
109
164
  ```ts
@@ -3,7 +3,7 @@ import { NodeDef, NodeRegistry, NodeSpec, Param, ParamSpec, Port, PortSpec, RunC
3
3
  import { ConnectCheck, GRAPH_FORMAT, GRAPH_VERSION, GraphDoc, GraphGroup, GraphLink, GraphNode, PortRef, SubgraphDef, addNode, canConnect, connect, createGraph, disconnect, getNode, graphId, linkInto, linksInto, normalizeGraph, removeNode } from "./doc.js";
4
4
  import { EvaluateOptions, EvaluateResult, FrameInfo, GraphEvaluator, NodeResult, OUTPUT_LISTS } from "./evaluate.js";
5
5
  import { BUILTIN_NODES, createNodeRegistry } from "./nodes.js";
6
- import { BehaviorValue, SCRIPT_NODE_TEMPLATE, behaviorRun, compileNodeScript } from "./script.js";
6
+ import { ModuleKind, SCRIPT_NODE_TEMPLATE, ScriptOptions, compileNodeScript } from "./script.js";
7
7
  import { BUILTIN_SOURCES } from "./sources.js";
8
8
  import { collapseToSubgraph, expandSubgraph, freeSubgraphType, registerSubgraphs, subgraphSpec } from "./subgraph.js";
9
- export { BUILTIN_NODES, BUILTIN_SOURCES, BehaviorValue, ConnectCheck, EvaluateOptions, EvaluateResult, FrameInfo, GRAPH_FORMAT, GRAPH_VERSION, GraphDoc, GraphEvaluator, GraphGroup, GraphLink, GraphNode, NodeDef, NodeRegistry, NodeResult, NodeSpec, OUTPUT_LISTS, Param, ParamSpec, ParsedType, Port, PortRef, PortSpec, PortTypeDef, RunContext, RunFn, SCRIPT_NODE_TEMPLATE, SubgraphDef, TypeRegistry, WidgetSpec, addNode, behaviorRun, canConnect, collapseToSubgraph, compileNodeScript, connect, createGraph, createNodeRegistry, defineNode, disconnect, expandSubgraph, freeSubgraphType, getNode, graphId, linkInto, linksInto, normalizeGraph, parseType, portTypes, registerSubgraphs, removeNode, subgraphSpec };
9
+ export { BUILTIN_NODES, BUILTIN_SOURCES, ConnectCheck, EvaluateOptions, EvaluateResult, FrameInfo, GRAPH_FORMAT, GRAPH_VERSION, GraphDoc, GraphEvaluator, GraphGroup, GraphLink, GraphNode, ModuleKind, NodeDef, NodeRegistry, NodeResult, NodeSpec, OUTPUT_LISTS, Param, ParamSpec, ParsedType, Port, PortRef, PortSpec, PortTypeDef, RunContext, RunFn, SCRIPT_NODE_TEMPLATE, ScriptOptions, SubgraphDef, TypeRegistry, WidgetSpec, addNode, canConnect, collapseToSubgraph, compileNodeScript, connect, createGraph, createNodeRegistry, defineNode, disconnect, expandSubgraph, freeSubgraphType, getNode, graphId, linkInto, linksInto, normalizeGraph, parseType, portTypes, registerSubgraphs, removeNode, subgraphSpec };
@@ -4,6 +4,6 @@ import { GraphEvaluator, OUTPUT_LISTS } from "./evaluate.js";
4
4
  import { NodeRegistry, defineNode } from "./node.js";
5
5
  import { BUILTIN_SOURCES } from "./sources.js";
6
6
  import { BUILTIN_NODES, createNodeRegistry } from "./nodes.js";
7
- import { SCRIPT_NODE_TEMPLATE, behaviorRun, compileNodeScript } from "./script.js";
7
+ import { SCRIPT_NODE_TEMPLATE, compileNodeScript } from "./script.js";
8
8
  import { collapseToSubgraph, expandSubgraph, freeSubgraphType, registerSubgraphs, subgraphSpec } from "./subgraph.js";
9
- export { BUILTIN_NODES, BUILTIN_SOURCES, GRAPH_FORMAT, GRAPH_VERSION, GraphEvaluator, NodeRegistry, OUTPUT_LISTS, SCRIPT_NODE_TEMPLATE, TypeRegistry, addNode, behaviorRun, canConnect, collapseToSubgraph, compileNodeScript, connect, createGraph, createNodeRegistry, defineNode, disconnect, expandSubgraph, freeSubgraphType, getNode, graphId, linkInto, linksInto, normalizeGraph, parseType, portTypes, registerSubgraphs, removeNode, subgraphSpec };
9
+ export { BUILTIN_NODES, BUILTIN_SOURCES, GRAPH_FORMAT, GRAPH_VERSION, GraphEvaluator, NodeRegistry, OUTPUT_LISTS, SCRIPT_NODE_TEMPLATE, TypeRegistry, addNode, canConnect, collapseToSubgraph, compileNodeScript, connect, createGraph, createNodeRegistry, defineNode, disconnect, expandSubgraph, freeSubgraphType, getNode, graphId, linkInto, linksInto, normalizeGraph, parseType, portTypes, registerSubgraphs, removeNode, subgraphSpec };
@@ -14,11 +14,11 @@ import { ParsedType } from "./types.js";
14
14
  *
15
15
  * ```ts
16
16
  * defineNode({
17
- * type: 'shapes/ball',
18
- * inputs: { at: 'vec2', radius: { type: 'number', default: 8, min: 0.5 } },
19
- * params: { color: { type: 'color', default: '#e8554e' } },
20
- * outputs: { entity: 'entity' },
21
- * run: ({ at, radius }, { color }) => ({ entity: { shape: 'ball', x: at.x, y: at.y, r: radius, color } }),
17
+ * type: 'math/lerp',
18
+ * inputs: { a: 'number', b: { type: 'number', default: 1 } },
19
+ * params: { t: { type: 'number', default: 0.5, min: 0, max: 1, step: 0.05 } },
20
+ * outputs: { value: 'number' },
21
+ * run: ({ a, b }, { t }) => ({ value: a + (b - a) * t }),
22
22
  * });
23
23
  * ```
24
24
  *
@@ -53,7 +53,7 @@ export type ParamSpec = {
53
53
  export interface RunContext {
54
54
  /** the node instance's id */
55
55
  nodeId: string;
56
- /** the node's type, and its source module (if it has one) — behaviour nodes pass these on */
56
+ /** the node's type, and its source module (if it has one), for nodes whose output carries their own code */
57
57
  type: string;
58
58
  source?: string;
59
59
  /** while broadcasting over lists: this call's index (else 0) and the call count (else 1) */
@@ -1,15 +1,15 @@
1
- import { NodeDef, RunContext } from "./node.js";
1
+ import { NodeDef, NodeSpec } from "./node.js";
2
2
  //#region src/graph/script.d.ts
3
3
  /**
4
4
  * Script nodes: a node type written as a plain ES module, compiled at runtime.
5
5
  *
6
6
  * ```js
7
- * export const title = 'Ball'; // optional: title, category, description, output, animate
8
- * export const inputs = { at: 'vec2', radius: { type: 'number', default: 8 } };
9
- * export const params = { color: { type: 'color', default: '#e8554e' } };
10
- * export const outputs = { entity: 'entity' };
11
- * export function run({ at, radius }, { color }, ctx) {
12
- * return { entity: { shape: 'ball', x: at.x, y: at.y, r: radius, color } };
7
+ * export const title = 'Lerp'; // optional: title, category, description, output, animate
8
+ * export const inputs = { a: 'number', b: { type: 'number', default: 1 } };
9
+ * export const params = { t: { type: 'number', default: 0.5, min: 0, max: 1, step: 0.05 } };
10
+ * export const outputs = { value: 'number' };
11
+ * export function run({ a, b }, { t }, ctx) {
12
+ * return { value: a + (b - a) * t };
13
13
  * }
14
14
  * ```
15
15
  *
@@ -20,37 +20,44 @@ import { NodeDef, RunContext } from "./node.js";
20
20
  * @module
21
21
  */
22
22
  /**
23
- * Compiles a script node's source into a node type named `type`.
23
+ * Another shape of script module a host understands, besides `run` nodes: a module that exports
24
+ * no `run` but any of `hooks` is compiled into a node with this `run` (and these outputs and
25
+ * category, unless the module declares its own). What the hooks mean is up to the host — e.g. a
26
+ * per-frame `update` it calls later: `run` typically packs the node's params and `ctx.source`
27
+ * into a value the host picks up from the output.
24
28
  *
25
- * @category Graph
26
- */
27
- export declare function compileNodeScript(type: string, source: string): Promise<NodeDef>;
28
- /**
29
- * A behaviour: what a behaviour node evaluates to. The host runs `source`'s `step` (and
30
- * `setup`) against whatever it's attached to, with `params`.
29
+ * ```ts
30
+ * const agent: ModuleKind = {
31
+ * hooks: ['update'],
32
+ * outputs: { agent: 'agent' },
33
+ * run: (inputs, params, ctx) => ({ agent: { params: { ...inputs, ...params }, source: ctx.source } }),
34
+ * };
35
+ * const def = await compileNodeScript('agents/wander', source, { kinds: [agent] });
36
+ * ```
31
37
  *
32
38
  * @category Graph
33
39
  */
34
- export interface BehaviorValue {
35
- kind: 'behavior';
36
- /** the behaviour node's type */
37
- type: string;
38
- /** the node instance (for error reports) */
39
- node: string;
40
- /** its inputs and params at evaluation time */
41
- params: Record<string, unknown>;
42
- /** the module with step / setup */
43
- source: string;
40
+ export interface ModuleKind {
41
+ /** exporting any of these (and no `run`) makes a module this kind */
42
+ hooks: readonly string[];
43
+ /** the node's run */
44
+ run: NodeSpec['run'];
45
+ /** outputs, unless the module exports its own */
46
+ outputs?: NodeSpec['outputs'];
47
+ /** category, unless the module exports its own */
48
+ category?: string;
49
+ }
50
+ /** @category Graph */
51
+ export interface ScriptOptions {
52
+ /** the module kinds this host understands besides `run` nodes (first match wins) */
53
+ kinds?: readonly ModuleKind[];
44
54
  }
45
55
  /**
46
- * The `run` of a behaviour node: packs its inputs, params and source into a {@link BehaviorValue}
47
- * on the `behavior` output. Behaviour modules (exporting `step`, no `run`) get it automatically.
56
+ * Compiles a script node's source into a node type named `type`.
48
57
  *
49
58
  * @category Graph
50
59
  */
51
- export declare function behaviorRun(inputs: Record<string, unknown>, params: Record<string, unknown>, ctx: RunContext): {
52
- behavior: BehaviorValue;
53
- };
60
+ export declare function compileNodeScript(type: string, source: string, options?: ScriptOptions): Promise<NodeDef>;
54
61
  /** A starting point for a new script node. @category Graph */
55
62
  export declare const SCRIPT_NODE_TEMPLATE = "// A node is a function with a typed interface.\n// inputs: pins wired from other nodes (an unconnected one uses its widget value / default)\n// params: widgets on the node\n// outputs: what run() returns\n// A \"type[]\" pin takes (or gives) a whole list; a list wired into a plain pin runs\n// run() once per item and collects the results into lists.\n\nexport const inputs = {\n a: { type: 'number', default: 1 },\n b: { type: 'number', default: 2 },\n};\n\nexport const params = {\n scale: { type: 'number', default: 1, min: 0, max: 10, step: 0.1 },\n};\n\nexport const outputs = {\n result: 'number',\n};\n\nexport function run({ a, b }, { scale }, ctx) {\n return { result: (a + b) * scale };\n}\n";
56
63
  //#endregion
@@ -1,41 +1,28 @@
1
1
  import { defineNode } from "./node.js";
2
2
  //#region src/graph/script.ts
3
3
  /**
4
- * Script nodes: a node type written as a plain ES module, compiled at runtime.
5
- *
6
- * ```js
7
- * export const title = 'Ball'; // optional: title, category, description, output, animate
8
- * export const inputs = { at: 'vec2', radius: { type: 'number', default: 8 } };
9
- * export const params = { color: { type: 'color', default: '#e8554e' } };
10
- * export const outputs = { entity: 'entity' };
11
- * export function run({ at, radius }, { color }, ctx) {
12
- * return { entity: { shape: 'ball', x: at.x, y: at.y, r: radius, color } };
13
- * }
14
- * ```
15
- *
16
- * The module is imported from a `data:` URL, which works in browsers, workers and Node.
17
- * It runs with the page's (or worker's) privileges — treat shared scripts as untrusted and
18
- * evaluate them in a worker.
19
- *
20
- * @module
21
- */
22
- /**
23
4
  * Compiles a script node's source into a node type named `type`.
24
5
  *
25
6
  * @category Graph
26
7
  */
27
- async function compileNodeScript(type, source) {
8
+ async function compileNodeScript(type, source, options = {}) {
28
9
  const mod = await import(
29
10
  /* @vite-ignore */
30
11
  `data:text/javascript;charset=utf-8,${encodeURIComponent(source)}`
31
12
  );
32
13
  const m = { ...mod.default && typeof mod.default === "object" && !mod.run ? mod.default : mod };
33
- if (typeof m.run !== "function" && (typeof m.step === "function" || typeof m.setup === "function")) {
34
- m.run = behaviorRun;
35
- m.outputs ??= { behavior: "behavior" };
36
- m.category ??= "behavior";
14
+ if (typeof m.run !== "function") {
15
+ const kind = options.kinds?.find((k) => k.hooks.some((h) => typeof m[h] === "function"));
16
+ if (kind) {
17
+ m.run = kind.run;
18
+ m.outputs ??= kind.outputs;
19
+ m.category ??= kind.category;
20
+ }
21
+ }
22
+ if (typeof m.run !== "function") {
23
+ const hooks = options.kinds?.flatMap((k) => k.hooks) ?? [];
24
+ throw new Error(`script node "${type}": export a run(inputs, params, ctx) function${hooks.length ? ` (or ${hooks.join(" / ")})` : ""}`);
37
25
  }
38
- if (typeof m.run !== "function") throw new Error(`script node "${type}": export a run(inputs, params, ctx) function (or step(self, world, dt, params) for a behaviour)`);
39
26
  return defineNode({
40
27
  type,
41
28
  title: m.title,
@@ -50,25 +37,6 @@ async function compileNodeScript(type, source) {
50
37
  source
51
38
  });
52
39
  }
53
- /**
54
- * The `run` of a behaviour node: packs its inputs, params and source into a {@link BehaviorValue}
55
- * on the `behavior` output. Behaviour modules (exporting `step`, no `run`) get it automatically.
56
- *
57
- * @category Graph
58
- */
59
- function behaviorRun(inputs, params, ctx) {
60
- if (!ctx.source) throw new Error(`behaviour node ${ctx.type} has no source module`);
61
- return { behavior: {
62
- kind: "behavior",
63
- type: ctx.type,
64
- node: ctx.nodeId,
65
- params: {
66
- ...inputs,
67
- ...params
68
- },
69
- source: ctx.source
70
- } };
71
- }
72
40
  /** A starting point for a new script node. @category Graph */
73
41
  const SCRIPT_NODE_TEMPLATE = `// A node is a function with a typed interface.
74
42
  // inputs: pins wired from other nodes (an unconnected one uses its widget value / default)
@@ -95,4 +63,4 @@ export function run({ a, b }, { scale }, ctx) {
95
63
  }
96
64
  `;
97
65
  //#endregion
98
- export { SCRIPT_NODE_TEMPLATE, behaviorRun, compileNodeScript };
66
+ export { SCRIPT_NODE_TEMPLATE, compileNodeScript };
@@ -1,6 +1,6 @@
1
1
  //#region src/graph/types.d.ts
2
2
  /**
3
- * Pin types. A type is a name (`number`, `vec2`, `entity`…) with a color for the editor;
3
+ * Pin types. A type is a name (`number`, `vec2`, your own…) with a color for the editor;
4
4
  * a trailing `[]` in a port declaration (`vec2[]`) makes the port a **list port** — it takes
5
5
  * or produces a whole list instead of one value at a time (see {@link GraphEvaluator}).
6
6
  *
@@ -48,7 +48,7 @@ export declare class TypeRegistry {
48
48
  all(): PortTypeDef[];
49
49
  }
50
50
  /**
51
- * The default pin types (colors match the apparatus palette).
51
+ * The default pin types. Add your own with `portTypes.define(name, color)`.
52
52
  *
53
53
  * @category Graph
54
54
  */
@@ -52,7 +52,7 @@ var TypeRegistry = class {
52
52
  }
53
53
  };
54
54
  /**
55
- * The default pin types (colors match the apparatus palette).
55
+ * The default pin types. Add your own with `portTypes.define(name, color)`.
56
56
  *
57
57
  * @category Graph
58
58
  */
package/dist/graph.cjs CHANGED
@@ -54,7 +54,7 @@ var TypeRegistry = class {
54
54
  }
55
55
  };
56
56
  /**
57
- * The default pin types (colors match the apparatus palette).
57
+ * The default pin types. Add your own with `portTypes.define(name, color)`.
58
58
  *
59
59
  * @category Graph
60
60
  */
@@ -1305,41 +1305,28 @@ function createNodeRegistry() {
1305
1305
  //#endregion
1306
1306
  //#region src/graph/script.ts
1307
1307
  /**
1308
- * Script nodes: a node type written as a plain ES module, compiled at runtime.
1309
- *
1310
- * ```js
1311
- * export const title = 'Ball'; // optional: title, category, description, output, animate
1312
- * export const inputs = { at: 'vec2', radius: { type: 'number', default: 8 } };
1313
- * export const params = { color: { type: 'color', default: '#e8554e' } };
1314
- * export const outputs = { entity: 'entity' };
1315
- * export function run({ at, radius }, { color }, ctx) {
1316
- * return { entity: { shape: 'ball', x: at.x, y: at.y, r: radius, color } };
1317
- * }
1318
- * ```
1319
- *
1320
- * The module is imported from a `data:` URL, which works in browsers, workers and Node.
1321
- * It runs with the page's (or worker's) privileges — treat shared scripts as untrusted and
1322
- * evaluate them in a worker.
1323
- *
1324
- * @module
1325
- */
1326
- /**
1327
1308
  * Compiles a script node's source into a node type named `type`.
1328
1309
  *
1329
1310
  * @category Graph
1330
1311
  */
1331
- async function compileNodeScript(type, source) {
1312
+ async function compileNodeScript(type, source, options = {}) {
1332
1313
  const mod = await import(
1333
1314
  /* @vite-ignore */
1334
1315
  `data:text/javascript;charset=utf-8,${encodeURIComponent(source)}`
1335
1316
  );
1336
1317
  const m = { ...mod.default && typeof mod.default === "object" && !mod.run ? mod.default : mod };
1337
- if (typeof m.run !== "function" && (typeof m.step === "function" || typeof m.setup === "function")) {
1338
- m.run = behaviorRun;
1339
- m.outputs ??= { behavior: "behavior" };
1340
- m.category ??= "behavior";
1318
+ if (typeof m.run !== "function") {
1319
+ const kind = options.kinds?.find((k) => k.hooks.some((h) => typeof m[h] === "function"));
1320
+ if (kind) {
1321
+ m.run = kind.run;
1322
+ m.outputs ??= kind.outputs;
1323
+ m.category ??= kind.category;
1324
+ }
1325
+ }
1326
+ if (typeof m.run !== "function") {
1327
+ const hooks = options.kinds?.flatMap((k) => k.hooks) ?? [];
1328
+ throw new Error(`script node "${type}": export a run(inputs, params, ctx) function${hooks.length ? ` (or ${hooks.join(" / ")})` : ""}`);
1341
1329
  }
1342
- if (typeof m.run !== "function") throw new Error(`script node "${type}": export a run(inputs, params, ctx) function (or step(self, world, dt, params) for a behaviour)`);
1343
1330
  return defineNode({
1344
1331
  type,
1345
1332
  title: m.title,
@@ -1354,25 +1341,6 @@ async function compileNodeScript(type, source) {
1354
1341
  source
1355
1342
  });
1356
1343
  }
1357
- /**
1358
- * The `run` of a behaviour node: packs its inputs, params and source into a {@link BehaviorValue}
1359
- * on the `behavior` output. Behaviour modules (exporting `step`, no `run`) get it automatically.
1360
- *
1361
- * @category Graph
1362
- */
1363
- function behaviorRun(inputs, params, ctx) {
1364
- if (!ctx.source) throw new Error(`behaviour node ${ctx.type} has no source module`);
1365
- return { behavior: {
1366
- kind: "behavior",
1367
- type: ctx.type,
1368
- node: ctx.nodeId,
1369
- params: {
1370
- ...inputs,
1371
- ...params
1372
- },
1373
- source: ctx.source
1374
- } };
1375
- }
1376
1344
  /** A starting point for a new script node. @category Graph */
1377
1345
  const SCRIPT_NODE_TEMPLATE = `// A node is a function with a typed interface.
1378
1346
  // inputs: pins wired from other nodes (an unconnected one uses its widget value / default)
@@ -1686,7 +1654,6 @@ exports.OUTPUT_LISTS = OUTPUT_LISTS;
1686
1654
  exports.SCRIPT_NODE_TEMPLATE = SCRIPT_NODE_TEMPLATE;
1687
1655
  exports.TypeRegistry = TypeRegistry;
1688
1656
  exports.addNode = addNode;
1689
- exports.behaviorRun = behaviorRun;
1690
1657
  exports.canConnect = canConnect;
1691
1658
  exports.collapseToSubgraph = collapseToSubgraph;
1692
1659
  exports.compileNodeScript = compileNodeScript;
package/dist/graph.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  //#region src/graph/types.d.ts
2
2
  /**
3
- * Pin types. A type is a name (`number`, `vec2`, `entity`…) with a color for the editor;
3
+ * Pin types. A type is a name (`number`, `vec2`, your own…) with a color for the editor;
4
4
  * a trailing `[]` in a port declaration (`vec2[]`) makes the port a **list port** — it takes
5
5
  * or produces a whole list instead of one value at a time (see {@link GraphEvaluator}).
6
6
  *
@@ -48,7 +48,7 @@ export declare class TypeRegistry {
48
48
  all(): PortTypeDef[];
49
49
  }
50
50
  /**
51
- * The default pin types (colors match the apparatus palette).
51
+ * The default pin types. Add your own with `portTypes.define(name, color)`.
52
52
  *
53
53
  * @category Graph
54
54
  */
@@ -69,11 +69,11 @@ export declare const portTypes: TypeRegistry;
69
69
  *
70
70
  * ```ts
71
71
  * defineNode({
72
- * type: 'shapes/ball',
73
- * inputs: { at: 'vec2', radius: { type: 'number', default: 8, min: 0.5 } },
74
- * params: { color: { type: 'color', default: '#e8554e' } },
75
- * outputs: { entity: 'entity' },
76
- * run: ({ at, radius }, { color }) => ({ entity: { shape: 'ball', x: at.x, y: at.y, r: radius, color } }),
72
+ * type: 'math/lerp',
73
+ * inputs: { a: 'number', b: { type: 'number', default: 1 } },
74
+ * params: { t: { type: 'number', default: 0.5, min: 0, max: 1, step: 0.05 } },
75
+ * outputs: { value: 'number' },
76
+ * run: ({ a, b }, { t }) => ({ value: a + (b - a) * t }),
77
77
  * });
78
78
  * ```
79
79
  *
@@ -108,7 +108,7 @@ export type ParamSpec = {
108
108
  export interface RunContext {
109
109
  /** the node instance's id */
110
110
  nodeId: string;
111
- /** the node's type, and its source module (if it has one) — behaviour nodes pass these on */
111
+ /** the node's type, and its source module (if it has one), for nodes whose output carries their own code */
112
112
  type: string;
113
113
  source?: string;
114
114
  /** while broadcasting over lists: this call's index (else 0) and the call count (else 1) */
@@ -471,12 +471,12 @@ export declare function createNodeRegistry(): NodeRegistry;
471
471
  * Script nodes: a node type written as a plain ES module, compiled at runtime.
472
472
  *
473
473
  * ```js
474
- * export const title = 'Ball'; // optional: title, category, description, output, animate
475
- * export const inputs = { at: 'vec2', radius: { type: 'number', default: 8 } };
476
- * export const params = { color: { type: 'color', default: '#e8554e' } };
477
- * export const outputs = { entity: 'entity' };
478
- * export function run({ at, radius }, { color }, ctx) {
479
- * return { entity: { shape: 'ball', x: at.x, y: at.y, r: radius, color } };
474
+ * export const title = 'Lerp'; // optional: title, category, description, output, animate
475
+ * export const inputs = { a: 'number', b: { type: 'number', default: 1 } };
476
+ * export const params = { t: { type: 'number', default: 0.5, min: 0, max: 1, step: 0.05 } };
477
+ * export const outputs = { value: 'number' };
478
+ * export function run({ a, b }, { t }, ctx) {
479
+ * return { value: a + (b - a) * t };
480
480
  * }
481
481
  * ```
482
482
  *
@@ -487,37 +487,44 @@ export declare function createNodeRegistry(): NodeRegistry;
487
487
  * @module
488
488
  */
489
489
  /**
490
- * Compiles a script node's source into a node type named `type`.
490
+ * Another shape of script module a host understands, besides `run` nodes: a module that exports
491
+ * no `run` but any of `hooks` is compiled into a node with this `run` (and these outputs and
492
+ * category, unless the module declares its own). What the hooks mean is up to the host — e.g. a
493
+ * per-frame `update` it calls later: `run` typically packs the node's params and `ctx.source`
494
+ * into a value the host picks up from the output.
491
495
  *
492
- * @category Graph
493
- */
494
- export declare function compileNodeScript(type: string, source: string): Promise<NodeDef>;
495
- /**
496
- * A behaviour: what a behaviour node evaluates to. The host runs `source`'s `step` (and
497
- * `setup`) against whatever it's attached to, with `params`.
496
+ * ```ts
497
+ * const agent: ModuleKind = {
498
+ * hooks: ['update'],
499
+ * outputs: { agent: 'agent' },
500
+ * run: (inputs, params, ctx) => ({ agent: { params: { ...inputs, ...params }, source: ctx.source } }),
501
+ * };
502
+ * const def = await compileNodeScript('agents/wander', source, { kinds: [agent] });
503
+ * ```
498
504
  *
499
505
  * @category Graph
500
506
  */
501
- export interface BehaviorValue {
502
- kind: 'behavior';
503
- /** the behaviour node's type */
504
- type: string;
505
- /** the node instance (for error reports) */
506
- node: string;
507
- /** its inputs and params at evaluation time */
508
- params: Record<string, unknown>;
509
- /** the module with step / setup */
510
- source: string;
507
+ export interface ModuleKind {
508
+ /** exporting any of these (and no `run`) makes a module this kind */
509
+ hooks: readonly string[];
510
+ /** the node's run */
511
+ run: NodeSpec['run'];
512
+ /** outputs, unless the module exports its own */
513
+ outputs?: NodeSpec['outputs'];
514
+ /** category, unless the module exports its own */
515
+ category?: string;
516
+ }
517
+ /** @category Graph */
518
+ export interface ScriptOptions {
519
+ /** the module kinds this host understands besides `run` nodes (first match wins) */
520
+ kinds?: readonly ModuleKind[];
511
521
  }
512
522
  /**
513
- * The `run` of a behaviour node: packs its inputs, params and source into a {@link BehaviorValue}
514
- * on the `behavior` output. Behaviour modules (exporting `step`, no `run`) get it automatically.
523
+ * Compiles a script node's source into a node type named `type`.
515
524
  *
516
525
  * @category Graph
517
526
  */
518
- export declare function behaviorRun(inputs: Record<string, unknown>, params: Record<string, unknown>, ctx: RunContext): {
519
- behavior: BehaviorValue;
520
- };
527
+ export declare function compileNodeScript(type: string, source: string, options?: ScriptOptions): Promise<NodeDef>;
521
528
  /** A starting point for a new script node. @category Graph */
522
529
  export declare const SCRIPT_NODE_TEMPLATE = "// A node is a function with a typed interface.\n// inputs: pins wired from other nodes (an unconnected one uses its widget value / default)\n// params: widgets on the node\n// outputs: what run() returns\n// A \"type[]\" pin takes (or gives) a whole list; a list wired into a plain pin runs\n// run() once per item and collects the results into lists.\n\nexport const inputs = {\n a: { type: 'number', default: 1 },\n b: { type: 'number', default: 2 },\n};\n\nexport const params = {\n scale: { type: 'number', default: 1, min: 0, max: 10, step: 0.1 },\n};\n\nexport const outputs = {\n result: 'number',\n};\n\nexport function run({ a, b }, { scale }, ctx) {\n return { result: (a + b) * scale };\n}\n";
523
530
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@n3rdw1z4rd/core",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "core library",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",