topotopo 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/NOTICE +30 -0
  2. package/README.md +35 -14
  3. package/dist/cli.js +28 -10
  4. package/dist/core/analysis.d.ts +5 -1
  5. package/dist/core/analysis.js +8 -3
  6. package/dist/core/bake.d.ts +2 -5
  7. package/dist/core/bake.js +12 -25
  8. package/dist/core/bevel.js +165 -97
  9. package/dist/core/geometry.js +1 -1
  10. package/dist/core/imageops.d.ts +6 -0
  11. package/dist/core/imageops.js +51 -0
  12. package/dist/core/materials.d.ts +4 -0
  13. package/dist/core/materials.js +11 -0
  14. package/dist/core/packed.js +11 -0
  15. package/dist/core/particles.d.ts +1 -1
  16. package/dist/core/particles.js +1 -1
  17. package/dist/core/rbd.js +13 -1
  18. package/dist/core/scatter.d.ts +1 -1
  19. package/dist/core/scatter.js +1 -1
  20. package/dist/core/scene.d.ts +20 -0
  21. package/dist/core/scene.js +71 -0
  22. package/dist/core/snippet-lib.d.ts +1 -1
  23. package/dist/core/snippet-lib.js +1 -1
  24. package/dist/core/solidify.d.ts +38 -0
  25. package/dist/core/solidify.js +356 -0
  26. package/dist/core/tangents.d.ts +52 -0
  27. package/dist/core/tangents.js +214 -0
  28. package/dist/core/texcoord.d.ts +4 -0
  29. package/dist/core/texcoord.js +14 -0
  30. package/dist/core/topology.d.ts +22 -0
  31. package/dist/core/topology.js +70 -7
  32. package/dist/core/traceimage.d.ts +7 -0
  33. package/dist/core/traceimage.js +221 -0
  34. package/dist/core/tritri.d.ts +5 -0
  35. package/dist/core/tritri.js +120 -0
  36. package/dist/core/uv.d.ts +13 -0
  37. package/dist/core/uv.js +3 -3
  38. package/dist/core/uvreport.d.ts +66 -0
  39. package/dist/core/uvreport.js +308 -0
  40. package/dist/core/xatlas.js +32 -2
  41. package/dist/gallery/app/gallery.css +100 -0
  42. package/dist/gallery/app/gallery.js +80 -0
  43. package/dist/gallery/bake.d.ts +34 -0
  44. package/dist/gallery/bake.js +144 -0
  45. package/dist/gallery/cli.d.ts +4 -0
  46. package/dist/gallery/cli.js +157 -0
  47. package/dist/gallery/library.d.ts +124 -0
  48. package/dist/gallery/library.js +366 -0
  49. package/dist/gallery/pages.d.ts +94 -0
  50. package/dist/gallery/pages.js +148 -0
  51. package/dist/gallery/server.d.ts +21 -0
  52. package/dist/gallery/server.js +391 -0
  53. package/dist/host/export-targets.js +1 -1
  54. package/dist/index.d.ts +3 -1
  55. package/dist/index.js +2 -1
  56. package/dist/inspect.d.ts +6 -1
  57. package/dist/inspect.js +13 -1
  58. package/dist/io/common.d.ts +8 -0
  59. package/dist/io/gltf.js +236 -19
  60. package/dist/io/targets.js +1 -1
  61. package/dist/mcp/docs.d.ts +1 -1
  62. package/dist/mcp/docs.js +58 -4
  63. package/dist/mcp/library.d.ts +12 -0
  64. package/dist/mcp/library.js +159 -0
  65. package/dist/mcp/server.js +29 -12
  66. package/dist/mcp/tools.js +16 -10
  67. package/dist/nodes/bake.js +56 -36
  68. package/dist/nodes/bevel.js +4 -3
  69. package/dist/nodes/code.js +1 -1
  70. package/dist/nodes/curves.js +7 -0
  71. package/dist/nodes/generate.js +1 -1
  72. package/dist/nodes/imageops.d.ts +1 -0
  73. package/dist/nodes/imageops.js +206 -0
  74. package/dist/nodes/index.d.ts +3 -0
  75. package/dist/nodes/index.js +3 -0
  76. package/dist/nodes/material.js +3 -0
  77. package/dist/nodes/measure.js +3 -2
  78. package/dist/nodes/rbd.js +1 -1
  79. package/dist/nodes/scene.d.ts +1 -0
  80. package/dist/nodes/scene.js +53 -0
  81. package/dist/nodes/solidify.d.ts +1 -0
  82. package/dist/nodes/solidify.js +52 -0
  83. package/dist/nodes/transform.js +5 -1
  84. package/dist/nodes/util.d.ts +1 -1
  85. package/dist/nodes/wasmcall.js +1 -1
  86. package/dist/render/options.js +1 -1
  87. package/dist/render/pbr.d.ts +28 -0
  88. package/dist/render/pbr.js +378 -0
  89. package/dist/render/preview.d.ts +58 -0
  90. package/dist/render/preview.js +24 -0
  91. package/dist/render/raster.d.ts +12 -2
  92. package/dist/render/raster.js +98 -11
  93. package/dist/render/texview.d.ts +1 -1
  94. package/dist/render/texview.js +7 -2
  95. package/dist/viewer/app/camera.js +1 -1
  96. package/dist/viewer/app/embed.js +80 -0
  97. package/dist/viewer/app/grid.js +1 -1
  98. package/dist/viewer/app/guides.js +1 -1
  99. package/dist/viewer/app/keymap.js +1 -1
  100. package/dist/viewer/app/layers.js +1 -1
  101. package/dist/viewer/app/main.js +1 -1
  102. package/dist/viewer/app/markers.js +1 -1
  103. package/dist/viewer/app/outliner.js +1 -1
  104. package/dist/viewer/app/props.js +1 -1
  105. package/dist/viewer/app/scene.js +6 -2
  106. package/dist/viewer/app/select.js +1 -1
  107. package/dist/viewer/app/selection.js +1 -1
  108. package/dist/viewer/app/status.js +1 -1
  109. package/dist/viewer/app/style.css +1 -1
  110. package/dist/viewer/app/units.js +1 -1
  111. package/dist/viewer/app/vars.js +1 -1
  112. package/dist/viewer/index.html +1 -1
  113. package/dist/viewer/server.d.ts +14 -2
  114. package/dist/viewer/server.js +30 -10
  115. package/dist/workspace.d.ts +13 -0
  116. package/dist/workspace.js +87 -1
  117. package/kernels/pkg/README.md +21 -28
  118. package/kernels/pkg-simd/README.md +21 -28
  119. package/package.json +9 -3
