topotopo 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (354) hide show
  1. package/NOTICE +40 -10
  2. package/README.md +475 -111
  3. package/dist/cli.js +328 -133
  4. package/dist/config.d.ts +48 -0
  5. package/dist/config.js +170 -0
  6. package/dist/core/analysis.d.ts +5 -1
  7. package/dist/core/analysis.js +8 -3
  8. package/dist/core/bake.d.ts +16 -8
  9. package/dist/core/bake.js +165 -29
  10. package/dist/core/bevel.d.ts +3 -1
  11. package/dist/core/bevel.js +238 -97
  12. package/dist/core/decimate.d.ts +65 -0
  13. package/dist/core/decimate.js +409 -3
  14. package/dist/core/erosion.d.ts +37 -0
  15. package/dist/core/erosion.js +41 -1
  16. package/dist/core/geometry.d.ts +5 -1
  17. package/dist/core/geometry.js +204 -4
  18. package/dist/core/heightfield.d.ts +27 -4
  19. package/dist/core/heightfield.js +54 -16
  20. package/dist/core/imageops.d.ts +6 -0
  21. package/dist/core/imageops.js +51 -0
  22. package/dist/core/intrinsics.d.ts +7 -0
  23. package/dist/core/intrinsics.js +94 -0
  24. package/dist/core/manifold.d.ts +12 -1
  25. package/dist/core/manifold.js +78 -6
  26. package/dist/core/materials.d.ts +11 -0
  27. package/dist/core/materials.js +56 -0
  28. package/dist/core/noise.d.ts +9 -0
  29. package/dist/core/noise.js +10 -1
  30. package/dist/core/packed.js +11 -0
  31. package/dist/core/particles.d.ts +1 -1
  32. package/dist/core/particles.js +1 -1
  33. package/dist/core/polymerge.d.ts +21 -0
  34. package/dist/core/polymerge.js +327 -0
  35. package/dist/core/rbd.js +13 -1
  36. package/dist/core/repair.d.ts +2 -0
  37. package/dist/core/repair.js +2 -0
  38. package/dist/core/report.d.ts +70 -0
  39. package/dist/core/report.js +275 -0
  40. package/dist/core/scatter.d.ts +1 -1
  41. package/dist/core/scatter.js +1 -1
  42. package/dist/core/scene.d.ts +20 -0
  43. package/dist/core/scene.js +72 -0
  44. package/dist/core/sha256.d.ts +4 -0
  45. package/dist/core/sha256.js +69 -0
  46. package/dist/core/shapes.d.ts +3 -0
  47. package/dist/core/shapes.js +34 -0
  48. package/dist/core/snippet-lib.d.ts +15 -2
  49. package/dist/core/snippet-lib.js +40 -14
  50. package/dist/core/solidify.d.ts +38 -0
  51. package/dist/core/solidify.js +356 -0
  52. package/dist/core/tangents.d.ts +54 -0
  53. package/dist/core/tangents.js +218 -0
  54. package/dist/core/texcoord.d.ts +4 -0
  55. package/dist/core/texcoord.js +14 -0
  56. package/dist/core/texnoise.d.ts +6 -1
  57. package/dist/core/texnoise.js +6 -2
  58. package/dist/core/texsdf.d.ts +131 -0
  59. package/dist/core/texsdf.js +637 -0
  60. package/dist/core/texture.d.ts +163 -9
  61. package/dist/core/texture.js +844 -20
  62. package/dist/core/topology.d.ts +32 -0
  63. package/dist/core/topology.js +238 -7
  64. package/dist/core/traceimage.d.ts +7 -0
  65. package/dist/core/traceimage.js +221 -0
  66. package/dist/core/tritri.d.ts +5 -0
  67. package/dist/core/tritri.js +120 -0
  68. package/dist/core/unwrap.d.ts +72 -0
  69. package/dist/core/unwrap.js +800 -0
  70. package/dist/core/usercode.d.ts +27 -0
  71. package/dist/core/usercode.js +87 -0
  72. package/dist/core/uv.d.ts +15 -16
  73. package/dist/core/uv.js +36 -189
  74. package/dist/core/uvislands.d.ts +62 -0
  75. package/dist/core/uvislands.js +574 -0
  76. package/dist/core/uvoverlap.d.ts +58 -0
  77. package/dist/core/uvoverlap.js +220 -0
  78. package/dist/core/uvpack.d.ts +64 -0
  79. package/dist/core/uvpack.js +628 -0
  80. package/dist/core/uvreport.d.ts +127 -0
  81. package/dist/core/uvreport.js +372 -0
  82. package/dist/core/wrangle.d.ts +6 -1
  83. package/dist/core/wrangle.js +27 -16
  84. package/dist/core/xatlas.d.ts +16 -1
  85. package/dist/core/xatlas.js +95 -61
  86. package/dist/engines.d.ts +63 -0
  87. package/dist/engines.js +180 -0
  88. package/dist/explain.d.ts +4 -3
  89. package/dist/explain.js +129 -12
  90. package/dist/graph/engine.d.ts +92 -29
  91. package/dist/graph/engine.js +298 -148
  92. package/dist/graph/expr.d.ts +6 -3
  93. package/dist/graph/expr.js +18 -8
  94. package/dist/graph/outputs.d.ts +23 -0
  95. package/dist/graph/outputs.js +41 -0
  96. package/dist/graph/packages.d.ts +72 -0
  97. package/dist/graph/packages.js +261 -0
  98. package/dist/graph/parallel.d.ts +3 -1
  99. package/dist/graph/parallel.js +4 -1
  100. package/dist/graph/params.d.ts +6 -0
  101. package/dist/graph/params.js +34 -7
  102. package/dist/graph/scope.d.ts +55 -0
  103. package/dist/graph/scope.js +14 -0
  104. package/dist/graph/types.d.ts +75 -12
  105. package/dist/graph/types.js +4 -2
  106. package/dist/graph/vars.d.ts +16 -0
  107. package/dist/graph/vars.js +80 -0
  108. package/dist/host/artifacts.d.ts +10 -1
  109. package/dist/host/artifacts.js +37 -6
  110. package/dist/host/cook.d.ts +241 -0
  111. package/dist/host/cook.js +844 -0
  112. package/dist/host/export-targets.d.ts +42 -5
  113. package/dist/host/export-targets.js +72 -13
  114. package/dist/host/godot-commands.d.ts +4 -0
  115. package/dist/host/godot-commands.js +21 -0
  116. package/dist/host/godot.d.ts +183 -0
  117. package/dist/host/godot.js +916 -0
  118. package/dist/host/node.d.ts +12 -7
  119. package/dist/host/node.js +27 -9
  120. package/dist/host/pool.js +51 -2
  121. package/dist/host/sidecars.d.ts +8 -0
  122. package/dist/host/sidecars.js +50 -0
  123. package/dist/host/types.d.ts +19 -6
  124. package/dist/host/version.d.ts +1 -0
  125. package/dist/host/version.js +3 -0
  126. package/dist/host/worker.js +5 -2
  127. package/dist/index.d.ts +5 -3
  128. package/dist/index.js +3 -2
  129. package/dist/inspect.d.ts +84 -1
  130. package/dist/inspect.js +271 -24
  131. package/dist/io/common.d.ts +33 -5
  132. package/dist/io/export.js +2 -1
  133. package/dist/io/files.d.ts +23 -4
  134. package/dist/io/files.js +60 -8
  135. package/dist/io/gltf.js +355 -51
  136. package/dist/io/heightmap.d.ts +3 -0
  137. package/dist/io/heightmap.js +1 -0
  138. package/dist/io/import.js +10 -0
  139. package/dist/io/inspect-scene.d.ts +55 -0
  140. package/dist/io/inspect-scene.js +155 -0
  141. package/dist/io/kinds.d.ts +81 -0
  142. package/dist/io/kinds.js +163 -0
  143. package/dist/io/points.d.ts +2 -1
  144. package/dist/io/points.js +3 -1
  145. package/dist/io/sidecars.d.ts +24 -0
  146. package/dist/io/sidecars.js +57 -0
  147. package/dist/io/source.d.ts +65 -0
  148. package/dist/io/source.js +112 -0
  149. package/dist/io/targets.d.ts +47 -3
  150. package/dist/io/targets.js +149 -14
  151. package/dist/io/textures.js +21 -1
  152. package/dist/io/unreal.js +5 -1
  153. package/dist/mcp/docs.d.ts +10 -1
  154. package/dist/mcp/docs.js +816 -119
  155. package/dist/mcp/inputs.d.ts +12 -5
  156. package/dist/mcp/inputs.js +50 -13
  157. package/dist/mcp/server.js +70 -24
  158. package/dist/mcp/tools.d.ts +14 -7
  159. package/dist/mcp/tools.js +207 -108
  160. package/dist/mcp/verify.d.ts +2 -2
  161. package/dist/mcp/verify.js +1 -1
  162. package/dist/mcp/workspace.d.ts +15 -0
  163. package/dist/mcp/workspace.js +349 -0
  164. package/dist/nodes/attributes.js +198 -1
  165. package/dist/nodes/bake.js +207 -83
  166. package/dist/nodes/beam.d.ts +1 -0
  167. package/dist/nodes/beam.js +201 -0
  168. package/dist/nodes/bevel.js +54 -5
  169. package/dist/nodes/cloth.js +2 -0
  170. package/dist/nodes/code.js +22 -10
  171. package/dist/nodes/curves.js +440 -93
  172. package/dist/nodes/flow.js +53 -33
  173. package/dist/nodes/generate.js +13 -39
  174. package/dist/nodes/heightfield.js +248 -77
  175. package/dist/nodes/imageops.d.ts +1 -0
  176. package/dist/nodes/imageops.js +203 -0
  177. package/dist/nodes/index.d.ts +4 -0
  178. package/dist/nodes/index.js +4 -0
  179. package/dist/nodes/material.js +91 -23
  180. package/dist/nodes/measure.js +45 -18
  181. package/dist/nodes/particles.js +2 -0
  182. package/dist/nodes/pcg.js +6 -5
  183. package/dist/nodes/procedural.js +4 -3
  184. package/dist/nodes/rbd.js +1 -1
  185. package/dist/nodes/remesh.js +71 -15
  186. package/dist/nodes/scene.d.ts +1 -0
  187. package/dist/nodes/scene.js +55 -0
  188. package/dist/nodes/sdf.js +10 -5
  189. package/dist/nodes/solid.js +20 -5
  190. package/dist/nodes/solidify.d.ts +1 -0
  191. package/dist/nodes/solidify.js +52 -0
  192. package/dist/nodes/splines.d.ts +15 -1
  193. package/dist/nodes/splines.js +112 -105
  194. package/dist/nodes/texture.d.ts +21 -6
  195. package/dist/nodes/texture.js +1318 -185
  196. package/dist/nodes/topology.d.ts +7 -0
  197. package/dist/nodes/topology.js +133 -6
  198. package/dist/nodes/transform.js +11 -3
  199. package/dist/nodes/util.d.ts +1 -1
  200. package/dist/nodes/uv.js +192 -174
  201. package/dist/nodes/wasmcall.js +6 -2
  202. package/dist/open.d.ts +19 -0
  203. package/dist/open.js +12 -0
  204. package/dist/package.d.ts +288 -0
  205. package/dist/package.js +772 -0
  206. package/dist/packages/check.d.ts +32 -0
  207. package/dist/packages/check.js +169 -0
  208. package/dist/packages/commands.d.ts +57 -0
  209. package/dist/packages/commands.js +537 -0
  210. package/dist/packages/registry.d.ts +796 -0
  211. package/dist/packages/registry.js +2998 -0
  212. package/dist/packages/update.d.ts +124 -0
  213. package/dist/packages/update.js +476 -0
  214. package/dist/render/options.d.ts +2 -0
  215. package/dist/render/options.js +44 -5
  216. package/dist/render/pbr.d.ts +28 -0
  217. package/dist/render/pbr.js +378 -0
  218. package/dist/render/preview.d.ts +69 -0
  219. package/dist/render/preview.js +26 -0
  220. package/dist/render/raster.d.ts +78 -7
  221. package/dist/render/raster.js +600 -145
  222. package/dist/render/texview.d.ts +7 -1
  223. package/dist/render/texview.js +34 -2
  224. package/dist/scan.d.ts +61 -0
  225. package/dist/scan.js +228 -0
  226. package/dist/session.d.ts +311 -0
  227. package/dist/session.js +849 -0
  228. package/dist/viewer/app/api.js +48 -6
  229. package/dist/viewer/app/camera.js +1 -1
  230. package/dist/viewer/app/cooking.js +78 -0
  231. package/dist/viewer/app/embed.js +100 -0
  232. package/dist/viewer/app/export-popover.js +118 -16
  233. package/dist/viewer/app/grid.js +6 -2
  234. package/dist/viewer/app/guides.js +123 -1
  235. package/dist/viewer/app/keymap.js +7 -4
  236. package/dist/viewer/app/layers.js +5 -5
  237. package/dist/viewer/app/main.js +186 -53
  238. package/dist/viewer/app/markers.js +61 -1
  239. package/dist/viewer/app/outliner.js +72 -27
  240. package/dist/viewer/app/output-info.js +45 -0
  241. package/dist/viewer/app/outputs.css +147 -8
  242. package/dist/viewer/app/outputs.js +168 -54
  243. package/dist/viewer/app/packages.js +614 -0
  244. package/dist/viewer/app/props.js +177 -53
  245. package/dist/viewer/app/scene.js +35 -6
  246. package/dist/viewer/app/select.js +5 -4
  247. package/dist/viewer/app/selection.js +1 -1
  248. package/dist/viewer/app/status.js +12 -15
  249. package/dist/viewer/app/style.css +66 -8
  250. package/dist/viewer/app/units.js +1 -1
  251. package/dist/viewer/app/vars.js +48 -1
  252. package/dist/viewer/app/welcome.js +72 -0
  253. package/dist/viewer/graph-file.d.ts +62 -0
  254. package/dist/viewer/graph-file.js +175 -0
  255. package/dist/viewer/index.html +24 -11
  256. package/dist/viewer/json-edit.d.ts +13 -0
  257. package/dist/viewer/json-edit.js +274 -0
  258. package/dist/viewer/outputs.d.ts +49 -5
  259. package/dist/viewer/outputs.js +264 -56
  260. package/dist/viewer/packages.d.ts +121 -0
  261. package/dist/viewer/packages.js +584 -0
  262. package/dist/viewer/server.d.ts +24 -7
  263. package/dist/viewer/server.js +289 -31
  264. package/dist/web/app/web.css +419 -0
  265. package/dist/web/app/web.js +188 -0
  266. package/dist/web/bake.d.ts +34 -0
  267. package/dist/web/bake.js +153 -0
  268. package/dist/web/folder-page.d.ts +101 -0
  269. package/dist/web/folder-page.js +146 -0
  270. package/dist/web/folders.d.ts +280 -0
  271. package/dist/web/folders.js +970 -0
  272. package/dist/web/library.d.ts +91 -0
  273. package/dist/web/library.js +228 -0
  274. package/dist/web/markdown.d.ts +45 -0
  275. package/dist/web/markdown.js +677 -0
  276. package/dist/web/pages.d.ts +258 -0
  277. package/dist/web/pages.js +301 -0
  278. package/dist/web/server.d.ts +24 -0
  279. package/dist/web/server.js +1068 -0
  280. package/dist/workspace.d.ts +88 -105
  281. package/dist/workspace.js +359 -375
  282. package/integrations/godot/addons/topotopo/LICENSE +202 -0
  283. package/integrations/godot/addons/topotopo/README.md +57 -0
  284. package/integrations/godot/addons/topotopo/context_menu.gd +43 -0
  285. package/integrations/godot/addons/topotopo/dock.gd +266 -0
  286. package/integrations/godot/addons/topotopo/dock.tscn +72 -0
  287. package/integrations/godot/addons/topotopo/export_filter.gd +72 -0
  288. package/integrations/godot/addons/topotopo/gltf_instancing.gd +131 -0
  289. package/integrations/godot/addons/topotopo/icons/topotopo.svg +1 -0
  290. package/integrations/godot/addons/topotopo/inspector.gd +38 -0
  291. package/integrations/godot/addons/topotopo/instances_post_import.gd +111 -0
  292. package/integrations/godot/addons/topotopo/package.gd +23 -0
  293. package/integrations/godot/addons/topotopo/package_importer.gd +187 -0
  294. package/integrations/godot/addons/topotopo/plugin.cfg +7 -0
  295. package/integrations/godot/addons/topotopo/plugin.gd +970 -0
  296. package/integrations/godot/addons/topotopo/record.gd +435 -0
  297. package/integrations/godot/addons/topotopo/runner.gd +458 -0
  298. package/integrations/godot/addons/topotopo/tools/check.gd +42 -0
  299. package/integrations/godot/addons/topotopo/watcher.gd +199 -0
  300. package/kernels/pkg/README.md +23 -29
  301. package/kernels/pkg-simd/README.md +23 -29
  302. package/library/architecture/versions/1.0/architecture.topo +12 -0
  303. package/{shelf → library/architecture/versions/1.0/graphs}/arch.json +3 -3
  304. package/{shelf → library/architecture/versions/1.0/graphs}/beam_truss.json +6 -6
  305. package/{shelf → library/architecture/versions/1.0/graphs}/brick_wall.json +8 -8
  306. package/{shelf → library/architecture/versions/1.0/graphs}/door_frame.json +3 -3
  307. package/{shelf → library/architecture/versions/1.0/graphs}/hex_grid_floor.json +3 -2
  308. package/{shelf → library/architecture/versions/1.0/graphs}/house.json +8 -8
  309. package/library/architecture/versions/1.0/graphs/lineup.json +42 -0
  310. package/{shelf → library/architecture/versions/1.0/graphs}/pillar.json +3 -2
  311. package/{shelf → library/architecture/versions/1.0/graphs}/railing.json +5 -5
  312. package/{shelf → library/architecture/versions/1.0/graphs}/roof_gable.json +2 -2
  313. package/{shelf → library/architecture/versions/1.0/graphs}/roof_hip.json +2 -2
  314. package/{shelf → library/architecture/versions/1.0/graphs}/roof_skeleton.json +2 -1
  315. package/{shelf → library/architecture/versions/1.0/graphs}/scaffold.json +4 -4
  316. package/{shelf → library/architecture/versions/1.0/graphs}/spiral_stairs.json +3 -2
  317. package/{shelf → library/architecture/versions/1.0/graphs}/stairs.json +6 -6
  318. package/{shelf → library/architecture/versions/1.0/graphs}/tile_floor.json +3 -2
  319. package/{shelf → library/architecture/versions/1.0/graphs}/wall_segment.json +10 -10
  320. package/{shelf → library/architecture/versions/1.0/graphs}/window_frame.json +2 -2
  321. package/library/architecture/versions/1.0/version.json +1119 -0
  322. package/{shelf → library/nature/versions/1.0/graphs}/bush.json +2 -2
  323. package/{shelf → library/nature/versions/1.0/graphs}/cliff_block.json +4 -3
  324. package/{shelf → library/nature/versions/1.0/graphs}/forest_patch.json +5 -5
  325. package/{shelf → library/nature/versions/1.0/graphs}/grass_clumps.json +2 -2
  326. package/library/nature/versions/1.0/graphs/lineup.json +24 -0
  327. package/{shelf → library/nature/versions/1.0/graphs}/log.json +6 -6
  328. package/{shelf → library/nature/versions/1.0/graphs}/rock.json +5 -4
  329. package/{shelf → library/nature/versions/1.0/graphs}/scatter_rocks.json +5 -5
  330. package/{shelf → library/nature/versions/1.0/graphs}/tree_lowpoly.json +3 -2
  331. package/library/nature/versions/1.0/nature.topo +12 -0
  332. package/library/nature/versions/1.0/version.json +534 -0
  333. package/{shelf → library/props/versions/1.0/graphs}/barrel.json +5 -4
  334. package/{shelf → library/props/versions/1.0/graphs}/crate.json +3 -3
  335. package/library/props/versions/1.0/graphs/lineup.json +18 -0
  336. package/{shelf → library/props/versions/1.0/graphs}/pallet.json +4 -3
  337. package/{shelf → library/props/versions/1.0/graphs}/pipe_run.json +3 -3
  338. package/{shelf → library/props/versions/1.0/graphs}/sandbag_wall.json +5 -5
  339. package/library/props/versions/1.0/props.topo +12 -0
  340. package/library/props/versions/1.0/version.json +336 -0
  341. package/{shelf → library/street/versions/1.0/graphs}/bench.json +5 -5
  342. package/{shelf → library/street/versions/1.0/graphs}/bollard.json +2 -1
  343. package/{shelf → library/street/versions/1.0/graphs}/cable.json +4 -4
  344. package/{shelf → library/street/versions/1.0/graphs}/fence.json +7 -7
  345. package/{shelf → library/street/versions/1.0/graphs}/lamp_post.json +2 -2
  346. package/library/street/versions/1.0/graphs/lineup.json +22 -0
  347. package/{shelf → library/street/versions/1.0/graphs}/road_strip.json +2 -2
  348. package/{shelf → library/street/versions/1.0/graphs}/sign_post.json +1 -1
  349. package/library/street/versions/1.0/street.topo +12 -0
  350. package/library/street/versions/1.0/version.json +421 -0
  351. package/package.json +23 -8
  352. package/dist/graph/migrate.d.ts +0 -23
  353. package/dist/graph/migrate.js +0 -58
  354. package/shelf/index.json +0 -190
