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,6 +1,11 @@
1
1
  // Output catalogue, previews, downloads and exports. Geometry stays server-side; cards and previews are lazy.
2
- // A published output exports to its target in the graph (io/targets.ts): its Export button writes it, Export all
3
- // writes every target, and a first export sets the target in the graph so the next click just writes again.
2
+ // A graph's results are cards, one per result (io/targets.ts publishedOutputs: the default output once, marked so). A
3
+ // card says what its result is (io/kinds.ts: its kind, mesh, instances, points, curves, terrain, textures, material, volume or
4
+ // scene, and its size; its tags; when it is not the kind its graph pins) and offers the formats that write it. Its Download gets the export as a browser download (the file itself, or a zip of its files: a sidecar, a
5
+ // textures folder), with the record of how it was made; its Export writes its target in the graph (io/targets.ts) into
6
+ // exports/, Export all every target, and a first export sets the target in the graph so the next click just writes
7
+ // again. Saved files (exports/, renders) are cards too: a sidecar or manifest beside an export (io/sidecars.ts) is
8
+ // metadata of it, not a card of its own.
4
9
  import fs from 'node:fs';
5
10
  import path from 'node:path';
6
11
  import zlib from 'node:zlib';
@@ -8,24 +13,37 @@ import { createHash } from 'node:crypto';
8
13
  import { zipSync } from 'fflate';
9
14
  import { ArtifactStore, artifactId } from '../host/artifacts.js';
10
15
  import { prepareTarget, writeTargets } from '../host/export-targets.js';
16
+ import { sidecarFile } from '../host/sidecars.js';
11
17
  import { Image, referenceableImages, imageToBytes, resizeLayer } from '../core/image.js';
12
18
  import { expandPacked } from '../core/packed.js';
13
19
  import { withHeightfieldPreview } from '../core/heightfield.js';
14
- import { withImagePreview } from '../render/texview.js';
20
+ import { withImagePreview, withMaterialPreview } from '../render/texview.js';
15
21
  import { renderGeometry } from '../render/raster.js';
16
22
  import { encodePNG } from '../render/png.js';
17
- import { exportGeometryAsync } from '../io/export.js';
18
- import { FORMAT_LABELS, TARGET_FORMATS, publishedOutputs, targetError, targetExtension } from '../io/targets.js';
23
+ import { exportGeometryAsync, exportFormatFromPath } from '../io/export.js';
24
+ import { SOURCE_INSIDE, stripExtension } from '../io/files.js';
25
+ import { fittingFormats, kindMismatch, outputKind } from '../io/kinds.js';
26
+ import { packagesNamedIn, packagesUsed } from '../graph/packages.js';
27
+ import { PackageUses } from '../packages/registry.js';
28
+ import { SIDECAR_NAMES, SIDECAR_TEXT } from '../io/sidecars.js';
29
+ import { STOPPED } from '../graph/engine.js';
30
+ import { FORMAT_LABELS, TARGET_FORMATS, prefixGone, publishedOutputs, resolveTarget, targetError, targetRefusal, targetExtension, targetFormat, targetPathText } from '../io/targets.js';
19
31
  import { summarize } from '../inspect.js';
20
32
  const digest = (x) => createHash('sha256').update(x).digest('hex');
21
33
  const imageExt = /\.(png|jpe?g|webp)$/i;
22
- const meshExt = /\.(glb|gltf|obj|stl|ply|geo|bgeo|json|csv)$/i;
23
- const mime = (p) => ({ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.glb': 'model/gltf-binary' })[path.extname(p).toLowerCase()] ?? 'application/octet-stream';
34
+ /** files the file node reads (io/import.ts): a saved one previews as a model */
35
+ const modelExt = /\.(glb|gltf|obj|stl|ply|geo|bgeo|json|csv)$/i;
36
+ const MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.glb': 'model/gltf-binary', '.gltf': 'model/gltf+json', '.json': 'application/json', '.zip': 'application/zip' };
37
+ const mime = (p) => MIME[path.extname(p).toLowerCase()] ?? 'application/octet-stream';
24
38
  const deflate = (d) => zlib.deflateSync(d, { level: 6 });
25
39
  const stamp = (p) => { const s = fs.statSync(p, { throwIfNoEntry: false }); return s ? `${s.size}:${s.mtimeMs}` : 'missing'; };
26
40
  function err(status, message) { throw Object.assign(new Error(message), { status }); }
27
41
  const idFor = (...parts) => digest(JSON.stringify(parts)).slice(0, 24);
28
42
  const inside = (dir, p) => { const rel = path.relative(dir, p); return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel)); };