@@ -0,0 +1,159 @@
1
+ // The `library` tool: the person's libraries of projects (src/gallery/library.ts). An agent
2
+ // lists and searches every library, reads a project, makes new ones, edits their project.json, bakes previews, and
3
+ // opens a project: the server's workspace becomes that project folder, so build/edit/render/export work on it.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { createProject, graphNames, isStale, listFiles, loadConfig, parseManifest, projectDirOf, readBakeState, readGraph, readManifest, scanAll, writeManifest, } from '../gallery/library.js';
7
+ const text = (t, isError = false) => ({ content: [{ type: 'text', text: t }], ...(isError ? { isError } : {}) });
8
+ export function libraryTool(host) {
9
+ const scan = () => { const cfg = loadConfig(); return { cfg, scans: scanAll(cfg) }; };
10
+ const urlsOf = (cfg, p) => {
11
+ const b = `http://127.0.0.1:${cfg.gallery.port}`;
12
+ return { page: `${b}/p/${p.lib}/${p.id}`, embed: `${b}/embed/${p.lib}/${p.id}`, thumb: `${b}/p/${p.lib}/${p.id}/thumb.png` };
13
+ };
14
+ const currentDir = () => projectDirOf(host.workspace().dir);
15
+ const statusOf = (p) => { const s = readBakeState(p.dir); return !s ? 'not baked' : !s.ok ? 'bake failed' : isStale(p) ? 'stale' : 'baked'; };
16
+ /** {library, id}, {path}, or nothing (the open project) */
17
+ const pick = (a, scans) => {
18
+ const all = scans.flatMap((s) => s.projects);
19
+ if (a.id) {
20
+ const hits = all.filter((p) => p.id === a.id && (!a.library || p.lib === a.library));
21
+ if (hits.length === 1)
22
+ return hits[0];
23
+ if (hits.length > 1)
24
+ throw new Error(`id "${a.id}" is in several libraries (${hits.map((p) => p.lib).join(', ')}): give "library"`);
25
+ throw new Error(`no project "${a.id}"${a.library ? ` in library "${a.library}"` : ''}. library {action:"list"} lists them`);
26
+ }
27
+ const dir = a.path ? projectDirOf(path.resolve(a.path)) : currentDir();
28
+ if (!dir)
29
+ throw new Error(a.path ? `${a.path}: no project.json there or above` : 'give {library, id}: the open workspace is not a library project');
30
+ const p = all.find((x) => x.dir === dir);
31
+ if (p)
32
+ return p;
33
+ // a project folder outside the configured libraries still works
34
+ const m = readManifest(dir);
35
+ return { lib: '', id: m.id, dir, rel: path.basename(dir), collection: '', manifest: m, updated: 0 };
36
+ };
37
+ return {
38
+ name: 'library',
39
+ description: 'The person\'s libraries of projects (the TopoTopo Gallery website shows them; a board links to them). A library is a folder; a project is a folder in it with project.json (title, description, tags, links to concept art/board pages) and is a workspace of its own (graphs/, assets/, inputs/, exports/, attachments/ for concept art and references). ' +
40
+ 'list {query?, tag?, library?}: every project with status and gallery URL. get {library, id} (or the open project): manifest, graphs and vars, attachments, exports, bake state, URLs; thumbnail:true adds the baked image. ' +
41
+ 'open {library, id} | {path}: make that project the workspace of every tool and the live viewer, then build/edit/render/export work in it. create {library, path:"props/lantern", title?, description?, tags?, links?}: a new project, opened. ' +
42
+ 'update {library?, id?, title?, description?, tags?, links?, graph?, bake?}: edit project.json (graph = the graph the gallery shows; bake = {graph?, node?, frame?} what its preview shows). bake {library?, id?}: render thumb.png and preview.glb now (the gallery also bakes on its own after changes). See help topic "library".',
43
+ inputSchema: {
44
+ type: 'object',
45
+ required: ['action'],
46
+ properties: {
47
+ action: { type: 'string', enum: ['list', 'get', 'open', 'create', 'update', 'bake'] },
48
+ library: { type: 'string', description: 'library name (list shows them)' },
49
+ id: { type: 'string', description: 'project id' },
50
+ path: { type: 'string', description: 'create: folder below the library ("props/lantern"); open/get: a project folder on disk instead of {library, id}' },
51
+ query: { type: 'string', description: 'list: words to match in title, id, collection, description, tags' },
52
+ tag: { type: 'string', description: 'list: only projects with this tag' },
53
+ title: { type: 'string' },
54
+ description: { type: 'string' },
55
+ tags: { type: 'array', items: { type: 'string' } },
56
+ links: { type: 'array', items: { type: 'object', properties: { label: { type: 'string' }, url: { type: 'string' } }, required: ['url'] }, description: 'links back to the board, concept pages, tickets' },
57
+ graph: { type: 'string', description: 'update: the graph the gallery shows and bakes (default "main")' },
58
+ bake: { type: 'object', properties: { graph: { type: 'string' }, node: { type: 'string' }, frame: { type: 'number' } }, description: 'update: what the preview shows instead of the graph output' },
59
+ thumbnail: { type: 'boolean', description: 'get: include the baked thumbnail image' },
60
+ open: { type: 'boolean', description: 'create: open the new project (default true)' },
61
+ },
62
+ },
63
+ run: async (a) => {
64
+ const { cfg, scans } = scan();
65
+ switch (a.action) {
66
+ case 'list': {
67
+ if (!cfg.libraries.length)
68
+ return text(`no libraries configured (${cfg.file}). The person adds one with \`topotopo library add <name> <folder>\`.`);
69
+ const cur = currentDir();
70
+ const words = String(a.query ?? '').toLowerCase().split(/\s+/).filter(Boolean);
71
+ const lines = [];
72
+ for (const s of scans) {
73
+ if (a.library && s.name !== a.library)
74
+ continue;
75
+ const ps = s.projects.filter((p) => {
76
+ const m = p.manifest, hay = [m.title, p.id, p.collection, m.description, ...m.tags].join(' ').toLowerCase();
77
+ return words.every((w) => hay.includes(w)) && (!a.tag || m.tags.includes(a.tag));
78
+ });
79
+ lines.push(`library "${s.name}" (${s.root}): ${ps.length}${ps.length !== s.projects.length ? ` of ${s.projects.length}` : ''} projects`);
80
+ for (const p of ps)
81
+ lines.push(` ${p.id}${p.dir === cur ? ' (open)' : ''} ${p.rel} "${p.manifest.title}"${p.manifest.tags.length ? ` [${p.manifest.tags.join(', ')}]` : ''} ${statusOf(p)} ${urlsOf(cfg, p).page}`);
82
+ for (const pr of s.problems)
83
+ lines.push(` ! ${pr}`);
84
+ }
85
+ return text(lines.join('\n') || 'no library matches');
86
+ }
87
+ case 'get': {
88
+ const p = pick(a, scans), m = p.manifest, s = readBakeState(p.dir), u = urlsOf(cfg, p);
89
+ const graphs = graphNames(p.dir).map((n) => {
90
+ const g = readGraph(p.dir, n) ?? {};
91
+ const vars = Object.entries(g.vars ?? {}).map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(', ');
92
+ return ` ${n}${n === m.graph ? ' (shown)' : ''}: ${Object.keys(g.nodes ?? {}).length} nodes${vars ? `; vars ${vars}` : ''}`;
93
+ });
94
+ const att = listFiles(path.join(p.dir, 'attachments')), exp = listFiles(path.join(p.dir, 'exports'));
95
+ const lines = [
96
+ `project ${p.lib ? `${p.lib}/` : ''}${p.id}: "${m.title}"${p.dir === currentDir() ? ' (open)' : ''}`,
97
+ `folder ${p.dir}`,
98
+ ...(m.description ? [`description: ${m.description}`] : []),
99
+ ...(m.tags.length ? [`tags: ${m.tags.join(', ')}`] : []),
100
+ ...(m.links.length ? ['links:', ...m.links.map((l) => ` ${l.label}: ${l.url}`)] : []),
101
+ `graphs (${graphs.length}):`, ...(graphs.length ? graphs : [' none yet']),
102
+ ...(att.length ? [`attachments/ (${att.length}): ${att.slice(0, 30).map((f) => f.path).join(', ')}${att.length > 30 ? ', …' : ''}`] : []),
103
+ ...(exp.length ? [`exports/ (${exp.length}): ${exp.slice(0, 30).map((f) => f.path).join(', ')}${exp.length > 30 ? ', …' : ''}`] : []),
104
+ `preview: ${statusOf(p)}${s ? `, baked ${new Date(s.at).toISOString().slice(0, 16)}` : ''}${s && !s.ok ? `: ${s.error}` : ''}${Object.keys(m.bake).length ? `; bake ${JSON.stringify(m.bake)}` : ''}`,
105
+ `gallery: ${u.page} embed: ${u.embed} thumbnail: ${u.thumb}`,
106
+ ];
107
+ const content = [{ type: 'text', text: lines.join('\n') }];
108
+ const thumb = path.join(p.dir, '.gallery', 'thumb.png');
109
+ if (a.thumbnail && fs.existsSync(thumb))
110
+ content.push({ type: 'image', data: fs.readFileSync(thumb).toString('base64'), mimeType: 'image/png' });
111
+ return { content };
112
+ }
113
+ case 'open': {
114
+ const p = pick(a, scans);
115
+ const r = await host.open(p.dir);
116
+ return text(`opened ${p.lib ? `${p.lib}/` : ''}${p.id} ("${p.manifest.title}"): the workspace of every tool is now ${p.dir} (${r.graphs} graphs, ${r.assets} assets). ` +
117
+ `Build into graph "${p.manifest.graph}" (the one the gallery shows); put reference images in attachments/ and guide files in inputs/. Gallery page: ${urlsOf(cfg, p).page}`);
118
+ }
119
+ case 'create': {
120
+ if (!a.library)
121
+ throw new Error(`"library" is required (${cfg.libraries.map((l) => l.name).join(', ') || 'none configured'})`);
122
+ if (!a.path)
123
+ throw new Error('"path" is required: the project folder below the library, e.g. "props/lantern"');
124
+ const lib = cfg.libraries.find((l) => l.name === a.library);
125
+ if (!lib)
126
+ throw new Error(`no library "${a.library}" (${cfg.libraries.map((l) => l.name).join(', ') || `none: the person adds one with \`topotopo library add <name> <folder>\``})`);
127
+ const p = createProject(lib, a.path, { title: a.title, description: a.description, tags: a.tags, links: a.links });
128
+ let opened = '';
129
+ if (a.open !== false) {
130
+ await host.open(p.dir);
131
+ opened = ' and opened it: build/edit now work in it (graph "main" is the one the gallery shows)';
132
+ }
133
+ return text(`created ${p.lib}/${p.id} at ${p.dir}${opened}. Gallery page: ${urlsOf(cfg, p).page}`);
134
+ }
135
+ case 'update': {
136
+ const p = pick(a, scans);
137
+ const m = { ...p.manifest };
138
+ for (const k of ['title', 'description', 'tags', 'links', 'graph', 'bake'])
139
+ if (a[k] !== undefined)
140
+ m[k] = a[k];
141
+ const checked = parseManifest(m, p.id);
142
+ writeManifest(p.dir, checked);
143
+ return text(`updated ${p.lib ? `${p.lib}/` : ''}${p.id}: ${JSON.stringify(checked)}`);
144
+ }
145
+ case 'bake': {
146
+ const p = pick(a, scans);
147
+ const { bakeProject } = await import('../gallery/bake.js');
148
+ const s = await bakeProject(p.dir);
149
+ if (!s.ok)
150
+ return text(`bake of ${p.id} failed: ${s.error}`, true);
151
+ const content = [{ type: 'text', text: `baked ${p.id} in ${s.ms} ms: ${s.points} points, ${s.prims} prims${s.glb ? '' : ' (no preview.glb: too large)'}${s.warnings?.length ? `; warnings: ${s.warnings.slice(0, 5).join('; ')}` : ''}` }];
152
+ content.push({ type: 'image', data: fs.readFileSync(path.join(p.dir, '.gallery', 'thumb.png')).toString('base64'), mimeType: 'image/png' });
153
+ return { content };
154
+ }
155
+ }
156
+ return text(`unknown action "${a.action}": list, get, open, create, update or bake`, true);
157
+ },
158
+ };
159
+ }
@@ -14,23 +14,18 @@ import { Engine } from '../graph/engine.js';
14
14
  import { createNodeHost } from '../host/node.js';
15
15
  import { Workspace } from '../workspace.js';
16
16
  import { makeTools } from './tools.js';
17
+ import { libraryTool } from './library.js';
17
18
  import { INSTRUCTIONS } from './docs.js';
18
19
  import { startViewer } from '../viewer/server.js';
19
20
  const argv = process.argv.slice(2);
20
21
  const argOf = (flag) => { const i = argv.indexOf(flag); return i >= 0 ? argv[i + 1] : undefined; };
21
22
  const wsDir = path.resolve(argOf('--workspace') ?? process.env.TOPOTOPO_WORKSPACE ?? path.join(process.cwd(), 'workspace'));
22
23
  const log = (...a) => process.stderr.write('[topotopo] ' + a.join(' ') + '\n');
23
- const engine = new Engine(createNodeHost({ baseDir: wsDir }));
24
- if (process.env.TOPOTOPO_SCRIPT_TIMEOUT_MS)
25
- engine.scriptTimeoutMs = Number(process.env.TOPOTOPO_SCRIPT_TIMEOUT_MS);
26
- if (process.env.TOPOTOPO_SIM_TIMEOUT_MS)
27
- engine.simTimeoutMs = Number(process.env.TOPOTOPO_SIM_TIMEOUT_MS);
28
- await engine.init();
29
- const ws = new Workspace(wsDir, engine);
30
- const loaded = ws.load();
31
- log(`workspace ${wsDir}: ${loaded.graphs} graphs, ${loaded.assets} assets, ${loaded.shelf} shelf assets`);
32
- for (const e of loaded.assetErrors)
33
- log('asset error:', e);
24
+ // The workspace can change while the server runs (library {action:"open"} opens a gallery project): every tool and
25
+ // the live viewer then work on the new folder. Each workspace has its own engine (asset registry, base directory,
26
+ // cache); the worker pool is shared by the process. Workspaces follow what other processes write into them
27
+ // (Workspace.watch: the gallery's editor, a person editing JSON).
28
+ let engine, ws, tools;
34
29
  let viewer = null;
35
30
  const ensureViewer = async () => {
36
31
  if (!viewer) {
@@ -39,9 +34,31 @@ const ensureViewer = async () => {
39
34
  }
40
35
  return viewer.url;
41
36
  };
37
+ const library = libraryTool({ workspace: () => ws, open: (dir) => openWorkspace(dir) });
38
+ async function openWorkspace(dir) {
39
+ const e = new Engine(createNodeHost({ baseDir: dir }));
40
+ if (process.env.TOPOTOPO_SCRIPT_TIMEOUT_MS)
41
+ e.scriptTimeoutMs = Number(process.env.TOPOTOPO_SCRIPT_TIMEOUT_MS);
42
+ if (process.env.TOPOTOPO_SIM_TIMEOUT_MS)
43
+ e.simTimeoutMs = Number(process.env.TOPOTOPO_SIM_TIMEOUT_MS);
44
+ await e.init();
45
+ const w = new Workspace(dir, e);
46
+ const loaded = w.load();
47
+ w.watch();
48
+ log(`workspace ${dir}: ${loaded.graphs} graphs, ${loaded.assets} assets, ${loaded.shelf} shelf assets`);
49
+ for (const x of loaded.assetErrors)
50
+ log('asset error:', x);
51
+ const prev = ws;
52
+ engine = e;
53
+ ws = w;
54
+ tools = [...makeTools(w, { onPreview: ensureViewer }), library];
55
+ viewer?.setWorkspace(w);
56
+ prev?.unwatch();
57
+ return loaded;
58
+ }
59
+ await openWorkspace(wsDir);
42
60
  if (argv.includes('--viewer') || process.env.TOPOTOPO_VIEWER === '1')
43
61
  await ensureViewer();
44
- const tools = makeTools(ws, { onPreview: ensureViewer });
45
62
  // package.json sits two levels above both src/mcp/server.ts and dist/mcp/server.js
46
63
  const pkg = JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
47
64
  const server = new Server({ name: 'topotopo', version: pkg.version }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
package/dist/mcp/tools.js CHANGED
@@ -8,7 +8,7 @@ import { didYouMean } from '../graph/params.js';
8
8
  import { migrateGraph } from '../graph/migrate.js';
9
9
  import { catalogText, nodeDoc, TOPICS, topicList, INSTRUCTIONS } from './docs.js';
10
10
  import { summarize, inspect } from '../inspect.js';
11
- import { renderGeometry } from '../render/raster.js';
11
+ import { renderGeometryAsync } from '../render/raster.js';
12
12
  import { renderArgs } from '../render/options.js';
13
13
  import { encodePNG } from '../render/png.js';
14
14
  import { EXPORT_FORMATS, exportFormatFromPath } from '../io/export.js';
@@ -57,8 +57,9 @@ function reportText(name, r, extraNotes = []) {
57
57
  const FRAME_PROP = {
58
58
  frame: { type: 'number', description: 'frame to cook at (default 1; frame 1 = time 0, 24 fps). Only time-dependent nodes (solver, @Frame wrangles, "=frame" params) change between frames.' },
59
59
  };
60
- function pngContent(g, o) {
61
- const r = renderGeometry(g, o);
60
+ /** Render to a PNG content block; shading "pbr" reads texture files through the host. */
61
+ async function pngContent(g, o, host) {
62
+ const r = await renderGeometryAsync(g, o, (t) => host.readFile(t));
62
63
  const png = encodePNG(r.rgba, r.width, r.height, (d) => zlib.deflateSync(d, { level: 6 }));
63
64
  return { img: { type: 'image', data: Buffer.from(png).toString('base64'), mimeType: 'image/png' }, notes: r.notes, png };
64
65
  }
@@ -128,7 +129,8 @@ const RENDER_PROPS = {
128
129
  label_pieces: { type: 'boolean', description: 'number connected pieces (#0, #1, … in connectivity order)' },
129
130
  label_attrib: { type: 'string', description: 'label each distinct value of a string/int attribute (e.g. "name") on its elements; colours match color_by' },
130
131
  legend: { type: 'boolean', description: 'legend for color_by (gradient bar with min/max, or categorical swatches) and highlight' },
131
- shading: { type: 'string', enum: ['default', 'flat', 'matcap', 'ao'], description: 'flat: facets (ignores N); matcap: clay that reads form; ao: screen-space ambient occlusion darkens creases and cavities' },
132
+ shading: { type: 'string', enum: ['default', 'flat', 'matcap', 'ao', 'pbr'], description: 'flat: facets (ignores N); matcap: clay that reads form; ao: screen-space ambient occlusion darkens creases and cavities; pbr: the exported metallic-roughness material (base colour, normal, orm/roughness maps, emissive, unlit) under a fixed studio light rig, deterministic' },
133
+ exposure: { type: 'number', description: 'shading "pbr": exposure in stops (default 0)' },
132
134
  ao_radius: { type: 'number', description: 'shading "ao": sample radius in pixels (default 10)' },
133
135
  look_at: { type: 'array', items: { type: 'number' }, description: 'look-at point [x,y,z] (same as target)' },
134
136
  ortho_scale: { type: 'number', description: 'ortho/section views: world width across a view (default: fit the bbox)' },
@@ -144,11 +146,11 @@ export function makeTools(ws, opts = {}) {
144
146
  const renderDestination = (name, node) => path.join(ws.exportDir, 'renders', `${name}-${node}`.replace(/[^A-Za-z0-9_.-]/g, '_') + '.png');
145
147
  const engine = ws.engine;
146
148
  /** The text (+ optional render) of a cook report. */
147
- const reportResult = (name, r, a, extraNotes = []) => {
149
+ const reportResult = async (name, r, a, extraNotes = []) => {
148
150
  const content = [{ type: 'text', text: reportText(name, r, extraNotes) }];
149
151
  if (r.geo && a.render) {
150
152
  const ro = renderOpts(typeof a.render === 'object' ? a.render : {}, r.geo, `${name}/${r.target}${atFrame(r)}`);
151
- const { img, notes, png } = pngContent(r.geo, ro);
153
+ const { img, notes, png } = await pngContent(r.geo, ro, engine.host);
152
154
  const renderPath = renderDestination(name, r.target);
153
155
  fs.mkdirSync(path.dirname(renderPath), { recursive: true });
154
156
  fs.writeFileSync(renderPath, png);
@@ -313,13 +315,16 @@ export function makeTools(ws, opts = {}) {
313
315
  },
314
316
  {
315
317
  name: 'inspect',
316
- description: 'Inspect any node\'s output as text: summary; detail "attributes" (min/max/mean, unique strings), "topology" (watertight/manifold, pieces, volume, area, genus), "elements" (list values for a range), or "all".',
318
+ description: 'Inspect any node\'s output as text: summary; detail "attributes" (min/max/mean, unique strings), "topology" (watertight/manifold, pieces, volume, area, genus, render/export triangle health), "elements" (list values for a range), "all", or "uv" (exact uv overlaps with triangle pairs and areas, collapsed / non-finite / out-of-tile triangles, charts, utilization, per-piece texel density with resolution; json:true appends the machine-readable report).',
317
319
  inputSchema: {
318
320
  type: 'object',
319
321
  properties: {
320
322
  graph: { type: 'string', description: 'graph name (default "main")' },
321
323
  node: { type: 'string', description: 'node to inspect (default: graph output)' },
322
- detail: { type: 'string', enum: ['summary', 'attributes', 'topology', 'elements', 'all'] },
324
+ detail: { type: 'string', enum: ['summary', 'attributes', 'topology', 'elements', 'all', 'uv'] },
325
+ uv_attrib: { type: 'string', description: 'detail "uv": the uv attribute (default "uv")' },
326
+ resolution: { description: 'detail "uv": texture size in texels for texel density, n or [width, height]', anyOf: [{ type: 'number' }, { type: 'array', items: { type: 'number' } }] },
327
+ json: { type: 'boolean', description: 'detail "uv": append the report as JSON' },
323
328
  class: { type: 'string', enum: ['point', 'prim', 'vertex', 'detail', 'edge'], description: 'element class; "edge" lists unique edges (point pair, length, polygon count, dihedral angle, edge groups)' },
324
329
  attribs: { type: 'array', items: { type: 'string' } },
325
330
  start: { type: 'number' }, count: { type: 'number' },
@@ -332,7 +337,7 @@ export function makeTools(ws, opts = {}) {
332
337
  const node = r.target;
333
338
  const res = r.results.get(node);
334
339
  const head = `${name}/${node}${atFrame(r)}${res ? ` (${res.cached ? 'cached' : res.ms.toFixed(0) + ' ms'})` : ''}`;
335
- return text(head + '\n' + inspect(geo, { detail: a.detail, cls: a.class, attribs: a.attribs, start: a.start, count: a.count, group: a.group }));
340
+ return text(head + '\n' + inspect(geo, { detail: a.detail, cls: a.class, attribs: a.attribs, start: a.start, count: a.count, group: a.group, uvAttrib: a.uv_attrib, uvResolution: a.resolution, json: a.json }));
336
341
  },
337
342
  },
338
343
  {
@@ -349,7 +354,7 @@ export function makeTools(ws, opts = {}) {
349
354
  },
350
355
  run: async (a) => {
351
356
  const { geo, name, r } = await resolveNodeGeo(a);
352
- const { img, notes, png } = pngContent(geo, renderOpts(a, geo, `${name}/${r.target}${atFrame(r)}`));
357
+ const { img, notes, png } = await pngContent(geo, renderOpts(a, geo, `${name}/${r.target}${atFrame(r)}`), engine.host);
353
358
  const content = [img];
354
359
  const info = [];
355
360
  {
@@ -390,6 +395,7 @@ export function makeTools(ws, opts = {}) {
390
395
  materials: { type: 'boolean', description: 'glTF: write materials from the prim "material" attribute + table (default true)' },
391
396
  compress: { type: 'string', enum: ['none', 'meshopt', 'draco'], description: 'glTF: meshopt = EXT_meshopt_compression + quantization; draco needs the optional draco3dgltf package' },
392
397
  quantize: { type: 'boolean', description: 'glTF: KHR_mesh_quantization (smaller, lossy) without compression' },
398
+ tangents: { type: 'string', enum: ['auto', 'preserve', 'none'], description: 'glTF TANGENT: auto (default) = MikkTSpace for normal-mapped materials, a valid supplied "tangent" attribute elsewhere; preserve = the supplied attribute wherever it exists (malformed = error); none = never' },
393
399
  attributes: { type: 'array', items: { type: 'string' }, description: 'csv / points.json: point attributes to write (default all)' },
394
400
  pcg: { type: 'boolean', description: 'csv: Unreal PCG columns (Position/Rotation/Scale/Density/Color/Seed) in Unreal space (Z-up, left-handed, cm)' },
395
401
  pcg_struct: { type: 'boolean', description: 'csv with pcg: Unreal struct-text cells ("(X=…,Y=…,Z=…)") for DataTable import with a row struct' },
@@ -1,5 +1,6 @@
1
1
  import { Image, MAIN_LAYER } from '../core/image.js';
2
- import { averagedVertexNormals, bakeSamples, curvatureEdges, dilate, edgeGrid, idColor, interpolate, normalize3, resolve, triangleTangents, uvIslands, vertexPositions, vertexValues, } from '../core/bake.js';
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
4
  import { RayScene, bboxDiagonal } from '../core/analysis.js';
4
5
  import { pointNormals, resolveVertexNormals, triangulate } from '../core/topology.js';
5
6
  import { defineNode } from '../graph/registry.js';
@@ -134,12 +135,28 @@ function rayDirs(b) {
134
135
  normalize3(R);
135
136
  return R;
136
137
  }
137
- /** Point normals of a mesh: its point N when present, else area-weighted face normals. */
138
+ /**
139
+ * Point normals of a mesh: its point N when present, else area-weighted face normals. Points whose N is zero or not
140
+ * finite take the computed normal: a merge of parts with and without N fills the missing ones with zeros, which would
141
+ * bake as grey.
142
+ */
138
143
  function pointNormalsOf(g) {
139
144
  const a = g.points.get('N');
140
- if (a && a.type === 'float' && a.size === 3)
141
- return a.data;
142
- return pointNormals(g);
145
+ if (!a || a.type !== 'float' || a.size !== 3)
146
+ return pointNormals(g);
147
+ const N = a.data;
148
+ let out = null, computed = null;
149
+ for (let i = 0; i < N.length; i += 3) {
150
+ const l = Math.hypot(N[i], N[i + 1], N[i + 2]);
151
+ if (l > 1e-12 && Number.isFinite(l))
152
+ continue;
153
+ out ??= N.slice();
154
+ computed ??= pointNormals(g);
155
+ out[i] = computed[i];
156
+ out[i + 1] = computed[i + 1];
157
+ out[i + 2] = computed[i + 2];
158
+ }
159
+ return out ?? N;
143
160
  }
144
161
  /** andThen() for a callback that may itself return a promise (a cook result); keeps synchronous runs synchronous. */
145
162
  const chain = (x, f) => (x instanceof Promise ? x.then(f) : f(x));
@@ -382,9 +399,11 @@ defineBake({
382
399
  type: 'bake_normal',
383
400
  summary: 'Bake a tangent-space normal map from a high-res mesh (input 1) onto the uv of the low mesh: OpenGL or DirectX.',
384
401
  description: 'Substance Painter / Marmoset "Normal". ' + BAKE_DOC + 'For each texel a ray from cage above the low surface along -N finds ' +
385
- 'the high-res surface (within cage below); its interpolated normal is written in the low mesh\'s tangent frame (N ' +
386
- 'interpolated, T from the uv per triangle, B by handedness) as 0.5 + 0.5 n. Misses and a missing input 1 give the ' +
387
- 'flat (0.5, 0.5, 1). glTF and Blender read OpenGL; Unreal DirectX (or flip green on import).',
402
+ 'the high-res surface (within cage below); its interpolated normal is written in the low mesh\'s MikkTSpace tangent ' +
403
+ 'frame as 0.5 + 0.5 n: the frame glTF export writes as TANGENT and Blender, Unreal and Unity compute, so the map ' +
404
+ 'decodes the same everywhere (N interpolated and normalised, T the interpolated MikkTSpace tangent made ' +
405
+ 'perpendicular to N, B = w · N × T). Misses and a missing input 1 give the flat (0.5, 0.5, 1). glTF and Blender ' +
406
+ 'read OpenGL; Unreal DirectX (or flip green on import).',
388
407
  aliases: ['normal_bake', 'bake_tangent_normal', 'bake_normal_map'],
389
408
  params: {
390
409
  ...BAKE_PARAMS('normal'),
@@ -415,36 +434,37 @@ defineBake({
415
434
  ctx.warn(`${ctx.type}: no high-res mesh on input 1: the map is flat (0.5, 0.5, 1)`);
416
435
  return finish(b, out, 4, [0.5, 0.5, 1, 1]);
417
436
  }
418
- const tan = triangleTangents(b.g, b.uv, b.tris);
419
437
  const dx = p.format === 'directx' ? -1 : 1;
420
- return andThen(onHigh(b, high), (h) => {
421
- for (let i = 0; i < n; i++) {
422
- if (!(h.D[i] === h.D[i]))
423
- continue;
424
- const t = b.s.tri[i];
425
- const nx = b.N[i * 3], ny = b.N[i * 3 + 1], nz = b.N[i * 3 + 2];
426
- let tx = tan.T[t * 3], ty = tan.T[t * 3 + 1], tz = tan.T[t * 3 + 2];
427
- const d = tx * nx + ty * ny + tz * nz;
428
- tx -= nx * d;
429
- ty -= ny * d;
430
- tz -= nz * d;
431
- const tl = Math.hypot(tx, ty, tz);
432
- if (!(tl > 1e-12))
433
- continue;
434
- tx /= tl;
435
- ty /= tl;
436
- tz /= tl;
437
- const sg = tan.sign[t];
438
- const bx = (ny * tz - nz * ty) * sg, by = (nz * tx - nx * tz) * sg, bz = (nx * ty - ny * tx) * sg;
439
- const hx = h.N[i * 3], hy = h.N[i * 3 + 1], hz = h.N[i * 3 + 2];
440
- const u = hx * tx + hy * ty + hz * tz, v = hx * bx + hy * by + hz * bz, w = hx * nx + hy * ny + hz * nz;
441
- const l = Math.hypot(u, v, w) || 1;
442
- out[i * 4] = 0.5 + (0.5 * u) / l;
443
- out[i * 4 + 1] = 0.5 + (0.5 * v * dx) / l;
444
- out[i * 4 + 2] = 0.5 + (0.5 * w) / l;
438
+ const bakeWith = () => {
439
+ // the same vertex normals (cusp 60°) and uv the exporter writes, so the frame matches the exported TANGENT
440
+ const { tangents, diag } = cornerTangents(b.g, b.tris, resolveVertexNormals(b.g, 60), b.uv);
441
+ if (diag.uvDegenerate || diag.uvNonFinite)
442
+ ctx.warn(`${ctx.type}: ${diag.uvDegenerate + diag.uvNonFinite} of ${diag.triangles} triangles have collapsed or non-finite uvs: no tangent frame there (flat texels)`);
443
+ const T = interpolateCorners(b.s, tangents, 4), f = new Float64Array(9);
444
+ const collapsed = new Uint8Array(diag.triangles);
445
+ for (let t = 0; t < diag.triangles; t++) {
446
+ const u0 = b.uv[b.tris[t * 3] * 2], v0 = b.uv[b.tris[t * 3] * 2 + 1];
447
+ const du1 = b.uv[b.tris[t * 3 + 1] * 2] - u0, dv1 = b.uv[b.tris[t * 3 + 1] * 2 + 1] - v0, du2 = b.uv[b.tris[t * 3 + 2] * 2] - u0, dv2 = b.uv[b.tris[t * 3 + 2] * 2 + 1] - v0;
448
+ if (!(Math.abs(du1 * dv2 - du2 * dv1) > 0))
449
+ collapsed[t] = 1;
445
450
  }
446
- return finish(b, out, 4, [0.5, 0.5, 1, 1]);
447
- });
451
+ return andThen(onHigh(b, high), (h) => {
452
+ for (let i = 0; i < n; i++) {
453
+ if (!(h.D[i] === h.D[i]) || collapsed[b.s.tri[i]])
454
+ continue;
455
+ if (!shadingFrame(b.N[i * 3], b.N[i * 3 + 1], b.N[i * 3 + 2], T[i * 4], T[i * 4 + 1], T[i * 4 + 2], T[i * 4 + 3], f))
456
+ continue;
457
+ const hx = h.N[i * 3], hy = h.N[i * 3 + 1], hz = h.N[i * 3 + 2];
458
+ const u = hx * f[0] + hy * f[1] + hz * f[2], v = hx * f[3] + hy * f[4] + hz * f[5], w = hx * f[6] + hy * f[7] + hz * f[8];
459
+ const l = Math.hypot(u, v, w) || 1;
460
+ out[i * 4] = 0.5 + (0.5 * u) / l;
461
+ out[i * 4 + 1] = 0.5 + (0.5 * v * dx) / l;
462
+ out[i * 4 + 2] = 0.5 + (0.5 * w) / l;
463
+ }
464
+ return finish(b, out, 4, [0.5, 0.5, 1, 1]);
465
+ });
466
+ };
467
+ return mikkTSpaceReady() ? bakeWith() : loadMikkTSpace().then(bakeWith);
448
468
  },
449
469
  });
450
470
  defineBake({
@@ -11,8 +11,9 @@ defineNode({
11
11
  'for a chamfer (triangle at a box corner), rings of quads for round bevels (a sphere octant at a box corner). A ' +
12
12
  'bevelled edge ending at an unbevelled point slides its offset along the neighbouring edges and ends flush; two ' +
13
13
  'bevelled edges meeting at a point with one other edge (a cylinder rim) are mitred. Boundary and non-manifold edges ' +
14
- 'are skipped with a warning (chamfering open-mesh boundary edges is out of scope). clamp scales all offsets down just ' +
15
- 'enough that no face edge collapses past another (huge offsets stay clean). Point mode truncates the selected points: ' +
14
+ 'are skipped with a warning (chamfering open-mesh boundary edges is out of scope). clamp shrinks the offsets only ' +
15
+ 'around edges that would cross (huge offsets stay clean; one short edge does not flatten every bevel), and leaves an ' +
16
+ 'edge sharp when a zero-length neighbour leaves no room. Point mode truncates the selected points: ' +
16
17
  'every edge at the point is cut at "offset", the corner becomes a polygon, or a dome of "divisions" rings. Faces keep ' +
17
18
  'their attributes (uv is interpolated inside each face), strips take prim attributes from the larger neighbouring face, ' +
18
19
  'corner patches from the first face around the point; N is recomputed if present. Select edges with patterns: ' +
@@ -29,7 +30,7 @@ defineNode({
29
30
  mode: { type: 'enum', options: ['edges', 'points'], default: 'edges', desc: 'bevel edges, or truncate points', aliases: ['bevel_type', 'class'] },
30
31
  offset: { type: 'float', default: 0.1, min: 0, desc: 'distance from the edge across each adjacent face (points mode: along each edge)', aliases: ['distance', 'width', 'radius', 'size', 'amount'] },
31
32
  offset_mode: { type: 'enum', options: ['distance', 'fraction'], default: 'distance', desc: 'distance = offset in scene units; fraction = offset x the shortest edge at the edge\'s points (stays proportional on small faces)', aliases: ['distance_mode', 'offsetmode'] },
32
- clamp: { type: 'bool', default: true, desc: 'scale all offsets down by one factor, just enough that no bevel crosses its neighbours (Houdini Clamp Offset); warns when it does', aliases: ['clamp_offset', 'clamp_overlap'] },
33
+ clamp: { type: 'bool', default: true, desc: 'shrink the offsets where bevels would cross their neighbours, only at the edges involved (Houdini Clamp Offset, applied locally); warns when it does', aliases: ['clamp_offset', 'clamp_overlap'] },
33
34
  divisions: { type: 'int', default: 0, min: 0, max: 64, desc: '0 = flat chamfer (one strip of quads per edge); n = round profile with n+1 strips', aliases: ['segments', 'divs', 'subdivisions'] },
34
35
  shape: { type: 'float', default: 0, min: -1, max: 1, desc: 'profile convexity for round bevels: 0 = circular arc, 1 = bulges out to a nearly square corner, -0.5 = straight, -1 = concave cove', aliases: ['profile_shape', 'convexity', 'profile'] },
35
36
  },
@@ -229,7 +229,7 @@ defineNode({
229
229
  run.stopped = true;
230
230
  }
231
231
  // what the script returned is user code too: `instanceof` (and Object.getPrototypeOf) run a Proxy's
232
- // getPrototypeOf trap here, outside the time limit, so only the engine's brand check looks at it (R-18)
232
+ // getPrototypeOf trap here, outside the time limit, so only the engine's brand check looks at it
233
233
  const bad = notGeometry(res);
234
234
  if (bad)
235
235
  throw new NodeError(`script must return a Geometry (got ${bad})`, 'return geo, a geometry from lib.run, or one built with lib.GeoBuilder / new lib.Geometry()');
@@ -271,6 +271,13 @@ defineNode({
271
271
  const a = ((a0 + (90 * k) / s) * Math.PI) / 180;
272
272
  pts2.push([cx + r * Math.cos(a), cy + r * Math.sin(a)]);
273
273
  }
274
+ // a radius of half the width or depth makes neighbouring arcs meet: keep their shared end point once
275
+ const eps = 1e-9 * Math.max(hw, hd);
276
+ for (let i = pts2.length - 1; i >= 0 && pts2.length > 3; i--) {
277
+ const q = pts2[(i + 1) % pts2.length];
278
+ if (Math.abs(pts2[i][0] - q[0]) <= eps && Math.abs(pts2[i][1] - q[1]) <= eps)
279
+ pts2.splice(i, 1);
280
+ }
274
281
  break;
275
282
  }
276
283
  case 'ngon':
@@ -463,7 +463,7 @@ defineNode({
463
463
  example: { type: 'point_grid', params: { counts: [10, 1, 10], size: [9, 0, 9], jitter: 0.3, seed: 1 } },
464
464
  cook: ({ p }) => {
465
465
  const [cx, cy, cz] = p.counts;
466
- // each count has a max, but not their product (R-17 N4: a huge grid ran the process out of heap)
466
+ // each count has a max, but not their product (a huge grid ran the process out of heap)
467
467
  if (cx * cy * cz > MAX_GRID_POINTS)
468
468
  throw new NodeError(`point_grid: counts [${cx}, ${cy}, ${cz}] give ${(cx * cy * cz).toLocaleString('en-US')} points, more than ${MAX_GRID_POINTS.toLocaleString('en-US')}`, 'lower the counts, or scatter points instead');
469
469
  const r = rng(p.seed);
@@ -0,0 +1 @@
1
+ export {};