@n3rdw1z4rd/core 0.22.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 { BEHAVIOR_HOOKS, 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 { BEHAVIOR_HOOKS, 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 { BEHAVIOR_HOOKS, 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 { BEHAVIOR_HOOKS, 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,45 +20,44 @@ import { NodeDef, RunContext } from "./node.js";
20
20
  * @module
21
21
  */
22
22
  /**
23
- * The functions a behaviour module can export (any of them, and no `run`): what they mean is up to
24
- * the host. apparatus runs `setup` once, `step` every physics step, and `enter` / `exit` when a body
25
- * starts / stops touching (or overlapping) the one the behaviour is on.
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.
26
28
  *
27
- * @category Graph
28
- */
29
- export declare const BEHAVIOR_HOOKS: readonly ["setup", "step", "enter", "exit"];
30
- /**
31
- * Compiles a script node's source into a node type named `type`.
32
- *
33
- * @category Graph
34
- */
35
- export declare function compileNodeScript(type: string, source: string): Promise<NodeDef>;
36
- /**
37
- * A behaviour: what a behaviour node evaluates to. The host runs `source`'s hooks
38
- * ({@link BEHAVIOR_HOOKS}) 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
+ * ```
39
37
  *
40
38
  * @category Graph
41
39
  */
42
- export interface BehaviorValue {
43
- kind: 'behavior';
44
- /** the behaviour node's type */
45
- type: string;
46
- /** the node instance (for error reports) */
47
- node: string;
48
- /** its inputs and params at evaluation time */
49
- params: Record<string, unknown>;
50
- /** the module with its hooks (setup / step / enter / exit) */
51
- 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[];
52
54
  }
53
55
  /**
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 a hook, no `run`) get it automatically.
56
+ * Compiles a script node's source into a node type named `type`.
56
57
  *
57
58
  * @category Graph
58
59
  */
59
- export declare function behaviorRun(inputs: Record<string, unknown>, params: Record<string, unknown>, ctx: RunContext): {
60
- behavior: BehaviorValue;
61
- };
60
+ export declare function compileNodeScript(type: string, source: string, options?: ScriptOptions): Promise<NodeDef>;
62
61
  /** A starting point for a new script node. @category Graph */
63
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";
64
63
  //#endregion
@@ -1,54 +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
- * The functions a behaviour module can export (any of them, and no `run`): what they mean is up to
24
- * the host. apparatus runs `setup` once, `step` every physics step, and `enter` / `exit` when a body
25
- * starts / stops touching (or overlapping) the one the behaviour is on.
26
- *
27
- * @category Graph
28
- */
29
- const BEHAVIOR_HOOKS = [
30
- "setup",
31
- "step",
32
- "enter",
33
- "exit"
34
- ];
35
- /**
36
4
  * Compiles a script node's source into a node type named `type`.
37
5
  *
38
6
  * @category Graph
39
7
  */
40
- async function compileNodeScript(type, source) {
8
+ async function compileNodeScript(type, source, options = {}) {
41
9
  const mod = await import(
42
10
  /* @vite-ignore */
43
11
  `data:text/javascript;charset=utf-8,${encodeURIComponent(source)}`
44
12
  );
45
13
  const m = { ...mod.default && typeof mod.default === "object" && !mod.run ? mod.default : mod };
46
- if (typeof m.run !== "function" && BEHAVIOR_HOOKS.some((h) => typeof m[h] === "function")) {
47
- m.run = behaviorRun;
48
- m.outputs ??= { behavior: "behavior" };
49
- 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(" / ")})` : ""}`);
50
25
  }
51
- if (typeof m.run !== "function") throw new Error(`script node "${type}": export a run(inputs, params, ctx) function (or setup / step / enter / exit for a behaviour)`);
52
26
  return defineNode({
53
27
  type,
54
28
  title: m.title,
@@ -63,25 +37,6 @@ async function compileNodeScript(type, source) {
63
37
  source
64
38
  });
65
39
  }
66
- /**
67
- * The `run` of a behaviour node: packs its inputs, params and source into a {@link BehaviorValue}
68
- * on the `behavior` output. Behaviour modules (exporting a hook, no `run`) get it automatically.
69
- *
70
- * @category Graph
71
- */
72
- function behaviorRun(inputs, params, ctx) {
73
- if (!ctx.source) throw new Error(`behaviour node ${ctx.type} has no source module`);
74
- return { behavior: {
75
- kind: "behavior",
76
- type: ctx.type,
77
- node: ctx.nodeId,
78
- params: {
79
- ...inputs,
80
- ...params
81
- },
82
- source: ctx.source
83
- } };
84
- }
85
40
  /** A starting point for a new script node. @category Graph */
86
41
  const SCRIPT_NODE_TEMPLATE = `// A node is a function with a typed interface.
87
42
  // inputs: pins wired from other nodes (an unconnected one uses its widget value / default)
@@ -108,4 +63,4 @@ export function run({ a, b }, { scale }, ctx) {
108
63
  }
109
64
  `;
110
65
  //#endregion
111
- export { BEHAVIOR_HOOKS, 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,54 +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
- * The functions a behaviour module can export (any of them, and no `run`): what they mean is up to
1328
- * the host. apparatus runs `setup` once, `step` every physics step, and `enter` / `exit` when a body
1329
- * starts / stops touching (or overlapping) the one the behaviour is on.
1330
- *
1331
- * @category Graph
1332
- */
1333
- const BEHAVIOR_HOOKS = [
1334
- "setup",
1335
- "step",
1336
- "enter",
1337
- "exit"
1338
- ];
1339
- /**
1340
1308
  * Compiles a script node's source into a node type named `type`.
1341
1309
  *
1342
1310
  * @category Graph
1343
1311
  */
1344
- async function compileNodeScript(type, source) {
1312
+ async function compileNodeScript(type, source, options = {}) {
1345
1313
  const mod = await import(
1346
1314
  /* @vite-ignore */
1347
1315
  `data:text/javascript;charset=utf-8,${encodeURIComponent(source)}`
1348
1316
  );
1349
1317
  const m = { ...mod.default && typeof mod.default === "object" && !mod.run ? mod.default : mod };
1350
- if (typeof m.run !== "function" && BEHAVIOR_HOOKS.some((h) => typeof m[h] === "function")) {
1351
- m.run = behaviorRun;
1352
- m.outputs ??= { behavior: "behavior" };
1353
- 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(" / ")})` : ""}`);
1354
1329
  }
1355
- if (typeof m.run !== "function") throw new Error(`script node "${type}": export a run(inputs, params, ctx) function (or setup / step / enter / exit for a behaviour)`);
1356
1330
  return defineNode({
1357
1331
  type,
1358
1332
  title: m.title,
@@ -1367,25 +1341,6 @@ async function compileNodeScript(type, source) {
1367
1341
  source
1368
1342
  });
1369
1343
  }
1370
- /**
1371
- * The `run` of a behaviour node: packs its inputs, params and source into a {@link BehaviorValue}
1372
- * on the `behavior` output. Behaviour modules (exporting a hook, no `run`) get it automatically.
1373
- *
1374
- * @category Graph
1375
- */
1376
- function behaviorRun(inputs, params, ctx) {
1377
- if (!ctx.source) throw new Error(`behaviour node ${ctx.type} has no source module`);
1378
- return { behavior: {
1379
- kind: "behavior",
1380
- type: ctx.type,
1381
- node: ctx.nodeId,
1382
- params: {
1383
- ...inputs,
1384
- ...params
1385
- },
1386
- source: ctx.source
1387
- } };
1388
- }
1389
1344
  /** A starting point for a new script node. @category Graph */
1390
1345
  const SCRIPT_NODE_TEMPLATE = `// A node is a function with a typed interface.
1391
1346
  // inputs: pins wired from other nodes (an unconnected one uses its widget value / default)
@@ -1689,7 +1644,6 @@ function expandSubgraph(doc, nodeId, defs = doc.subgraphs) {
1689
1644
  return [...ids.values()];
1690
1645
  }
1691
1646
  //#endregion
1692
- exports.BEHAVIOR_HOOKS = BEHAVIOR_HOOKS;
1693
1647
  exports.BUILTIN_NODES = BUILTIN_NODES;
1694
1648
  exports.BUILTIN_SOURCES = BUILTIN_SOURCES;
1695
1649
  exports.GRAPH_FORMAT = GRAPH_FORMAT;
@@ -1700,7 +1654,6 @@ exports.OUTPUT_LISTS = OUTPUT_LISTS;
1700
1654
  exports.SCRIPT_NODE_TEMPLATE = SCRIPT_NODE_TEMPLATE;
1701
1655
  exports.TypeRegistry = TypeRegistry;
1702
1656
  exports.addNode = addNode;
1703
- exports.behaviorRun = behaviorRun;
1704
1657
  exports.canConnect = canConnect;
1705
1658
  exports.collapseToSubgraph = collapseToSubgraph;
1706
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,45 +487,44 @@ export declare function createNodeRegistry(): NodeRegistry;
487
487
  * @module
488
488
  */
489
489
  /**
490
- * The functions a behaviour module can export (any of them, and no `run`): what they mean is up to
491
- * the host. apparatus runs `setup` once, `step` every physics step, and `enter` / `exit` when a body
492
- * starts / stops touching (or overlapping) the one the behaviour is on.
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.
493
495
  *
494
- * @category Graph
495
- */
496
- export declare const BEHAVIOR_HOOKS: readonly ["setup", "step", "enter", "exit"];
497
- /**
498
- * Compiles a script node's source into a node type named `type`.
499
- *
500
- * @category Graph
501
- */
502
- export declare function compileNodeScript(type: string, source: string): Promise<NodeDef>;
503
- /**
504
- * A behaviour: what a behaviour node evaluates to. The host runs `source`'s hooks
505
- * ({@link BEHAVIOR_HOOKS}) 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
+ * ```
506
504
  *
507
505
  * @category Graph
508
506
  */
509
- export interface BehaviorValue {
510
- kind: 'behavior';
511
- /** the behaviour node's type */
512
- type: string;
513
- /** the node instance (for error reports) */
514
- node: string;
515
- /** its inputs and params at evaluation time */
516
- params: Record<string, unknown>;
517
- /** the module with its hooks (setup / step / enter / exit) */
518
- 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[];
519
521
  }
520
522
  /**
521
- * The `run` of a behaviour node: packs its inputs, params and source into a {@link BehaviorValue}
522
- * on the `behavior` output. Behaviour modules (exporting a hook, no `run`) get it automatically.
523
+ * Compiles a script node's source into a node type named `type`.
523
524
  *
524
525
  * @category Graph
525
526
  */
526
- export declare function behaviorRun(inputs: Record<string, unknown>, params: Record<string, unknown>, ctx: RunContext): {
527
- behavior: BehaviorValue;
528
- };
527
+ export declare function compileNodeScript(type: string, source: string, options?: ScriptOptions): Promise<NodeDef>;
529
528
  /** A starting point for a new script node. @category Graph */
530
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";
531
530
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@n3rdw1z4rd/core",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "description": "core library",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",