43
+ /** The folder every path shares, so zip entries named relative to it never climb out with "../". */
44
+ const commonDir = (paths) => paths.map((p) => path.dirname(p)).reduce((a, b) => { while (a !== path.dirname(a) && path.relative(a, b).startsWith('..'))
45
+ a = path.dirname(a); return a; });
46
+ const fmt = (x) => String(+x.toFixed(Math.abs(x) >= 100 ? 1 : 2));
29
47
  /** Predictable ZIP bytes, retaining the bundle directory structure. */
30
48
  export function outputZip(files) {
31
49
  const entries = Object.create(null);
@@ -33,6 +51,26 @@ export function outputZip(files) {
33
51
  entries[f.name] = [f.bytes, { mtime: new Date(1980, 0, 1), level: 6 }];
34
52
  return zipSync(entries);
35
53
  }
54
+ /**
55
+ * The files a download of an export carries: all it writes, except the standalone record of a format whose one file
56
+ * carries the record itself (glb, gltf: io/files.ts SOURCE_INSIDE), so a GLB downloads as itself.
57
+ */
58
+ export function downloadFiles(format, files, sourceManifest) {
59
+ return SOURCE_INSIDE.includes(format) && sourceManifest ? files.filter((f) => f.path !== sourceManifest) : files;
60
+ }
61
+ /** What a saved heightmap is, from its sidecar: "heightmap 2049 × 2049, 2 m · height 0 .. 350 m". */
62
+ function heightmapAbout(sidecar) {
63
+ try {
64
+ const j = JSON.parse(fs.readFileSync(sidecar, 'utf8'));
65
+ const [w, h] = j.resolution ?? [];
66
+ if (!(w > 0 && h > 0))
67
+ return undefined;
68
+ return `heightmap ${w} × ${h}${typeof j.cell_size === 'number' ? `, ${fmt(j.cell_size)} m` : ''}${typeof j.height_min === 'number' && typeof j.height_max === 'number' ? ` · height ${fmt(j.height_min)} .. ${fmt(j.height_max)} m` : ''}`;
69
+ }
70
+ catch {
71
+ return undefined;
72
+ }
73
+ }
36
74
  export function createOutputs(ws, changed, opts = {}) {
37
75
  const store = new ArtifactStore(ws.exportDir);
38
76
  const items = new Map(), previewCache = new Map();
@@ -61,10 +99,54 @@ export function createOutputs(ws, changed, opts = {}) {
61
99
  for (const [name, img] of referenceableImages(item.geo)) {
62
100
  const id = idFor(item.entry.id, name);
63
101
  items.set(id, { owner: item, img, entry: { id, origin: item.entry.origin, parent: item.entry.id, graph: item.entry.graph, node: item.entry.node,
64
- label: name, kind: 'image', generated: true, status: 'ready', revision: item.entry.revision,
102
+ label: name, view: 'image', about: `${img.width} × ${img.height} px`, generated: true, status: 'ready', revision: item.entry.revision,
65
103
  width: img.width, height: img.height, layers: [...img.layers.keys()], layer: img.mainLayer, image: name } });
66
104
  }
67
105
  };
106
+ /**
107
+ * What a cooked result is, on its card: kind, words, size, heightfield; a published one's fitting formats, and a
108
+ * warning when it is not the kind its graph pins (publishing the package would block on it).
109
+ */
110
+ const describe = (e, g) => {
111
+ const info = outputKind(g);
112
+ e.kind = info.published ?? 'empty';
113
+ e.parts = info.kind;
114
+ e.about = info.text;
115
+ e.size = info.size;
116
+ if (info.heightfield)
117
+ e.heightfield = info.heightfield;
118
+ else
119
+ delete e.heightfield;
120
+ if (e.exportable)
121
+ e.formats = fittingFormats(info);
122
+ const said = e.pinned ? kindMismatch(e.pinned, info) : null;
123
+ if (said)
124
+ e.warning = `${e.output ? `output "${e.output}": ` : ''}${said}`;
125
+ else
126
+ delete e.warning;
127
+ return info;
128
+ };
129
+ /**
130
+ * A card whose cook a person stopped (Session.held) goes back to the card it replaced, with the last finished
131
+ * result; one that never finished says it was stopped.
132
+ */
133
+ const unstop = (item, at) => {
134
+ const prev = item.prev, e = item.entry;
135
+ if (!prev) {
136
+ e.status = 'error';
137
+ e.error = `${STOPPED}${at ? ` at ${at}` : ''}: change a value (or the graph) to cook it`;
138
+ return;
139
+ }
140
+ // it shows the last finished result: out of date with the values now
141
+ prev.entry.stale = true;
142
+ items.set(e.id, prev);
143
+ for (const v of items.values())
144
+ if (v.owner === item) {
145
+ v.owner = prev;
146
+ v.entry.status = 'ready';
147
+ delete v.entry.error;
148
+ }
149
+ };
68
150
  const cook = (item) => {
69
151
  if (item.pending)
70
152
  return item.pending;
@@ -75,25 +157,49 @@ export function createOutputs(ws, changed, opts = {}) {
75
157
  if (closed || items.get(e.id) !== item)
76
158
  return;
77
159
  try {
160
+ // a graph whose cooks the person stopped is not cooked again on its own: the card waits for a change
161
+ if (!item.file && ws.held(e.graph)) {
162
+ unstop(item);
163
+ return;
164
+ }
78
165
  const r = item.file
79
166
  ? await ws.engine.cook({ nodes: { file: { type: 'file', params: { path: item.file } } }, output: 'file' })
80
- : await ws.cook(e.graph, e.node);
167
+ : await ws.cook(e.graph, e.node, undefined, { kind: 'preview' });
81
168
  if (item.key !== key || items.get(e.id) !== item)
82
169
  return;
170
+ // stopped for a newer value: the next refresh (after that value's cook) cooks the card again
171
+ if (r.stopped && !ws.held(e.graph)) {
172
+ item.key = undefined;
173
+ return;
174
+ }
175
+ if (r.stopped) {
176
+ unstop(item, r.stopped);
177
+ return;
178
+ }
83
179
  if (!r.ok || !r.geo)
84
180
  throw new Error(r.errors.map((x) => `${x.node}: ${x.message}`).join('\n') || 'no geometry');
181
+ delete item.prev;
85
182
  item.geo = r.geo;
86
183
  e.status = 'ready';
87
184
  delete e.error;
185
+ delete e.stale;
186
+ // a saved file that says what it is already (a heightmap by its sidecar) keeps that
187
+ const info = item.file && e.kind ? outputKind(r.geo) : describe(e, r.geo);
188
+ if (item.file && !e.parts)
189
+ e.parts = info.kind;
88
190
  const firstImage = referenceableImages(r.geo).values().next().value;
89
- if (!r.geo.numPoints && !r.geo.numPrims && firstImage) {
191
+ if (info.kind === 'image' && firstImage) {
90
192
  item.img = firstImage;
91
- e.kind = 'image';
193
+ e.view = 'image';
92
194
  e.width = firstImage.width;
93
195
  e.height = firstImage.height;
94
196
  e.layers = [...firstImage.layers.keys()];
95
197
  e.layer = firstImage.mainLayer;
96
198
  }
199
+ else if (!item.file) {
200
+ e.view = 'model';
201
+ delete item.img;
202
+ }
97
203
  if (!item.file)
98
204
  e.revision = digest(`${key}:${r.results.get(r.target)?.sig ?? ''}`);
99
205
  e.summary = summarize(r.geo);
@@ -119,7 +225,8 @@ export function createOutputs(ws, changed, opts = {}) {
119
225
  };
120
226
  /** The last export of a published output to its current target, from the receipts. */
121
227
  const lastSaved = (records, graph, p) => {
122
- if (!p.target)
228
+ // a target refused (its path written with a prefix that is gone) writes nothing
229
+ if (!p.target || p.target.refused)
123
230
  return undefined;
124
231
  const dest = path.join(ws.exportDir, ...p.target.path.split('/'));
125
232
  let best;
@@ -135,6 +242,38 @@ export function createOutputs(ws, changed, opts = {}) {
135
242
  }
136
243
  return best;
137
244
  };
245
+ /** How a saved file shows: an image, a model the file node reads, or a file to download. */
246
+ const viewOf = (file) => (imageExt.test(file) ? 'image' : modelExt.test(file) && !/\.r16$/i.test(file) ? 'model' : 'file');
247
+ /** A saved output: its files (the main one first, each sidecar with its role), how it shows and downloads. */
248
+ const savedEntry = (a, files, id, revision) => {
249
+ const role = new Map();
250
+ for (const p of files) {
251
+ const s = sidecarFile(p);
252
+ if (s)
253
+ role.set(p, s.role);
254
+ }
255
+ const main = files.find((p) => !role.has(p)) ?? files[0];
256
+ const ordered = [main, ...files.filter((p) => p !== main)];
257
+ const format = a.format ?? exportFormatFromPath(main);
258
+ const heightmapSidecar = ordered.find((p) => role.get(p) === 'heightmap');
259
+ const meta = role.has(main);
260
+ const fileList = ordered.map((p) => {
261
+ const r = role.get(p);
262
+ return { id: artifactId(p), name: path.relative(path.dirname(main), p).split(path.sep).join('/'), size: fs.statSync(p, { throwIfNoEntry: false })?.size ?? 0,
263
+ ...(r ? { role: r, about: `${SIDECAR_NAMES[r]}: ${SIDECAR_TEXT[r]}` } : {}) };
264
+ });
265
+ // the record of a glb / gltf is inside it: its download is the file itself (downloadFiles)
266
+ const zip = downloadFiles(exportFormatFromPath(main), ordered.map((p) => ({ path: p })), `${main}.source.json`).length > 1;
267
+ const label = targetFormat(format) ? FORMAT_LABELS[targetFormat(format)] : path.extname(main).slice(1).toUpperCase() || 'file';
268
+ return { file: main, files: ordered, entry: {
269
+ id, origin: 'saved', label: a.label, graph: a.graph, node: a.node, status: 'ready', revision,
270
+ view: meta ? 'file' : viewOf(main), ...(meta ? { kind: 'metadata' } : heightmapSidecar ? { kind: 'terrain' } : imageExt.test(main) ? { kind: 'textures' } : {}),
271
+ about: meta ? `${SIDECAR_NAMES[role.get(main)]}: ${SIDECAR_TEXT[role.get(main)]}` : (heightmapSidecar && heightmapAbout(heightmapSidecar)) || `${label}${ordered.length > 1 ? ` · ${ordered.length} files` : ''}`,
272
+ summary: a.format === 'reference' ? 'Reference image' : `Saved ${a.format ?? path.extname(main).slice(1)} output`,
273
+ files: fileList,
274
+ download: { name: zip ? `${path.basename(stripExtension(a.label.replace(/[\\/]+$/, ''))) || 'export'}.zip` : path.basename(main), zip },
275
+ } };
276
+ };
138
277
  const refresh = () => {
139
278
  const alive = new Set();
140
279
  const inputStamp = JSON.stringify(ws.listInputs().map((f) => [f.path, f.size, f.mtime]));
@@ -155,21 +294,46 @@ export function createOutputs(ws, changed, opts = {}) {
155
294
  }
156
295
  catch { /* a disappearing file is reported by the next cook */ }
157
296
  }
158
- const workspaceRevision = digest(JSON.stringify([...ws.graphs]) + inputStamp + JSON.stringify([...sourceFiles]));
297
+ // the session values (a person tuning a graph file in the viewer) are part of what each output shows, and so are
298
+ // the packages: an update, or a save in a working folder the session follows, changes what they resolve to
299
+ const sessionRevision = digest(JSON.stringify([...ws.graphs].map(([n, g]) => [n, g, ws.sessionVars(n)])) + inputStamp + JSON.stringify([...sourceFiles]) + (ws.packages?.revision() ?? ''));
159
300
  const records = store.records();
160
- for (const [graph, spec] of ws.graphs) {
301
+ // the packages shown live this session (their working folders): the results that use them show unpublished edits
302
+ const following = ws.packages instanceof PackageUses ? ws.packages.following().map((f) => f.package) : [];
303
+ // the graph the page shows first cooks first: its cards are queued before the others'
304
+ const first = opts.first?.();
305
+ const graphs = [...ws.graphs].sort(([a], [b]) => Number(b === first) - Number(a === first));
306
+ for (const [graph, spec] of graphs) {
307
+ const live = following.length ? packagesNamedIn(spec).filter((x) => following.includes(x)) : [];
161
308
  for (const p of publishedOutputs(graph, spec, ws.engine.findOutput(spec).name)) {
162
309
  const id = idFor('graph', graph, p.output === null ? 'default' : 'named', p.output ?? 'main');
163
310
  alive.add(id);
164
- const key = workspaceRevision, old = items.get(id);
165
- const meta = { label: p.label, output: p.output, target: p.target ? { format: p.target.format, path: p.target.path, options: p.target.options } : null, saved: lastSaved(records, graph, p) };
166
- if (old?.key === key) {
311
+ const key = sessionRevision, old = items.get(id);
312
+ const named = p.output === null ? undefined : spec.outputs?.[p.output], pinned = named?.kind, tags = named?.tags;
313
+ const meta = {
314
+ label: p.label, output: p.output, default: p.default, target: p.target ? { format: p.target.format, path: targetPathText(p.target), options: p.target.options, ...(p.target.refused ? { refused: prefixGone(p.target.refused) } : {}) } : null,
315
+ saved: lastSaved(records, graph, p), ...(pinned ? { pinned } : {}), ...(Array.isArray(tags) && tags.length ? { tags } : {}), ...(live.length ? { live } : {}),
316
+ };
317
+ // the same inputs, or a graph held after a stop (the card keeps what it shows until something changes)
318
+ if (old?.key === key || (old && ws.held(graph))) {
167
319
  Object.assign(old.entry, meta);
168
320
  if (!meta.saved)
169
321
  delete old.entry.saved;
322
+ if (!meta.tags)
323
+ delete old.entry.tags;
324
+ if (!meta.live)
325
+ delete old.entry.live;
170
326
  continue;
171
327
  }
172
- const item = { geo: old?.geo, key, entry: { id, origin: 'published', graph, node: p.node, kind: 'geometry', generated: true, exportable: true, status: 'loading', revision: key, ...meta } };
328
+ // while it cooks again, the card keeps what it said (summary, kind, formats), so the details shown for it keep
329
+ // their size; the card it replaces comes back if a person stops the cook
330
+ const prev = old?.prev ?? (old?.entry.status === 'ready' ? old : undefined);
331
+ const kept = {};
332
+ if (old)
333
+ for (const k of ['summary', 'kind', 'parts', 'about', 'size', 'heightfield', 'formats', 'width', 'height', 'layers', 'layer', 'warning'])
334
+ if (old.entry[k] !== undefined)
335
+ kept[k] = old.entry[k];
336
+ const item = { geo: old?.geo, img: old?.img, key, prev, entry: { id, origin: 'published', graph, node: p.node, view: old?.entry.view ?? 'model', generated: true, exportable: true, status: 'loading', revision: key, ...kept, ...meta } };
173
337
  if (!meta.saved)
174
338
  delete item.entry.saved;
175
339
  // Carry last valid images until the replacement cook completes.
@@ -195,28 +359,29 @@ export function createOutputs(ws, changed, opts = {}) {
195
359
  const revision = digest(files.map((p) => p + stamp(p)).join('|'));
196
360
  if (items.get(id)?.entry.revision === revision)
197
361
  continue;
198
- const file = files[0];
199
- const kind = files.length > 1 ? 'bundle' : imageExt.test(file) ? 'image' : meshExt.test(file) ? 'geometry' : 'file';
200
- items.set(id, { file, files, entry: { id, origin: 'saved', label: a.label, graph: a.graph, node: a.node, kind, status: 'ready', revision,
201
- summary: a.format === 'reference' ? 'Reference image' : `Saved ${a.format ?? path.extname(file).slice(1)} output`,
202
- files: files.map((p) => ({ id: artifactId(p), name: path.relative(path.dirname(file), p).split(path.sep).join('/'), size: fs.statSync(p, { throwIfNoEntry: false })?.size ?? 0 })) } });
362
+ items.set(id, savedEntry(a, files, id, revision));
363
+ }
364
+ // A bundle's own files (not its sidecars) are individual inspectable outputs as well as downloads.
365
+ for (const item of [...items.values()]) {
366
+ if (!alive.has(item.entry.id) || item.entry.origin !== 'saved' || !item.files)
367
+ continue;
368
+ const parts = item.files.filter((p, i) => !item.entry.files?.[i]?.role);
369
+ if (parts.length < 2)
370
+ continue;
371
+ for (const file of parts) {
372
+ const stat = fs.statSync(file, { throwIfNoEntry: false });
373
+ if (!stat?.isFile())
374
+ continue;
375
+ const id = item.entry.id + '-' + artifactId(file);
376
+ alive.add(id);
377
+ const revision = digest(stamp(file));
378
+ if (items.get(id)?.entry.revision === revision)
379
+ continue;
380
+ items.set(id, { file, files: [file], entry: { id, origin: item.entry.origin, parent: item.entry.id, graph: item.entry.graph, label: path.basename(file),
381
+ view: viewOf(file), ...(imageExt.test(file) ? {} : { about: path.extname(file).slice(1).toUpperCase() }), status: 'ready', revision,
382
+ files: [{ id: artifactId(file), name: path.basename(file), size: stat.size }], download: { name: path.basename(file), zip: false } } });
383
+ }
203
384
  }
204
- // Bundle contents are individual inspectable outputs as well as downloads.
205
- for (const item of [...items.values()])
206
- if (alive.has(item.entry.id) && item.files && item.files.length > 1)
207
- for (const file of item.files) {
208
- const stat = fs.statSync(file, { throwIfNoEntry: false });
209
- if (!stat?.isFile())
210
- continue;
211
- const id = item.entry.id + '-' + artifactId(file);
212
- alive.add(id);
213
- const revision = digest(stamp(file));
214
- if (items.get(id)?.entry.revision === revision)
215
- continue;
216
- items.set(id, { file, files: [file], entry: { id, origin: item.entry.origin, parent: item.entry.id, graph: item.entry.graph, label: path.basename(file),
217
- kind: imageExt.test(file) ? 'image' : meshExt.test(file) ? 'geometry' : 'file', status: 'ready', revision,
218
- files: [{ id: artifactId(file), name: path.basename(file), size: stat.size }] } });
219
- }
220
385
  for (const [id, item] of items)
221
386
  if (!alive.has(id) && !item.owner) {
222
387
  items.delete(id);
@@ -239,12 +404,17 @@ export function createOutputs(ws, changed, opts = {}) {
239
404
  const spec = ws.getGraph(entry.graph);
240
405
  return publishedOutputs(entry.graph, spec, ws.engine.findOutput(spec).name).find((p) => p.output === entry.output) ?? err(404, 'output no longer exists');
241
406
  };
242
- /** Cook now and serialize to the target: the export writes the current graph, whatever the preview last showed. */
407
+ /**
408
+ * Cook now and serialize to the target (nothing is written yet): the export writes the current graph, whatever the
409
+ * preview last showed, and its record names the time the cook ran at.
410
+ */
243
411
  const prepare = async (graph, p) => {
244
- const r = await ws.cook(graph, p.node);
412
+ const r = await ws.cook(graph, p.node, undefined, { kind: 'export' });
413
+ if (r.stopped)
414
+ err(409, `${p.label} (${graph}): the export was stopped at ${r.stopped}; nothing was written`);
245
415
  if (!r.ok || !r.geo)
246
416
  err(422, `${p.label} (${graph}): ` + (r.errors.map((e) => `${e.node}: ${e.message}`).join('; ') || 'no geometry'));
247
- return prepareTarget(r.geo, graph, p, ws.exportDir, ws.engine.host);
417
+ return prepareTarget(r.geo, graph, p, ws.exportDir, ws.engine.host, { frame: r.frame, fps: r.fps, packages: packagesUsed(ws.engine, p.spec, ws.packages?.published?.() ?? ws.engine.root) });
248
418
  };
249
419
  /** One export at a time, so two clicks never interleave their writes. */
250
420
  const exclusive = async (work) => {
@@ -275,12 +445,12 @@ export function createOutputs(ws, changed, opts = {}) {
275
445
  async handle(req, res, u, readJSON) {
276
446
  if (!u.pathname.startsWith('/api/output'))
277
447
  return false;
278
- const send = (body, type, name) => {
279
- res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', ...(name ? { 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}` } : {}) });
448
+ const send = (body, type, name, extra = {}) => {
449
+ res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', ...(name ? { 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}` } : {}), ...extra });
280
450
  res.end(body);
281
451
  };
282
452
  const json = (j) => send(JSON.stringify(j), 'application/json');
283
- const posts = ['/api/output/export', '/api/output/export-all'];
453
+ const posts = ['/api/output/export', '/api/output/export-all', '/api/output/download'];
284
454
  try {
285
455
  if (posts.includes(u.pathname) ? req.method !== 'POST' : req.method !== 'GET')
286
456
  err(405, posts.includes(u.pathname) ? 'POST required' : 'method not allowed');
@@ -298,15 +468,28 @@ export function createOutputs(ws, changed, opts = {}) {
298
468
  return await exclusive(async () => {
299
469
  const graph = item.entry.graph;
300
470
  if (body.export !== undefined) {
301
- if (body.export !== null && targetError(body.export))
302
- err(400, targetError(body.export));
471
+ // a target that is invalid, or written with the prefix that is gone, is refused before it is set or saved
472
+ if (body.export !== null) {
473
+ const why = targetError(body.export) ?? targetRefusal(body.export);
474
+ if (why)
475
+ err(400, why);
476
+ }
303
477
  try {
304
478
  await ws.edit(graph, [{ op: 'export', ...(item.entry.output === null ? {} : { output: item.entry.output }), export: body.export }]);
305
479
  }
306
480
  catch (e) {
307
481
  err(400, e.message);
308
482
  }
309
- opts.persistGraph?.(graph);
483
+ // a graph from a file: the target goes into the file (only that key changes), the session values stay
484
+ if (opts.source?.graph === graph) {
485
+ const at = item.entry.output === null ? ['export'] : ['outputs', item.entry.output, 'export'];
486
+ try {
487
+ opts.source.save([{ path: at, value: body.export ?? undefined }]);
488
+ }
489
+ catch (e) {
490
+ err(500, `could not write ${opts.source.label}: ${e.message}`);
491
+ }
492
+ }
310
493
  if (body.export === null) {
311
494
  rescan();
312
495
  changed();
@@ -321,17 +504,40 @@ export function createOutputs(ws, changed, opts = {}) {
321
504
  writeTargets([prepared], ws.exportDir);
322
505
  rescan();
323
506
  changed();
324
- json({ ok: true, path: p.target.path, files: prepared.files.length, summary: prepared.summary, warnings: prepared.warnings });
507
+ json({ ok: true, path: targetPathText(p.target), file: path.join(prepared.root, ...p.target.path.split('/')), files: prepared.files.length, summary: prepared.summary, warnings: prepared.warnings });
325
508
  return true;
326
509
  });
327
510
  }
511
+ if (u.pathname === '/api/output/download') {
512
+ // {id, export?}: the export (its target, or the format and options given) as a download; nothing is written
513
+ const body = await readJSON(req), item = get(body?.id);
514
+ if (!item.entry.exportable)
515
+ err(400, 'only a published output downloads in a format of choice; a saved file downloads as it is');
516
+ const p = published(item.entry), spec = body.export ?? (p.target ? { format: p.target.format, path: targetPathText(p.target), ...p.target.options } : null);
517
+ if (!spec)
518
+ err(400, 'choose a format to download');
519
+ if (targetError(spec))
520
+ err(400, targetError(spec));
521
+ const target = resolveTarget(spec, p.output ?? item.entry.graph);
522
+ const prepared = await prepare(item.entry.graph, { ...p, target });
523
+ const files = downloadFiles(target.format, prepared.files, prepared.sourceManifest);
524
+ const extra = { 'x-file-count': String(files.length) };
525
+ if (files.length === 1) {
526
+ send(files[0].bytes, mime(files[0].path), path.basename(files[0].path), extra);
527
+ return true;
528
+ }
529
+ const root = commonDir(files.map((f) => f.path));
530
+ const zip = outputZip(files.map((f) => ({ name: path.relative(root, f.path).split(path.sep).join('/'), bytes: f.bytes })));
531
+ send(zip, 'application/zip', `${path.basename(stripExtension(target.path.replace(/[\\/]+$/, ''))) || 'export'}.zip`, extra);
532
+ return true;
533
+ }
328
534
  if (u.pathname === '/api/output/export-all') {
329
535
  return await exclusive(async () => {
330
536
  const targets = [], skipped = [];
331
537
  for (const [graph, spec] of ws.graphs)
332
538
  for (const p of publishedOutputs(graph, spec, ws.engine.findOutput(spec).name))
333
539
  if (p.target)
334
- targets.push({ graph, p });
540
+ targets.push({ graph, p: p });
335
541
  else
336
542
  skipped.push({ graph, label: p.label });
337
543
  if (!targets.length)
@@ -360,10 +566,8 @@ export function createOutputs(ws, changed, opts = {}) {
360
566
  if (!item.files?.length)
361
567
  err(400, 'no saved files');
362
568
  // names relative to the folder every file shares, so no entry climbs out with "../"
363
- const common = (a, b) => { while (a !== path.dirname(a) && path.relative(a, b).startsWith('..'))
364
- a = path.dirname(a); return a; };
365
- const root = item.files.map((p) => path.dirname(p)).reduce(common);
366
- send(outputZip(item.files.map((p) => ({ name: path.relative(root, p).split(path.sep).join('/'), bytes: fs.readFileSync(p) }))), 'application/zip', item.entry.label + '.zip');
569
+ const root = commonDir(item.files);
570
+ send(outputZip(item.files.map((p) => ({ name: path.relative(root, p).split(path.sep).join('/'), bytes: fs.readFileSync(p) }))), 'application/zip', item.entry.download?.zip ? item.entry.download.name : item.entry.label + '.zip');
367
571
  return true;
368
572
  }
369
573
  if (u.pathname === '/api/output/image' || u.pathname === '/api/output/thumb' && item.img) {
@@ -412,10 +616,14 @@ export function createOutputs(ws, changed, opts = {}) {
412
616
  send(fs.readFileSync(item.file), mime(item.file));
413
617
  return true;
414
618
  }
619
+ if (item.entry.view === 'file')
620
+ err(400, `${item.entry.label} is not geometry to show: download it`);
415
621
  const g = await geometry(item), thumb = u.pathname.endsWith('/thumb');
416
- const bytes = await cache(`${item.entry.id}:${item.entry.revision}:${thumb}`, async () => {
622
+ // heightfields: the layer drawn in red (the page's layer picker; the mask by default)
623
+ const tint = u.searchParams.get('heightfield_layer') || 'mask';
624
+ const bytes = await cache(`${item.entry.id}:${item.entry.revision}:${thumb}:${thumb ? '' : tint}`, async () => {
417
625
  if (!thumb)
418
- return exportGeometryAsync(withImagePreview(withHeightfieldPreview(g)), 'glb', { custom: false, splitByName: false, readFile: (p) => ws.engine.host.readFile(p) });
626
+ return exportGeometryAsync(withImagePreview(withMaterialPreview(withHeightfieldPreview(g, 256, tint))), 'glb', { custom: false, splitByName: false, readFile: (p) => ws.engine.host.readFile(p) });
419
627
  const r = renderGeometry(g, { size: 160, views: ['persp'], viewLabels: false });
420
628
  return encodePNG(r.rgba.subarray(0, r.width * 160 * 4), r.width, 160, deflate);
421
629
  });
@@ -0,0 +1,121 @@
1
+ import type http from 'node:http';
2
+ import type { Session } from '../session.ts';
3
+ /** A version on a package's card: its number, note and date; `big` when it starts a big version, `marked` by its author. */
4
+ export interface VersionRow {
5
+ version: string;
6
+ note: string;
7
+ published: string;
8
+ big: boolean;
9
+ marked: boolean;
10
+ }
11
+ /** A package on the Packages tab. */
12
+ export interface PackageRow {
13
+ package: string;
14
+ /** the version in use (the manifest's "uses"); null for a package the session follows without using it yet */
15
+ version: string | null;
16
+ /** the note and date of the version in use, from the package's copy */
17
+ note?: string;
18
+ published?: string;
19
+ /**
20
+ * the outputs of the version in use (its copy's record) with their kinds and tags: "owner/name/output", or
21
+ * "owner/name" for a default output that is no named output; `used` when a graph of the package names it
22
+ */
23
+ outputs?: {
24
+ type: string;
25
+ label?: string;
26
+ kind?: string;
27
+ tags: string[];
28
+ used?: boolean;
29
+ }[];
30
+ /** one of TopoTopo's own packages (its built-in library) */
31
+ builtin: boolean;
32
+ /**
33
+ * it can show the edits of its working folder live: it has exactly one, and it is not one of TopoTopo's own unless the
34
+ * package is inside TopoTopo's own repository (whose library folder holds the built-in packages' working folders)
35
+ */
36
+ canFollow: boolean;
37
+ /** the nodes of the package's graphs that use it: a node of its type, or one whose nested graph names it */
38
+ usedBy: {
39
+ graph: string;
40
+ node: string;
41
+ type: string;
42
+ }[];
43
+ /** the small update (the newest version with the same big number) and the big one */
44
+ small?: string;
45
+ big?: string;
46
+ /** every version after the one in use, oldest first */
47
+ newer: VersionRow[];
48
+ /** the place that has it, as people read it (the workspace "x", library "props", TopoTopo's built-in library) */
49
+ places: string[];
50
+ /** its working folder there: the follow switch needs one */
51
+ working: {
52
+ place: string;
53
+ dir: string;
54
+ }[];
55
+ /** the working folder this session follows, null while it cooks from its copy */
56
+ followed: {
57
+ place: string;
58
+ dir: string;
59
+ } | null;
60
+ /** why its versions could not be looked up */
61
+ error?: string;
62
+ /** after a big update applied in this viewer: what the graphs must change for it, until the person dismisses it */
63
+ mustChange?: {
64
+ from: string;
65
+ to: string;
66
+ items: string[];
67
+ };
68
+ }
69
+ /** A before/after in progress (the {compare} events), or how it ended. */
70
+ export interface CompareProgress {
71
+ id: string;
72
+ package: string;
73
+ from: string;
74
+ to: string;
75
+ big: boolean;
76
+ /** cooks done, of all (two per place), and what cooks now */
77
+ done: number;
78
+ total: number;
79
+ what: string;
80
+ /** ms since it started */
81
+ elapsed: number;
82
+ running: boolean;
83
+ /** a stop was asked for: the node cooking runs to its end */
84
+ stopping: boolean;
85
+ stopped?: boolean;
86
+ /** a newer before/after took its place */
87
+ superseded?: boolean;
88
+ error?: string;
89
+ }
90
+ export interface PackagesState {
91
+ /** the open package: its id, title, label, folder, the places it finds packages in (TopoTopo's built-in library after them) and the name it publishes under; null: the viewer's graphs are in no package (nothing to show) */
92
+ package: {
93
+ id: string;
94
+ title: string;
95
+ label: string;
96
+ dir: string;
97
+ places: string[];
98
+ name: string | null;
99
+ } | null;
100
+ packages: PackageRow[];
101
+ problems: string[];
102
+ /** the before/after in progress, and the last one finished (GET /api/packages/compare has it in full) */
103
+ running: CompareProgress | null;
104
+ compare: {
105
+ id: string;
106
+ package: string;
107
+ from: string;
108
+ to: string;
109
+ } | null;
110
+ }
111
+ export declare function createPackages(ws: Session, broadcast: (ev: object) => void): {
112
+ /** what the Packages tab shows (GET /api/packages) */
113
+ state: () => PackagesState;
114
+ /**
115
+ * What a change in a package's working folder sets off (`rel`: the file, as the watcher names it), and the check
116
+ * the timer makes, at once: for a test, or a host that knows a folder changed, without waiting for the watchers.
117
+ */
118
+ poke(pkg?: string, rel?: string): void;
119
+ close(): void;
120
+ handle(req: http.IncomingMessage, res: http.ServerResponse, u: URL, readJSON: (r: http.IncomingMessage) => Promise<any>): Promise<boolean>;
121
+ };