topotopo 0.4.0 → 0.5.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/NOTICE +10 -10
- package/README.md +460 -117
- package/dist/cli.js +323 -146
- package/dist/config.d.ts +48 -0
- package/dist/config.js +170 -0
- package/dist/core/bake.d.ts +14 -3
- package/dist/core/bake.js +153 -4
- package/dist/core/bevel.d.ts +3 -1
- package/dist/core/bevel.js +76 -3
- package/dist/core/decimate.d.ts +65 -0
- package/dist/core/decimate.js +409 -3
- package/dist/core/erosion.d.ts +37 -0
- package/dist/core/erosion.js +41 -1
- package/dist/core/geometry.d.ts +5 -1
- package/dist/core/geometry.js +203 -3
- package/dist/core/heightfield.d.ts +27 -4
- package/dist/core/heightfield.js +54 -16
- package/dist/core/intrinsics.d.ts +7 -0
- package/dist/core/intrinsics.js +94 -0
- package/dist/core/manifold.d.ts +12 -1
- package/dist/core/manifold.js +78 -6
- package/dist/core/materials.d.ts +7 -0
- package/dist/core/materials.js +45 -0
- package/dist/core/noise.d.ts +9 -0
- package/dist/core/noise.js +10 -1
- package/dist/core/polymerge.d.ts +21 -0
- package/dist/core/polymerge.js +327 -0
- package/dist/core/repair.d.ts +2 -0
- package/dist/core/repair.js +2 -0
- package/dist/core/report.d.ts +70 -0
- package/dist/core/report.js +275 -0
- package/dist/core/scene.js +2 -1
- package/dist/core/sha256.d.ts +4 -0
- package/dist/core/sha256.js +69 -0
- package/dist/core/shapes.d.ts +3 -0
- package/dist/core/shapes.js +34 -0
- package/dist/core/snippet-lib.d.ts +14 -1
- package/dist/core/snippet-lib.js +39 -13
- package/dist/core/tangents.d.ts +2 -0
- package/dist/core/tangents.js +5 -1
- package/dist/core/texnoise.d.ts +6 -1
- package/dist/core/texnoise.js +6 -2
- package/dist/core/texsdf.d.ts +131 -0
- package/dist/core/texsdf.js +637 -0
- package/dist/core/texture.d.ts +163 -9
- package/dist/core/texture.js +844 -20
- package/dist/core/topology.d.ts +10 -0
- package/dist/core/topology.js +168 -0
- package/dist/core/unwrap.d.ts +72 -0
- package/dist/core/unwrap.js +800 -0
- package/dist/core/usercode.d.ts +27 -0
- package/dist/core/usercode.js +87 -0
- package/dist/core/uv.d.ts +4 -18
- package/dist/core/uv.js +35 -188
- package/dist/core/uvislands.d.ts +62 -0
- package/dist/core/uvislands.js +574 -0
- package/dist/core/uvoverlap.d.ts +58 -0
- package/dist/core/uvoverlap.js +220 -0
- package/dist/core/uvpack.d.ts +64 -0
- package/dist/core/uvpack.js +628 -0
- package/dist/core/uvreport.d.ts +61 -0
- package/dist/core/uvreport.js +207 -143
- package/dist/core/wrangle.d.ts +6 -1
- package/dist/core/wrangle.js +27 -16
- package/dist/core/xatlas.d.ts +16 -1
- package/dist/core/xatlas.js +66 -62
- package/dist/engines.d.ts +63 -0
- package/dist/engines.js +180 -0
- package/dist/explain.d.ts +4 -3
- package/dist/explain.js +129 -12
- package/dist/graph/engine.d.ts +92 -29
- package/dist/graph/engine.js +298 -148
- package/dist/graph/expr.d.ts +6 -3
- package/dist/graph/expr.js +18 -8
- package/dist/graph/outputs.d.ts +23 -0
- package/dist/graph/outputs.js +41 -0
- package/dist/graph/packages.d.ts +72 -0
- package/dist/graph/packages.js +261 -0
- package/dist/graph/parallel.d.ts +3 -1
- package/dist/graph/parallel.js +4 -1
- package/dist/graph/params.d.ts +6 -0
- package/dist/graph/params.js +34 -7
- package/dist/graph/scope.d.ts +55 -0
- package/dist/graph/scope.js +14 -0
- package/dist/graph/types.d.ts +75 -12
- package/dist/graph/types.js +4 -2
- package/dist/graph/vars.d.ts +16 -0
- package/dist/graph/vars.js +80 -0
- package/dist/host/artifacts.d.ts +10 -1
- package/dist/host/artifacts.js +37 -6
- package/dist/host/cook.d.ts +241 -0
- package/dist/host/cook.js +844 -0
- package/dist/host/export-targets.d.ts +42 -5
- package/dist/host/export-targets.js +72 -13
- package/dist/host/godot-commands.d.ts +4 -0
- package/dist/host/godot-commands.js +21 -0
- package/dist/host/godot.d.ts +183 -0
- package/dist/host/godot.js +916 -0
- package/dist/host/node.d.ts +12 -7
- package/dist/host/node.js +27 -9
- package/dist/host/pool.js +51 -2
- package/dist/host/sidecars.d.ts +8 -0
- package/dist/host/sidecars.js +50 -0
- package/dist/host/types.d.ts +19 -6
- package/dist/host/version.d.ts +1 -0
- package/dist/host/version.js +3 -0
- package/dist/host/worker.js +5 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/inspect.d.ts +80 -2
- package/dist/inspect.js +265 -30
- package/dist/io/common.d.ts +25 -5
- package/dist/io/export.js +2 -1
- package/dist/io/files.d.ts +23 -4
- package/dist/io/files.js +60 -8
- package/dist/io/gltf.js +134 -47
- package/dist/io/heightmap.d.ts +3 -0
- package/dist/io/heightmap.js +1 -0
- package/dist/io/import.js +10 -0
- package/dist/io/inspect-scene.d.ts +55 -0
- package/dist/io/inspect-scene.js +155 -0
- package/dist/io/kinds.d.ts +81 -0
- package/dist/io/kinds.js +163 -0
- package/dist/io/points.d.ts +2 -1
- package/dist/io/points.js +3 -1
- package/dist/io/sidecars.d.ts +24 -0
- package/dist/io/sidecars.js +57 -0
- package/dist/io/source.d.ts +65 -0
- package/dist/io/source.js +112 -0
- package/dist/io/targets.d.ts +47 -3
- package/dist/io/targets.js +148 -13
- package/dist/io/textures.js +21 -1
- package/dist/io/unreal.js +5 -1
- package/dist/mcp/docs.d.ts +10 -1
- package/dist/mcp/docs.js +786 -143
- package/dist/mcp/inputs.d.ts +12 -5
- package/dist/mcp/inputs.js +50 -13
- package/dist/mcp/server.js +56 -27
- package/dist/mcp/tools.d.ts +14 -7
- package/dist/mcp/tools.js +196 -103
- package/dist/mcp/verify.d.ts +2 -2
- package/dist/mcp/verify.js +1 -1
- package/dist/mcp/workspace.d.ts +15 -0
- package/dist/mcp/workspace.js +349 -0
- package/dist/nodes/attributes.js +198 -1
- package/dist/nodes/bake.js +151 -47
- package/dist/nodes/beam.d.ts +1 -0
- package/dist/nodes/beam.js +201 -0
- package/dist/nodes/bevel.js +51 -3
- package/dist/nodes/cloth.js +2 -0
- package/dist/nodes/code.js +21 -9
- package/dist/nodes/curves.js +433 -93
- package/dist/nodes/flow.js +53 -33
- package/dist/nodes/generate.js +12 -38
- package/dist/nodes/heightfield.js +248 -77
- package/dist/nodes/imageops.js +16 -19
- package/dist/nodes/index.d.ts +1 -0
- package/dist/nodes/index.js +1 -0
- package/dist/nodes/material.js +89 -24
- package/dist/nodes/measure.js +43 -17
- package/dist/nodes/particles.js +2 -0
- package/dist/nodes/pcg.js +6 -5
- package/dist/nodes/procedural.js +4 -3
- package/dist/nodes/remesh.js +71 -15
- package/dist/nodes/scene.js +4 -2
- package/dist/nodes/sdf.js +10 -5
- package/dist/nodes/solid.js +20 -5
- package/dist/nodes/splines.d.ts +15 -1
- package/dist/nodes/splines.js +112 -105
- package/dist/nodes/texture.d.ts +21 -6
- package/dist/nodes/texture.js +1318 -185
- package/dist/nodes/topology.d.ts +7 -0
- package/dist/nodes/topology.js +133 -6
- package/dist/nodes/transform.js +6 -2
- package/dist/nodes/uv.js +192 -174
- package/dist/nodes/wasmcall.js +5 -1
- package/dist/open.d.ts +19 -0
- package/dist/open.js +12 -0
- package/dist/package.d.ts +288 -0
- package/dist/package.js +772 -0
- package/dist/packages/check.d.ts +32 -0
- package/dist/packages/check.js +169 -0
- package/dist/packages/commands.d.ts +57 -0
- package/dist/packages/commands.js +537 -0
- package/dist/packages/registry.d.ts +796 -0
- package/dist/packages/registry.js +2998 -0
- package/dist/packages/update.d.ts +124 -0
- package/dist/packages/update.js +476 -0
- package/dist/render/options.d.ts +2 -0
- package/dist/render/options.js +44 -5
- package/dist/render/preview.d.ts +15 -4
- package/dist/render/preview.js +6 -4
- package/dist/render/raster.d.ts +66 -5
- package/dist/render/raster.js +506 -138
- package/dist/render/texview.d.ts +6 -0
- package/dist/render/texview.js +27 -0
- package/dist/scan.d.ts +61 -0
- package/dist/scan.js +228 -0
- package/dist/session.d.ts +311 -0
- package/dist/session.js +849 -0
- package/dist/viewer/app/api.js +48 -6
- package/dist/viewer/app/cooking.js +78 -0
- package/dist/viewer/app/embed.js +27 -7
- package/dist/viewer/app/export-popover.js +118 -16
- package/dist/viewer/app/grid.js +5 -1
- package/dist/viewer/app/guides.js +122 -0
- package/dist/viewer/app/keymap.js +6 -3
- package/dist/viewer/app/layers.js +4 -4
- package/dist/viewer/app/main.js +185 -52
- package/dist/viewer/app/markers.js +60 -0
- package/dist/viewer/app/outliner.js +72 -27
- package/dist/viewer/app/output-info.js +45 -0
- package/dist/viewer/app/outputs.css +147 -8
- package/dist/viewer/app/outputs.js +168 -54
- package/dist/viewer/app/packages.js +614 -0
- package/dist/viewer/app/props.js +176 -52
- package/dist/viewer/app/scene.js +30 -5
- package/dist/viewer/app/select.js +4 -3
- package/dist/viewer/app/status.js +12 -15
- package/dist/viewer/app/style.css +65 -7
- package/dist/viewer/app/vars.js +47 -0
- package/dist/viewer/app/welcome.js +72 -0
- package/dist/viewer/graph-file.d.ts +62 -0
- package/dist/viewer/graph-file.js +175 -0
- package/dist/viewer/index.html +23 -10
- package/dist/viewer/json-edit.d.ts +13 -0
- package/dist/viewer/json-edit.js +274 -0
- package/dist/viewer/outputs.d.ts +49 -5
- package/dist/viewer/outputs.js +264 -56
- package/dist/viewer/packages.d.ts +121 -0
- package/dist/viewer/packages.js +584 -0
- package/dist/viewer/server.d.ts +14 -9
- package/dist/viewer/server.js +266 -28
- package/dist/web/app/web.css +419 -0
- package/dist/web/app/web.js +188 -0
- package/dist/{gallery → web}/bake.d.ts +4 -4
- package/dist/{gallery → web}/bake.js +24 -15
- package/dist/web/folder-page.d.ts +101 -0
- package/dist/web/folder-page.js +146 -0
- package/dist/web/folders.d.ts +280 -0
- package/dist/web/folders.js +970 -0
- package/dist/web/library.d.ts +91 -0
- package/dist/web/library.js +228 -0
- package/dist/web/markdown.d.ts +45 -0
- package/dist/web/markdown.js +677 -0
- package/dist/web/pages.d.ts +258 -0
- package/dist/web/pages.js +301 -0
- package/dist/web/server.d.ts +24 -0
- package/dist/web/server.js +1068 -0
- package/dist/workspace.d.ts +88 -118
- package/dist/workspace.js +358 -460
- package/integrations/godot/addons/topotopo/LICENSE +202 -0
- package/integrations/godot/addons/topotopo/README.md +57 -0
- package/integrations/godot/addons/topotopo/context_menu.gd +43 -0
- package/integrations/godot/addons/topotopo/dock.gd +266 -0
- package/integrations/godot/addons/topotopo/dock.tscn +72 -0
- package/integrations/godot/addons/topotopo/export_filter.gd +72 -0
- package/integrations/godot/addons/topotopo/gltf_instancing.gd +131 -0
- package/integrations/godot/addons/topotopo/icons/topotopo.svg +1 -0
- package/integrations/godot/addons/topotopo/inspector.gd +38 -0
- package/integrations/godot/addons/topotopo/instances_post_import.gd +111 -0
- package/integrations/godot/addons/topotopo/package.gd +23 -0
- package/integrations/godot/addons/topotopo/package_importer.gd +187 -0
- package/integrations/godot/addons/topotopo/plugin.cfg +7 -0
- package/integrations/godot/addons/topotopo/plugin.gd +970 -0
- package/integrations/godot/addons/topotopo/record.gd +435 -0
- package/integrations/godot/addons/topotopo/runner.gd +458 -0
- package/integrations/godot/addons/topotopo/tools/check.gd +42 -0
- package/integrations/godot/addons/topotopo/watcher.gd +199 -0
- package/kernels/pkg/README.md +2 -1
- package/kernels/pkg-simd/README.md +2 -1
- package/library/architecture/versions/1.0/architecture.topo +12 -0
- package/{shelf → library/architecture/versions/1.0/graphs}/arch.json +3 -3
- package/{shelf → library/architecture/versions/1.0/graphs}/beam_truss.json +6 -6
- package/{shelf → library/architecture/versions/1.0/graphs}/brick_wall.json +8 -8
- package/{shelf → library/architecture/versions/1.0/graphs}/door_frame.json +3 -3
- package/{shelf → library/architecture/versions/1.0/graphs}/hex_grid_floor.json +3 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/house.json +8 -8
- package/library/architecture/versions/1.0/graphs/lineup.json +42 -0
- package/{shelf → library/architecture/versions/1.0/graphs}/pillar.json +3 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/railing.json +5 -5
- package/{shelf → library/architecture/versions/1.0/graphs}/roof_gable.json +2 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/roof_hip.json +2 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/roof_skeleton.json +2 -1
- package/{shelf → library/architecture/versions/1.0/graphs}/scaffold.json +4 -4
- package/{shelf → library/architecture/versions/1.0/graphs}/spiral_stairs.json +3 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/stairs.json +6 -6
- package/{shelf → library/architecture/versions/1.0/graphs}/tile_floor.json +3 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/wall_segment.json +10 -10
- package/{shelf → library/architecture/versions/1.0/graphs}/window_frame.json +2 -2
- package/library/architecture/versions/1.0/version.json +1119 -0
- package/{shelf → library/nature/versions/1.0/graphs}/bush.json +2 -2
- package/{shelf → library/nature/versions/1.0/graphs}/cliff_block.json +4 -3
- package/{shelf → library/nature/versions/1.0/graphs}/forest_patch.json +5 -5
- package/{shelf → library/nature/versions/1.0/graphs}/grass_clumps.json +2 -2
- package/library/nature/versions/1.0/graphs/lineup.json +24 -0
- package/{shelf → library/nature/versions/1.0/graphs}/log.json +6 -6
- package/{shelf → library/nature/versions/1.0/graphs}/rock.json +5 -4
- package/{shelf → library/nature/versions/1.0/graphs}/scatter_rocks.json +5 -5
- package/{shelf → library/nature/versions/1.0/graphs}/tree_lowpoly.json +3 -2
- package/library/nature/versions/1.0/nature.topo +12 -0
- package/library/nature/versions/1.0/version.json +534 -0
- package/{shelf → library/props/versions/1.0/graphs}/barrel.json +5 -4
- package/{shelf → library/props/versions/1.0/graphs}/crate.json +3 -3
- package/library/props/versions/1.0/graphs/lineup.json +18 -0
- package/{shelf → library/props/versions/1.0/graphs}/pallet.json +4 -3
- package/{shelf → library/props/versions/1.0/graphs}/pipe_run.json +3 -3
- package/{shelf → library/props/versions/1.0/graphs}/sandbag_wall.json +5 -5
- package/library/props/versions/1.0/props.topo +12 -0
- package/library/props/versions/1.0/version.json +336 -0
- package/{shelf → library/street/versions/1.0/graphs}/bench.json +5 -5
- package/{shelf → library/street/versions/1.0/graphs}/bollard.json +2 -1
- package/{shelf → library/street/versions/1.0/graphs}/cable.json +4 -4
- package/{shelf → library/street/versions/1.0/graphs}/fence.json +7 -7
- package/{shelf → library/street/versions/1.0/graphs}/lamp_post.json +2 -2
- package/library/street/versions/1.0/graphs/lineup.json +22 -0
- package/{shelf → library/street/versions/1.0/graphs}/road_strip.json +2 -2
- package/{shelf → library/street/versions/1.0/graphs}/sign_post.json +1 -1
- package/library/street/versions/1.0/street.topo +12 -0
- package/library/street/versions/1.0/version.json +421 -0
- package/package.json +17 -8
- package/dist/gallery/app/gallery.css +0 -100
- package/dist/gallery/app/gallery.js +0 -80
- package/dist/gallery/cli.d.ts +0 -4
- package/dist/gallery/cli.js +0 -157
- package/dist/gallery/library.d.ts +0 -124
- package/dist/gallery/library.js +0 -366
- package/dist/gallery/pages.d.ts +0 -94
- package/dist/gallery/pages.js +0 -148
- package/dist/gallery/server.d.ts +0 -21
- package/dist/gallery/server.js +0 -391
- package/dist/graph/migrate.d.ts +0 -23
- package/dist/graph/migrate.js +0 -58
- package/dist/mcp/library.d.ts +0 -12
- package/dist/mcp/library.js +0 -159
- package/shelf/index.json +0 -190
package/dist/session.js
ADDED
|
@@ -0,0 +1,849 @@
|
|
|
1
|
+
// A session: a folder's named graphs (persisted as JSON files), saved assets, the human's input files, and the engine
|
|
2
|
+
// that cooks them. Shared by the MCP server, the live viewer and the CLI.
|
|
3
|
+
// <dir>/graphs/<name>.json graphs <dir>/assets/<name>.json saved assets
|
|
4
|
+
// <dir>/<name>.json in a package (a folder with an <id>.topo file), its graph files beside that file are
|
|
5
|
+
// graphs too (examples/ keeps its graphs there); graphs/ wins a name both have
|
|
6
|
+
// <dir>/inputs/… files people drop in (meshes, guide curves, PNG masks), read with file nodes; or a
|
|
7
|
+
// folder given to the constructor (`topotopo view`: inputs/ beside the graph file)
|
|
8
|
+
// <dir>/exports/… export output
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { Engine, wiringOf } from './graph/engine.js';
|
|
12
|
+
import { didYouMean, renameExprRefs } from './graph/params.js';
|
|
13
|
+
import { maybeSidecar, sidecarOf } from './io/sidecars.js';
|
|
14
|
+
import { fileFormat } from './host/sidecars.js';
|
|
15
|
+
import { godotIgnore, isEngineFile } from './engines.js';
|
|
16
|
+
import { targetRefusal } from './io/targets.js';
|
|
17
|
+
export const NAME_RE = /^[A-Za-z_][\w.-]*$/;
|
|
18
|
+
const GEOMETRY_EXTS = new Set(['obj', 'stl', 'ply', 'glb', 'gltf', 'geo', 'bgeo', 'blend', 'csv', 'json', 'points.json']);
|
|
19
|
+
const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'webp']);
|
|
20
|
+
/** Lower-case extension of a file name without the dot; ".points.json" is one extension, dot-files have none. */
|
|
21
|
+
export function inputExt(file) {
|
|
22
|
+
const b = file.toLowerCase().replace(/^.*[\\/]/, '');
|
|
23
|
+
if (b.endsWith('.points.json') && b.length > '.points.json'.length)
|
|
24
|
+
return 'points.json';
|
|
25
|
+
const i = b.lastIndexOf('.');
|
|
26
|
+
return i > 0 ? b.slice(i + 1) : '';
|
|
27
|
+
}
|
|
28
|
+
export function inputKind(ext) {
|
|
29
|
+
return GEOMETRY_EXTS.has(ext) ? 'geometry' : IMAGE_EXTS.has(ext) ? 'image' : 'other';
|
|
30
|
+
}
|
|
31
|
+
const now = () => performance.now();
|
|
32
|
+
const sameValue = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
33
|
+
/** A var's value in a graph: its "vars" entry, else the default its "params" entry declares. */
|
|
34
|
+
export function graphVarValue(g, k) {
|
|
35
|
+
return g.vars && Object.hasOwn(g.vars, k) ? g.vars[k] : g.params?.[k]?.default;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* What a session value of var `k` depends on in a graph: the declared type, range and options, and the kind of the
|
|
39
|
+
* graph's value (a number, a string, a 3-vector …). null when the graph has no such var (neither in vars nor params).
|
|
40
|
+
*/
|
|
41
|
+
export function varDeclaration(g, k) {
|
|
42
|
+
const vd = g.params?.[k];
|
|
43
|
+
if (!vd && !(g.vars && Object.hasOwn(g.vars, k)))
|
|
44
|
+
return null;
|
|
45
|
+
const v = graphVarValue(g, k);
|
|
46
|
+
const kind = Array.isArray(v) ? `array${v.length}` : v === null || v === undefined ? 'none' : typeof v;
|
|
47
|
+
return JSON.stringify([vd?.type ?? null, vd?.min ?? null, vd?.max ?? null, vd?.options ?? null, kind]);
|
|
48
|
+
}
|
|
49
|
+
/** Thrown by Session.edit when the edited graph does not validate; the stored graph is unchanged. */
|
|
50
|
+
export class EditRejected extends Error {
|
|
51
|
+
errors;
|
|
52
|
+
constructor(errors, notes = []) {
|
|
53
|
+
super(`✗ edits rejected (graph unchanged) — ${errors.length} error(s):\n` + errors.map((e) => ` [${e.node}] ${e.message}${e.hint ? `\n hint: ${e.hint}` : ''}`).join('\n') + notes.map((n) => `\nnote: ${n}`).join(''));
|
|
54
|
+
this.name = 'EditRejected';
|
|
55
|
+
this.errors = errors;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** The folders a package makes in its own folder (Session.load): graphs, assets, exports and inputs. */
|
|
59
|
+
export const PACKAGE_FOLDERS = ['graphs', 'assets', 'exports', 'inputs'];
|
|
60
|
+
/** The extension of a package's manifest: a package is a folder holding one <id>.topo file (src/package.ts). */
|
|
61
|
+
export const MANIFEST_EXT = '.topo';
|
|
62
|
+
/** The .topo files directly in a folder, by name, sorted: one makes it a package. */
|
|
63
|
+
export function topoFiles(dir) {
|
|
64
|
+
try {
|
|
65
|
+
return fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile() && e.name.endsWith(MANIFEST_EXT) && e.name.length > MANIFEST_EXT.length).map((e) => e.name).sort();
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return [];
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/** A graph file's text holds a graph: an object with "nodes" (other JSON files do not). */
|
|
72
|
+
const holdsGraph = (j) => !!j && typeof j === 'object' && !Array.isArray(j) && !!j.nodes && typeof j.nodes === 'object';
|
|
73
|
+
/**
|
|
74
|
+
* The graph files of a folder by graph name: graphs/<name>.json, and in a package (a folder holding a .topo file) the
|
|
75
|
+
* graph files beside that file, not below it, whose name graphs/ does not have. A file there is a graph when it
|
|
76
|
+
* holds an object with "nodes"; an unreadable one is left out. The web app, `topotopo edit` and the MCP server read a
|
|
77
|
+
* package's graphs here.
|
|
78
|
+
*/
|
|
79
|
+
export function graphFiles(dir) {
|
|
80
|
+
const out = new Map();
|
|
81
|
+
const json = (d) => { try {
|
|
82
|
+
return fs.readdirSync(d).filter((f) => f.endsWith('.json')).sort();
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return [];
|
|
86
|
+
} };
|
|
87
|
+
for (const f of json(path.join(dir, 'graphs'))) {
|
|
88
|
+
const name = f.slice(0, -'.json'.length);
|
|
89
|
+
if (NAME_RE.test(name))
|
|
90
|
+
out.set(name, path.join(dir, 'graphs', f));
|
|
91
|
+
}
|
|
92
|
+
if (!topoFiles(dir).length)
|
|
93
|
+
return out;
|
|
94
|
+
for (const f of json(dir)) {
|
|
95
|
+
const name = f.slice(0, -'.json'.length), file = path.join(dir, f);
|
|
96
|
+
if (out.has(name) || !NAME_RE.test(name))
|
|
97
|
+
continue;
|
|
98
|
+
try {
|
|
99
|
+
if (fs.statSync(file).isFile() && holdsGraph(JSON.parse(fs.readFileSync(file, 'utf8'))))
|
|
100
|
+
out.set(name, file);
|
|
101
|
+
}
|
|
102
|
+
catch { /* not a graph */ }
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
export class Session {
|
|
107
|
+
dir;
|
|
108
|
+
engine;
|
|
109
|
+
graphs = new Map();
|
|
110
|
+
versions = new Map();
|
|
111
|
+
lastReport = new Map();
|
|
112
|
+
/** how the last cook of each whole graph ended, stopped ones included (lastReport keeps the last one that ran through) */
|
|
113
|
+
lastCook = new Map();
|
|
114
|
+
listeners = new Set();
|
|
115
|
+
/** told when the cooks of a graph start, move to another node (with that node's event), are asked to stop and end (see activity) */
|
|
116
|
+
activityListeners = new Set();
|
|
117
|
+
/** the packages used by the package that holds the session's folder, when whoever opened it attached them (src/packages/registry.ts) */
|
|
118
|
+
packages = null;
|
|
119
|
+
/**
|
|
120
|
+
* Session values: var values a person set in the live viewer over a graph file (`topotopo view`). They shadow the
|
|
121
|
+
* graph's vars in this session's cooks without changing the graph, and stay when the graph is replaced (a reload
|
|
122
|
+
* of the file) unless the var's declaration changed (varDeclaration), the var is gone, or the graph now holds the
|
|
123
|
+
* same value itself. graph → var → value and the declaration it was set under.
|
|
124
|
+
*/
|
|
125
|
+
sessions = new Map();
|
|
126
|
+
running = new Map();
|
|
127
|
+
/** per graph: since when it has been cooking, through cooks that follow one another (a newer value's), and when it last fell idle */
|
|
128
|
+
busy = new Map();
|
|
129
|
+
holds = new Map();
|
|
130
|
+
/** per graph: the last whole-graph cook started, and the newest one whose outcome was recorded */
|
|
131
|
+
cookSeq = new Map();
|
|
132
|
+
recordedSeq = new Map();
|
|
133
|
+
lastYield = 0;
|
|
134
|
+
/** graphs kept in a package's own folder (graphFiles): their file, where they are saved; the others go in graphs/ */
|
|
135
|
+
besidePackage = new Map();
|
|
136
|
+
/** the inputs folder given to the constructor (SessionOptions.inputs), if any */
|
|
137
|
+
inputsAt;
|
|
138
|
+
exportsAt;
|
|
139
|
+
constructor(dir, engine, opts = {}) {
|
|
140
|
+
this.dir = path.resolve(dir);
|
|
141
|
+
this.engine = engine;
|
|
142
|
+
this.inputsAt = opts.inputs === undefined ? undefined : path.resolve(opts.inputs);
|
|
143
|
+
this.exportsAt = opts.exports === undefined ? undefined : path.resolve(opts.exports);
|
|
144
|
+
engine.root.graphs = (n) => this.graphs.get(n);
|
|
145
|
+
}
|
|
146
|
+
// the folders of PACKAGE_FOLDERS
|
|
147
|
+
get graphDir() { return path.join(this.dir, 'graphs'); }
|
|
148
|
+
get assetDir() { return path.join(this.dir, 'assets'); }
|
|
149
|
+
get exportDir() { return this.exportsAt ?? path.join(this.dir, 'exports'); }
|
|
150
|
+
/**
|
|
151
|
+
* files people drop in: meshes, guide curves and points, PNG masks and heightmaps (read as "inputs/<path>");
|
|
152
|
+
* <dir>/inputs unless the constructor was given another folder
|
|
153
|
+
*/
|
|
154
|
+
get inputDir() { return this.inputsAt ?? path.join(this.dir, 'inputs'); }
|
|
155
|
+
load() {
|
|
156
|
+
// the package's own inputs/ is made at once (people open it to drop files in); a folder given to the constructor
|
|
157
|
+
// is made by the first file written into it
|
|
158
|
+
for (const d of [this.dir, this.graphDir, this.assetDir, this.exportDir, ...(this.inputsAt ? [] : [this.inputDir])])
|
|
159
|
+
fs.mkdirSync(d, { recursive: true });
|
|
160
|
+
// Hide package working folders from Godot, including folders first created after addon setup.
|
|
161
|
+
godotIgnore(this.dir, this.inputsAt ? [] : ['inputs']);
|
|
162
|
+
// as a package version reads them (registerAssets): an asset that uses one registered later is tried again
|
|
163
|
+
const assetErrors = [], graphErrors = [];
|
|
164
|
+
registerAssets(this.engine, this.engine.root, this.dir, assetErrors);
|
|
165
|
+
for (const [name, file] of graphFiles(this.dir)) {
|
|
166
|
+
try {
|
|
167
|
+
this.graphs.set(name, JSON.parse(fs.readFileSync(file, 'utf8')));
|
|
168
|
+
}
|
|
169
|
+
catch (e) {
|
|
170
|
+
graphErrors.push(`${path.relative(this.dir, file).split(path.sep).join('/')}: ${e.message}`);
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (path.dirname(file) === this.dir)
|
|
174
|
+
this.besidePackage.set(name, file);
|
|
175
|
+
}
|
|
176
|
+
return { graphs: this.graphs.size, assets: this.engine.assetsIn().length, assetErrors, graphErrors };
|
|
177
|
+
}
|
|
178
|
+
/** Where a graph is saved: its file beside the package's manifest, or graphs/<name>.json. */
|
|
179
|
+
graphFile(name) {
|
|
180
|
+
return this.besidePackage.get(name) ?? path.join(this.graphDir, name + '.json');
|
|
181
|
+
}
|
|
182
|
+
persist(name) {
|
|
183
|
+
const g = this.graphs.get(name);
|
|
184
|
+
const file = this.graphFile(name);
|
|
185
|
+
if (!g) {
|
|
186
|
+
if (fs.existsSync(file))
|
|
187
|
+
fs.unlinkSync(file);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
fs.writeFileSync(file, JSON.stringify(g, null, 2));
|
|
191
|
+
}
|
|
192
|
+
bump(name) {
|
|
193
|
+
const v = (this.versions.get(name) ?? 0) + 1;
|
|
194
|
+
this.versions.set(name, v);
|
|
195
|
+
for (const l of this.listeners)
|
|
196
|
+
try {
|
|
197
|
+
l({ graph: name, version: v });
|
|
198
|
+
}
|
|
199
|
+
catch { /* ignore */ }
|
|
200
|
+
}
|
|
201
|
+
getGraph(name) {
|
|
202
|
+
const g = this.graphs.get(name);
|
|
203
|
+
if (!g) {
|
|
204
|
+
const s = didYouMean(name, [...this.graphs.keys()]);
|
|
205
|
+
throw new Error(`no graph "${name}"${s.length ? ` — did you mean ${s.join(', ')}?` : ''}. Graphs: ${[...this.graphs.keys()].join(', ') || '(none yet — use build)'}`);
|
|
206
|
+
}
|
|
207
|
+
return g;
|
|
208
|
+
}
|
|
209
|
+
setGraph(name, spec) {
|
|
210
|
+
if (!NAME_RE.test(name))
|
|
211
|
+
throw new Error(`graph name must match ${NAME_RE}`);
|
|
212
|
+
this.graphs.set(name, spec);
|
|
213
|
+
this.settleSession(name);
|
|
214
|
+
this.persist(name);
|
|
215
|
+
}
|
|
216
|
+
deleteGraph(name) {
|
|
217
|
+
this.getGraph(name);
|
|
218
|
+
this.graphs.delete(name);
|
|
219
|
+
this.sessions.delete(name);
|
|
220
|
+
this.persist(name);
|
|
221
|
+
}
|
|
222
|
+
// ------------------------------------------------------------ session values
|
|
223
|
+
/** The session values of a graph (the vars that differ from the graph's own), {} when there are none. */
|
|
224
|
+
sessionVars(name) {
|
|
225
|
+
return Object.fromEntries([...(this.sessions.get(name) ?? [])].map(([k, e]) => [k, e.value]));
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Set session values of a graph (null: back to the graph's value). They are not checked here: validate the graph
|
|
229
|
+
* with them first (Engine.validate on effectiveGraph). A value the graph holds itself is no session value.
|
|
230
|
+
*/
|
|
231
|
+
setSessionVars(name, vars) {
|
|
232
|
+
const g = this.getGraph(name);
|
|
233
|
+
let s = this.sessions.get(name);
|
|
234
|
+
if (!s)
|
|
235
|
+
this.sessions.set(name, s = new Map());
|
|
236
|
+
for (const [k, v] of Object.entries(vars)) {
|
|
237
|
+
if (v === null)
|
|
238
|
+
s.delete(k);
|
|
239
|
+
else
|
|
240
|
+
s.set(k, { value: structuredClone(v), decl: varDeclaration(g, k) });
|
|
241
|
+
}
|
|
242
|
+
this.settleSession(name);
|
|
243
|
+
}
|
|
244
|
+
/** The graph as its cooks see it: its vars with the session values over them. */
|
|
245
|
+
effectiveGraph(name) {
|
|
246
|
+
const g = this.getGraph(name), s = this.sessions.get(name);
|
|
247
|
+
return s?.size ? { ...g, vars: { ...(g.vars ?? {}), ...this.sessionVars(name) } } : g;
|
|
248
|
+
}
|
|
249
|
+
/** Keep the session values that still apply to the graph as it is now (see sessions). */
|
|
250
|
+
settleSession(name) {
|
|
251
|
+
const s = this.sessions.get(name);
|
|
252
|
+
if (!s)
|
|
253
|
+
return;
|
|
254
|
+
const g = this.graphs.get(name);
|
|
255
|
+
for (const [k, e] of s) {
|
|
256
|
+
const decl = g ? varDeclaration(g, k) : null;
|
|
257
|
+
if (!g || decl === null || decl !== e.decl || sameValue(graphVarValue(g, k), e.value))
|
|
258
|
+
s.delete(k);
|
|
259
|
+
}
|
|
260
|
+
if (!s.size)
|
|
261
|
+
this.sessions.delete(name);
|
|
262
|
+
}
|
|
263
|
+
// ------------------------------------------------------------ cooks in progress
|
|
264
|
+
/** What is cooking for a graph now, or null. */
|
|
265
|
+
activity(name) {
|
|
266
|
+
const runs = this.running.get(name);
|
|
267
|
+
if (!runs?.size)
|
|
268
|
+
return null;
|
|
269
|
+
const t = now();
|
|
270
|
+
let t0 = this.busy.get(name)?.since ?? Infinity, node = null, nodeT0 = Infinity, inner = null, stopping = true, superseded = false;
|
|
271
|
+
const kinds = new Set();
|
|
272
|
+
for (const r of runs) {
|
|
273
|
+
t0 = Math.min(t0, r.t0);
|
|
274
|
+
stopping &&= r.ac.signal.aborted && !r.superseded;
|
|
275
|
+
superseded ||= r.ac.signal.aborted && !!r.superseded;
|
|
276
|
+
kinds.add(r.kind);
|
|
277
|
+
for (const [n, since] of r.nodes)
|
|
278
|
+
if (since < nodeT0) {
|
|
279
|
+
nodeT0 = since;
|
|
280
|
+
node = n;
|
|
281
|
+
inner = r.inner.get(n) ?? null;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return { cooks: runs.size, kinds: [...kinds], elapsed: t - t0, node, nodeElapsed: node ? t - nodeT0 : 0, inner, stopping, superseded };
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Stop the cooks of a graph in progress (all, or those of the given kinds) at their next node boundary; returns how
|
|
288
|
+
* many were asked to. `superseded`: they stop for a newer value, and how they end is not the graph's last outcome.
|
|
289
|
+
*/
|
|
290
|
+
stop(name, kinds, opts = {}) {
|
|
291
|
+
let n = 0;
|
|
292
|
+
for (const r of this.running.get(name) ?? []) {
|
|
293
|
+
if (kinds && !kinds.includes(r.kind))
|
|
294
|
+
continue;
|
|
295
|
+
// a person's stop of a cook already stopping for a newer value: now it is theirs
|
|
296
|
+
if (r.ac.signal.aborted) {
|
|
297
|
+
if (r.superseded && !opts.superseded) {
|
|
298
|
+
r.superseded = false;
|
|
299
|
+
n++;
|
|
300
|
+
}
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
r.superseded = !!opts.superseded;
|
|
304
|
+
r.ac.abort();
|
|
305
|
+
n++;
|
|
306
|
+
}
|
|
307
|
+
if (n)
|
|
308
|
+
this.notifyActivity(name);
|
|
309
|
+
return n;
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Hold a graph as it is now (a person stopped its cooks): held() is true until the graph, its session values or the
|
|
313
|
+
* packages it can use change, and what cooks on its own (the viewer's previews) waits for that change instead of
|
|
314
|
+
* cooking it again.
|
|
315
|
+
*/
|
|
316
|
+
hold(name) {
|
|
317
|
+
if (this.graphs.has(name))
|
|
318
|
+
this.holds.set(name, this.holdKey(name));
|
|
319
|
+
}
|
|
320
|
+
held(name) {
|
|
321
|
+
const h = this.holds.get(name);
|
|
322
|
+
if (h === undefined)
|
|
323
|
+
return false;
|
|
324
|
+
if (this.graphs.has(name) && h === this.holdKey(name))
|
|
325
|
+
return true;
|
|
326
|
+
this.holds.delete(name);
|
|
327
|
+
return false;
|
|
328
|
+
}
|
|
329
|
+
holdKey(name) {
|
|
330
|
+
return JSON.stringify(this.effectiveGraph(name)) + (this.packages ? `|${this.packages.revision()}` : '');
|
|
331
|
+
}
|
|
332
|
+
notifyActivity(name, ev) {
|
|
333
|
+
for (const l of this.activityListeners)
|
|
334
|
+
try {
|
|
335
|
+
l(name, ev);
|
|
336
|
+
}
|
|
337
|
+
catch { /* ignore */ }
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* The progress hook of one cook: tracks its nodes, and lets the event loop turn (requests, a stop, the progress the
|
|
341
|
+
* listeners send) before each of the graph's nodes cooks, which may hold the thread for long, and at least every
|
|
342
|
+
* 15 ms between the nodes of nested cooks and the steps of long nodes.
|
|
343
|
+
*/
|
|
344
|
+
onNode(name, run, ev) {
|
|
345
|
+
if (ev.phase !== 'step') {
|
|
346
|
+
if (ev.depth === 0) {
|
|
347
|
+
if (ev.phase === 'start')
|
|
348
|
+
run.nodes.set(ev.node, now());
|
|
349
|
+
else {
|
|
350
|
+
run.nodes.delete(ev.node);
|
|
351
|
+
run.inner.delete(ev.node);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
else if (ev.phase === 'start' && ev.within.length)
|
|
355
|
+
run.inner.set(ev.within[0], ev.node);
|
|
356
|
+
this.notifyActivity(name, ev);
|
|
357
|
+
}
|
|
358
|
+
if (ev.phase === 'end' || (ev.depth > 0 || ev.phase === 'step') && now() - this.lastYield <= 15)
|
|
359
|
+
return;
|
|
360
|
+
this.lastYield = now();
|
|
361
|
+
return new Promise((resolve) => setImmediate(resolve));
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Every file under inputs/, recursively: posix paths relative to it, sorted. Dot-files and dot-folders are skipped, as
|
|
365
|
+
* are the files an engine writes beside ours (*.import, *.uid, *.translation, *.uasset).
|
|
366
|
+
* An export's sidecar (a heightmap's .json, <file>.source.json …) is kind "metadata", with the file it describes.
|
|
367
|
+
*/
|
|
368
|
+
listInputs() {
|
|
369
|
+
const out = [];
|
|
370
|
+
const walk = (dir, rel, depth) => {
|
|
371
|
+
let entries;
|
|
372
|
+
try {
|
|
373
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
374
|
+
}
|
|
375
|
+
catch {
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
for (const e of entries) {
|
|
379
|
+
if (e.name.startsWith('.') || (!e.isDirectory() && isEngineFile(e.name)))
|
|
380
|
+
continue;
|
|
381
|
+
const abs = path.join(dir, e.name), r = rel ? `${rel}/${e.name}` : e.name;
|
|
382
|
+
let st;
|
|
383
|
+
try {
|
|
384
|
+
st = fs.statSync(abs);
|
|
385
|
+
}
|
|
386
|
+
catch {
|
|
387
|
+
continue;
|
|
388
|
+
} // a broken link
|
|
389
|
+
if (st.isDirectory()) {
|
|
390
|
+
if (depth < 32)
|
|
391
|
+
walk(abs, r, depth + 1);
|
|
392
|
+
} // the depth cap stops link cycles
|
|
393
|
+
else if (st.isFile()) {
|
|
394
|
+
const ext = inputExt(e.name);
|
|
395
|
+
out.push({ path: r, kind: inputKind(ext), ext, size: st.size, mtime: Math.round(st.mtimeMs) });
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
walk(this.inputDir, '', 0);
|
|
400
|
+
// sidecars: the files and folders here are what they can describe
|
|
401
|
+
const there = new Set(out.flatMap((f) => f.path.split('/').map((_, i, s) => s.slice(0, i + 1).join('/'))));
|
|
402
|
+
for (const f of out) {
|
|
403
|
+
if (!maybeSidecar(f.path))
|
|
404
|
+
continue;
|
|
405
|
+
const s = sidecarOf(f.path, fileFormat(path.join(this.inputDir, ...f.path.split('/'))), (p) => there.has(p));
|
|
406
|
+
if (s) {
|
|
407
|
+
f.kind = 'metadata';
|
|
408
|
+
f.sidecar = s;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
412
|
+
}
|
|
413
|
+
/** Merge nodes/vars/output of `patch` into an existing graph (upsert). */
|
|
414
|
+
mergeGraph(name, patch) {
|
|
415
|
+
patch = patch;
|
|
416
|
+
const base = structuredClone(this.graphs.get(name) ?? { nodes: {} });
|
|
417
|
+
Object.assign(base.nodes, patch.nodes ?? {});
|
|
418
|
+
if (patch.vars)
|
|
419
|
+
base.vars = { ...(base.vars ?? {}), ...patch.vars };
|
|
420
|
+
if (patch.params)
|
|
421
|
+
base.params = { ...(base.params ?? {}), ...patch.params };
|
|
422
|
+
if (patch.output)
|
|
423
|
+
base.output = patch.output;
|
|
424
|
+
if (patch.outputs)
|
|
425
|
+
base.outputs = { ...base.outputs, ...patch.outputs };
|
|
426
|
+
if (patch.export !== undefined)
|
|
427
|
+
base.export = patch.export;
|
|
428
|
+
if (patch.description)
|
|
429
|
+
base.description = patch.description;
|
|
430
|
+
return base;
|
|
431
|
+
}
|
|
432
|
+
/** Apply edit operations; returns the new graph (not yet stored) and notes. */
|
|
433
|
+
applyEdits(name, ops) {
|
|
434
|
+
const g = structuredClone(this.getGraph(name));
|
|
435
|
+
const notes = [];
|
|
436
|
+
const need = (n, what) => {
|
|
437
|
+
if (!n)
|
|
438
|
+
throw new Error(`${what}: "node" is required`);
|
|
439
|
+
if (!g.nodes[n]) {
|
|
440
|
+
const s = didYouMean(n, Object.keys(g.nodes));
|
|
441
|
+
throw new Error(`${what}: no node "${n}"${s.length ? ` — did you mean ${s.join(', ')}?` : ''}`);
|
|
442
|
+
}
|
|
443
|
+
return n;
|
|
444
|
+
};
|
|
445
|
+
const refsTo = (target) => {
|
|
446
|
+
const out = [];
|
|
447
|
+
for (const [k, spec] of Object.entries(g.nodes)) {
|
|
448
|
+
if (Array.isArray(spec.in))
|
|
449
|
+
spec.in.forEach((r, i) => r === target && out.push({ node: k, idx: i }));
|
|
450
|
+
else if (typeof spec.in === 'string') {
|
|
451
|
+
if (spec.in === target)
|
|
452
|
+
out.push({ node: k, idx: 0 });
|
|
453
|
+
}
|
|
454
|
+
else if (spec.in && typeof spec.in === 'object')
|
|
455
|
+
for (const [ik, r] of Object.entries(spec.in))
|
|
456
|
+
if (r === target)
|
|
457
|
+
out.push({ node: k, idx: ik });
|
|
458
|
+
}
|
|
459
|
+
return out;
|
|
460
|
+
};
|
|
461
|
+
const setRef = (node, idx, value) => {
|
|
462
|
+
const spec = g.nodes[node];
|
|
463
|
+
if (typeof spec.in === 'string')
|
|
464
|
+
spec.in = [value];
|
|
465
|
+
else if (Array.isArray(spec.in))
|
|
466
|
+
spec.in[idx] = value;
|
|
467
|
+
else if (spec.in && typeof spec.in === 'object')
|
|
468
|
+
spec.in[idx] = value;
|
|
469
|
+
};
|
|
470
|
+
for (const [i, op] of ops.entries()) {
|
|
471
|
+
const where = `op ${i} (${op.op})`;
|
|
472
|
+
switch (op.op) {
|
|
473
|
+
case 'set': {
|
|
474
|
+
const n = need(op.node, where);
|
|
475
|
+
const spec = g.nodes[n];
|
|
476
|
+
spec.params = { ...(spec.params ?? {}) };
|
|
477
|
+
for (const [k, v] of Object.entries(op.params ?? {})) {
|
|
478
|
+
if (v === null)
|
|
479
|
+
delete spec.params[k];
|
|
480
|
+
else
|
|
481
|
+
spec.params[k] = v;
|
|
482
|
+
}
|
|
483
|
+
break;
|
|
484
|
+
}
|
|
485
|
+
case 'add': {
|
|
486
|
+
if (!op.node || !NAME_RE.test(op.node))
|
|
487
|
+
throw new Error(`${where}: "node" must be a valid new node name`);
|
|
488
|
+
if (g.nodes[op.node])
|
|
489
|
+
throw new Error(`${where}: node "${op.node}" already exists (use set/replace)`);
|
|
490
|
+
g.nodes[op.node] = op.spec ?? { type: op.type, ...(op.in !== undefined ? { in: op.in } : {}), ...(op.params ? { params: op.params } : {}) };
|
|
491
|
+
if (!g.nodes[op.node].type)
|
|
492
|
+
throw new Error(`${where}: "type" is required`);
|
|
493
|
+
break;
|
|
494
|
+
}
|
|
495
|
+
case 'replace': {
|
|
496
|
+
const n = need(op.node, where);
|
|
497
|
+
g.nodes[n] = op.spec ?? { ...g.nodes[n], ...(op.type ? { type: op.type } : {}), ...(op.params ? { params: op.params } : {}), ...(op.in !== undefined ? { in: op.in } : {}) };
|
|
498
|
+
break;
|
|
499
|
+
}
|
|
500
|
+
case 'remove': {
|
|
501
|
+
const n = need(op.node, where);
|
|
502
|
+
const refs = refsTo(n);
|
|
503
|
+
// reconnect consumers to this node's first input when possible
|
|
504
|
+
const def = this.engine.resolveDef(g.nodes[n].type);
|
|
505
|
+
const up = def ? wiringOf(g.nodes[n], def).list[0] ?? null : null;
|
|
506
|
+
for (const r of refs)
|
|
507
|
+
setRef(r.node, r.idx, up);
|
|
508
|
+
if (refs.length)
|
|
509
|
+
notes.push(`removed "${n}"; rewired ${refs.map((r) => r.node).join(', ')} to ${up ?? '(nothing)'}`);
|
|
510
|
+
delete g.nodes[n];
|
|
511
|
+
if (g.output === n)
|
|
512
|
+
delete g.output;
|
|
513
|
+
for (const [id, out] of Object.entries(g.outputs ?? {}))
|
|
514
|
+
if (out.node === n)
|
|
515
|
+
delete g.outputs[id];
|
|
516
|
+
break;
|
|
517
|
+
}
|
|
518
|
+
case 'connect': {
|
|
519
|
+
const n = need(op.node, where);
|
|
520
|
+
if (op.in !== undefined)
|
|
521
|
+
g.nodes[n].in = op.in;
|
|
522
|
+
else if (op.input !== undefined) {
|
|
523
|
+
const spec = g.nodes[n];
|
|
524
|
+
const def = this.engine.resolveDef(spec.type);
|
|
525
|
+
const list = def ? wiringOf(spec, def).list.slice() : [];
|
|
526
|
+
while (list.length <= op.input)
|
|
527
|
+
list.push(null);
|
|
528
|
+
list[op.input] = op.from ?? null;
|
|
529
|
+
spec.in = list;
|
|
530
|
+
}
|
|
531
|
+
else
|
|
532
|
+
throw new Error(`${where}: give "in" (full wiring) or "input" + "from"`);
|
|
533
|
+
break;
|
|
534
|
+
}
|
|
535
|
+
case 'rename': {
|
|
536
|
+
const n = need(op.node, where);
|
|
537
|
+
if (!op.to || !NAME_RE.test(op.to) || g.nodes[op.to])
|
|
538
|
+
throw new Error(`${where}: "to" must be a new valid name`);
|
|
539
|
+
g.nodes[op.to] = g.nodes[n];
|
|
540
|
+
delete g.nodes[n];
|
|
541
|
+
for (const r of refsTo(n))
|
|
542
|
+
setRef(r.node, r.idx, op.to);
|
|
543
|
+
if (g.output === n)
|
|
544
|
+
g.output = op.to;
|
|
545
|
+
for (const out of Object.values(g.outputs ?? {}))
|
|
546
|
+
if (out.node === n)
|
|
547
|
+
out.node = op.to;
|
|
548
|
+
// expression references: npoints("old"), ch("old/param") …
|
|
549
|
+
const touched = [];
|
|
550
|
+
for (const [k, spec] of Object.entries(g.nodes)) {
|
|
551
|
+
if (!spec.params)
|
|
552
|
+
continue;
|
|
553
|
+
const before = JSON.stringify(spec.params);
|
|
554
|
+
spec.params = Object.fromEntries(Object.entries(spec.params).map(([pk, pv]) => [pk, renameExprRefs(pv, n, op.to)]));
|
|
555
|
+
if (JSON.stringify(spec.params) !== before)
|
|
556
|
+
touched.push(k);
|
|
557
|
+
}
|
|
558
|
+
if (touched.length)
|
|
559
|
+
notes.push(`updated expression references to "${n}" in ${touched.join(', ')}`);
|
|
560
|
+
break;
|
|
561
|
+
}
|
|
562
|
+
case 'output':
|
|
563
|
+
g.output = need(op.node, where);
|
|
564
|
+
break;
|
|
565
|
+
case 'vars': {
|
|
566
|
+
g.vars = { ...(g.vars ?? {}) };
|
|
567
|
+
for (const [k, v] of Object.entries(op.vars ?? {})) {
|
|
568
|
+
if (v === null)
|
|
569
|
+
delete g.vars[k];
|
|
570
|
+
else
|
|
571
|
+
g.vars[k] = v;
|
|
572
|
+
}
|
|
573
|
+
break;
|
|
574
|
+
}
|
|
575
|
+
case 'bypass':
|
|
576
|
+
g.nodes[need(op.node, where)].bypass = op.value ?? true;
|
|
577
|
+
break;
|
|
578
|
+
case 'export': {
|
|
579
|
+
// the target of the default output, or of a named one; null removes it (validated with the graph)
|
|
580
|
+
if (op.export === undefined)
|
|
581
|
+
throw new Error(`${where}: give "export": a format ("glb"), {format, path?, ...options}, or null`);
|
|
582
|
+
// a new target never takes the prefix that is gone (one a graph holds already only warns when it cooks)
|
|
583
|
+
const refused = op.export === null ? null : targetRefusal(op.export);
|
|
584
|
+
if (refused)
|
|
585
|
+
throw new Error(`${where}: ${refused}`);
|
|
586
|
+
if (op.output === undefined) {
|
|
587
|
+
if (op.export === null)
|
|
588
|
+
delete g.export;
|
|
589
|
+
else
|
|
590
|
+
g.export = op.export;
|
|
591
|
+
break;
|
|
592
|
+
}
|
|
593
|
+
const out = g.outputs?.[op.output];
|
|
594
|
+
if (!out) {
|
|
595
|
+
const s = didYouMean(op.output, Object.keys(g.outputs ?? {}));
|
|
596
|
+
throw new Error(`${where}: no output "${op.output}"${s.length ? ` — did you mean ${s.join(', ')}?` : ''} (publish it in "outputs" first)`);
|
|
597
|
+
}
|
|
598
|
+
if (op.export === null)
|
|
599
|
+
delete out.export;
|
|
600
|
+
else
|
|
601
|
+
out.export = op.export;
|
|
602
|
+
break;
|
|
603
|
+
}
|
|
604
|
+
case 'insert': {
|
|
605
|
+
const after = need(op.after, `${where} after`);
|
|
606
|
+
if (!op.node || !NAME_RE.test(op.node) || g.nodes[op.node])
|
|
607
|
+
throw new Error(`${where}: "node" must be a new valid name`);
|
|
608
|
+
if (!op.type && !op.spec)
|
|
609
|
+
throw new Error(`${where}: "type" is required`);
|
|
610
|
+
const consumers = refsTo(after);
|
|
611
|
+
g.nodes[op.node] = op.spec ?? { type: op.type, in: [after], ...(op.params ? { params: op.params } : {}) };
|
|
612
|
+
for (const r of consumers)
|
|
613
|
+
setRef(r.node, r.idx, op.node);
|
|
614
|
+
if (g.output === after)
|
|
615
|
+
g.output = op.node;
|
|
616
|
+
notes.push(`inserted "${op.node}" after "${after}"${consumers.length ? `; now feeds ${consumers.map((c) => c.node).join(', ')}` : ''}`);
|
|
617
|
+
break;
|
|
618
|
+
}
|
|
619
|
+
default: throw new Error(`${where}: unknown op. Use set, add, remove, connect, rename, output, vars, bypass, replace, insert, export`);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
return { graph: g, notes };
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* The one path for an edit, whoever makes it (the MCP edit tool, the viewer's controls): apply the ops, validate as a
|
|
626
|
+
* dry run sees the graph (an invalid result throws EditRejected listing the per-node errors, and stores, adds and
|
|
627
|
+
* writes nothing), add the packages the graph now names to the package (first use), store, cook at `frame`, then
|
|
628
|
+
* notify the listeners. They hear after the cook so that what they read (lastReport, cached geometry) is the new
|
|
629
|
+
* version's; a cook that throws still notifies, since the graph was stored. A cook that was stopped (`signal`,
|
|
630
|
+
* Session.stop) does not: whoever stopped it cooks again or tells the listeners.
|
|
631
|
+
*/
|
|
632
|
+
async edit(name, ops, opts = {}) {
|
|
633
|
+
const { graph, notes } = this.applyEdits(name, ops);
|
|
634
|
+
const v = this.engine.validate(graph, '', this.dryScope(graph).scope);
|
|
635
|
+
if (v.errors.length)
|
|
636
|
+
throw new EditRejected(v.errors, notes);
|
|
637
|
+
notes.push(...(this.packages?.addFor(graph) ?? []));
|
|
638
|
+
this.setGraph(name, graph);
|
|
639
|
+
let report;
|
|
640
|
+
try {
|
|
641
|
+
report = await this.cook(name, undefined, opts.frame, { kind: opts.kind, signal: opts.signal });
|
|
642
|
+
}
|
|
643
|
+
finally {
|
|
644
|
+
if (!report?.stopped)
|
|
645
|
+
this.bump(name);
|
|
646
|
+
}
|
|
647
|
+
return { graph: this.getGraph(name), notes, report };
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* The scope a graph is checked in where nothing may be written (a dry run, a trial of a person's values): the
|
|
651
|
+
* engine's root, whose packages include those the graph names for the first time at the version build or edit would
|
|
652
|
+
* add (SessionPackages.dryRun), with notes that say so, under an id of its own. Nothing is copied or written.
|
|
653
|
+
*/
|
|
654
|
+
dryScope(graph) {
|
|
655
|
+
const root = this.engine.root, d = this.packages?.dryRun(graph);
|
|
656
|
+
if (!d || d.resolver === root.packages)
|
|
657
|
+
return { scope: root, notes: d?.notes ?? [] };
|
|
658
|
+
return { scope: { ...root, id: d.id, packages: d.resolver }, notes: d.notes };
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* Cook a graph (its output, or `target`) with its session values, as a cook of `kind`. Session.stop and `signal`
|
|
662
|
+
* stop it at a node boundary; activity() reports it while it runs. A cook of the whole graph records its outcome
|
|
663
|
+
* (lastCook) and, unless it was stopped, its report (lastReport), when no cook started after it has done so first.
|
|
664
|
+
* An export cooks with the published copies of the packages the session shows live, and records nothing.
|
|
665
|
+
*/
|
|
666
|
+
async cook(name, target, frame, opts = {}) {
|
|
667
|
+
const g = this.getGraph(name);
|
|
668
|
+
// a followed working folder edited since the last cook resolves to its new files
|
|
669
|
+
this.packages?.refresh();
|
|
670
|
+
const run = { kind: opts.kind ?? 'cook', ac: new AbortController(), t0: now(), nodes: new Map(), inner: new Map() };
|
|
671
|
+
const outer = opts.signal;
|
|
672
|
+
const signal = { get aborted() { return run.ac.signal.aborted || !!outer?.aborted; } };
|
|
673
|
+
const seq = target ? 0 : (this.cookSeq.get(name) ?? 0) + 1;
|
|
674
|
+
if (seq)
|
|
675
|
+
this.cookSeq.set(name, seq);
|
|
676
|
+
let runs = this.running.get(name);
|
|
677
|
+
if (!runs)
|
|
678
|
+
this.running.set(name, runs = new Set());
|
|
679
|
+
runs.add(run);
|
|
680
|
+
// the cook of a newer value that follows the one it stopped within 100 ms continues its busy time
|
|
681
|
+
const b = this.busy.get(name);
|
|
682
|
+
if (b && (b.idleAt === null || (run.t0 - b.idleAt <= 100 && run.kind === 'edit')))
|
|
683
|
+
b.idleAt = null;
|
|
684
|
+
else
|
|
685
|
+
this.busy.set(name, { since: run.t0, idleAt: null });
|
|
686
|
+
this.notifyActivity(name);
|
|
687
|
+
try {
|
|
688
|
+
const s = this.sessions.get(name);
|
|
689
|
+
// an export uses the published copies of the packages this session shows live (SessionPackages.published)
|
|
690
|
+
const scope = run.kind === 'export' ? this.packages?.published?.() ?? null : null;
|
|
691
|
+
const r = await this.engine.cook(g, { target, frame, signal, onNode: (ev) => this.onNode(name, run, ev), ...(s?.size ? { vars: this.sessionVars(name) } : {}), ...(scope ? { scope } : {}) });
|
|
692
|
+
if (seq && !scope && !(r.stopped && run.superseded) && seq > (this.recordedSeq.get(name) ?? 0)) {
|
|
693
|
+
this.recordedSeq.set(name, seq);
|
|
694
|
+
if (!r.stopped)
|
|
695
|
+
this.lastReport.set(name, r);
|
|
696
|
+
// a cook that found every result cached (a target set, a reload without change) keeps the outcome of the
|
|
697
|
+
// cook that made them: its time is what the graph takes
|
|
698
|
+
const fresh = [...r.results.values()].some((x) => !x.cached);
|
|
699
|
+
if (!r.ok || fresh || !this.lastCook.get(name)?.ok)
|
|
700
|
+
this.lastCook.set(name, { ok: r.ok, ms: r.ms, at: Date.now(), ...(r.stopped ? { stopped: r.stopped } : {}), ...(r.errors[0] ? { error: r.errors[0] } : {}) });
|
|
701
|
+
}
|
|
702
|
+
return r;
|
|
703
|
+
}
|
|
704
|
+
finally {
|
|
705
|
+
runs.delete(run);
|
|
706
|
+
if (!runs.size) {
|
|
707
|
+
this.running.delete(name);
|
|
708
|
+
this.busy.get(name).idleAt = now();
|
|
709
|
+
}
|
|
710
|
+
this.notifyActivity(name);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
watchers = [];
|
|
714
|
+
watchTimers = new Map();
|
|
715
|
+
/**
|
|
716
|
+
* Follow what other processes write into graphs/ and assets/, and in a package the graph files beside its manifest (a
|
|
717
|
+
* second Session on the same folder: the web app's editor next to an MCP server, or a person editing the JSON). A
|
|
718
|
+
* graph file whose content differs from the stored graph replaces it and notifies the listeners; a removed file
|
|
719
|
+
* removes the graph. Our own writes read back equal, so they change nothing. An asset whose content changed is
|
|
720
|
+
* registered again and every graph is notified (any may use it); a removed asset stays registered until the next
|
|
721
|
+
* load(). Two writers to one graph: the last write wins.
|
|
722
|
+
*/
|
|
723
|
+
watch() {
|
|
724
|
+
if (this.watchers.length)
|
|
725
|
+
return;
|
|
726
|
+
const on = (dir, apply) => {
|
|
727
|
+
try {
|
|
728
|
+
const w = fs.watch(dir, (_ev, f) => {
|
|
729
|
+
const rel = f ? String(f) : '';
|
|
730
|
+
// Windows names a removed folder by its absolute path: stop rather than follow a folder that is gone
|
|
731
|
+
if (path.isAbsolute(rel)) {
|
|
732
|
+
w.close();
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
if (!rel.endsWith('.json') || rel.includes(path.sep) || rel.startsWith('.'))
|
|
736
|
+
return;
|
|
737
|
+
const name = rel.slice(0, -'.json'.length), key = dir + '|' + name;
|
|
738
|
+
clearTimeout(this.watchTimers.get(key));
|
|
739
|
+
// persist() is not atomic: let the writer finish, and read again if the JSON is still half written
|
|
740
|
+
let tries = 0;
|
|
741
|
+
const run = () => {
|
|
742
|
+
this.watchTimers.delete(key);
|
|
743
|
+
try {
|
|
744
|
+
apply(name, path.join(dir, rel));
|
|
745
|
+
}
|
|
746
|
+
catch (e) {
|
|
747
|
+
if (e instanceof SyntaxError && ++tries < 5)
|
|
748
|
+
this.watchTimers.set(key, setTimeout(run, 100).unref());
|
|
749
|
+
}
|
|
750
|
+
};
|
|
751
|
+
this.watchTimers.set(key, setTimeout(run, 150).unref());
|
|
752
|
+
});
|
|
753
|
+
w.on('error', () => w.close());
|
|
754
|
+
w.unref();
|
|
755
|
+
this.watchers.push(w);
|
|
756
|
+
}
|
|
757
|
+
catch { /* no folder: nothing to follow */ }
|
|
758
|
+
};
|
|
759
|
+
const graphChanged = (name, file) => {
|
|
760
|
+
if (!NAME_RE.test(name) || this.graphFile(name) !== file)
|
|
761
|
+
return;
|
|
762
|
+
if (!fs.existsSync(file)) {
|
|
763
|
+
this.besidePackage.delete(name);
|
|
764
|
+
if (this.graphs.delete(name)) {
|
|
765
|
+
this.lastReport.delete(name);
|
|
766
|
+
this.bump(name);
|
|
767
|
+
}
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
const j = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
771
|
+
if (!holdsGraph(j))
|
|
772
|
+
return;
|
|
773
|
+
const spec = j;
|
|
774
|
+
const cur = this.graphs.get(name);
|
|
775
|
+
if (cur && JSON.stringify(cur) === JSON.stringify(spec))
|
|
776
|
+
return;
|
|
777
|
+
this.graphs.set(name, spec);
|
|
778
|
+
this.settleSession(name);
|
|
779
|
+
this.lastReport.delete(name);
|
|
780
|
+
this.bump(name);
|
|
781
|
+
};
|
|
782
|
+
on(this.graphDir, graphChanged);
|
|
783
|
+
// a package's graph files beside its manifest, when graphs/ has no graph of that name
|
|
784
|
+
if (topoFiles(this.dir).length)
|
|
785
|
+
on(this.dir, (name, file) => {
|
|
786
|
+
if (fs.existsSync(path.join(this.graphDir, name + '.json')))
|
|
787
|
+
return;
|
|
788
|
+
if (!this.graphs.has(name) && fs.existsSync(file))
|
|
789
|
+
this.besidePackage.set(name, file);
|
|
790
|
+
graphChanged(name, file);
|
|
791
|
+
});
|
|
792
|
+
on(this.assetDir, (name, file) => {
|
|
793
|
+
if (!fs.existsSync(file))
|
|
794
|
+
return;
|
|
795
|
+
const spec = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
796
|
+
const before = this.engine.asset(name)?.hash;
|
|
797
|
+
this.engine.registerAsset(name, spec);
|
|
798
|
+
if (this.engine.asset(name)?.hash === before)
|
|
799
|
+
return;
|
|
800
|
+
for (const g of this.graphs.keys()) {
|
|
801
|
+
this.lastReport.delete(g);
|
|
802
|
+
this.bump(g);
|
|
803
|
+
}
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
/** Stop following the folders (watch()). */
|
|
807
|
+
unwatch() {
|
|
808
|
+
for (const w of this.watchers)
|
|
809
|
+
w.close();
|
|
810
|
+
for (const t of this.watchTimers.values())
|
|
811
|
+
clearTimeout(t);
|
|
812
|
+
this.watchers = [];
|
|
813
|
+
this.watchTimers.clear();
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
/** Register a folder's assets/*.json into a scope; an asset that uses one registered later is tried again. */
|
|
817
|
+
export function registerAssets(engine, scope, dir, problems) {
|
|
818
|
+
let pending = [];
|
|
819
|
+
let files = [];
|
|
820
|
+
try {
|
|
821
|
+
files = fs.readdirSync(path.join(dir, 'assets')).filter((f) => f.endsWith('.json')).sort();
|
|
822
|
+
}
|
|
823
|
+
catch { /* no assets */ }
|
|
824
|
+
for (const f of files) {
|
|
825
|
+
try {
|
|
826
|
+
pending.push({ name: f.slice(0, -5), graph: JSON.parse(fs.readFileSync(path.join(dir, 'assets', f), 'utf8')) });
|
|
827
|
+
}
|
|
828
|
+
catch (e) {
|
|
829
|
+
problems.push(`assets/${f}: ${e.message}`);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
for (let pass = 0; pending.length; pass++) {
|
|
833
|
+
const failed = [];
|
|
834
|
+
for (const a of pending) {
|
|
835
|
+
try {
|
|
836
|
+
engine.registerAsset(a.name, a.graph, { scope });
|
|
837
|
+
}
|
|
838
|
+
catch (e) {
|
|
839
|
+
failed.push({ ...a, error: e.message });
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
if (failed.length === pending.length || pass > 8) {
|
|
843
|
+
for (const a of failed)
|
|
844
|
+
problems.push(`assets/${a.name}.json: ${a.error}`);
|
|
845
|
+
break;
|
|
846
|
+
}
|
|
847
|
+
pending = failed;
|
|
848
|
+
}
|
|
849
|
+
}
|