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
@@ -11,25 +11,45 @@ async function json(url, init) {
11
11
  const j = await res.json().catch(() => ({ ok: false, error: `${res.status} ${res.statusText}` }));
12
12
  return { status: res.status, j };
13
13
  }
14
- /** A GLB route: {ok, buf} or {ok: false, error}. */
14
+ /** A GLB route: {ok, buf} or {ok: false, error, stopped?} (stopped: the node its cook was stopped at). */
15
15
  async function glb(url) {
16
16
  let res;
17
17
  try { res = await fetch(url); } catch { return fail(offline); }
18
- if (!res.ok) { const j = await res.json().catch(() => ({})); return fail(j.error ?? `${res.status} ${res.statusText}`); }
18
+ if (!res.ok) { const j = await res.json().catch(() => ({})); return { ...fail(j.error ?? `${res.status} ${res.statusText}`), ...(j.stopped ? { stopped: j.stopped } : {}) }; }
19
19
  return { ok: true, buf: await res.arrayBuffer() };
20
20
  }
21
21
  const post = (body) => ({ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
22
22
 
23
+ /** At most one run at a time; calls during a run request one more run afterwards and wait for it. */
24
+ export function coalesce(fn) {
25
+ let busy = null, again = false;
26
+ return () => {
27
+ if (busy) { again = true; return busy; }
28
+ busy = (async () => { try { do { again = false; await fn(); } while (again); } finally { busy = null; } })();
29
+ return busy;
30
+ };
31
+ }
32
+
23
33
  export const api = {
24
- /** [{name, output, version, vars, params, nodes: [{name, type, in, error, ms}]}] or null */
34
+ /**
35
+ * [{name, output, version, vars, graphVars, overrides, params, mode, file, cook, nodes: [{name, type, in, error, ms}]}]
36
+ * or null. vars: what the controls show; graphVars: the graph's own; mode "file": session values over a graph file.
37
+ */
25
38
  async graphs() { const { status, j } = await json('/api/graphs'); return status === 200 && Array.isArray(j) ? j : null; },
39
+ /** {package: {id, title, description, graph, name, dir} | null, folder, file, builtin} or null */
40
+ async package() { const { status, j } = await json('/api/package'); return status === 200 ? j : null; },
26
41
  /** the last cook of a graph: {ok, ms, target, errors, warnings} */
27
42
  async report(graph) { const { status, j } = await json('/api/report?' + q({ graph })); return status === 200 ? j : null; },
28
- geo: (graph, node) => glb('/api/geo?' + q({ graph, node })),
29
- /** {target, summary, ms} or null */
43
+ /** the output (or a node) as a GLB; heightfields with `layer` in red (default the mask) */
44
+ geo: (graph, node, layer) => glb('/api/geo?' + q({ graph, node, ...(layer ? { heightfield_layer: layer } : {}) })),
45
+ /** {target, summary, ms, about: what it is (kind, text, size, heightfield)} or null */
30
46
  async info(graph, node) { const { status, j } = await json('/api/info?' + q({ graph, node })); return status === 200 ? j : null; },
31
- /** {ok, ms, errors, vars?} */
47
+ /** {ok, ms, errors, vars?, graphVars?, overrides?, stopped?}, once a cook has applied the values (or a stop ended it) */
32
48
  async vars(graph, vars) { const { status, j } = await json('/api/vars?' + q({ graph }), post({ vars })); return status ? j : { ok: false, ms: 0, errors: [offline] }; },
49
+ /** Save values to the graph file: {ok, saved, file, vars, graphVars, overrides} or {ok: false, error} */
50
+ async saveVars(graph, vars) { const { status, j } = await json('/api/vars/save?' + q({ graph }), post({ vars })); return status === 200 ? j : fail(j.error ?? `${status}`); },
51
+ /** Stop the cooks of a graph: {ok, stopping} or {ok: false, error} */
52
+ async stop(graph) { const { status, j } = await json('/api/cook/stop?' + q({ graph }), post({})); return status === 200 ? j : fail(j.error ?? `${status}`); },
33
53
  async inputs() { const { status, j } = await json('/api/inputs'); return status === 200 && Array.isArray(j) ? j : null; },
34
54
  /** {dir, where} or null */
35
55
  async inputsDir() { const { status, j } = await json('/api/inputs_dir'); return status === 200 ? j : null; },
@@ -53,6 +73,28 @@ export const api = {
53
73
  const { status, j } = await json('/api/markers', { method: 'POST', headers: { 'content-type': 'application/json' }, body });
54
74
  return status === 200 && j.ok ? j : fail(j.error ?? `${status}`);
55
75
  },
76
+ /** The packages in use: {package, packages, problems, running, compare} (package null: no package), or null */
77
+ async packages() { const { status, j } = await json('/api/packages'); return status === 200 ? j : null; },
78
+ /** Find packages: {libraries: [{name, standing, hits}], problems} or {ok: false, error} */
79
+ async searchPackages(q) { const { status, j } = await json('/api/packages/search?' + new URLSearchParams({ q })); return status === 200 ? { ok: true, ...j } : fail(j.error ?? `${status}`); },
80
+ /** In a package that publishes versions: {ok, package, last, published, note, changed} */
81
+ async authorState() { const { status, j } = await json('/api/packages/author'); return status === 200 ? j : fail(j.error ?? `${status}`); },
82
+ /** The publish dry run: {ok, check: {ok, version, previous, blocks, warnings, changes, bigBecause}} */
83
+ async checkPublish() { const { status, j } = await json('/api/packages/check', post({})); return status === 200 ? j : fail(j.error ?? `${status}`); },
84
+ /** The before/after of updating a package (to `to`, else the newest with the same big number), once it is done or stopped */
85
+ async compare(pkg, to) { const { status, j } = await json('/api/packages/compare', post({ package: pkg, ...(to ? { to } : {}) })); return status === 200 ? j : { ...fail(j.error ?? `${status}`), status }; },
86
+ /** {compare: the last before/after or null, running: the one in progress or null} */
87
+ async lastCompare() { const { status, j } = await json('/api/packages/compare'); return status === 200 ? j : { compare: null, running: null }; },
88
+ /** a place of a before/after as a GLB: side "a" (the version in use), "b" (the new one) or "overlay" */
89
+ compareGeo: (id, place, side) => glb('/api/packages/compare/geo?' + q({ id, place, side })),
90
+ /** Stop the before/after in progress: {ok, stopping} */
91
+ async stopCompare() { const { status, j } = await json('/api/packages/stop', post({})); return status === 200 ? j : fail(j.error ?? `${status}`); },
92
+ /** Apply an update the person looked at: {ok, text, from, to, big, mustChange} or {ok: false, error} */
93
+ async updatePackage(pkg, from, to) { const { status, j } = await json('/api/packages/update', post({ package: pkg, from, to })); return status === 200 ? j : fail(j.error ?? `${status}`); },
94
+ /** Follow a package's working folder for this session (on), or go back to its copy: {ok, text, followed} or {ok: false, error} */
95
+ async followPackage(pkg, on) { const { status, j } = await json('/api/packages/follow', post({ package: pkg, on })); return status === 200 ? j : fail(j.error ?? `${status}`); },
96
+ /** Drop the list of what the graphs must change, kept after a big update */
97
+ async dismissPackage(pkg) { const { status, j } = await json('/api/packages/dismiss', post({ package: pkg })); return status === 200 ? j : fail(j.error ?? `${status}`); },
56
98
  /** The event stream: on({open, error, message}); returns the EventSource. */
57
99
  events(on) {
58
100
  const es = new EventSource('/api/events');
@@ -1,4 +1,4 @@
1
- // Cameras and views (docs/design/viewer.md section 3): our own controller, no OrbitControls. Tumble around a pivot,
1
+ // Cameras and views: our own controller, no OrbitControls. Tumble around a pivot,
2
2
  // track, dolly towards a point, no inertia: the camera moves only while the person drags, scrolls or frames. Seven
3
3
  // named cameras (persp and the axis views); one view, or four in a 2×2 quad, each showing one of them with its own
4
4
  // shading. Orthographic cameras cannot tumble. Near and far planes follow the scene size (the renderer keeps a
@@ -0,0 +1,78 @@
1
+ // The cook state the page shows in the status bar and above the Controls: what is cooking (the node, the time), how
2
+ // the last cook ended (its time, the failing node and message, where it was stopped), and the progress of a package
3
+ // update's before/after. The server sends the state ({cook} and {compare} events, /api/graphs); between events the
4
+ // page counts the time itself. Plain functions, tested in Node (test/viewer-logic.ts).
5
+
6
+ /** "850 ms", "12.3 s", "2 min 05 s". */
7
+ export function fmtDuration(ms) {
8
+ if (!Number.isFinite(ms) || ms < 0) ms = 0;
9
+ if (ms < 1000) return `${Math.round(ms)} ms`;
10
+ if (ms < 60000) return `${(ms / 1000).toFixed(ms < 10000 ? 2 : 1)} s`;
11
+ const s = Math.round(ms / 1000);
12
+ return `${Math.floor(s / 60)} min ${String(s % 60).padStart(2, '0')} s`;
13
+ }
14
+
15
+ const firstLine = (s) => String(s ?? '').split('\n')[0];
16
+
17
+ /** A cook shows as running once it has run this long (ms): shorter ones do not flicker. */
18
+ export const SHOW_AFTER = 150;
19
+
20
+ /**
21
+ * The line for a graph's cook state: {kind, text, title}. kind: "running", "stopping", "ok", "failed", "stopped" or
22
+ * "none". `state`: {running: {cooks, kinds, elapsed, node, nodeElapsed, inner, stopping} | null, last: {ok, ms,
23
+ * stopped?, error?: {node, message}} | null}; `since`: ms since it arrived, added to the running times.
24
+ */
25
+ export function cookLine(state, since = 0) {
26
+ const r = state?.running;
27
+ if (r && (r.elapsed + since >= SHOW_AFTER || r.stopping)) {
28
+ const where = r.node ? `${r.node}${r.inner ? ` › ${r.inner}` : ''}` : '';
29
+ const total = fmtDuration(r.elapsed + since);
30
+ const node = r.node ? `${r.node} has cooked for ${fmtDuration(r.nodeElapsed + since)}` : 'between nodes';
31
+ if (r.stopping) {
32
+ return {
33
+ kind: 'stopping', text: `stopping${where ? ` after ${where}` : ''} · ${total}`,
34
+ title: `${node}. A node cannot be interrupted mid-way: the cook stops when it has finished, and the view keeps the last finished cook.`,
35
+ };
36
+ }
37
+ const verb = r.kinds?.length && r.kinds.every((k) => k === 'export') ? 'exporting' : 'cooking';
38
+ if (r.superseded && where) {
39
+ return {
40
+ kind: 'running', text: `${verb} ${where} · the new value follows · ${total}`,
41
+ title: `${node}. A node cannot be interrupted mid-way: the newest value cooks once it has finished (values in between are skipped).`,
42
+ };
43
+ }
44
+ return { kind: 'running', text: `${verb}${where ? ` ${where}` : ''} · ${total}`, title: `${node}${r.cooks > 1 ? ` (${r.cooks} cooks of this graph)` : ''}. Stop ends it at the next node; changing a value starts over with the new value.` };
45
+ }
46
+ const l = state?.last;
47
+ if (!l) return { kind: 'none', text: '', title: '' };
48
+ if (l.stopped) return { kind: 'stopped', text: `stopped at ${l.stopped} · the view shows the last finished cook`, title: 'change a value (or save the graph file) to cook again' };
49
+ if (!l.ok) {
50
+ const msg = l.error?.message ?? 'failed';
51
+ return { kind: 'failed', text: `failed at ${l.error?.node ?? 'the graph'}: ${firstLine(msg)}`, title: `${l.error?.node ?? ''}: ${msg}` };
52
+ }
53
+ return { kind: 'ok', text: `cooked in ${fmtDuration(l.ms)}`, title: `the last cook of the whole graph took ${fmtDuration(l.ms)}` };
54
+ }
55
+
56
+ /** True while a cook state shows a cook in progress (the page then ticks its time). */
57
+ export const isRunning = (state) => !!state?.running;
58
+
59
+ /**
60
+ * The line for the before/after of a package update in progress (src/viewer/packages.ts): {kind, text, title}, kind
61
+ * "running" or "stopping". `state`: {package, from, to, done, total, what, elapsed, stopping}; `since`: ms since it
62
+ * arrived, added to the time.
63
+ */
64
+ export function compareLine(state, since = 0) {
65
+ const total = fmtDuration(state.elapsed + since);
66
+ const head = `${state.package}${state.from && state.to ? ` ${state.from} → ${state.to}` : ''}`;
67
+ if (state.stopping) {
68
+ return {
69
+ kind: 'stopping', text: `stopping the before/after of ${head} · ${total}`,
70
+ title: 'A node cannot be interrupted mid-way: the before/after stops when it has finished, and keeps the places it compared.',
71
+ };
72
+ }
73
+ const step = state.total ? `${Math.min(state.done + 1, state.total)}/${state.total} ` : '';
74
+ return {
75
+ kind: 'running', text: `before/after ${head} · ${step}${state.what} · ${total}`,
76
+ title: 'Every place this package uses the updated package cooks with the version in use and with the new one. Stop ends it at the next node; the places compared stay.',
77
+ };
78
+ }
@@ -0,0 +1,100 @@
1
+ // The embed page (src/web/pages.ts embedPage): a baked preview.glb under an orbit camera, made to sit in an iframe
2
+ // on a board or a package's folder page; and the 3D view of a model file on a folder page (modelPage: a .glb, or a
3
+ // .gltf whose buffers and textures load from beside it). Not the editor viewport: no panels, no diagnostic overlays,
4
+ // and three's OrbitControls (left drag orbits, right drag pans, wheel zooms, as model viewers do), slowly turning until
5
+ // touched. In a page that scrolls (data-wheel="click") the wheel scrolls that page until the view is clicked, and
6
+ // again once the pointer leaves it; with Ctrl held it zooms at once. The thumbnail behind the canvas, when there is
7
+ // one, stays visible until the model is in, and when it cannot load.
8
+ import * as THREE from 'three';
9
+ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
10
+ import { parseGLB, createLights } from './scene.js';
11
+
12
+ const canvas = document.getElementById('gl');
13
+ const note = document.getElementById('note');
14
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
15
+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
16
+ renderer.setClearColor(0x2b2d31, 1);
17
+ const scene = new THREE.Scene();
18
+ const camera = new THREE.PerspectiveCamera(35, 1, 0.01, 1000);
19
+ const controls = new OrbitControls(camera, canvas);
20
+ controls.enableDamping = true;
21
+ controls.autoRotate = true;
22
+ controls.autoRotateSpeed = 0.6;
23
+ controls.addEventListener('start', () => { controls.autoRotate = false; });
24
+ const lights = createLights(scene);
25
+
26
+ // the wheel: in a page that scrolls, the page's until the view is clicked
27
+ const hint = document.getElementById('hint');
28
+ if (canvas.dataset.wheel === 'click') {
29
+ let armed = false;
30
+ const arm = (on) => { armed = on; if (hint) hint.style.opacity = on ? '0' : '1'; };
31
+ controls.enableZoom = false;
32
+ canvas.addEventListener('pointerdown', () => arm(true));
33
+ canvas.addEventListener('pointerleave', () => arm(false));
34
+ // before OrbitControls sees the event: Ctrl zooms without a click (and keeps the browser's page zoom out of it)
35
+ window.addEventListener('wheel', (e) => { controls.enableZoom = armed || e.ctrlKey; }, { capture: true, passive: true });
36
+ }
37
+
38
+ let dirty = true;
39
+ controls.addEventListener('change', () => { dirty = true; });
40
+ const resize = () => {
41
+ const w = canvas.clientWidth, h = canvas.clientHeight;
42
+ if (!w || !h) return;
43
+ renderer.setSize(w, h, false);
44
+ camera.aspect = w / h;
45
+ camera.updateProjectionMatrix();
46
+ dirty = true;
47
+ };
48
+ new ResizeObserver(resize).observe(canvas);
49
+
50
+ /** Frame the bounding sphere from the thumbnail's angle (35° around, 25° up). */
51
+ function frame(root) {
52
+ const box = new THREE.Box3().setFromObject(root);
53
+ if (box.isEmpty()) return;
54
+ const sphere = box.getBoundingSphere(new THREE.Sphere());
55
+ const r = Math.max(sphere.radius, 1e-3);
56
+ const dist = r / Math.sin(THREE.MathUtils.degToRad(camera.fov / 2)) * 1.05;
57
+ const az = THREE.MathUtils.degToRad(35), el = THREE.MathUtils.degToRad(25);
58
+ camera.position.copy(sphere.center).add(new THREE.Vector3(Math.sin(az) * Math.cos(el), Math.sin(el), Math.cos(az) * Math.cos(el)).multiplyScalar(dist));
59
+ camera.near = dist / 1000;
60
+ camera.far = dist * 100;
61
+ camera.updateProjectionMatrix();
62
+ controls.target.copy(sphere.center);
63
+ controls.minDistance = r * 0.05;
64
+ controls.maxDistance = dist * 20;
65
+ controls.update();
66
+ }
67
+
68
+ async function load() {
69
+ try {
70
+ const src = new URL(canvas.dataset.src, location.href);
71
+ const res = await fetch(src);
72
+ if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
73
+ // a .gltf finds its buffers and textures beside it
74
+ const root = await parseGLB(await res.arrayBuffer(), new URL('.', src).href);
75
+ root.traverse((o) => {
76
+ // a point's size in pixels, as in the editor, not in metres
77
+ if (o.isPoints) { o.material.size = 3; o.material.sizeAttenuation = false; }
78
+ if (o.isMesh) for (const m of [o.material].flat()) m.side = THREE.DoubleSide;
79
+ });
80
+ scene.add(root);
81
+ resize();
82
+ frame(root);
83
+ const poster = document.getElementById('poster');
84
+ if (poster) poster.hidden = true;
85
+ note.textContent = '';
86
+ if (hint) hint.hidden = false;
87
+ } catch (e) {
88
+ canvas.hidden = true;
89
+ note.textContent = `3D preview unavailable (${e.message})`;
90
+ }
91
+ }
92
+
93
+ renderer.setAnimationLoop(() => {
94
+ const moving = controls.update() || controls.autoRotate;
95
+ if (!dirty && !moving) return;
96
+ lights.follow(camera, controls.target);
97
+ renderer.render(scene, camera);
98
+ dirty = false;
99
+ });
100
+ load();
@@ -1,5 +1,7 @@
1
- // The export target popover: a format and a file name inside exports/, opened by an output's Export button when it
2
- // has no target yet, or to change it. Submitting stores the target in the graph and exports.
1
+ // The format popover of an output card, opened by its Download button (a format; Download gets the export as a
2
+ // browser download) or its Export button (a format and a file inside exports/; Export stores that target in the graph
3
+ // and writes). It offers the formats that write the output, best first, each saying in a line what it writes: the
4
+ // server decides them from the cooked geometry (io/kinds.ts) and the export code's own formats (io/files.ts).
3
5
  const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; };
4
6
 
5
7
  /** A file name stem like the server's (io/targets.ts fileStem). */
@@ -18,32 +20,129 @@ export function swapExtension(p, from, to, formats) {
18
20
  return stem + b;
19
21
  }
20
22
 
23
+ /** A path inside `folder` (the exports folder as the server gives it), written with that folder's separators. */
24
+ export function inFolder(folder, p) {
25
+ const sep = String(folder).includes('\\') ? '\\' : '/';
26
+ return `${String(folder).replace(/[\\/]+$/, '')}${sep}${String(p).split(/[\\/]/).join(sep)}`;
27
+ }
28
+
29
+ /**
30
+ * Why a path typed for a target inside exports/ is refused, '' when it is fine: the "engine:" prefix is gone (the path
31
+ * without it said), and a path stays inside exports/.
32
+ */
33
+ export function exportPathError(p) {
34
+ if (p.startsWith(GONE)) return `the "${GONE}" prefix is gone: write the path inside exports/ ("${p.slice(GONE.length)}")`;
35
+ if (!p || p.startsWith('/') || /^[A-Za-z]:/.test(p) || p.split('/').some((s) => !s || s === '.' || s === '..')) return 'a path inside exports/, without ".." or a drive';
36
+ return '';
37
+ }
38
+ /** The export path prefix that is gone (io/targets.ts), kept only to refuse it. */
39
+ const GONE = 'engine' + ':';
40
+
41
+ /** A target's path as the popover starts with it: one still written with the prefix that is gone, without it. */
42
+ export const targetPathShown = (p) => (String(p).startsWith(GONE) ? String(p).slice(GONE.length) : String(p));
43
+
44
+ /** A file name without its folders and extension (".points.json" counts as one), as the server names a zip. */
45
+ export const stemOf = (p) => String(p).replace(/[\\/]+$/, '').replace(/^.*[\\/]/, '').replace(/(\.points\.json|\.[^.]*)$/i, '') || 'export';
46
+
47
+ /**
48
+ * The formats a card offers: the ones that write it (item.formats, from the server), and its target's format when
49
+ * that one does not (an older target: marked, so the person sees why it writes nothing of the output). An output that
50
+ * has not cooked yet (it failed) offers every format.
51
+ */
52
+ export function offeredFormats(item, formats) {
53
+ const fits = item.formats ?? formats.map((f) => ({ ...f, writes: '', leaves: [], oneFile: false }));
54
+ const t = item.target?.format;
55
+ if (!t || fits.some((f) => f.format === t)) return fits;
56
+ const f = formats.find((x) => x.format === t) ?? { format: t, label: t, extension: '' };
57
+ return [...fits, { ...f, writes: 'does not fit this output: it writes none of it', leaves: [], oneFile: false, misfit: true }];
58
+ }
59
+
21
60
  /**
22
- * Open the popover under `anchor`. item: an output entry (label, kind, graph, output, target); formats: [{format, label,
23
- * extension}] from /api/outputs; directory: the exports folder. Resolves to {format, path} or null (cancelled).
61
+ * A format's line in the popover: what it writes, and the parts of the output it leaves out. A download is the file
62
+ * itself (or a zip): what an export would add beside it in exports/ is not said there.
24
63
  */
25
- export function exportPopover({ anchor, item, formats, directory }) {
64
+ export const writesLine = (fit, download = false) => {
65
+ if (!fit) return '';
66
+ const writes = download ? fit.writes.replace(/\s*\(\+ [^)]*in exports\/\)/, '') : fit.writes;
67
+ return `${writes}${fit.leaves?.length ? ` · not the ${fit.leaves.join(' or the ')}` : ''}`;
68
+ };
69
+
70
+ /**
71
+ * The name a download in `format` gets: the target's file name when the format is the target's, else the output's
72
+ * stem with the format's extension; a zip (<stem>.zip) unless the format downloads as one file (fit.oneFile).
73
+ */
74
+ export function downloadName(item, fit) {
75
+ const own = item.target && item.target.format === fit.format ? item.target.path : null;
76
+ const stem = own ? stemOf(own) : fileStem(item.output ?? item.graph ?? 'output');
77
+ if (!fit.oneFile) return `${stem}.zip`;
78
+ return own ? String(own).replace(/^.*[\\/]/, '') : stem + (fit.extension ?? '');
79
+ }
80
+
81
+ /** The target a download asks for: the card's own target (its path and options) for its format, else the format alone. */
82
+ export function downloadSpec(item, format) {
83
+ const t = item.target;
84
+ return t && t.format === format ? { format, path: t.path, ...(t.options ?? {}) } : format;
85
+ }
86
+
87
+ /** The file name of a Content-Disposition header (filename*=UTF-8''…), or null. */
88
+ export function filenameOf(header) {
89
+ const m = /filename\*=UTF-8''([^;]+)/i.exec(header ?? '') ?? /filename="?([^";]+)"?/i.exec(header ?? '');
90
+ try { return m ? decodeURIComponent(m[1]) : null; } catch { return m ? m[1] : null; }
91
+ }
92
+
93
+ /**
94
+ * Open the popover under `anchor`. item: an output entry (label, graph, output, target, formats); formats: every format
95
+ * [{format, label, extension}] from /api/outputs; directory: the exports folder; mode "export" (a format and a file in
96
+ * exports/) or "download" (a format). Resolves to {format, path} (export) or {format} (download), or null (cancelled).
97
+ */
98
+ export function exportPopover({ anchor, item, formats, directory, mode = 'export' }) {
26
99
  document.querySelector('.export-popover')?.dispatchEvent(new Event('cancel'));
100
+ const download = mode === 'download';
27
101
  return new Promise((resolve) => {
28
102
  const stem = item.output ?? item.graph ?? 'output';
29
- const startFormat = item.target?.format ?? (item.kind === 'image' ? 'textures' : 'glb');
103
+ // a download offers what writes the output; the export target, its own format too when that one does not
104
+ const offered = download ? item.formats ?? [] : offeredFormats(item, formats);
105
+ const startFormat = offered.find((f) => f.format === item.target?.format)?.format ?? offered[0]?.format;
30
106
  const box = el('form', 'export-popover');
31
- box.setAttribute('role', 'dialog'); box.setAttribute('aria-label', `Export ${item.label}`);
32
- const title = el('div', 'export-title', item.target ? `Export target of ${item.label}` : `Export ${item.label}`);
107
+ box.setAttribute('role', 'dialog'); box.setAttribute('aria-label', `${download ? 'Download' : 'Export'} ${item.label}`);
108
+ const title = el('div', 'export-title', download ? `Download ${item.label}` : item.target ? `Export target of ${item.label}` : `Export ${item.label}`);
109
+ const about = el('div', 'export-about dim', item.about ?? '');
110
+ // a result that uses a package shown live: the file holds the published version, not the edits shown
111
+ const live = item.live?.length ? el('div', 'export-live', `Writes the published ${item.live.join(', ')}, not the live edits shown`) : null;
33
112
  const format = el('select'); format.setAttribute('aria-label', 'Format');
34
- for (const f of formats) format.append(new Option(f.label, f.format));
35
- format.value = startFormat;
113
+ for (const f of offered) format.append(new Option(f.misfit ? `${f.label} (does not fit)` : f.label, f.format));
114
+ if (startFormat) format.value = startFormat;
115
+ const writes = el('div', 'export-writes');
36
116
  const file = el('input'); file.type = 'text'; file.spellcheck = false; file.setAttribute('aria-label', 'File in exports/');
37
- file.value = item.target?.path ?? defaultPath(stem, startFormat, formats);
117
+ const dflt = startFormat ? defaultPath(stem, startFormat, formats) : '';
118
+ file.value = item.target?.path ? targetPathShown(item.target.path) || dflt : dflt;
38
119
  const where = el('div', 'export-where dim');
39
120
  const error = el('div', 'export-error err');
40
- const cancel = el('button', '', 'Cancel'), go = el('button', 'primary', 'Export');
121
+ const cancel = el('button', '', 'Cancel'), go = el('button', 'primary', download ? 'Download' : 'Export');
41
122
  cancel.type = 'button'; go.type = 'submit';
42
123
  const field = (label, input) => { const l = el('label', 'export-field'); l.append(el('span', 'dim', label), input); return l; };
43
124
  const actions = el('div', 'export-actions'); actions.append(cancel, go);
44
- box.append(title, field('Format', format), field('File', file), where, error, actions);
125
+ box.append(title);
126
+ if (item.about) box.append(about);
127
+ if (live) box.append(live);
128
+ if (offered.length) box.append(field('Format', format), writes);
129
+ else box.append(el('div', 'export-writes err', item.kind === 'volume'
130
+ ? 'no format writes an SDF volume of functions: sdf_to_mesh makes it a mesh to export'
131
+ : 'no format writes this output: it holds nothing to export'));
132
+ if (!download && offered.length) box.append(field('File', file), where);
133
+ box.append(error, actions);
134
+ go.disabled = !offered.length;
45
135
  let previous = format.value;
46
- const sync = () => { where.textContent = `${directory}/${file.value.trim() || '…'}`; error.textContent = ''; };
136
+ const fit = () => offered.find((f) => f.format === format.value);
137
+ const sync = () => {
138
+ const f = fit();
139
+ writes.textContent = writesLine(f, download);
140
+ writes.classList.toggle('err', !!f?.misfit);
141
+ writes.classList.toggle('part', !!f?.leaves?.length);
142
+ where.textContent = download ? '' : inFolder(directory, file.value.trim() || '…');
143
+ if (download && f) go.textContent = `Download ${downloadName(item, f)}`;
144
+ error.textContent = '';
145
+ };
47
146
  format.onchange = () => { file.value = swapExtension(file.value.trim(), previous, format.value, formats); previous = format.value; sync(); };
48
147
  file.oninput = sync;
49
148
  const close = (value) => { box.remove(); removeEventListener('pointerdown', outside, true); anchor?.focus?.(); resolve(value); };
@@ -53,8 +152,11 @@ export function exportPopover({ anchor, item, formats, directory }) {
53
152
  box.onkeydown = (e) => { if (e.key === 'Escape') { e.preventDefault(); close(null); } };
54
153
  box.onsubmit = (e) => {
55
154
  e.preventDefault();
155
+ if (!offered.length) return;
156
+ if (download) { close({ format: format.value }); return; }
56
157
  const p = file.value.trim().replace(/\\/g, '/');
57
- if (!p || p.startsWith('/') || /^[A-Za-z]:/.test(p) || p.split('/').some((s) => !s || s === '.' || s === '..')) { error.textContent = 'a path inside exports/, without ".." or a drive'; file.focus(); return; }
158
+ const wrong = exportPathError(p);
159
+ if (wrong) { error.textContent = wrong; file.focus(); return; }
58
160
  close({ format: format.value, path: p });
59
161
  };
60
162
  sync();
@@ -63,6 +165,6 @@ export function exportPopover({ anchor, item, formats, directory }) {
63
165
  box.style.left = Math.max(6, Math.min(r.left, innerWidth - box.offsetWidth - 6)) + 'px';
64
166
  box.style.top = (r.bottom + 4 + box.offsetHeight < innerHeight ? r.bottom + 4 : Math.max(6, r.top - box.offsetHeight - 4)) + 'px';
65
167
  addEventListener('pointerdown', outside, true);
66
- format.focus();
168
+ (download && offered.length ? go : offered.length ? format : cancel).focus();
67
169
  });
68
170
  }
@@ -1,4 +1,4 @@
1
- // The adaptive metre grid, the world axes, the axis gizmo and each view's readouts (docs/design/viewer.md section 4).
1
+ // The adaptive metre grid, the world axes, the axis gizmo and each view's readouts.
2
2
  // The grid lies on y = 0 under persp and the top / bottom views, and on each side view's own plane (front: XY,
3
3
  // right: ZY), as Maya and Houdini draw them; minor lines every `step`, major every 10 steps, the axes in the
4
4
  // standard colours. One plane is set up again before each view renders.
@@ -16,7 +16,11 @@ const vertex = /* glsl */`
16
16
  void main() {
17
17
  vec4 w = modelMatrix * vec4(position, 1.0);
18
18
  vWorld = w.xyz;
19
- gl_Position = projectionMatrix * viewMatrix * w;
19
+ // a sliver behind its plane, so a ground lying on y = 0 hides it instead of fighting it for each pixel (polygon
20
+ // offset does not reach a logarithmic depth buffer)
21
+ vec4 mv = viewMatrix * w;
22
+ if (isPerspectiveMatrix(projectionMatrix)) mv.xyz *= 1.002; else mv.z -= 6e-5 * (-2.0 / projectionMatrix[2][2]);
23
+ gl_Position = projectionMatrix * mv;
20
24
  #include <logdepthbuf_vertex>
21
25
  }`;
22
26
  const fragment = /* glsl */`
@@ -1,4 +1,4 @@
1
- // Guides (docs/design/viewer.md section 7): nulls, curves, areas and volumes, the markers agents read as
1
+ // Guides: nulls, curves, areas and volumes, the markers agents read as
2
2
  // inputs/markers.json (roles site, path, zone, volume). Drawn as the standard objects they are, in one desaturated
3
3
  // cyan, on top of the scene: a null is an axis cross (its radius circle only while hovered or selected), a curve a
4
4
  // polyline with CV squares and a direction tick, an area a closed curve with a light diagonal hatch, a volume a wire
@@ -11,6 +11,7 @@ import { api } from './api.js';
11
11
  import * as M from './markers.js';
12
12
  import { COLORS, fatSegments, lineMaterial, disposeTree } from './scene.js';
13
13
  import { fmtLen } from './units.js';
14
+ import { AXIS_VIEWS } from './camera.js';
14
15
 
15
16
  export const guideId = (id) => `guide:${id}`;
16
17
  export const PLACE_KINDS = { placeNull: 'site', placeCurve: 'path', placeArea: 'zone', placeVolume: 'volume' };
@@ -398,5 +399,126 @@ export function createGuides(ctx) {
398
399
  G.drawDraft(); G.hint();
399
400
  };
400
401
  G.leave = () => { if (G.cursor) { G.cursor = null; G.drawDraft(); } };
402
+
403
+ // ------------------------------------------------------------------ dragging (select mode)
404
+ // A plain left press on a guide grabs what is under it: a null's point, a CV of a curve or an area or a volume's
405
+ // ground corner moves that point (onto a reference layer under the pointer, else in the plane through it facing the
406
+ // view); a press on a line or a volume's edge moves the whole guide in that plane. The guide follows the pointer
407
+ // and is saved once, on release, as one undo step. Double-click a CV to remove it, a line to add one there.
408
+ /** The plane a drag moves in: horizontal in persp, top and bottom; the view's own axis plane in front, right… */
409
+ const dragPlane = (slot, at) => {
410
+ const c = ctx.views.cam(slot), f = c.name === 'persp' ? [0, -1, 0] : AXIS_VIEWS[c.name]?.f ?? [0, -1, 0];
411
+ const n = new THREE.Vector3(Math.abs(f[0]), Math.abs(f[1]), Math.abs(f[2]));
412
+ return new THREE.Plane().setFromNormalAndCoplanarPoint(n, at);
413
+ };
414
+ const onPlane = (slot, x, y, plane) => ctx.views.ray(slot, x, y).ray.intersectPlane(plane, new THREE.Vector3());
415
+ /**
416
+ * What a press at (x, y) would grab: {id, part: 'point' | 'corner' | 'body', k, seg?, t?, at: [x, y, z]} or null.
417
+ * Points (CVs, a null, corners) win over lines within their few pixels; the nearest wins among guides.
418
+ */
419
+ G.handleAt = (slot, x, y) => {
420
+ if (ctx.isolated) return null;
421
+ const cam = ctx.views.camera(slot);
422
+ const proj = (p) => ctx.views.project(slot, V3(p), cam);
423
+ let best = null;
424
+ const offer = (d, h, limit) => { if (d <= limit && d < (best?.d ?? Infinity)) best = { ...h, d }; };
425
+ for (const m of G.list) {
426
+ if (G.hidden.has(m.id)) continue;
427
+ const id = m.id;
428
+ if (m.kind === 'site') { const c = proj(m.points[0]); if (c) offer(Math.hypot(c.x - x, c.y - y), { id, part: 'point', k: 0, at: m.points[0] }, CROSS_PX); continue; }
429
+ if (m.kind === 'volume') {
430
+ M.volumeCorners(m).forEach((p, k) => { const c = proj(p); if (c) offer(Math.hypot(c.x - x, c.y - y) - 2, { id, part: 'corner', k, at: p }, CV_PX + 2); });
431
+ const { lo, hi } = M.boxOf(m);
432
+ for (const [a, b] of boxEdges(lo, hi)) {
433
+ const A = ctx.views.project(slot, a, cam), B = ctx.views.project(slot, b, cam);
434
+ if (A && B) offer(segDist(x, y, A, B) + 1, { id, part: 'body', at: [a.x, lo[1], a.z] }, PICK_PX);
435
+ }
436
+ continue;
437
+ }
438
+ m.points.forEach((p, k) => { const c = proj(p); if (c) offer(Math.hypot(c.x - x, c.y - y) - 2, { id, part: 'point', k, at: p }, CV_PX + 2); });
439
+ M.segmentsOf(m).forEach(([i, j], s) => {
440
+ const A = proj(m.points[i]), B = proj(m.points[j]);
441
+ if (!A || !B) return;
442
+ const dx = B.x - A.x, dy = B.y - A.y, l2 = dx * dx + dy * dy;
443
+ const t = l2 ? Math.max(0, Math.min(1, ((x - A.x) * dx + (y - A.y) * dy) / l2)) : 0;
444
+ // A screen-space fraction is not a world-space fraction in perspective. Project the viewing ray onto the
445
+ // actual segment so inserting a CV lands where the line was clicked, even when its ends differ in depth.
446
+ const a = V3(m.points[i]), b = V3(m.points[j]), at = new THREE.Vector3();
447
+ ctx.views.ray(slot, x, y).ray.distanceSqToSegment(a, b, undefined, at);
448
+ offer(segDist(x, y, A, B) + 1, { id, part: 'body', seg: s, t, at: [at.x, at.y, at.z] }, PICK_PX);
449
+ });
450
+ }
451
+ return best;
452
+ };
453
+ /** A left press on a handle starts a drag (nothing moves until the pointer does). */
454
+ G.dragStart = (slot, x, y, h) => {
455
+ const m = byId(h.id);
456
+ if (!m) return;
457
+ G.dragging = { slot, x, y, h, start: M.cloneMarkers([m])[0], plane: dragPlane(slot, V3(h.at)), from: null, moved: false, live: null };
458
+ G.dragging.from = onPlane(slot, x, y, G.dragging.plane);
459
+ };
460
+ /** The guide under the drag, moved for the pointer at (x, y). */
461
+ G.dragMove = (slot, x, y) => {
462
+ const d = G.dragging;
463
+ if (!d) return;
464
+ if (!d.moved && Math.hypot(x - d.x, y - d.y) <= 4) return;
465
+ d.moved = true;
466
+ let next = null;
467
+ if (d.h.part === 'body') {
468
+ const p = onPlane(d.slot, x, y, d.plane);
469
+ if (!p || !d.from) return;
470
+ next = M.translateMarker(d.start, [p.x - d.from.x, p.y - d.from.y, p.z - d.from.z]);
471
+ } else {
472
+ // onto a reference layer under the pointer (an imported terrain or blockout), else in the plane through the
473
+ // point: never onto the output, which the graph builds from these guides (a CV would climb the house it makes)
474
+ const hit = ctx.surfacePoint(d.slot, x, y, { layersOnly: true });
475
+ const p = hit?.surface ? hit.point : onPlane(d.slot, x, y, d.plane);
476
+ if (!p) return;
477
+ next = d.h.part === 'corner' ? M.resizeVolume(d.start, d.h.k, [p.x, p.y, p.z]) : M.movePoint(d.start, d.h.k, [p.x, p.y, p.z]);
478
+ }
479
+ if (!next) return;
480
+ d.live = next;
481
+ const i = G.list.findIndex((o) => o.id === d.h.id);
482
+ if (i >= 0) G.list[i] = next;
483
+ entries(); G.draw(); ctx.emit('guides');
484
+ const what = d.h.part === 'body' ? next.name : d.h.part === 'corner' ? `a corner of ${next.name}` : next.kind === 'site' ? next.name : `CV ${d.h.k} of ${next.name}`;
485
+ ctx.message(`moving ${what}`, 'busy');
486
+ };
487
+ /** The release: one undo step and one save for the whole drag; false when nothing moved (the press was a click). */
488
+ G.dragEnd = (cancel = false) => {
489
+ const d = G.dragging;
490
+ G.dragging = null;
491
+ if (!d || !d.moved || !d.live) return false;
492
+ const i = G.list.findIndex((o) => o.id === d.h.id);
493
+ if (i < 0) return true;
494
+ G.list[i] = d.start; // the list as it was, so the change records the drag as one step
495
+ if (cancel) {
496
+ // An earlier queued save may already have captured the live preview. Reconcile after it finishes; without
497
+ // an in-flight save this sees the original saved body and writes nothing.
498
+ entries(); G.draw(); save(); ctx.emit('guides'); ctx.message(''); return true;
499
+ }
500
+ const live = d.live;
501
+ const label = d.h.part === 'body' || live.kind === 'site' ? `move ${live.name}` : d.h.part === 'corner' ? `resize ${live.name}` : `move CV ${d.h.k} of ${live.name}`;
502
+ G.change(label, (list) => { const j = list.findIndex((o) => o.id === live.id); if (j < 0) return false; list[j] = live; });
503
+ ctx.message(`${label} · ${M.EDITOR_NAMES[live.kind]} saved to inputs/markers.json`, 'ok', 1500);
504
+ return true;
505
+ };
506
+ /** Double-click in select mode: on a CV removes it, on a line of a curve or an area adds a CV there. */
507
+ G.doubleClick = (slot, x, y) => {
508
+ const h = G.handleAt(slot, x, y), m = h && byId(h.id);
509
+ if (!m || (m.kind !== 'path' && m.kind !== 'zone')) return false;
510
+ if (h.part === 'point') {
511
+ const next = M.removePoint(m, h.k);
512
+ if (!next) { ctx.message(`${m.name} keeps its CV: a${m.kind === 'zone' ? 'n area needs 3' : ' curve needs 2'}`, '', 2000); return true; }
513
+ G.change(`remove CV ${h.k} of ${m.name}`, (list) => { list[list.findIndex((o) => o.id === m.id)] = next; });
514
+ ctx.message(`removed CV ${h.k} of ${m.name}`, 'ok', 1500);
515
+ return true;
516
+ }
517
+ const next = M.insertPoint(m, h.seg, h.at);
518
+ if (!next) return false;
519
+ G.change(`add a CV to ${m.name}`, (list) => { list[list.findIndex((o) => o.id === m.id)] = next; });
520
+ ctx.message(`added a CV to ${m.name} · drag it, double-click it to remove it`, 'ok', 2000);
521
+ return true;
522
+ };
401
523
  return G;
402
524
  }
@@ -1,4 +1,4 @@
1
- // The keymap of docs/design/viewer.md section 9: one table of actions, four presets (TopoTopo, the default;
1
+ // The keymap: one table of actions, four presets (TopoTopo, the default;
2
2
  // Maya, Houdini, Blender). Each row carries the text the overlay prints per preset and the built actions' bindings:
3
3
  // chord → action. Transform and snapping rows (phase 2) ship their text but no bindings, so a preset never changes
4
4
  // shape later. Plain data and functions: the overlay is the only DOM code, and it runs only when called.
@@ -47,6 +47,9 @@ export const ROWS = [
47
47
  },
48
48
  { label: 'place a null / curve / area / volume', maya: ['Shift+1 / 2 / 3 / 4', { keys: place }], houdini: ['Shift+1 / 2 / 3 / 4', { keys: place }], blender: ['Shift+1 / 2 / 3 / 4', { keys: place }] },
49
49
  { label: 'finish a curve / remove its last point / cancel', maya: ['Enter / Backspace / Esc', { keys: curve }], houdini: ['Enter / Backspace / Esc', { keys: curve }], blender: ['Enter / Backspace / Esc', { keys: curve }] },
50
+ // the mouse in select mode (main.js and guides.js handle these; no chords to bind)
51
+ { label: 'move a guide / one of its points', maya: ['L drag its line / the point'], houdini: ['L drag its line / the point'], blender: ['L drag its line / the point'] },
52
+ { label: 'add a CV to a curve or area / remove one', maya: ['double-click its line / the CV'], houdini: ['double-click its line / the CV'], blender: ['double-click its line / the CV'] },
50
53
  { label: 'delete the selection', maya: ['Delete', { keys: { Delete: 'delete' } }], houdini: ['Delete', { keys: { Delete: 'delete' } }], blender: ['X, Delete', { keys: { X: 'delete', Delete: 'delete' } }] },
51
54
  {
52
55
  label: 'undo / redo (guides and vars)',
@@ -179,12 +182,12 @@ export function toggleOverlay(host, presetId) {
179
182
  head.className = 'km-head';
180
183
  head.textContent = `Keymap — ${PRESETS.find((p) => p.id === presetId)?.label ?? presetId}`;
181
184
  const table = doc.createElement('table');
182
- for (const r of overlayRows(presetId)) {
185
+ // the actions the viewer has (the table holds the later ones too, so a preset never changes shape)
186
+ for (const r of overlayRows(presetId).filter((x) => x.built)) {
183
187
  const tr = doc.createElement('tr');
184
- if (!r.built) tr.className = 'later';
185
188
  const a = doc.createElement('td'), b = doc.createElement('td');
186
189
  a.textContent = r.label;
187
- b.textContent = r.text + (r.built ? '' : ' (phase 2)');
190
+ b.textContent = r.text;
188
191
  tr.append(a, b);
189
192
  table.append(tr);
190
193
  }