topotopo 0.5.0 → 0.5.2

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
@@ -237,7 +237,7 @@ works in that package's folder. The first reply the agent gets says which of the
237
237
  | `edit` | incremental ops: set, add, insert-after, remove (auto-rewire), connect, rename, replace, output, vars, bypass |
238
238
  | `inputs` | `list` the files in the package `inputs/` folder (kind, size, date, counts, bbox, object names; PNG size and bit depth) and `describe` one: polygons vs open polylines vs loose points vs packed prims, bbox, attributes, groups, every `name` / `role` value, materials |
239
239
  | `inspect` | one-screen summary (counts, triangles, bbox to the millimetre, parts, materials, images, uv state, open edges), `detail: "budget"` (triangles per part, per LOD and per node), `detail: "scene"` (the glb export read back: nodes, sockets, parents, meshes, materials, images), attribute stats, topology health (a closed solid or why not: open edges counted after welding uv/normal seam splits, non-manifold edges, flipped faces, inward pieces, degenerate faces, each with the part and world position of the first one and the fix; pieces, volume, genus, render/export triangle slivers), element listings, images (size and per-layer ranges), `detail: "uv"` (exact uv overlaps split into in-tile, tiling and across-LOD overlap with parts and positions, collapsed and out-of-tile triangles, charts, utilization, per-piece texel density; `json: true`) |