@@ -1,3 +1,3 @@
1
- import type { Workspace } from '../workspace.ts';
1
+ import type { Session } from '../session.ts';
2
2
  import type { ToolDef } from './tools.ts';
3
- export declare function verifyTools(ws: Workspace): ToolDef[];
3
+ export declare function verifyTools(ws: Session): ToolDef[];
@@ -54,7 +54,7 @@ export function verifyTools(ws) {
54
54
  },
55
55
  {
56
56
  name: 'diff',
57
- description: 'Compare two geometries (two graphs, two nodes of one graph, or two frames) to see what a change did: point/prim counts, bbox delta, topology and volume, attribute schema and group changes, symmetric Hausdorff and mean surface distance (sampled, BVH), per-point displacement when point counts match, and a one-line verdict. render:true adds a quad-view overlay PNG: grey = unchanged, blue = only in b (moved or new), orange = only in a. Tip: graphs {action:"duplicate"} before an edit, then diff the copy against the edited graph.',
57
+ description: 'Compare two geometries (two graphs, two nodes of one graph, or two frames) to see what a change did: point/prim counts, bbox delta, topology and volume, attribute schema and group changes, heightfields, images and SDF grids sample by sample, symmetric Hausdorff and mean surface distance (sampled, BVH), per-point displacement when point counts match, and a one-line verdict. render:true adds a quad-view overlay PNG: grey = unchanged, blue = only in b (moved or new), orange = only in a. Tip: graphs {action:"duplicate"} before an edit, then diff the copy against the edited graph.',
58
58
  inputSchema: {
59
59
  type: 'object',
60
60
  required: ['a', 'b'],
@@ -0,0 +1,15 @@
1
+ import type { Session } from '../session.ts';
2
+ import type { ToolDef } from './tools.ts';
3
+ import type { PackageUses } from '../packages/registry.ts';
4
+ export interface WorkspaceToolHost {
5
+ /** the session the other tools use now (its folder, graphs, assets and engine) */
6
+ session(): Session;
7
+ /** the packages used by the package that holds the session's folder */
8
+ packages(): PackageUses;
9
+ /** make a folder the one every tool (and the live viewer) works in */
10
+ open(dir: string): Promise<{
11
+ graphs: number;
12
+ assets: number;
13
+ }>;
14
+ }
15
+ export declare function workspaceTool(host: WorkspaceToolHost): ToolDef;
@@ -0,0 +1,349 @@
1
+ // The `workspace` tool: the workspace around the open package (its packages, found by scanning it, and the shared
2
+ // libraries it lists), the person's registered workspaces and libraries (src/web/library.ts), and the packages the open
3
+ // package uses (src/packages/registry.ts, src/packages/update.ts). An agent lists and searches them, reads a package,
4
+ // makes new ones, edits their manifest (<id>.topo), bakes previews, and opens a package: the server's folder becomes
5
+ // that package's folder, so build/edit/render/export work on it; or it makes the server's folder a package (init), when
6
+ // the person says so: only a package's graphs use packages. In the open package it publishes a version (or a dry run of
7
+ // one), searches the outputs of every place it looks in and says which the package can use, lists and adds the
8
+ // packages it uses, follows a package's working folder for the session, says which packages are out of date, and shows
9
+ // the before/after of an update, which it applies only when the person says so. It changes the shared libraries the
10
+ // workspace lists when the person says so; registering a library stays the person's act (the CLI).
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { loadConfig } from '../config.js';
14
+ import { initPackage, locate, manifestFile, oldManifestAbove, ownPackageName, parseManifest, program, packageDirOf, packageId, readManifest, withPackageLock, within, writeManifest } from '../package.js';
15
+ import { createPackage, graphNames, isStale, listFiles, placeNamed, readBakeState, readGraph, scanAll, scanLibrary, workspaceRef } from '../web/library.js';
16
+ import { KINDS } from '../graph/outputs.js';
17
+ import { NothingToUpdate, packageText, packagesText, publishPackage, publishText, searchPackages, searchText } from '../packages/registry.js';
18
+ import { applyUpdate, beforeAfter, beforeAfterText, outdatedText, overlayRenders, removePackage } from '../packages/update.js';
19
+ const text = (t, isError = false) => ({ content: [{ type: 'text', text: t }], ...(isError ? { isError } : {}) });
20
+ export function workspaceTool(host) {
21
+ /**
22
+ * The registered libraries and workspaces, scanned, and the open package's workspace when it is not registered
23
+ * (its packages are found by name as a workspace's: {library: "<workspace name>", id}).
24
+ */
25
+ const scan = () => {
26
+ const cfg = loadConfig(), scans = scanAll(cfg);
27
+ const places = [...cfg.libraries.filter((l) => !cfg.workspaces.some((w) => within(l.path, w.path))), ...cfg.workspaces.map(workspaceRef)];
28
+ const ws = locate(host.session().dir).workspace;
29
+ if (ws && !scans.some((s) => s.workspace && path.resolve(s.root) === path.resolve(ws))) {
30
+ const ref = workspaceRef({ name: path.basename(ws), path: ws });
31
+ scans.push(scanLibrary(ref));
32
+ places.push(ref);
33
+ }
34
+ return { cfg, scans, places };
35
+ };
36
+ const urlsOf = (cfg, p) => {
37
+ const b = `http://127.0.0.1:${cfg.web.port}`;
38
+ return { page: `${b}/p/${p.lib}/${p.id}`, embed: `${b}/embed/${p.lib}/${p.id}`, thumb: `${b}/p/${p.lib}/${p.id}/thumb.png` };
39
+ };
40
+ const currentDir = () => packageDirOf(host.session().dir);
41
+ const statusOf = (p) => { const s = readBakeState(p.dir); return !s ? 'not baked' : !s.ok ? 'bake failed' : isStale(p) ? 'stale' : 'baked'; };
42
+ /**
43
+ * {library, id}, {path}, or nothing (the open package). The libraries are scanned for an id; for a folder, only to
44
+ * name the library it is in (a config that cannot be read leaves that out).
45
+ */
46
+ const pick = (a, scans) => {
47
+ if (a.id) {
48
+ const hits = scans().flatMap((s) => s.packages).filter((p) => p.id === a.id && (!a.library || p.lib === a.library));
49
+ if (hits.length === 1)
50
+ return hits[0];
51
+ // two folders of one place holding the id (the scan said so): "library" cannot tell them apart, their folders can
52
+ const places = [...new Set(hits.map((p) => p.lib))];
53
+ if (hits.length > 1 && places.length === 1)
54
+ throw new Error(`id "${a.id}" is used by ${hits.length} folders of "${places[0]}": ${hits.map((p) => p.rel).join(', ')} (rename one's .topo file); give {path} for one`);
55
+ if (hits.length > 1)
56
+ throw new Error(`id "${a.id}" is in several libraries (${places.join(', ')}): give "library"`);
57
+ throw new Error(`no package "${a.id}"${a.library ? ` in "${a.library}"` : ''}. workspace {action:"list"} lists them`);
58
+ }
59
+ const dir = a.path ? packageDirOf(path.resolve(a.path)) : currentDir();
60
+ if (!dir)
61
+ throw new Error(a.path ? `${a.path}: no .topo file there or above${oldManifestAbove(path.resolve(a.path))}` : `give {library, id}: the server's folder is in no package (workspace {action:"init"} makes it one, when the person says so)${oldManifestAbove(host.session().dir)}`);
62
+ let all = [];
63
+ try {
64
+ all = scans().flatMap((s) => s.packages);
65
+ }
66
+ catch { /* named without its library */ }
67
+ const p = all.find((x) => x.dir === dir);
68
+ if (p)
69
+ return p;
70
+ // a package folder outside the configured libraries still works
71
+ return { lib: '', id: packageId(dir), dir, rel: path.basename(dir), collection: '', manifest: readManifest(dir), updated: 0 };
72
+ };
73
+ return {
74
+ name: 'workspace',
75
+ description: 'Three words: a workspace is a folder tree (topotopo-workspace.json at its root; best inside the engine\'s content folder: the Godot project folder, Unreal\'s Content/); a package is a folder of graphs and the models they make, marked by one <id>.topo file, and every folder of a workspace with one is a package of it; a library is a registered folder of packages shared across workspaces, which a workspace lists to use it (TopoTopo ships one built in, always there). Packages in a workspace find each other by themselves; outside a workspace a package finds packages in every registered library. This tool works on the workspace around the open package, the person\'s registered workspaces and libraries (the web app shows them; a board links to them) and the packages the open package uses and publishes. A package holds <id>.topo (title, description, tags, links to concept art and board pages) and its own graphs/, assets/, inputs/, exports/ and attachments/ (concept art and references). ' +
76
+ 'list {query?, tag?, library?}: every package of the registered libraries and workspaces (and of the open package\'s workspace) with status and web app URL. get {library, id} (or the open package; library: a library\'s or a workspace\'s name): manifest, graphs and vars, attachments, exports, bake state, URLs; thumbnail:true adds the baked image. ' +
77
+ 'open {library, id} | {path}: make that package the folder every tool and the live viewer work in, then build/edit/render/export work in it. create {library, path:"props/lantern", title?, description?, tags?, links?}: a new package in a library or a workspace (by its name), opened. ' +
78
+ 'show: the workspace around the open package: its engine project, the shared libraries it lists, its packages. libraries {add?, remove?}: the shared libraries the open package\'s workspace lists (topotopo-workspace.json "libraries"); with neither, what it lists and where its packages find packages; add / remove a registered library\'s name or a folder outside the workspace (a relative path is read from the server\'s folder), only when the person names the library (registering a new library is the person\'s own act: topotopo library add <name> <folder>). init_workspace {path, name?, engine?, libraries?, follow?} makes a folder (path: its root, as the person names it) a workspace (topotopo-workspace.json; the engine project at or above it found, else one below; its packages then share one copy of each package, in topotopo-packages/, and their own copies move there), when the person says so. ' +
79
+ 'init {name?}: make the server\'s folder a package (<id>.topo, graphs/main.json, .gitignore, .gitattributes), when it is none and the person says so: only a package\'s graphs use packages (TopoTopo\'s own included), and a build outside any package that names one fails saying so. ' +
80
+ 'set {library?, id?, title?, description?, tags?, links?, graph?, bake?, name?}: edit the manifest (graph = the graph its page shows; bake = {graph?, node?, frame?} what its preview shows; name = "owner/name", the name the package publishes under, set once by its author). bake {library?, id?}: render thumb.png and preview.glb now (the web app also bakes on its own after changes). ' +
81
+ `The packages of the open package: packages (what it uses and can use, one line each: version, outputs, up to date or the newer version that is out, the place that has it), packages {package} (one package: its versions and notes, its outputs with their kinds, tags, params and inputs); search {query?, kind?, tag?}: the outputs of every place the package looks in (its workspace, the shared libraries the workspace lists, TopoTopo\'s built-in one; outside a workspace every registered library) by words, kind (${KINDS.join(', ')}) and tag, each with its full name, kind, tags, label, version and description, and whether the package can use it; in a workspace also the registered libraries it does not list, with the libraries action that would list one; use {package:"owner/name", version?} adds one (a graph that names "owner/name/output" adds it too); remove {package} removes one no graph of the package names; follow {package, on} uses a package\'s working folder instead of its copy for this session. ` +
82
+ 'publish {dry_run:true, note?, big?} is a dry run: every check and cook, the version number it would get, its changes, blocks and warnings, nothing written. Publishing is permanent: run the dry run first, show it to the person, and publish {note, big?} only when they say so. ' +
83
+ 'outdated: the packages it uses that have newer versions, with their notes, and one line for those up to date. check: cook what the workspace relies on (the newest version of its packages that publish, every graph of the others, the newest versions in the shared libraries it lists; outside a workspace the package and its library), and list what broke and why; it changes nothing but missing .gdignore files (after a TopoTopo update, say). update {package, to?}: the before/after of updating it (to the newest version with the same big number; a big version needs "to"): every place the package uses it, cooked with the version in use and the new one, what changed in each, overlay renders, the notes of the versions between and, for a big version, what the graphs must change. It writes nothing. Show the before/after to the person and apply it only when they say so: update {package, from, to, apply:true} (the versions of the before/after they saw) copies the new version in, updates the uses and the lock, and deletes the copies nothing uses any more. See help topics "workspace" and "packages".',
84
+ inputSchema: {
85
+ type: 'object',
86
+ required: ['action'],
87
+ properties: {
88
+ action: { type: 'string', enum: ['list', 'get', 'open', 'create', 'init', 'init_workspace', 'show', 'libraries', 'set', 'bake', 'packages', 'search', 'use', 'remove', 'follow', 'publish', 'outdated', 'check', 'update'] },
89
+ library: { type: 'string', description: 'a library\'s or a workspace\'s name (list shows them)' },
90
+ id: { type: 'string', description: 'package id' },
91
+ path: { type: 'string', description: 'create: folder below the library ("props/lantern"); open/get: a package folder on disk instead of {library, id}' },
92
+ query: { type: 'string', description: 'list: words to match in title, id, collection, description, tags; search: words each of which must start a word of a published output\'s full name, label, description or tags, or of its package\'s title or package tags' },
93
+ tag: { type: 'string', description: 'list: only packages with this tag; search: only outputs with this tag' },
94
+ kind: { type: 'string', enum: [...KINDS], description: 'search: only outputs of this kind' },
95
+ dry_run: { type: 'boolean', description: 'publish: a dry run, which writes nothing: every check, every output cooked, the version number it would get, the changes, blocks and warnings' },
96
+ libraries: { type: 'array', items: { type: 'string' }, description: 'init_workspace: the shared libraries the new workspace lists, as the person names them: registered names, or folders outside the workspace (read from the server\'s folder)' },
97
+ add: { type: 'string', description: 'libraries: a shared library for the workspace to list: a registered library\'s name, or a folder outside the workspace (a relative path is read from the server\'s folder)' },
98
+ version: { type: 'string', description: 'use: the version to add, such as "1.1" (default: the newest)' },
99
+ from: { type: 'string', description: 'update with apply: the version in use when the person saw the before/after' },
100
+ title: { type: 'string' },
101
+ description: { type: 'string' },
102
+ tags: { type: 'array', items: { type: 'string' } },
103
+ links: { type: 'array', items: { type: 'object', properties: { label: { type: 'string' }, url: { type: 'string' } }, required: ['url'] }, description: 'links back to the board, concept pages, tickets' },
104
+ graph: { type: 'string', description: 'set: the graph its page shows and bakes (default "main")' },
105
+ bake: { type: 'object', properties: { graph: { type: 'string' }, node: { type: 'string' }, frame: { type: 'number' } }, description: 'set: what the preview shows instead of the graph output' },
106
+ thumbnail: { type: 'boolean', description: 'get: include the baked thumbnail image' },
107
+ name: { type: 'string', description: 'init_workspace: the workspace\'s name (default: the folder\'s); set and init: the name the package publishes under, "owner/name"' },
108
+ engine: { type: 'string', description: 'init_workspace: the engine project, "godot:../project.godot" or "unreal:../../Game.uproject" from the workspace folder, or "none" (default: the one at or above the folder, else the one found below it)' },
109
+ follow: { type: 'boolean', description: 'init_workspace: true shows the workspace\'s own packages live from their working folders, for looking (exports use the published versions); false stops it' },
110
+ open: { type: 'boolean', description: 'create: open the new package (default true)' },
111
+ package: { type: 'string', description: 'use / remove / follow / update / packages: a package, "owner/name"' },
112
+ remove: { type: 'string', description: 'libraries: a shared library the workspace lists, to unlist: its entry, its registered name or its folder' },
113
+ on: { type: 'boolean', description: 'follow: true to follow the package\'s working folder (default), false to go back to its copy' },
114
+ note: { type: 'string', description: 'publish: one line on what changed (required)' },
115
+ big: { type: 'boolean', description: 'publish: mark the version big (its meaning changed in a way the tools cannot see)' },
116
+ to: { type: 'string', description: 'update: the version to go to, such as "2.0" (default: the newest with the same big number); apply needs it, with "from"' },
117
+ apply: { type: 'boolean', description: 'update: apply it, once the person saw the before/after and said so (default false: show the before/after); needs "from" and "to"' },
118
+ },
119
+ },
120
+ run: async (a, call) => {
121
+ // the registered libraries are read and scanned only by the actions on them: a broken config or a slow library
122
+ // does not stand in the way of the packages the open package uses
123
+ let scanned = null;
124
+ const libs = () => (scanned ??= scan());
125
+ // the packages of the open package as its files are now (a person may have edited its manifest)
126
+ if (['packages', 'search', 'use', 'remove', 'follow', 'publish', 'outdated', 'update', 'libraries'].includes(a.action))
127
+ host.packages().refresh();
128
+ switch (a.action) {
129
+ case 'list': {
130
+ const { cfg, scans } = libs();
131
+ if (!scans.length)
132
+ return text(`no libraries or workspaces registered (${cfg.file}), and the open package is in no workspace. The person registers one with \`${program()} library add <name> <folder>\` or \`${program()} workspace add <folder>\`.`);
133
+ const cur = currentDir();
134
+ const words = String(a.query ?? '').toLowerCase().split(/\s+/).filter(Boolean);
135
+ const lines = [];
136
+ for (const s of scans) {
137
+ if (a.library && s.name !== a.library)
138
+ continue;
139
+ const ps = s.packages.filter((p) => {
140
+ const m = p.manifest, hay = [m.title, p.id, p.collection, m.description, ...m.tags].join(' ').toLowerCase();
141
+ return words.every((w) => hay.includes(w)) && (!a.tag || m.tags.includes(a.tag));
142
+ });
143
+ lines.push(`${s.workspace ? 'workspace' : 'library'} "${s.name}" (${s.root}): ${ps.length}${ps.length !== s.packages.length ? ` of ${s.packages.length}` : ''} packages`);
144
+ for (const p of ps)
145
+ 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}`);
146
+ for (const pr of s.problems)
147
+ lines.push(` ! ${pr}`);
148
+ }
149
+ return text(lines.join('\n') || 'no library matches');
150
+ }
151
+ case 'get': {
152
+ const { cfg } = libs(), p = pick(a, () => libs().scans), m = p.manifest, s = readBakeState(p.dir), u = urlsOf(cfg, p);
153
+ const graphs = graphNames(p.dir).map((n) => {
154
+ const g = readGraph(p.dir, n) ?? {};
155
+ const vars = Object.entries(g.vars ?? {}).map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(', ');
156
+ return ` ${n}${n === m.graph ? ' (shown)' : ''}: ${Object.keys(g.nodes ?? {}).length} nodes${vars ? `; vars ${vars}` : ''}`;
157
+ });
158
+ const att = listFiles(path.join(p.dir, 'attachments')), exp = listFiles(path.join(p.dir, 'exports'));
159
+ const lines = [
160
+ `package ${p.lib ? `${p.lib}/` : ''}${p.id}: "${m.title}"${p.dir === currentDir() ? ' (open)' : ''}`,
161
+ `folder ${p.dir}`,
162
+ ...(m.description ? [`description: ${m.description}`] : []),
163
+ ...(m.tags.length ? [`tags: ${m.tags.join(', ')}`] : []),
164
+ ...(m.links.length ? ['links:', ...m.links.map((l) => ` ${l.label}: ${l.url}`)] : []),
165
+ `graphs (${graphs.length}):`, ...(graphs.length ? graphs : [' none yet']),
166
+ ...(att.length ? [`attachments/ (${att.length}): ${att.slice(0, 30).map((f) => f.path).join(', ')}${att.length > 30 ? ', …' : ''}`] : []),
167
+ ...(exp.length ? [`exports/ (${exp.length}): ${exp.slice(0, 30).map((f) => f.path).join(', ')}${exp.length > 30 ? ', …' : ''}`] : []),
168
+ `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)}` : ''}`,
169
+ `page: ${u.page} embed: ${u.embed} thumbnail: ${u.thumb}`,
170
+ ];
171
+ const content = [{ type: 'text', text: lines.join('\n') }];
172
+ const thumb = path.join(p.dir, '.web', 'thumb.png');
173
+ if (a.thumbnail && fs.existsSync(thumb))
174
+ content.push({ type: 'image', data: fs.readFileSync(thumb).toString('base64'), mimeType: 'image/png' });
175
+ return { content };
176
+ }
177
+ case 'open': {
178
+ const p = pick(a, () => libs().scans);
179
+ const r = await host.open(p.dir);
180
+ let page = '';
181
+ try {
182
+ page = ` Package page: ${urlsOf(libs().cfg, p).page}`;
183
+ }
184
+ catch { /* no config to read the port from */ }
185
+ return text(`opened ${p.lib ? `${p.lib}/` : ''}${p.id} ("${p.manifest.title}"): every tool now works in ${p.dir} (${r.graphs} graphs, ${r.assets} assets). ` +
186
+ `Build into graph "${p.manifest.graph}" (the one its page shows); put reference images in attachments/ and guide files in inputs/.${page}`);
187
+ }
188
+ case 'create': {
189
+ const { cfg, places } = libs();
190
+ if (!a.library)
191
+ throw new Error(`"library" is required: a library's or a workspace's name (${places.map((l) => l.name).join(', ') || 'none registered'})`);
192
+ if (!a.path)
193
+ throw new Error('"path" is required: the package folder below the library or workspace, e.g. "props/lantern"');
194
+ // a registered library inside a registered workspace is the workspace's: the package is made there
195
+ const at = placeNamed(cfg, String(a.library)) ?? (() => { const l = places.find((x) => x.name === a.library); return l ? { place: l, prefix: '' } : null; })();
196
+ if (!at)
197
+ throw new Error(`no library or workspace "${a.library}" (${places.map((l) => l.name).join(', ') || `none: the person registers one with \`${program()} library add <name> <folder>\` or \`${program()} workspace add <folder>\``})`);
198
+ const p = createPackage(at.place, at.prefix ? `${at.prefix}/${a.path}` : a.path, { title: a.title, description: a.description, tags: a.tags, links: a.links });
199
+ let opened = '';
200
+ if (a.open !== false) {
201
+ await host.open(p.dir);
202
+ opened = ' and opened it: build/edit now work in it (graph "main" is the one its page shows)';
203
+ }
204
+ return text(`created ${p.lib}/${p.id} at ${p.dir}${opened}. Package page: ${urlsOf(cfg, p).page}`);
205
+ }
206
+ case 'show': {
207
+ const { workspaceText } = await import('../workspace.js');
208
+ return text(workspaceText(host.session().dir));
209
+ }
210
+ case 'libraries': {
211
+ const { workspaceLibrary, workspaceLibrariesText } = await import('../workspace.js');
212
+ if (a.add !== undefined && a.remove !== undefined)
213
+ throw new Error('libraries: "add" or "remove", not both');
214
+ const dir = host.session().dir;
215
+ if (a.add === undefined && a.remove === undefined)
216
+ return text(workspaceLibrariesText(dir));
217
+ const said = workspaceLibrary(a.add !== undefined ? 'add' : 'remove', String(a.add ?? a.remove), { at: dir, cwd: dir });
218
+ host.packages().refresh();
219
+ return text(said);
220
+ }
221
+ case 'init_workspace': {
222
+ const { initWorkspace, workspaceText } = await import('../workspace.js');
223
+ if (!a.path)
224
+ throw new Error('init_workspace needs path: the workspace\'s folder (its root), as the person names it');
225
+ const r = initWorkspace(path.resolve(host.session().dir, String(a.path)), { name: a.name, engine: a.engine, assets: a.assets, libraries: Array.isArray(a.libraries) ? a.libraries.map(String) : undefined, follow: typeof a.follow === 'boolean' ? a.follow : undefined, cwd: host.session().dir });
226
+ host.packages().refresh();
227
+ return text(`${r.text}\n${workspaceText(r.dir)}`);
228
+ }
229
+ case 'init': {
230
+ const dir = host.session().dir, inside = packageDirOf(dir);
231
+ if (inside)
232
+ throw new Error(`the folder ${dir} is in a package already: ${manifestFile(inside)}${a.name ? `; workspace {action:"set", name:"${a.name}"} names the package it is` : ''}`);
233
+ const { id, manifest } = initPackage(dir, { name: a.name });
234
+ // the tools take in the package (its packages) as a folder opened afresh
235
+ const r = await host.open(dir);
236
+ return text(`made the folder ${dir} a package, id "${id}"${manifest.name ? `, package ${manifest.name}` : ''} (${id}.topo, graphs/${manifest.graph}.json; ${r.graphs} graphs, ${r.assets} assets): ` +
237
+ 'its graphs use packages now. A build that names one adds it on first use: TopoTopo\'s own (topotopo/…) from TopoTopo\'s built-in library, others from its workspace and the shared libraries the workspace lists (workspace {action:"libraries"} shows them), or outside a workspace from every registered library. workspace {action:"packages"} shows them');
238
+ }
239
+ case 'set': {
240
+ if (a.libraries !== undefined)
241
+ throw new Error('"libraries" is no longer set on a package: the workspace lists the shared libraries its packages use (workspace {action:"libraries", add:"<name or folder>"}, when the person names the library); outside a workspace every registered library counts');
242
+ const p = pick(a, () => libs().scans);
243
+ const m = { ...p.manifest };
244
+ for (const k of ['title', 'description', 'tags', 'links', 'graph', 'bake', 'name'])
245
+ if (a[k] !== undefined)
246
+ m[k] = a[k];
247
+ if (a.name !== undefined && a.name !== p.manifest.name)
248
+ ownPackageName(String(a.name));
249
+ const checked = parseManifest(m, p.id);
250
+ const said = [];
251
+ withPackageLock(p.dir, () => {
252
+ // the manifest as it is on disk now: the fields set over it, "uses" as the packages left it
253
+ const now = readManifest(p.dir);
254
+ writeManifest(p.dir, { ...checked, uses: now.uses });
255
+ });
256
+ const pk = host.packages();
257
+ if (pk.dir === p.dir)
258
+ pk.refresh();
259
+ const shown = readManifest(p.dir);
260
+ return text([`set in ${p.lib ? `${p.lib}/` : ''}${p.id}: ${JSON.stringify(shown)}`, ...said].join('\n'));
261
+ }
262
+ case 'outdated': return text(outdatedText(host.packages(), true));
263
+ case 'check': {
264
+ const { checkAll, checkText } = await import('../packages/check.js');
265
+ return text(checkText(await checkAll(host.session().dir)));
266
+ }
267
+ case 'update': {
268
+ if (!a.package)
269
+ throw new Error('"package" is required: "owner/name", a package the open package uses (outdated lists them)');
270
+ const pkg = String(a.package), to = a.to === undefined ? undefined : String(a.to);
271
+ if (a.apply) {
272
+ if (to === undefined || a.from === undefined)
273
+ throw new Error('apply:true needs "from" and "to": the version in use and the version of the before/after the person saw');
274
+ const r = applyUpdate(host.packages(), pkg, { from: String(a.from), to });
275
+ // every graph may use it: they cook again, and the viewer shows it
276
+ const ws = host.session();
277
+ for (const g of ws.graphs.keys()) {
278
+ ws.lastReport.delete(g);
279
+ ws.bump(g);
280
+ }
281
+ return text(r.text);
282
+ }
283
+ let r;
284
+ try {
285
+ r = await beforeAfter(host.packages(), pkg, { to, signal: call?.signal, progress: call?.progress });
286
+ }
287
+ catch (e) {
288
+ if (e instanceof NothingToUpdate)
289
+ return text(e.message);
290
+ throw e;
291
+ }
292
+ const content = [{ type: 'text', text: beforeAfterText(r, `Nothing was written. Show the person this before/after, and apply it only when they say so: workspace {action:"update", package:"${pkg}", from:"${r.target.from}", to:"${r.target.to}", apply:true}`) }];
293
+ const renders = overlayRenders(r);
294
+ if (renders.length) {
295
+ const changed = r.compared.filter((c) => c.diff && !c.diff.identical).length;
296
+ content.push({ type: 'text', text: `overlay renders of ${renders.length === changed ? `the ${changed === 1 ? 'place' : `${changed} places`} that changed` : `the ${renders.length} places that changed most (of ${changed})`}, in order: ${renders.map((x) => x.title).join(', ')}. Grey: the same with both versions; blue: only with ${r.target.to} (moved or new); orange: only with ${r.target.from} (moved from or gone)` });
297
+ for (const x of renders)
298
+ content.push({ type: 'image', data: Buffer.from(x.png).toString('base64'), mimeType: 'image/png' });
299
+ }
300
+ return { content };
301
+ }
302
+ case 'packages': return text(a.package ? packageText(host.packages(), String(a.package), true) : packagesText(host.packages(), true));
303
+ case 'use': {
304
+ if (!a.package)
305
+ throw new Error('"package" is required: "owner/name"');
306
+ const r = host.packages().use(String(a.package), { version: a.version === undefined ? undefined : String(a.version) });
307
+ return text(`${r.text}. Its outputs are node types now: workspace {action:"packages", package:"${a.package}"} lists them, help {nodes:[...]} gives one's params`);
308
+ }
309
+ case 'remove': {
310
+ if (!a.package)
311
+ throw new Error('"package" is required: "owner/name", a package the open package uses (packages lists them)');
312
+ return text(removePackage(host.packages(), String(a.package)).text);
313
+ }
314
+ case 'follow': {
315
+ if (!a.package)
316
+ throw new Error('"package" is required: "owner/name"');
317
+ const said = host.packages().follow(String(a.package), a.on !== false);
318
+ // every graph may use it: they cook again, and the viewer shows it
319
+ const ws = host.session();
320
+ for (const g of ws.graphs.keys()) {
321
+ ws.lastReport.delete(g);
322
+ ws.bump(g);
323
+ }
324
+ return text(said);
325
+ }
326
+ case 'publish': {
327
+ const r = await publishPackage(host.packages(), { note: a.note, big: a.big, dryRun: a.dry_run === true });
328
+ return text(publishText(r), !r.ok);
329
+ }
330
+ case 'search': {
331
+ const pk = host.packages();
332
+ const r = searchPackages(pk.dir ?? host.session().dir, { query: a.query, kind: a.kind, tag: a.tag }, { builtin: pk.builtin });
333
+ return text(searchText(r, true));
334
+ }
335
+ case 'bake': {
336
+ const p = pick(a, () => libs().scans);
337
+ const { bakePackage } = await import('../web/bake.js');
338
+ const s = await bakePackage(p.dir);
339
+ if (!s.ok)
340
+ return text(`bake of ${p.id} failed: ${s.error}`, true);
341
+ 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('; ')}` : ''}` }];
342
+ content.push({ type: 'image', data: fs.readFileSync(path.join(p.dir, '.web', 'thumb.png')).toString('base64'), mimeType: 'image/png' });
343
+ return { content };
344
+ }
345
+ }
346
+ return text(`unknown action "${a.action}": list, get, open, create, init, init_workspace, show, libraries, set, bake, packages, search, use, remove, follow, publish, outdated, check or update`, true);
347
+ },
348
+ };
349
+ }
@@ -762,7 +762,7 @@ defineNode({
762
762
  name: { type: 'string', default: 'group1', desc: 'group name' },
763
763
  class: { type: 'enum', options: ['prim', 'point', 'vertex', 'edge'], default: 'prim', desc: 'element class (edge = point pairs)' },
764
764
  pattern: { type: 'group', default: '', desc: 'base pattern ("" = no pattern filter): names, ranges, "@P.y>0", "!grp"; edges also "boundary", "angle>30", "p3-7", "border:grp"' },
765
- expr: { type: 'code', default: '', desc: 'JS wrangle-style boolean expression per element, e.g. "@P.y > 0.5 && @N.y > 0.9" (vertex class runs over vertices; edge class: the expression must hold for both points of the edge)' },
765
+ expr: { type: 'code', default: '', desc: 'JS wrangle-style boolean expression per element, e.g. "@P.y > 0.5 && @N.y > 0.9" or "@P.y > height" with a graph var (vertex class runs over vertices; edge class: the expression must hold for both points of the edge)' },
766
766
  bbox_min: { type: 'vec3', default: [-1e9, -1e9, -1e9], desc: 'keep elements inside this box (points; prims use centroid; vertices their point; edges their midpoint)' },
767
767
  bbox_max: { type: 'vec3', default: [1e9, 1e9, 1e9], desc: 'box max' },
768
768
  normal: { type: 'vec3', default: [0, 0, 0], desc: 'keep elements whose normal is within spread_angle of this direction ([0,0,0] = off; vertices use vertex normals, edges the mean of their polygons)' },
@@ -772,6 +772,8 @@ defineNode({
772
772
  mode: { type: 'enum', options: ['replace', 'union', 'intersect', 'subtract'], default: 'replace', desc: 'combine with an existing group of the same name' },
773
773
  invert: { type: 'bool', default: false, desc: 'invert the selection' },
774
774
  },
775
+ // the expression runs as a wrangle: the graph vars it names key the cache
776
+ usesVars: (p) => String(p.expr ?? ''),
775
777
  example: { type: 'group', params: { name: 'top', class: 'prim', normal: [0, 1, 0], spread_angle: 20 } },
776
778
  cook: (ctx) => {
777
779
  const { input, p, engine, vars, inputs } = ctx;
@@ -1101,6 +1103,195 @@ defineNode({
1101
1103
  return g;
1102
1104
  },
1103
1105
  });
1106
+ /** Text of an attribute value for a name pattern: integers as they are, floats to 6 significant digits, tuples joined by "_". */
1107
+ function valueText(v) {
1108
+ const one = (x) => (typeof x === 'number' ? (Number.isInteger(x) ? String(x) : String(+x.toPrecision(6))) : String(x ?? ''));
1109
+ return Array.isArray(v) ? v.map(one).join('_') : one(v);
1110
+ }
1111
+ defineNode({
1112
+ type: 'attrib_string',
1113
+ category: 'attribute',
1114
+ packed: 'keep',
1115
+ summary: 'Write or edit a string attribute per element: a pattern with the element\'s number, its piece number and other attributes ("hull_{piece:03}"), then find/replace and case. Names for pieces, LODs and engine suffixes in one node.',
1116
+ description: 'Houdini: Attribute String Edit + a name wrangle. For each element of class (in group) the value is built in three ' +
1117
+ 'steps: format, when set, makes it from a pattern ("" keeps the current value); find/replace edits it (plain text, ' +
1118
+ 'or a JavaScript regular expression with regex, $1 for groups); case lowers or raises it. Placeholders in format: ' +
1119
+ '{value} the current value, {index} the element number, {piece} the number of the element\'s piece, {pieces} how ' +
1120
+ 'many there are, and {<attribute>} any attribute of the element (prim, then point and detail; a tuple joins with ' +
1121
+ '"_"). A width pads numbers with zeros: {piece:03} → 007. Pieces are connected pieces (prims sharing points), or ' +
1122
+ 'with piece_attrib the distinct values of that attribute (class, copynum, a name), numbered in order of first ' +
1123
+ 'appearance; start offsets {index} and {piece} (1 counts from one). Examples: name 146 convex hulls for Godot in one ' +
1124
+ 'node {format:"hull_{piece:03}-convcolonly"}; LOD names to lower case {find:"_LOD", replace:"_lod"}; a prefix on ' +
1125
+ 'every part {format:"gun_{value}"}; copies {format:"crate_{copynum}"}.',
1126
+ aliases: ['string_edit', 'attrib_string_edit', 'name_pieces', 'rename_pieces', 'attribstringedit'],
1127
+ inputs: [{ name: 'geo', desc: 'geometry' }],
1128
+ params: {
1129
+ name: { type: 'string', default: 'name', desc: 'string attribute to write (created when missing)', aliases: ['attrib', 'attribute'] },
1130
+ class: { ...CLS, default: 'prim' },
1131
+ format: { type: 'string', default: '', desc: 'pattern of the new value, e.g. "hull_{piece:03}" ("" = keep the current value; placeholders {value} {index} {piece} {pieces} {<attribute>}, width {index:03})', aliases: ['pattern', 'template'] },
1132
+ piece_attrib: { type: 'string', default: '', desc: 'what makes a piece for {piece}: "" = connected pieces, else an attribute whose distinct values are the pieces (class, copynum, name)', aliases: ['piece_attribute', 'by'] },
1133
+ start: { type: 'int', default: 0, min: -1000000, max: 1000000, desc: 'first number of {index} and {piece} (1 counts from one)', aliases: ['offset', 'first'] },
1134
+ find: { type: 'string', default: '', desc: 'text to replace in the value ("" = none)', aliases: ['search', 'from'] },
1135
+ replace: { type: 'string', default: '', desc: 'what find becomes (every occurrence)', aliases: ['to', 'replace_with'] },
1136
+ regex: { type: 'bool', default: false, desc: 'find is a JavaScript regular expression (replace may use $1, $2 …)', aliases: ['regexp', 'use_regex'] },
1137
+ case: { type: 'enum', options: ['keep', 'lower', 'upper'], default: 'keep', desc: 'change the letter case last', aliases: ['letter_case'] },
1138
+ group: { type: 'group', default: '', desc: 'only elements in this group (point and prim classes)' },
1139
+ },
1140
+ outputs: 'string attribute <name> on <class>',
1141
+ example: {
1142
+ nodes: {
1143
+ ball: { type: 'sphere', params: { type: 'ico', level: 2 } },
1144
+ shards: { type: 'voronoi_fracture', in: ['ball'], params: { count: 8, gap: 0.02 } },
1145
+ hulls: { type: 'attrib_string', in: ['shards'], params: { format: 'hull_{piece:03}-convcolonly' } },
1146
+ },
1147
+ output: 'hulls',
1148
+ },
1149
+ cook: ({ input, p, type }) => {
1150
+ const g = input(0).clone();
1151
+ const name = String(p.name ?? '').trim();
1152
+ if (!name)
1153
+ throw new NodeError(`${type}: name is empty`);
1154
+ const cls = p.class;
1155
+ const n = elemCount(g, cls);
1156
+ const old = g.table(cls).get(name);
1157
+ if (old && old.type !== 'string')
1158
+ throw new NodeError(`${type}: ${cls} attribute "${name}" is ${old.type}, not a string`, 'write another name, or attrib_delete it first');
1159
+ const cur = old && !old.isArray ? old.data : null;
1160
+ const sel = cls === 'point' || cls === 'prim' ? mask(g, cls, p.group) : null;
1161
+ const start = Math.trunc(p.start) || 0;
1162
+ // pieces: connected pieces, or the distinct values of piece_attrib, numbered by first appearance
1163
+ let piece = null, pieces = 0;
1164
+ const fmt = String(p.format ?? '');
1165
+ if (/\{pieces?(:\d+)?\}/.test(fmt)) {
1166
+ piece = new Int32Array(n);
1167
+ const pa = String(p.piece_attrib ?? '').trim();
1168
+ if (pa) {
1169
+ const order = cls === 'point' ? ['point', 'prim', 'detail'] : cls === 'vertex' ? ['vertex', 'point', 'prim', 'detail'] : ['prim', 'point', 'detail'];
1170
+ const f = g.findAttrib(pa, order);
1171
+ if (!f)
1172
+ throw new NodeError(`${type}: no attribute "${pa}" for piece_attrib`, 'e.g. class (connectivity), copynum (copy nodes) or name');
1173
+ const ids = new Map();
1174
+ for (let i = 0; i < n; i++) {
1175
+ const e = elemIndex(g, cls, f.cls, i);
1176
+ const key = JSON.stringify(f.attr.get(e));
1177
+ let id = ids.get(key);
1178
+ if (id === undefined) {
1179
+ id = ids.size;
1180
+ ids.set(key, id);
1181
+ }
1182
+ piece[i] = id;
1183
+ }
1184
+ pieces = ids.size;
1185
+ }
1186
+ else {
1187
+ const c = connectivity(g);
1188
+ const ids = new Map();
1189
+ for (let i = 0; i < n; i++) {
1190
+ const raw = cls === 'point' ? c.ptClass[i] : cls === 'prim' ? c.primClass[i] : cls === 'vertex' ? c.primClass[vertexPrim(g, i)] : 0;
1191
+ let id = ids.get(raw);
1192
+ if (id === undefined) {
1193
+ id = ids.size;
1194
+ ids.set(raw, id);
1195
+ }
1196
+ piece[i] = id;
1197
+ }
1198
+ pieces = ids.size;
1199
+ }
1200
+ }
1201
+ // the placeholders, checked once
1202
+ const order = cls === 'point' ? ['point', 'prim', 'detail'] : cls === 'vertex' ? ['vertex', 'point', 'prim', 'detail'] : cls === 'detail' ? ['detail'] : ['prim', 'point', 'detail'];
1203
+ const tokens = [...fmt.matchAll(/\{([A-Za-z_][\w]*)(?::(\d+))?\}/g)];
1204
+ const lookups = new Map();
1205
+ for (const [, key] of tokens) {
1206
+ if (['value', 'index', 'piece', 'pieces'].includes(key) || lookups.has(key))
1207
+ continue;
1208
+ const f = g.findAttrib(key, order);
1209
+ if (!f)
1210
+ throw new NodeError(`${type}: format "${fmt}" names {${key}}, which is no attribute here`, `placeholders: {value} {index} {piece} {pieces} or an attribute (${[...g.table(cls).map.keys()].slice(0, 12).join(', ') || 'none'})`);
1211
+ lookups.set(key, f);
1212
+ }
1213
+ let re = null;
1214
+ const find = String(p.find ?? '');
1215
+ if (find && p.regex) {
1216
+ try {
1217
+ re = new RegExp(find, 'g');
1218
+ }
1219
+ catch (e) {
1220
+ throw new NodeError(`${type}: find is not a valid regular expression: ${e.message}`);
1221
+ }
1222
+ }
1223
+ const pad = (x, w) => (w ? String(x).padStart(Number(w), '0') : String(x));
1224
+ const out = cur ? cur.slice() : new Array(n).fill('');
1225
+ for (let i = 0; i < n; i++) {
1226
+ if (sel && !sel[i])
1227
+ continue;
1228
+ let s = cur ? cur[i] : '';
1229
+ if (fmt) {
1230
+ s = fmt.replace(/\{([A-Za-z_][\w]*)(?::(\d+))?\}/g, (_m, key, w) => {
1231
+ if (key === 'value')
1232
+ return cur ? cur[i] : '';
1233
+ if (key === 'index')
1234
+ return pad(i + start, w);
1235
+ if (key === 'piece')
1236
+ return pad(piece[i] + start, w);
1237
+ if (key === 'pieces')
1238
+ return pad(pieces, w);
1239
+ const f = lookups.get(key);
1240
+ const v = f.attr.get(elemIndex(g, cls, f.cls, i));
1241
+ return typeof v === 'number' && Number.isInteger(v) ? pad(v, w) : valueText(v);
1242
+ });
1243
+ }
1244
+ if (find)
1245
+ s = re ? s.replace(re, String(p.replace ?? '')) : s.split(find).join(String(p.replace ?? ''));
1246
+ if (p.case === 'lower')
1247
+ s = s.toLowerCase();
1248
+ else if (p.case === 'upper')
1249
+ s = s.toUpperCase();
1250
+ out[i] = s;
1251
+ }
1252
+ g.table(cls).set(name, new Attribute('string', 1, out, ''));
1253
+ return g;
1254
+ },
1255
+ });
1256
+ /** The prim of vertex v. */
1257
+ function vertexPrim(g, v) {
1258
+ let lo = 0, hi = g.numPrims - 1;
1259
+ while (lo < hi) {
1260
+ const mid = (lo + hi + 1) >> 1;
1261
+ if (g.primStart[mid] <= v)
1262
+ lo = mid;
1263
+ else
1264
+ hi = mid - 1;
1265
+ }
1266
+ return lo;
1267
+ }
1268
+ /** First prim using each point (-1 = none), cached per geometry. */
1269
+ const firstPrims = new WeakMap();
1270
+ function pointPrim(g, pt) {
1271
+ let a = firstPrims.get(g);
1272
+ if (!a) {
1273
+ a = new Int32Array(g.numPoints).fill(-1);
1274
+ for (let pr = g.numPrims - 1; pr >= 0; pr--)
1275
+ for (let v = g.primStart[pr]; v < g.primStart[pr + 1]; v++)
1276
+ a[g.vertexPoint[v]] = pr;
1277
+ firstPrims.set(g, a);
1278
+ }
1279
+ return Math.max(0, a[pt]);
1280
+ }
1281
+ /** The element of class `to` that element i of class `from` reads (a point reads its first prim, a prim its first point). */
1282
+ function elemIndex(g, from, to, i) {
1283
+ if (to === 'detail')
1284
+ return 0;
1285
+ if (from === to)
1286
+ return i;
1287
+ if (from === 'vertex')
1288
+ return to === 'point' ? g.vertexPoint[i] : vertexPrim(g, i);
1289
+ if (from === 'prim' && to === 'point')
1290
+ return g.vertexPoint[g.primStart[i]] ?? 0;
1291
+ if (from === 'point' && to === 'prim')
1292
+ return pointPrim(g, i);
1293
+ return 0;
1294
+ }
1104
1295
  defineNode({
1105
1296
  type: 'sort',
1106
1297
  category: 'topology',
@@ -1195,6 +1386,12 @@ defineNode({
1195
1386
  type: 'uv_project',
1196
1387
  category: 'uv',
1197
1388
  summary: 'Project UVs: planar, box (tri-planar per face), cylindrical or spherical.',
1389
+ description: 'uv = world position / scale + offset (no packing: the uv runs over many tiles, for tiling textures; uv_layout or uv_unwrap make an atlas). ' +
1390
+ 'planar projects along axis: y → u = x, v = z; x → u = z, v = y; z → u = x, v = y. box projects each polygon the same way along the axis ' +
1391
+ 'its normal is closest to. Both sides of an axis share one projection, so the faces looking along +X, +Y and -Z get MIRRORED uv (a ' +
1392
+ 'texture reads backwards there, and their uv winding is opposite to the polygon\'s: inspect uv counts them as mirrored), while -X, -Y and ' +
1393
+ '+Z read the right way round. cylindrical: u = angle around axis (one turn per scale[0]), v = height along axis / scale[1]; spherical: u ' +
1394
+ '= angle, v = polar angle (0..1 times scale[1]); both measured from center, with a seam where the angle wraps.',
1198
1395
  aliases: ['uvproject', 'texture', 'uv_texture'],
1199
1396
  inputs: [{ name: 'geo', desc: 'geometry' }],
1200
1397
  params: {