240
- | `render` | PNG with persp/front/right/top views (every 3D view fits the bounds; `zoom` is relative to that fit), three-quarter views (`front_left`, `back_right`, …), `size: "1600x600"` for wide views, `transparent` background, `grid: false`, a reference image behind the views (`underlay`, `underlay_opacity`, `underlay_fit`), scene empties as labelled dots (`sockets`), `turntable`, a `uv` view (`quad_uv`), uv checker, a `texture` view of images and `textures: true` for base colour maps on meshes, colour by attribute (+ `legend`), group highlight, flipped normals in blue; opt-in overlays: `section` view and `clip` plane with filled caps, edge overlays (`wireframe` all / hard / boundary / groups), `glyphs` (N, up, orient, v), group / piece / attribute labels and point / prim numbers, `shading` flat / matcap / ao, `shading: "pbr"` (the exported metallic-roughness material with its base colour, normal, orm and roughness maps under a fixed studio rig; deterministic, `exposure` in stops), `scale: 2`, `view_labels: false` (no view labels or axis gizmo, as in the built-in packages' thumbnails), `heightfield_res` (heightfield quads drawn per side, default 256, or `"full"`), `heightfield_layer` (the heightfield layer drawn in red, default the mask, or `"none"`); a footer line names what is shown (help topic `render`) |
240
+ | `render` | PNG with persp/front/right/top views (every 3D view fits the bounds; `zoom` is relative to that fit), three-quarter views (`front_left`, `back_right`, …), `size: "1600x600"` for wide views, `transparent` background, `grid: false`, a reference image behind the views (`underlay`, `underlay_opacity`, `underlay_fit`), scene empties as labelled dots (`sockets`), `turntable`, a `uv` view (`quad_uv`), uv checker, a `texture` view of images and `textures: true` for base colour maps on meshes, colour by attribute (+ `legend`), group highlight, flipped normals in blue; opt-in overlays: `section` view and `clip` plane with filled caps, edge overlays (`wireframe` all / hard / boundary / groups), `glyphs` (N, up, orient, v), group / piece / attribute labels and point / prim numbers, `shading` flat / matcap / ao, `shading: "pbr"` (the exported metallic-roughness material with its base colour, normal, orm and roughness maps under a fixed studio rig; deterministic, `exposure` in stops), `scale: 2`, `view_labels: false` (no view labels or axis gizmo, as in the built-in packages' thumbnails), `bounds` (world-space `[[x0, y0, z0], [x1, y1, z1]]` that every 3D view frames, so a timelapse or turntable shares one camera), `footer: false` (no footer strip), `heightfield_res` (heightfield quads drawn per side, default 256, or `"full"`), `heightfield_layer` (the heightfield layer drawn in red, default the mask, or `"none"`); a footer line names what is shown (help topic `render`) |
241
241
  | `export` | glb / gltf / obj / usda / ply / stl / json / geo / csv / points.json (packed instances: instance rows + meshes sidecar + one GLB per source); heightfields: png16 / r16 (+ JSON sidecar with the Unreal import numbers) / mask_png / unreal_landscape (a directory bundle); images: textures (one PNG per image; glb/gltf embed and usda writes the textures materials use); every export records its source (graph, vars, seeds, frame, version) to be made again |
242
242
  | `graphs` | list / get / delete / rename / duplicate package graphs (stored as JSON in the package's `graphs/`) |
243
243
  | `assets` | save a graph with vars as a reusable node type (like an HDA); list / get / delete; `fork` copies a package output's graph (TopoTopo's own included) into the package's assets to edit |
package/dist/cli.js CHANGED
@@ -92,7 +92,8 @@ const graphName = (file) => path.basename(file).replace(/\.json$/i, '').replace(
92
92
  const prog = import.meta.url.endsWith('.ts') ? 'node src/cli.ts' : 'topotopo';
93
93
  // the hints of every command name it so
94
94
  setProgram(prog);
95
- if (argv.includes('-v') || argv.includes('-V') || argv.includes('--version')) {
95
+ // the global version flag is the first argument (or the only one); later ones belong to the command (use <package> --version 1.0)
96
+ if (['-v', '-V', '--version'].includes(argv[0] ?? '')) {
96
97
  console.log(`topotopo ${TOPOTOPO_VERSION}`);
97
98
  process.exit(0);
98
99
  }
@@ -120,13 +121,14 @@ if (!argv.length || argv.includes('-h') || argv.includes('--help')) {
120
121
  ' framing: every 3D view fits the bounds; [--zoom 1] is relative to that fit (above 1 only with --look-at or --ortho-scale)',
121
122
  ' [--azimuth 35] (degrees around +Y: 0 = camera on +Z at the front, 90 = on +X, the right side) [--elevation 25] (degrees above the horizon)',
122
123
  ' [--look-at x,y,z] (world metres, Y up, +Z front) [--ortho-scale 0.5] (metres across an ortho view)',
124
+ ' [--bounds x0,y0,z0,x1,y1,z1] (world metres: every 3D view frames these corners instead of the own box of the geometry, so a sequence shares one camera)',
123
125
  ' [--transparent] (PNG with alpha) [--no-grid] [--sockets] (scene empties as labelled dots with orient axes)',
124
126
  ' [--underlay ref.png] (a reference PNG behind the 3D views) [--underlay-opacity 0.5] [--underlay-fit bounds|width|height|view]',
125
127
  ' [--textures] (base colour maps on meshes) [--texture name|image/layer|material] (adds the texture view)',
126
128
  ' [--max-triangles 600000] (packed instances drawn; above it an evenly spread subset)',
127
129
  ' [--heightfield-res 256|full] (heightfields: quads drawn per side, default 256, said in the footer when a field has more; full = every sample)',
128
130
  ' [--heightfield-layer flow] (heightfields: the layer drawn in red, default mask; none draws none)',
129
- ' [--no-view-labels] (no view name labels or axis gizmo, e.g. for thumbnails)',
131
+ ' [--no-view-labels] (no view name labels or axis gizmo, e.g. for thumbnails) [--no-footer] (no footer strip: the image is the tiles only)',
130
132
  ' several renders per cook: repeat --render; the options after a --render apply to that render (up to the next --render),',
131
133
  ' options before the first --render apply to every render. Example (both 1200x600):',
132
134
  ' --size 1200x600 --render side.png --views front --underlay ref.png --render beauty.png --views front_left --shading pbr',
@@ -391,16 +393,16 @@ async function cook() {
391
393
  }
392
394
  /** Every render flag (renderFlags reads them, plus --views, --color-by, --checker). */
393
395
  const RENDER_FLAGS = ['--wireframe', '--hard-angle', '--section', '--clip', '--glyphs', '--glyph-attrib', '--glyph-scale', '--max-glyphs', '--labels', '--max-labels',
394
- '--shading', '--ao-radius', '--size', '--render-scale', '--azimuth', '--elevation', '--zoom', '--look-at', '--ortho-scale', '--texture', '--max-triangles', '--exposure',
396
+ '--shading', '--ao-radius', '--size', '--render-scale', '--azimuth', '--elevation', '--zoom', '--look-at', '--bounds', '--ortho-scale', '--texture', '--max-triangles', '--exposure',
395
397
  '--heightfield-res', '--heightfield-layer', '--underlay', '--underlay-opacity', '--underlay-fit', '--legend', '--points', '--annotate', '--textures', '--transparent',
396
- '--sockets', '--no-view-labels', '--no-grid', '--views', '--color-by', '--checker'];
398
+ '--sockets', '--no-view-labels', '--no-footer', '--no-grid', '--views', '--color-by', '--checker'];
397
399
  /** Render overlay flags → render tool arguments → RenderOptions (src/render/options.ts). */
398
400
  function renderFlags(get, has) {
399
401
  const a = {};
400
402
  for (const [f, k] of [['--wireframe', 'wireframe'], ['--hard-angle', 'hard_angle'], ['--section', 'section'], ['--clip', 'clip'], ['--glyphs', 'glyphs'],
401
403
  ['--glyph-attrib', 'glyph_attrib'], ['--glyph-scale', 'glyph_scale'], ['--max-glyphs', 'max_glyphs'], ['--labels', 'labels'], ['--max-labels', 'max_labels'],
402
404
  ['--shading', 'shading'], ['--ao-radius', 'ao_radius'], ['--size', 'size'], ['--render-scale', 'scale'], ['--azimuth', 'azimuth'], ['--elevation', 'elevation'],
403
- ['--zoom', 'zoom'], ['--look-at', 'look_at'], ['--ortho-scale', 'ortho_scale'], ['--texture', 'texture'], ['--max-triangles', 'max_triangles'], ['--exposure', 'exposure'],
405
+ ['--zoom', 'zoom'], ['--look-at', 'look_at'], ['--bounds', 'bounds'], ['--ortho-scale', 'ortho_scale'], ['--texture', 'texture'], ['--max-triangles', 'max_triangles'], ['--exposure', 'exposure'],
404
406
  ['--heightfield-res', 'heightfield_res'], ['--heightfield-layer', 'heightfield_layer'], ['--underlay-opacity', 'underlay_opacity'], ['--underlay-fit', 'underlay_fit']])
405
407
  if (get(f) !== undefined)
406
408
  a[k] = get(f);
@@ -411,6 +413,8 @@ async function cook() {
411
413
  a.view_labels = false;
412
414
  if (has('--no-grid'))
413
415
  a.grid = false;
416
+ if (has('--no-footer'))
417
+ a.footer = false;
414
418
  // a reference image path is relative to the current folder, as the output paths are
415
419
  if (get('--underlay') !== undefined)
416
420
  a.underlay = path.resolve(get('--underlay'));
@@ -1,6 +1,14 @@
1
1
  import type { Geometry } from './geometry.ts';
2
- /** Load (once) and initialise the MikkTSpace WebAssembly module. */
2
+ /** loadMikkTSpace() starts a fresh MikkTSpace instance when the heap of the current one is larger than this. */
3
+ export declare const MIKK_RESET_BYTES: number;
4
+ /**
5
+ * Load and initialise the MikkTSpace WebAssembly module; when the loaded instance's heap has grown past
6
+ * MIKK_RESET_BYTES (or it aborted), replace it with a fresh one. Callers await this before each synchronous run of
7
+ * tangent work (an export, a render, a bake). While a replacement loads, mikkTSpaceReady() is false.
8
+ */
3
9
  export declare function loadMikkTSpace(): Promise<void>;
10
+ /** Bytes of WebAssembly memory the loaded MikkTSpace instance holds (0 when none is loaded). */
11
+ export declare const mikkTSpaceHeapBytes: () => number;
4
12
  /** True once loadMikkTSpace() has finished. */
5
13
  export declare const mikkTSpaceReady: () => boolean;
6
14
  export interface TangentDiagnostics {
@@ -6,25 +6,75 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
6
6
  }
7
7
  return path;
8
8
  };
9
+ /** loadMikkTSpace() starts a fresh MikkTSpace instance when the heap of the current one is larger than this. */
10
+ export const MIKK_RESET_BYTES = 256 * 2 ** 20;
9
11
  let mod = null;
10
12
  let loading = null;
11
- /** Load (once) and initialise the MikkTSpace WebAssembly module. */
13
+ let spent = false; // the instance aborted (out of memory): replace it on the next load
14
+ /**
15
+ * Load and initialise the MikkTSpace WebAssembly module; when the loaded instance's heap has grown past
16
+ * MIKK_RESET_BYTES (or it aborted), replace it with a fresh one. Callers await this before each synchronous run of
17
+ * tangent work (an export, a render, a bake). While a replacement loads, mikkTSpaceReady() is false.
18
+ */
12
19
  export async function loadMikkTSpace() {
13
- if (mod)
20
+ if (mod && !spent && mikkTSpaceHeapBytes() <= MIKK_RESET_BYTES)
14
21
  return;
15
22
  if (!loading) {
23
+ const old = mod;
24
+ mod = null;
16
25
  loading = (async () => {
17
- const spec = 'three/examples/jsm/libs/mikktspace.module.js';
18
- const m = await import(__rewriteRelativeImportExtension(spec));
19
- await m.ready;
20
- return m;
26
+ try {
27
+ let m;
28
+ if (old) {
29
+ m = old;
30
+ m.dispose();
31
+ }
32
+ else {
33
+ const spec = 'three/examples/jsm/libs/mikktspace.module.js';
34
+ m = await import(__rewriteRelativeImportExtension(spec));
35
+ }
36
+ await m.ready;
37
+ spent = false;
38
+ mod = m;
39
+ }
40
+ finally {
41
+ loading = null;
42
+ }
21
43
  })();
22
- loading.catch(() => { loading = null; });
23
44
  }
24
- mod = await loading;
45
+ await loading;
46
+ }
47
+ /** Bytes of WebAssembly memory the loaded MikkTSpace instance holds (0 when none is loaded). */
48
+ export const mikkTSpaceHeapBytes = () => mod?.wasm?.memory.buffer.byteLength ?? 0;
49
+ /** One generateTangents call on the raw exports: 4 floats (xyz, w) per corner. */
50
+ function generate(w, P, N, T) {
51
+ const pass = (a) => {
52
+ const p = w.__wbindgen_malloc(a.length * 4) >>> 0;
53
+ new Float32Array(w.memory.buffer, p, a.length).set(a);
54
+ return p;
55
+ };
56
+ const ret = w.__wbindgen_add_to_stack_pointer(-16) >>> 0;
57
+ try {
58
+ try {
59
+ w.generateTangents(ret, pass(P), P.length, pass(N), N.length, pass(T), T.length);
60
+ }
61
+ catch (e) {
62
+ if (!(e instanceof globalThis.WebAssembly.RuntimeError))
63
+ throw e; // a trap: in practice memory.grow failed at 4 GiB
64
+ spent = true;
65
+ throw new Error(`MikkTSpace ran out of WebAssembly memory (${w.memory.buffer.byteLength / 2 ** 20 | 0} MiB) on ${P.length / 9} triangles`);
66
+ }
67
+ const [ptr, len] = new Uint32Array(w.memory.buffer, ret, 2);
68
+ const out = new Float32Array(w.memory.buffer, ptr, len).slice();
69
+ w.__wbindgen_free(ptr, len * 4);
70
+ return out;
71
+ }
72
+ finally {
73
+ w.__wbindgen_add_to_stack_pointer(16);
74
+ }
25
75
  }
26
76
  /** True once loadMikkTSpace() has finished. */
27
- export const mikkTSpaceReady = () => mod !== null;
77
+ export const mikkTSpaceReady = () => mod?.wasm != null;
28
78
  /** uv triangles whose doubled area is below this fraction of their squared edge lengths are collapsed. */
29
79
  const UV_DEGENERATE = 1e-9;
30
80
  /**
@@ -33,7 +83,7 @@ const UV_DEGENERATE = 1e-9;
33
83
  * loaded.
34
84
  */
35
85
  export function mikkTangents(pos, nrm, uv) {
36
- if (!mod)
86
+ if (!mod?.wasm)
37
87
  throw new Error('MikkTSpace is not loaded: await loadMikkTSpace() first (exportGLB, renderPBR and bake_normal do)');
38
88
  const nt = Math.floor(pos.length / 9);
39
89
  const diag = { triangles: nt, uvNonFinite: 0, uvDegenerate: 0, fallbackCorners: 0, firstBad: -1 };
@@ -75,7 +125,7 @@ export function mikkTangents(pos, nrm, uv) {
75
125
  N[i + 2] = 1;
76
126
  }
77
127
  }
78
- const out = nt ? mod.generateTangents(P, N, T) : new Float32Array(0);
128
+ const out = nt ? generate(mod.wasm, P, N, T) : new Float32Array(0);
79
129
  for (let t = 0; t < nt; t++)
80
130
  for (let k = 0; k < 3; k++) {
81
131
  const c = t * 3 + k, o = c * 4, n = c * 3;
@@ -111,8 +111,15 @@ export interface FrameRange {
111
111
  end: number;
112
112
  step?: number;
113
113
  }
114
+ /**
115
+ * Approximate memory of a geometry for the cache budget: topology, attributes, groups and volume buffers. With `seen`,
116
+ * a buffer already in the set is not counted again (shared between geometries); the buffers counted are added to it.
117
+ */
118
+ export declare function geoBytes(g: Geometry, seen?: Set<ArrayBuffer>): number;
114
119
  declare class GeoCache {
115
120
  private map;
121
+ /** volume buffer → entries holding it: a shared buffer is charged once */
122
+ private owners;
116
123
  private bytes;
117
124
  maxBytes: number;
118
125
  constructor(maxBytes?: number);
@@ -49,7 +49,19 @@ import { VAR_NAME_HINT, varNameError } from './vars.js';
49
49
  import { codeVarNames, pickVars } from '../core/usercode.js';
50
50
  export { STOPPED };
51
51
  // ---------------------------------------------------------------- cache
52
- function geoBytes(g) {
52
+ /** The large typed-array buffers the volumes of a geometry hold (image and heightfield layers, SDF grid samples), each once. */
53
+ function volumeBuffers(g) {
54
+ const out = new Set();
55
+ for (const v of g.volumes) {
56
+ if (v.kind === 'grid')
57
+ out.add(v.values.buffer);
58
+ else if (v.kind === 'image' || v.kind === 'heightfield')
59
+ for (const l of v.layers.values())
60
+ out.add(l.buffer);
61
+ }
62
+ return [...out];
63
+ }
64
+ function baseBytes(g) {
53
65
  let b = g.primStart.byteLength + g.vertexPoint.byteLength + g.primClosed.byteLength + 256;
54
66
  // packed: the per-prim arrays (sources are shared with the nodes that made them)
55
67
  if (g.primKind)
@@ -63,8 +75,26 @@ function geoBytes(g) {
63
75
  b += m.byteLength;
64
76
  return b;
65
77
  }
78
+ /**
79
+ * Approximate memory of a geometry for the cache budget: topology, attributes, groups and volume buffers. With `seen`,
80
+ * a buffer already in the set is not counted again (shared between geometries); the buffers counted are added to it.
81
+ */
82
+ export function geoBytes(g, seen) {
83
+ let b = baseBytes(g);
84
+ for (const buf of volumeBuffers(g)) {
85
+ if (seen) {
86
+ if (seen.has(buf))
87
+ continue;
88
+ seen.add(buf);
89
+ }
90
+ b += buf.byteLength;
91
+ }
92
+ return b;
93
+ }
66
94
  class GeoCache {
67
95
  map = new Map();
96
+ /** volume buffer → entries holding it: a shared buffer is charged once */
97
+ owners = new Map();
68
98
  bytes = 0;
69
99
  maxBytes;
70
100
  constructor(maxBytes = 1.5e9) { this.maxBytes = maxBytes; }
@@ -79,19 +109,37 @@ class GeoCache {
79
109
  set(k, geo) {
80
110
  if (this.map.has(k))
81
111
  return;
82
- const bytes = geoBytes(geo);
83
- if (bytes > this.maxBytes / 2)
112
+ const own = baseBytes(geo), bufs = volumeBuffers(geo);
113
+ let add = own;
114
+ for (const buf of bufs)
115
+ if (!this.owners.has(buf))
116
+ add += buf.byteLength;
117
+ if (add > this.maxBytes / 2)
84
118
  return;
85
- this.map.set(k, { geo, bytes });
86
- this.bytes += bytes;
119
+ for (const buf of bufs) {
120
+ if (!this.owners.has(buf))
121
+ this.bytes += buf.byteLength;
122
+ this.owners.set(buf, (this.owners.get(buf) ?? 0) + 1);
123
+ }
124
+ this.map.set(k, { geo, bytes: own });
125
+ this.bytes += own;
87
126
  for (const [key, e] of this.map) {
88
127
  if (this.bytes <= this.maxBytes)
89
128
  break;
90
129
  this.map.delete(key);
91
130
  this.bytes -= e.bytes;
131
+ for (const buf of volumeBuffers(e.geo)) {
132
+ const n = (this.owners.get(buf) ?? 1) - 1;
133
+ if (n > 0)
134
+ this.owners.set(buf, n);
135
+ else {
136
+ this.owners.delete(buf);
137
+ this.bytes -= buf.byteLength;
138
+ }
139
+ }
92
140
  }
93
141
  }
94
- clear() { this.map.clear(); this.bytes = 0; }
142
+ clear() { this.map.clear(); this.owners.clear(); this.bytes = 0; }
95
143
  get stats() { return { entries: this.map.size, mb: +(this.bytes / 1e6).toFixed(1) }; }
96
144
  }
97
145
  // ---------------------------------------------------------------- helpers
package/dist/mcp/tools.js CHANGED
@@ -155,6 +155,8 @@ const RENDER_PROPS = {
155
155
  exposure: { type: 'number', description: 'shading "pbr": exposure in stops (default 0)' },
156
156
  ao_radius: { type: 'number', description: 'shading "ao": sample radius in pixels (default 10)' },
157
157
  look_at: { type: 'array', items: { type: 'number' }, description: 'look-at point [x, y, z] in world metres (x right, y up, z towards the front; default the bbox centre): the view centres on it and still fits the bounds; with zoom > 1 it zooms into that point' },
158
+ bounds: { type: 'array', items: { type: 'array', items: { type: 'number' } }, description: 'world-space [[x0, y0, z0], [x1, y1, z1]] (min then max, metres, Y up): every 3D view frames these bounds instead of the box of the geometry, so renders of different geometries share one camera (timelapse frames, turntable azimuths)' },
159
+ footer: { type: 'boolean', description: 'false leaves out the footer strip (the image is exactly the tiles; annotate is then ignored); default true' },
158
160
  ortho_scale: { type: 'number', description: 'ortho and section views: the world width in metres across a view (default: fit the bounds), e.g. 0.5 shows 50 cm across' },
159
161
  scale: { type: 'number', description: '2 (up to 4) for a 2× image: tiles, text, lines and markers scaled' },
160
162
  annotate: { type: 'boolean', description: 'second footer line naming the active overlays plus geometry notes (pieces, open edges, back-facing %); default on whenever an overlay option is used' },
@@ -1,6 +1,6 @@
1
1
  import { Image, MAIN_LAYER } from '../core/image.js';
2
2
  import { averagedVertexNormals, bakeSamples, curvatureEdges, dilate, edgeGrid, idColor, interpolate, interpolateCorners, normalize3, resolve, uvIslands, vertexPositions, vertexValues, } from '../core/bake.js';
3
- import { cornerTangents, loadMikkTSpace, mikkTSpaceReady, shadingFrame } from '../core/tangents.js';
3
+ import { MIKK_RESET_BYTES, cornerTangents, loadMikkTSpace, mikkTSpaceHeapBytes, mikkTSpaceReady, shadingFrame } from '../core/tangents.js';
4
4
  import { RayScene, bboxDiagonal } from '../core/analysis.js';
5
5
  import { pointNormals, resolveVertexNormals, triangulate } from '../core/topology.js';
6
6
  import { defineNode } from '../graph/registry.js';
@@ -568,7 +568,7 @@ defineBake({
568
568
  return finish(b, out, 4, [0.5, 0.5, 1, 1]);
569
569
  });
570
570
  };
571
- return mikkTSpaceReady() ? bakeWith() : loadMikkTSpace().then(bakeWith);
571
+ return mikkTSpaceReady() && mikkTSpaceHeapBytes() <= MIKK_RESET_BYTES ? bakeWith() : loadMikkTSpace().then(bakeWith);
572
572
  },
573
573
  });
574
574
  defineBake({
@@ -63,7 +63,7 @@ export function renderArgs(a) {
63
63
  o.points = pts === 'auto' ? 'auto' : bool(pts);
64
64
  for (const [s, c] of [['point_numbers', 'pointNumbers'], ['prim_numbers', 'primNumbers'], ['label_groups', 'labelGroups'], ['label_pieces', 'labelPieces'],
65
65
  ['legend', 'legend'], ['checker', 'checker'], ['grid', 'grid'], ['annotate', 'annotate'], ['section_absolute', 'sectionAbsolute'], ['textures', 'textures'], ['view_labels', 'viewLabels'],
66
- ['transparent', 'transparent'], ['sockets', 'sockets']]) {
66
+ ['transparent', 'transparent'], ['sockets', 'sockets'], ['footer', 'footer']]) {
67
67
  const v = pick(s, c);
68
68
  if (v !== undefined)
69
69
  o[c] = bool(v);
@@ -134,6 +134,19 @@ export function renderArgs(a) {
134
134
  throw new Error(`render: look_at expects [x, y, z], got ${JSON.stringify(look)}`);
135
135
  o.target = [+v[0], +v[1], +v[2]];
136
136
  }
137
+ // bounds: [[x0, y0, z0], [x1, y1, z1]] (or "x0,y0,z0,x1,y1,z1") in world metres, min then max
138
+ const bd = pick('bounds');
139
+ if (bd !== undefined) {
140
+ const v = typeof bd === 'string' ? bd.split(',').map((x) => (x.trim() === '' ? NaN : Number(x))) : bd;
141
+ const flat = Array.isArray(v) && v.length === 6 && !v.some(Array.isArray) ? v : Array.isArray(v) && v.length === 2 && v.every((t) => Array.isArray(t) && t.length === 3) ? [...v[0], ...v[1]] : null;
142
+ const msg = `render: bounds expects [[x0, y0, z0], [x1, y1, z1]] (world metres, min then max, each min <= max), got ${JSON.stringify(bd)}`;
143
+ if (!flat || !flat.every((x) => typeof x === 'number' && Number.isFinite(x)))
144
+ throw new Error(msg);
145
+ for (let k = 0; k < 3; k++)
146
+ if (flat[k] > flat[k + 3])
147
+ throw new Error(msg);
148
+ o.bounds = [[flat[0], flat[1], flat[2]], [flat[3], flat[4], flat[5]]];
149
+ }
137
150
  // shorthand labels: "groups,pieces,points,prims,attrib:name"
138
151
  if (typeof a.labels === 'string') {
139
152
  for (const t of a.labels.split(/[\s,]+/).filter(Boolean)) {
@@ -4,6 +4,8 @@ import type { ExportOptions } from '../io/common.ts';
4
4
  /** Render options of a thumbnail: one persp view, `size` px (256), matcap, no view label, plus the graph's meta.thumbnail_render. */
5
5
  export declare function thumbOptions(g: GraphSpec, size?: number): {
6
6
  views?: import("./raster.ts").ViewName[];
7
+ bounds?: [import("../core/math.ts").Vec3, import("../core/math.ts").Vec3];
8
+ footer?: boolean;
7
9
  size?: number | [number, number];
8
10
  transparent?: boolean;
9
11
  underlay?: string | null;
@@ -35,6 +35,14 @@ export interface ClipOptions {
35
35
  }
36
36
  export interface RenderOptions {
37
37
  views?: ViewName[];
38
+ /**
39
+ * world-space min and max corners (metres, Y up) every view frames instead of the geometry's own bounding box, so
40
+ * renders of different geometries (the frames of a timelapse, the azimuths of a turntable) share one camera. An empty
41
+ * geometry renders the empty frame at that camera. Default: the geometry's bounding box
42
+ */
43
+ bounds?: [Vec3, Vec3];
44
+ /** false: no footer strip (the output is exactly the tiles; annotate is then ignored). Default true */
45
+ footer?: boolean;
38
46
  /** pixels per view: n (square) or [width, height]; the views fit the bounds to that aspect (default 800 single, 512 several) */
39
47
  size?: number | [number, number];
40
48
  /** background pixels (no surface, line or point) get alpha 0; the ground grid is off; the footer stays opaque */
@@ -26,6 +26,7 @@ import { withSdfGridPreview } from '../core/sdfgrid.js';
26
26
  import { drawTextureView, textureSampler, withMaterialPreview } from './texview.js';
27
27
  import { EMPTY_ATTRIB } from '../core/scene.js';
28
28
  import { pbrScene, preparePBR } from './pbr.js';
29
+ import { loadMikkTSpace } from '../core/tangents.js';
29
30
  import { decodePNG } from '../io/png-decode.js';
30
31
  /**
31
32
  * Named three-quarter views: persp views at these azimuths (degrees; 0 = the camera on +Z looking at the front, 90 =
@@ -106,9 +107,20 @@ const SECTION_CAM = [ORTHO.right, ORTHO.top, ORTHO.front];
106
107
  /**
107
108
  * The points a view fits: the geometry's points (evenly subsampled above 200,000), or the bbox corners when there are
108
109
  * none (volumes only). Fitting the points rather than the bbox keeps rotated content (a square turned 20°) as large as
109
- * it can be; nothing outside the bbox exists, so the fit never crops.
110
+ * it can be; nothing outside the bbox exists, so the fit never crops. With fixed (RenderOptions.bounds) it is the 8
111
+ * corners of the given bounds.
110
112
  */
111
- function fitPoints(g, bmin, bmax) {
113
+ function fitPoints(g, bmin, bmax, fixed = false) {
114
+ if (fixed) {
115
+ // explicit bounds: the view frames their 8 corners, whatever the geometry holds
116
+ const out = new Float64Array(24);
117
+ for (let k = 0; k < 8; k++) {
118
+ out[k * 3] = k & 1 ? bmax[0] : bmin[0];
119
+ out[k * 3 + 1] = k & 2 ? bmax[1] : bmin[1];
120
+ out[k * 3 + 2] = k & 4 ? bmax[2] : bmin[2];
121
+ }
122
+ return out;
123
+ }
112
124
  const np = g.numPoints, n = Math.min(np, 200_000);
113
125
  // volumes drawn in 3D (SDFs as their bounds) count with their bbox corners
114
126
  const corners = !np || g.volumes.some((v) => v.kind !== 'image') ? 8 : 0;
@@ -200,6 +212,9 @@ export async function renderGeometryAsync(g, o = {}, readFile) {
200
212
  o = { ...o, pbrTextures: await preparePBR(g, readFile) };
201
213
  if (o.underlay && !o.underlayImage)
202
214
  o = { ...o, underlayImage: await readUnderlay(o.underlay, readFile) };
215
+ // last, so no other task replaces the MikkTSpace instance between this and the synchronous render
216
+ if (o.shading === 'pbr')
217
+ await loadMikkTSpace();
203
218
  return renderGeometry(g, o);
204
219
  }
205
220
  /** A reference image for the underlay option: a PNG read through readFile (errors say what to pass instead). */
@@ -322,7 +337,8 @@ export function renderGeometry(g, o = {}) {
322
337
  // a heightfield drawn at fewer samples than it has: said on the second footer line (unless annotate is false)
323
338
  const hfLine = hfShown.map((x) => `HEIGHTFIELD ${hfShown.length > 1 ? x.v.name.toUpperCase() + ' ' : ''}SHOWN AT ${x.shown[0]}×${x.shown[1]} OF ${x.v.width}×${x.v.height}`).join(' · ');
324
339
  const hfFooter = !!hfLine && o.annotate !== false;
325
- const footerH = 22 * ui + (annotate || hfFooter ? 16 * ui : 0);
340
+ const showFooter = o.footer !== false;
341
+ const footerH = showFooter ? 22 * ui + (annotate || hfFooter ? 16 * ui : 0) : 0;
326
342
  const viewLabels = o.viewLabels ?? true;
327
343
  const outW = cols * TW + (cols - 1) * 2, outH = rows * TH + (rows - 1) * 2 + footerH;
328
344
  const notes = hfShown.map((x) => `heightfield "${x.v.name}" shown at ${x.shown[0]}×${x.shown[1]} of ${x.v.width}×${x.v.height} samples (1 in ${x.step} per side); heightfield_res "full" (CLI --heightfield-res full) draws every sample`);
@@ -334,8 +350,9 @@ export function renderGeometry(g, o = {}) {
334
350
  // --- scene data shared by all views
335
351
  const Pd = g.P, np = g.numPoints;
336
352
  const bb = g.bbox(true);
337
- const bmin = bb.min, bmax = bb.max;
338
- const fitPts = fitPoints(g, bmin, bmax);
353
+ const fixedBounds = !!o.bounds;
354
+ const bmin = o.bounds ? [...o.bounds[0]] : bb.min, bmax = o.bounds ? [...o.bounds[1]] : bb.max;
355
+ const fitPts = fitPoints(g, bmin, bmax, fixedBounds);
339
356
  const { tris, triPrim } = triangulate(g);
340
357
  const nTri = tris.length / 3;
341
358
  if (nTri > 4e6)
@@ -1768,11 +1785,13 @@ export function renderGeometry(g, o = {}) {
1768
1785
  });
1769
1786
  // footer
1770
1787
  const fy = outH - footerH + 4 * ui;
1771
- const ext = [bmax[0] - bmin[0], bmax[1] - bmin[1], bmax[2] - bmin[2]];
1788
+ // the geometry's own box (not o.bounds, which only frames the views)
1789
+ const ext = [bb.max[0] - bb.min[0], bb.max[1] - bb.min[1], bb.max[2] - bb.min[2]];
1772
1790
  // EDGES AUTO early on the line, so a long title cannot push it off the image
1773
- const stats = `${np} PTS ${g.numPrims} PRIMS${autoEdgesShown ? ' EDGES AUTO' : ''} BBOX ${fmtNum(ext[0])}×${fmtNum(ext[1])}×${fmtNum(ext[2])} CENTER ${fmtNum((bmin[0] + bmax[0]) / 2)},${fmtNum((bmin[1] + bmax[1]) / 2)},${fmtNum((bmin[2] + bmax[2]) / 2)}`;
1774
- drawText(out, outW, outH, 6 * ui, fy, (o.title ? o.title.toUpperCase() + ' ' : '') + stats, [0.85, 0.85, 0.85], 2 * ui, false);
1775
- if (legend) {
1791
+ const stats = `${np} PTS ${g.numPrims} PRIMS${autoEdgesShown ? ' EDGES AUTO' : ''} BBOX ${fmtNum(ext[0])}×${fmtNum(ext[1])}×${fmtNum(ext[2])} CENTER ${fmtNum((bb.min[0] + bb.max[0]) / 2)},${fmtNum((bb.min[1] + bb.max[1]) / 2)},${fmtNum((bb.min[2] + bb.max[2]) / 2)}`;
1792
+ if (showFooter)
1793
+ drawText(out, outW, outH, 6 * ui, fy, (o.title ? o.title.toUpperCase() + ' ' : '') + stats, [0.85, 0.85, 0.85], 2 * ui, false);
1794
+ if (legend && showFooter) {
1776
1795
  const lx = outW - textWidth(legend, 2 * ui) - 8 * ui;
1777
1796
  // drawn when it fits; the note below reports it either way (once)
1778
1797
  if (lx > textWidth(stats, 2 * ui) + 30 * ui)
@@ -1821,7 +1840,8 @@ export function renderGeometry(g, o = {}) {
1821
1840
  fs2 = ui;
1822
1841
  while (txt.length > 4 && textWidth(txt, fs2) > maxW)
1823
1842
  txt = txt.slice(0, -4) + '..';
1824
- drawText(out, outW, outH, 6 * ui, fy + 18 * ui + (fs2 < 2 * ui ? 3 * ui : 0), txt, [0.62, 0.84, 1], fs2, false);
1843
+ if (showFooter)
1844
+ drawText(out, outW, outH, 6 * ui, fy + 18 * ui + (fs2 < 2 * ui ? 3 * ui : 0), txt, [0.62, 0.84, 1], fs2, false);
1825
1845
  if (annotate)
1826
1846
  notes.push('overlays: ' + overlays.toLowerCase());
1827
1847
  }
package/dist/session.d.ts CHANGED
@@ -293,15 +293,19 @@ export declare class Session {
293
293
  kind?: CookKind;
294
294
  signal?: StopSignal;
295
295
  }): Promise<CookReport>;
296
+ /** the folder each watcher follows; a folder that is missing has none until it is made again */
296
297
  private watchers;
297
298
  private watchTimers;
299
+ private watching;
298
300
  /**
299
301
  * Follow what other processes write into graphs/ and assets/, and in a package the graph files beside its manifest (a
300
302
  * second Session on the same folder: the web app's editor next to an MCP server, or a person editing the JSON). A
301
303
  * graph file whose content differs from the stored graph replaces it and notifies the listeners; a removed file
302
304
  * removes the graph. Our own writes read back equal, so they change nothing. An asset whose content changed is
303
305
  * registered again and every graph is notified (any may use it); a removed asset stays registered until the next
304
- * load(). Two writers to one graph: the last write wins.
306
+ * load(). Two writers to one graph: the last write wins. graphs/ and assets/ may be removed and made again (a git
307
+ * checkout, stash or branch switch): the package folder is followed too, and a folder made again is followed again
308
+ * and read again whole, as if each of its files had changed.
305
309
  */
306
310
  watch(): void;
307
311
  /** Stop following the folders (watch()). */
package/dist/session.js CHANGED
@@ -710,51 +710,93 @@ export class Session {
710
710
  this.notifyActivity(name);
711
711
  }
712
712
  }
713
- watchers = [];
713
+ /** the folder each watcher follows; a folder that is missing has none until it is made again */
714
+ watchers = new Map();
714
715
  watchTimers = new Map();
716
+ watching = false;
715
717
  /**
716
718
  * Follow what other processes write into graphs/ and assets/, and in a package the graph files beside its manifest (a
717
719
  * second Session on the same folder: the web app's editor next to an MCP server, or a person editing the JSON). A
718
720
  * graph file whose content differs from the stored graph replaces it and notifies the listeners; a removed file
719
721
  * removes the graph. Our own writes read back equal, so they change nothing. An asset whose content changed is
720
722
  * 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.
723
+ * load(). Two writers to one graph: the last write wins. graphs/ and assets/ may be removed and made again (a git
724
+ * checkout, stash or branch switch): the package folder is followed too, and a folder made again is followed again
725
+ * and read again whole, as if each of its files had changed.
722
726
  */
723
727
  watch() {
724
- if (this.watchers.length)
728
+ if (this.watching)
725
729
  return;
726
- const on = (dir, apply) => {
730
+ this.watching = true;
731
+ const later = (key, ms, fn) => {
732
+ clearTimeout(this.watchTimers.get(key));
733
+ this.watchTimers.set(key, setTimeout(() => { this.watchTimers.delete(key); if (this.watching)
734
+ fn(); }, ms).unref());
735
+ };
736
+ // persist() is not atomic: let the writer finish, and read again if the JSON is still half written
737
+ const settle = (dir, name, apply) => {
738
+ let tries = 0;
739
+ const run = () => {
740
+ try {
741
+ apply(name, path.join(dir, name + '.json'));
742
+ }
743
+ catch (e) {
744
+ if (e instanceof SyntaxError && ++tries < 5)
745
+ later(dir + '|' + name, 100, run);
746
+ }
747
+ };
748
+ later(dir + '|' + name, 150, run);
749
+ };
750
+ const attach = (dir, onFile, onGone, onEntry) => {
751
+ const old = this.watchers.get(dir);
752
+ this.watchers.delete(dir);
753
+ old?.close();
754
+ let w;
727
755
  try {
728
- const w = fs.watch(dir, (_ev, f) => {
756
+ w = fs.watch(dir, (ev, f) => {
729
757
  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();
758
+ // the folder itself was removed: Windows names it by its absolute path, Linux by its own name
759
+ if (path.isAbsolute(rel) || (rel === path.basename(dir) && !fs.existsSync(dir))) {
760
+ gone();
733
761
  return;
734
762
  }
763
+ if (ev === 'rename' && onEntry)
764
+ onEntry(rel);
735
765
  if (!rel.endsWith('.json') || rel.includes(path.sep) || rel.startsWith('.'))
736
766
  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());
767
+ onFile(rel.slice(0, -'.json'.length));
752
768
  });
753
- w.on('error', () => w.close());
754
- w.unref();
755
- this.watchers.push(w);
756
769
  }
757
- catch { /* no folder: nothing to follow */ }
770
+ catch {
771
+ return; /* no folder: the package folder's watcher hears when it is made */
772
+ }
773
+ // a removed folder: close at once (Windows keeps a watched folder from going while its handle is open)
774
+ const gone = () => {
775
+ if (this.watchers.get(dir) !== w)
776
+ return;
777
+ this.watchers.delete(dir);
778
+ w.close();
779
+ onGone();
780
+ };
781
+ w.on('error', gone);
782
+ w.on('close', gone);
783
+ w.unref();
784
+ this.watchers.set(dir, w);
785
+ };
786
+ // graphs/ or assets/: follow its files; when it goes or comes back, follow the folder now there and read it again
787
+ const child = (dir, apply, known) => {
788
+ const reopen = () => {
789
+ attach(dir, (name) => settle(dir, name, apply), () => later(dir, 150, reopen));
790
+ let files = [];
791
+ try {
792
+ files = fs.readdirSync(dir).filter((f) => f.endsWith('.json') && !f.startsWith('.')).map((f) => f.slice(0, -'.json'.length));
793
+ }
794
+ catch { /* gone */ }
795
+ for (const name of new Set([...known(), ...files]))
796
+ settle(dir, name, apply);
797
+ };
798
+ attach(dir, (name) => settle(dir, name, apply), () => later(dir, 150, reopen));
799
+ return () => later(dir, 150, reopen);
758
800
  };
759
801
  const graphChanged = (name, file) => {
760
802
  if (!NAME_RE.test(name) || this.graphFile(name) !== file)
@@ -779,17 +821,8 @@ export class Session {
779
821
  this.lastReport.delete(name);
780
822
  this.bump(name);
781
823
  };
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) => {
824
+ const graphsBack = child(this.graphDir, graphChanged, () => [...this.graphs.keys()].filter((n) => this.graphFile(n) === path.join(this.graphDir, n + '.json')));
825
+ const assetsBack = child(this.assetDir, (name, file) => {
793
826
  if (!fs.existsSync(file))
794
827
  return;
795
828
  const spec = JSON.parse(fs.readFileSync(file, 'utf8'));
@@ -801,15 +834,35 @@ export class Session {
801
834
  this.lastReport.delete(g);
802
835
  this.bump(g);
803
836
  }
837
+ }, () => []);
838
+ // the package folder: graphs/ and assets/ removed or made again, and a package's graph files beside its manifest,
839
+ // when graphs/ has no graph of that name
840
+ const beside = (name, file) => {
841
+ if (fs.existsSync(path.join(this.graphDir, name + '.json')))
842
+ return;
843
+ if (!this.graphs.has(name) && fs.existsSync(file))
844
+ this.besidePackage.set(name, file);
845
+ graphChanged(name, file);
846
+ };
847
+ const isPackage = topoFiles(this.dir).length > 0;
848
+ const top = path.basename(this.graphDir), assets = path.basename(this.assetDir);
849
+ attach(this.dir, (name) => { if (isPackage)
850
+ settle(this.dir, name, beside); }, () => { }, (rel) => {
851
+ if (rel === top)
852
+ graphsBack();
853
+ else if (rel === assets)
854
+ assetsBack();
804
855
  });
805
856
  }
806
857
  /** Stop following the folders (watch()). */
807
858
  unwatch() {
808
- for (const w of this.watchers)
859
+ this.watching = false;
860
+ const ws = [...this.watchers.values()];
861
+ this.watchers.clear();
862
+ for (const w of ws)
809
863
  w.close();
810
864
  for (const t of this.watchTimers.values())
811
865
  clearTimeout(t);
812
- this.watchers = [];
813
866
  this.watchTimers.clear();
814
867
  }
815
868
  }
@@ -11,11 +11,14 @@ async function json(url, init) {
11
11
  const j = await res.json().catch(() => ({ ok: false, error: `${res.status} ${res.statusText}` }));
12
12
  return { status: res.status, j };
13
13
  }
14
- /** A GLB route: {ok, buf} or {ok: false, error, stopped?} (stopped: the node its cook was stopped at). */
14
+ /**
15
+ * A GLB route: {ok, buf} or {ok: false, error, stopped?, preview?} (stopped: the node its cook was stopped at; preview:
16
+ * the result cooked but its GLB could not be written).
17
+ */
15
18
  async function glb(url) {
16
19
  let res;
17
20
  try { res = await fetch(url); } catch { return fail(offline); }
18
- if (!res.ok) { const j = await res.json().catch(() => ({})); return { ...fail(j.error ?? `${res.status} ${res.statusText}`), ...(j.stopped ? { stopped: j.stopped } : {}) }; }
21
+ if (!res.ok) { const j = await res.json().catch(() => ({})); return { ...fail(j.error ?? `${res.status} ${res.statusText}`), ...(j.stopped ? { stopped: j.stopped } : {}), ...(j.preview ? { preview: true } : {}) }; }
19
22
  return { ok: true, buf: await res.arrayBuffer() };
20
23
  }
21
24
  const post = (body) => ({ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
@@ -20,9 +20,11 @@ export const SHOW_AFTER = 150;
20
20
  /**
21
21
  * The line for a graph's cook state: {kind, text, title}. kind: "running", "stopping", "ok", "failed", "stopped" or
22
22
  * "none". `state`: {running: {cooks, kinds, elapsed, node, nodeElapsed, inner, stopping} | null, last: {ok, ms,
23
- * stopped?, error?: {node, message}} | null}; `since`: ms since it arrived, added to the running times.
23
+ * stopped?, error?: {node, message}} | null}; `since`: ms since it arrived, added to the running times. `preview`: why the
24
+ * cooked result could not be shown ("preview failed: …", the GLB route's or the page's), a failure the view keeps the
25
+ * last shown result through.
24
26
  */
25
- export function cookLine(state, since = 0) {
27
+ export function cookLine(state, since = 0, preview = null) {
26
28
  const r = state?.running;
27
29
  if (r && (r.elapsed + since >= SHOW_AFTER || r.stopping)) {
28
30
  const where = r.node ? `${r.node}${r.inner ? ` › ${r.inner}` : ''}` : '';
@@ -44,12 +46,16 @@ export function cookLine(state, since = 0) {
44
46
  return { kind: 'running', text: `${verb}${where ? ` ${where}` : ''} · ${total}`, title: `${node}${r.cooks > 1 ? ` (${r.cooks} cooks of this graph)` : ''}. Stop ends it at the next node; changing a value starts over with the new value.` };
45
47
  }
46
48
  const l = state?.last;
47
- if (!l) return { kind: 'none', text: '', title: '' };
49
+ // the cook ended well but its result cannot be shown: said like a failed cook (a failed or stopped one says more)
50
+ const shown = preview && !l?.stopped && l?.ok !== false
51
+ ? { kind: 'failed', text: firstLine(preview), title: `${preview} (the cook finished; the view keeps the last result it could show)` } : null;
52
+ if (!l) return shown ?? { kind: 'none', text: '', title: '' };
48
53
  if (l.stopped) return { kind: 'stopped', text: `stopped at ${l.stopped} · the view shows the last finished cook`, title: 'change a value (or save the graph file) to cook again' };
49
54
  if (!l.ok) {
50
55
  const msg = l.error?.message ?? 'failed';
51
56
  return { kind: 'failed', text: `failed at ${l.error?.node ?? 'the graph'}: ${firstLine(msg)}`, title: `${l.error?.node ?? ''}: ${msg}` };
52
57
  }
58
+ if (shown) return shown;
53
59
  return { kind: 'ok', text: `cooked in ${fmtDuration(l.ms)}`, title: `the last cook of the whole graph took ${fmtDuration(l.ms)}` };
54
60
  }
55
61
 
@@ -72,7 +72,8 @@ ctx.cookState = (graph) => cooks.get(graph)?.state ?? null;
72
72
  function setCook(graph, state) { cooks.set(graph, { state, at: performance.now() }); renderCook(); }
73
73
  function renderCook() {
74
74
  const c = cooks.get(ctx.graph?.name), compare = ctx.packages?.running;
75
- const line = compare ? compareLine(compare, performance.now() - compare.at) : cookLine(c?.state, c ? performance.now() - c.at : 0);
75
+ const pe = ctx.output?.previewError, preview = pe && pe.at === `${ctx.graph?.name}/${ctx.graph?.node ?? ''}` ? pe.message : null;
76
+ const line = compare ? compareLine(compare, performance.now() - compare.at) : cookLine(c?.state, c ? performance.now() - c.at : 0, preview);
76
77
  for (const el of cookLines) {
77
78
  el.className = `cookline ${line.kind}`;
78
79
  const t = el.querySelector('.ctext');
@@ -164,6 +165,8 @@ ctx.setHover = (id) => { if (ctx.hover === id) return; ctx.hover = id; ctx.emit(
164
165
  // the output: the node being shown, its display mode and visibility remembered
165
166
  ctx.output = {
166
167
  mesh: null, summary: '', error: null, report: null, loading: false,
168
+ /** {at: "graph/node", message: "preview failed: …"} when that node's result cooked but could not be shown */
169
+ previewError: null,
167
170
  visible: local.get('output.visible', true), display: local.get('output.display', 'view'),
168
171
  setVisible(v) { this.visible = v; local.set('output.visible', v); outEntry(); ctx.emit('output'); ctx.requestRender(); },
169
172
  setDisplay(m) { this.display = m; local.set('output.display', m); outEntry(); ctx.emit('output'); ctx.requestRender(); },
@@ -259,19 +262,30 @@ const loadGeo = ctx.coalesce(async () => {
259
262
  const r = await api.geo(graph, node, ctx.sceneLayer.get());
260
263
  o.loading = false;
261
264
  if (graph !== G.name || node !== (G.node ?? '') || ctx.outputs?.active) { ctx.emit('output'); return; }
265
+ // the result cooked but cannot be shown (its GLB was not written, or does not load here): the cook line says so and
266
+ // the view keeps the last result it showed
267
+ const previewFailed = (e) => {
268
+ const msg = String(e?.message ?? e);
269
+ o.previewError = { at: `${graph}/${node}`, message: msg.startsWith('preview failed') ? msg : `preview failed: ${msg}` };
270
+ if (e?.stack) console.error(e);
271
+ ctx.emit('output'); updateCook(); renderCook();
272
+ };
262
273
  if (!r.ok) {
263
274
  // the last good geometry stays; a stopped cook is no error (the cook line says where it stopped)
275
+ if (r.preview) return previewFailed(r.error);
264
276
  if (!r.stopped) o.error = r.error;
265
277
  ctx.emit('output'); updateCook();
266
278
  return;
267
279
  }
268
- let src;
269
- try { src = await parseGLB(r.buf); } catch (e) { o.error = String(e?.message ?? e); ctx.emit('output'); updateCook(); return; }
280
+ let src, mesh;
281
+ try { src = await parseGLB(r.buf); } catch (e) { return previewFailed(e); }
270
282
  if (graph !== G.name || node !== (G.node ?? '') || ctx.outputs?.active) { new MeshObject('', src).dispose(); return; }
283
+ try { mesh = new MeshObject('out', src); } catch (e) { return previewFailed(e); }
271
284
  const prev = o.mesh;
272
- o.mesh = new MeshObject('out', src);
285
+ o.mesh = mesh;
273
286
  o.mesh.onReady = () => { ctx.requestRender(); ctx.emit('output'); };
274
287
  o.error = null;
288
+ if (o.previewError) { o.previewError = null; renderCook(); }
275
289
  ctx.outputRoot.add(o.mesh.root);
276
290
  if (prev) prev.dispose();
277
291
  outEntry();
@@ -67,8 +67,25 @@ function outputsLine(v, most = 6) {
67
67
  const names = Object.entries(v.outputs).filter(([, o]) => !isDefaultOutput(v, o)).map(([k]) => k);
68
68
  return `${names.length} output${names.length === 1 ? '' : 's'}${names.length ? `: ${names.slice(0, most).join(', ')}${names.length > most ? ' …' : ''}` : ''}`;
69
69
  }
70
+ /** The preview GLB could not be written: the result cooked, the page cannot be shown it (500, {preview: true}). */
71
+ class PreviewError extends HttpError {
72
+ constructor(msg) { super(500, `preview failed: ${msg}`); }
73
+ }
74
+ /**
75
+ * The GLB a geometry route serves (previewGLB). Writing it fails as the preview's error, not the cook's, and the stack
76
+ * goes to the server's log (stderr) so the step that failed is named.
77
+ */
78
+ async function previewOf(g, o = {}) {
79
+ try {
80
+ return await previewGLB(g, o);
81
+ }
82
+ catch (e) {
83
+ console.error(`preview failed: ${e?.stack ?? e}`);
84
+ throw new PreviewError(String(e?.message ?? e));
85
+ }
86
+ }
70
87
  /** The shape every geometry route serves: the same GLB options as /api/geo; images alone show as textured quads. */
71
- const toGLB = (g) => previewGLB(g);
88
+ const toGLB = (g) => previewOf(g);
72
89
  const issueText = (e) => `[${e.node}] ${e.message}`;
73
90
  /**
74
91
  * A dropped file's name as stored in inputs/: a plain basename with its extension. Path separators and ".." are
@@ -748,7 +765,7 @@ export async function startViewer(ws, port = Number(process.env.TOPOTOPO_PORT ??
748
765
  if (u.pathname === '/api/info')
749
766
  return send(200, JSON.stringify({ target: r.target, summary: summarize(r.geo), ms: r.ms, about: outputKind(r.geo) }), MIME['.json']);
750
767
  // heightfields: the layer drawn in red (the page's layer picker; the mask by default)
751
- return send(200, await previewGLB(r.geo, { heightfieldLayer: u.searchParams.get('heightfield_layer') || undefined }), MIME['.glb']);
768
+ return send(200, await previewOf(r.geo, { heightfieldLayer: u.searchParams.get('heightfield_layer') || undefined }), MIME['.glb']);
752
769
  }
753
770
  send(404, 'not found');
754
771
  }
@@ -758,7 +775,7 @@ export async function startViewer(ws, port = Number(process.env.TOPOTOPO_PORT ??
758
775
  const status = e instanceof HttpError ? e.status : 500;
759
776
  const msg = String(e?.message ?? e);
760
777
  res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store', ...(status === 413 ? { connection: 'close' } : {}) });
761
- res.end(JSON.stringify(route === '/api/vars' ? { ok: false, ms: 0, errors: [msg] } : { ok: false, error: msg }));
778
+ res.end(JSON.stringify(route === '/api/vars' ? { ok: false, ms: 0, errors: [msg] } : { ok: false, error: msg, ...(e instanceof PreviewError ? { preview: true } : {}) }));
762
779
  }
763
780
  });
764
781
  const listen = (p) => new Promise((resolve, reject) => {
@@ -3,5 +3,5 @@
3
3
  name="TopoTopo"
4
4
  description="Imports TopoTopo packages (<id>.topo): their published outputs are cooked into GLBs and PNGs that Godot imports itself, and kept current while the package changes."
5
5
  author="TopoTopo"
6
- version="0.5.0"
6
+ version="0.5.2"
7
7
  script="plugin.gd"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "topotopo",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "An open-source procedural geometry engine: node graphs in JSON, cooked headless and deterministic, exported to Unreal, Blender and Houdini. Built for LLM agents through MCP, and for people through the CLI.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -39,11 +39,8 @@
39
39
  "mcp": "node src/mcp/server.ts",
40
40
  "preview": "node scripts/preview.ts --examples",
41
41
  "cook": "node src/cli.ts",
42
- "test": "node test/smoke.ts && node test/golden.ts && node test/property.ts && node test/fuzz.ts && node test/docs.ts && node test/portability.ts && node test/examples.ts && node scripts/gen-notice.ts --check && node test/io.ts && node test/import.ts && node test/interop.ts && node test/mcp.ts && node test/engine.ts && node test/scopes.ts && node test/packages.ts && node test/cook.ts && node test/viewer.ts && node test/viewer-logic.ts && node test/topology.ts && node test/deform.ts && node test/cloth.ts && node test/arrays.ts && node test/bugs.ts && node test/uv.ts && node test/polyedit.ts && node test/bevel.ts && node test/meshops.ts && node test/measure.ts && node test/render.ts && node test/packed.ts && node test/heightfield.ts && node test/remesh.ts && node test/pcg.ts && node test/scatterkernel.ts && node test/splines.ts && node test/builtin.ts && node test/textures.ts && node test/texnodes.ts && node test/imageops.ts && node test/pool.ts && node test/kernelsloader.ts && node test/kernels.ts && node test/sdfgrid.ts && node test/remeshquad.ts && node test/erosionkernel.ts && node test/erosionsimd.ts && node test/particles.ts && node test/rbd.ts && node test/limits.ts && node test/viewer-outputs.ts && node test/viewer-packages.ts && node test/library.ts && node test/web.ts && node test/tangents.ts && node test/pbr.ts && node test/materials.ts && node test/sockets.ts && node test/uvreport.ts && node test/solidify.ts && node test/llmbench.ts",
42
+ "test": "node test/smoke.ts && node test/golden.ts && node test/property.ts && node test/fuzz.ts && node test/docs.ts && node test/portability.ts && node test/examples.ts && node scripts/gen-notice.ts --check && node test/io.ts && node test/import.ts && node test/interop.ts && node test/mcp.ts && node test/engine.ts && node test/scopes.ts && node test/packages.ts && node test/cook.ts && node test/viewer.ts && node test/session-watch.ts && node test/viewer-logic.ts && node test/topology.ts && node test/deform.ts && node test/cloth.ts && node test/arrays.ts && node test/bugs.ts && node test/uv.ts && node test/polyedit.ts && node test/bevel.ts && node test/meshops.ts && node test/measure.ts && node test/render.ts && node test/packed.ts && node test/heightfield.ts && node test/remesh.ts && node test/pcg.ts && node test/scatterkernel.ts && node test/splines.ts && node test/builtin.ts && node test/textures.ts && node test/texnodes.ts && node test/imageops.ts && node test/pool.ts && node test/kernelsloader.ts && node test/kernels.ts && node test/sdfgrid.ts && node test/remeshquad.ts && node test/erosionkernel.ts && node test/erosionsimd.ts && node test/particles.ts && node test/rbd.ts && node test/limits.ts && node test/viewer-outputs.ts && node test/viewer-packages.ts && node test/library.ts && node test/web.ts && node test/tangents.ts && node test/pbr.ts && node test/materials.ts && node test/sockets.ts && node test/uvreport.ts && node test/solidify.ts",
43
43
  "test:limits": "node test/limits.ts",
44
- "test:llmbench": "node test/llmbench.ts",
45
- "bench:llm": "node bench/llm/run.ts",
46
- "bench:llm:report": "node bench/llm/report.ts",
47
44
  "kernels:build": "node scripts/kernels-build.ts",
48
45
  "test:kernels": "node test/scatterkernel.ts && node test/kernelsloader.ts && node test/kernels.ts && node test/sdfgrid.ts && node test/remeshquad.ts && node test/erosionkernel.ts && node test/erosionsimd.ts",
49
46
  "test:remeshquad": "node test/remeshquad.ts",
@@ -77,7 +74,7 @@
77
74
  "test:examples": "node test/examples.ts",
78
75
  "test:interop": "node test/interop.ts",
79
76
  "test:web": "node test/library.ts && node test/web.ts",
80
- "test:viewer": "node test/viewer.ts && node test/viewer-logic.ts && node test/viewer-outputs.ts && node test/viewer-packages.ts",
77
+ "test:viewer": "node test/viewer.ts && node test/session-watch.ts && node test/viewer-logic.ts && node test/viewer-outputs.ts && node test/viewer-packages.ts",
81
78
  "showcase": "node test/showcase.ts",
82
79
  "export:demo": "node scripts/export-demo.ts",
83
80
  "demo:footage": "node scripts/demo-footage.ts",
@@ -122,7 +119,6 @@
122
119
  "xatlas-wasm": "0.1.3"
123
120
  },
124
121
  "devDependencies": {
125
- "@anthropic-ai/sdk": "^1.4.0",
126
122
  "@types/d3-delaunay": "^6.0.4",
127
123
  "@types/node": "^26.6.4",
128
124
  "@types/three": "^0.186.0",