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
@@ -3,9 +3,9 @@
3
3
  // Geometry.volumes (core/heightfield.ts): a grid in XZ with named float layers. Every node clones its input and
4
4
  // writes new layer arrays (Heightfield.writable), never into arrays it did not allocate.
5
5
  import { Geometry } from '../core/geometry.js';
6
- import { Heightfield, MAX_SAMPLES, asHeightfield, bilinear, blurGrid, curvesOf, distanceTransform, heightfieldToMesh, heightfieldsOf, isHeightfield, layerStats, rasterizeMesh, slopeLayer, smoothstep, splatSegment, transformHeightfield, } from '../core/heightfield.js';
7
- import { erodeStep, makeErosionField } from '../core/erosion.js';
8
- import { fractal, makeNoise } from '../core/noise.js';
6
+ import { Heightfield, MAX_SAMPLES, asHeightfield, bilinear, blurGrid, cropHeightfield, curvesOf, distanceTransform, heightfieldToMesh, heightfieldsOf, isHeightfield, layerStats, rasterizeMesh, slopeLayer, smoothstep, splatSegment, transformHeightfield, } from '../core/heightfield.js';
7
+ import { dropletParams, erodeStep, makeErosionField } from '../core/erosion.js';
8
+ import { fractal, makeNoise, makeWarp } from '../core/noise.js';
9
9
  import { rng } from '../core/random.js';
10
10
  import { decodePNG, pngChannel } from '../io/png-decode.js';
11
11
  import { defineNode } from '../graph/registry.js';
@@ -16,6 +16,8 @@ import { connectivity } from '../core/topology.js';
16
16
  import { minDistanceSelect } from '../core/pcg.js';
17
17
  import { P, simBudget } from './util.js';
18
18
  import { wasmCallUnderBudget } from './wasmcall.js';
19
+ import { codeVarDecl, codeVarNames, codeVarValues } from '../core/usercode.js';
20
+ import { scriptVarsGuard } from '../core/snippet-lib.js';
19
21
  import { getLoadedKernels, loadHostKernels } from '../wasm/kernels.js';
20
22
  // ---------------------------------------------------------------- shared
21
23
  const NO_FIELD = 'create one with heightfield, heightfield_from_mesh or heightfield_from_image';
@@ -159,6 +161,11 @@ const NOISE_PARAMS = {
159
161
  range: { type: 'enum', options: ['zero_centered', 'positive'], default: 'zero_centered', desc: 'zero_centered: noise in [-amplitude, amplitude]; positive: [0, amplitude]' },
160
162
  offset: { type: 'vec3', default: [0, 0, 0], desc: 'noise-space offset (scrolls the pattern; Y picks another slice)', aliases: ['translate_noise', 'noise_offset'] },
161
163
  seed: P.seed(),
164
+ warp_amplitude: { type: 'float', default: 0, min: 0, desc: 'domain warp: how far (metres) a second noise moves each sample\'s lookup along X and Z, bending ridges, valleys and contours into meanders (0 = off)', aliases: ['warp', 'warp_amount'] },
165
+ warp_element_size: { type: 'float', default: 10, min: 0.001, desc: 'domain warp: size of the bends (metres); frequency = 1 / warp_element_size' },
166
+ warp_frequency: { type: 'float', default: 0, min: 0, desc: 'domain warp: bends per metre; > 0 overrides warp_element_size' },
167
+ warp_octaves: { type: 'int', default: 3, min: 1, max: 8, desc: 'domain warp: fractal octaves of the warp noise (more = wigglier bends)' },
168
+ warp_seed: { ...P.seed(), desc: 'domain warp: seed of the warp noise (independent of seed)' },
162
169
  };
163
170
  function noiseValues(hf, p) {
164
171
  const base = makeNoise(p.noise, p.seed);
@@ -168,10 +175,22 @@ function noiseValues(hf, p) {
168
175
  const [ox, oy, oz] = p.offset;
169
176
  const worley = p.noise === 'worley' && (p.fractal === 'fbm' || p.fractal === 'none');
170
177
  const positive = p.range === 'positive';
178
+ // domain warp: the lookup at world (x, z) moves by amplitude × the warp noise there, both in world metres, so it is
179
+ // the same at any resolution and on any tile of a map
180
+ const A = p.warp_amplitude > 0 ? p.warp_amplitude : 0;
181
+ const warp = A ? makeWarp(p.warp_seed, p.warp_octaves) : null;
182
+ const fw = p.warp_frequency > 0 ? p.warp_frequency : 1 / Math.max(1e-6, p.warp_element_size);
183
+ const qy = oy * fw;
171
184
  for (let j = 0; j < hf.height; j++) {
172
- const z = (hf.z(j) + oz) * f;
185
+ const zw = hf.z(j) + oz, z = zw * f, qz = zw * fw;
173
186
  for (let i = 0; i < hf.width; i++) {
174
- let v = n((hf.x(i) + ox) * f, oy * f, z);
187
+ let v;
188
+ if (warp) {
189
+ const x = hf.x(i) + ox, qx = x * fw;
190
+ v = n((x + A * warp.x(qx, qy, qz)) * f, oy * f, (zw + A * warp.z(qx, qy, qz)) * f);
191
+ }
192
+ else
193
+ v = n((hf.x(i) + ox) * f, oy * f, z);
175
194
  if (worley)
176
195
  v = v * 2 - 1;
177
196
  if (positive)
@@ -185,7 +204,7 @@ defineNode({
185
204
  type: 'heightfield_noise',
186
205
  category: 'heightfield',
187
206
  summary: 'Add (or multiply, replace, max, min) fractal noise on a heightfield layer: mountains, hills, dunes, mask variation.',
188
- description: 'Houdini: HeightField Noise. Noise is sampled at each sample\'s world X/Z, so it is resolution-independent. For mountains use fractal ridged, amplitude a few metres, element_size about a third of the field. mask_layer blends the result in by a 0..1 layer.',
207
+ description: 'Houdini: HeightField Noise. Noise is sampled at each sample\'s world X/Z, so it is resolution-independent and a tile of a map gets the map\'s values. For mountains use fractal ridged, amplitude a few metres, element_size about a third of the field. Domain warp (warp_amplitude > 0) moves each lookup by a second noise, in metres: ridges, escarpments and valleys meander instead of running straight (warp_element_size a few times element_size for broad bends, smaller for wiggles; terrace the result for meandering cliff bands). mask_layer blends the result in by a 0..1 layer.',
189
208
  aliases: ['hf_noise', 'heightfield_mountain'],
190
209
  inputs: [{ name: 'heightfield', desc: 'geometry with a heightfield' }],
191
210
  params: {
@@ -195,7 +214,7 @@ defineNode({
195
214
  mask_layer: maskParam(),
196
215
  },
197
216
  outputs: 'the layer (created if missing)',
198
- example: { nodes: { hf: { type: 'heightfield', params: { size: [20, 20], resolution: 0.1 } }, mtn: { type: 'heightfield_noise', in: ['hf'], params: { fractal: 'ridged', amplitude: 4, element_size: 8, range: 'positive' } } }, output: 'mtn' },
217
+ example: { nodes: { hf: { type: 'heightfield', params: { size: [20, 20], resolution: 0.1 } }, mtn: { type: 'heightfield_noise', in: ['hf'], params: { fractal: 'ridged', amplitude: 4, element_size: 8, range: 'positive', warp_amplitude: 2.5, warp_element_size: 12 } } }, output: 'mtn' },
199
218
  cook: (ctx) => {
200
219
  const { p } = ctx;
201
220
  checkName(p.layer, ctx.type);
@@ -209,7 +228,7 @@ defineNode({
209
228
  type: 'heightfield_mask_noise',
210
229
  category: 'heightfield',
211
230
  summary: 'Noise into a mask layer (clamped 0..1): break up masks, vary scatter density and materials.',
212
- description: 'Houdini: HeightField Mask Noise. Same noise as heightfield_noise with mask defaults: range positive, mode replace; use mode multiply to break up an existing mask.',
231
+ description: 'Houdini: HeightField Mask Noise. Same noise as heightfield_noise (domain warp included) with mask defaults: range positive, mode replace; use mode multiply to break up an existing mask. A band around 0.5 of a warped mask noise traces meandering lines: rivers, paths, strata.',
213
232
  aliases: ['hf_mask_noise'],
214
233
  inputs: [{ name: 'heightfield', desc: 'geometry with a heightfield' }],
215
234
  params: {
@@ -296,29 +315,32 @@ defineNode({
296
315
  type: 'heightfield_from_image',
297
316
  category: 'heightfield',
298
317
  summary: 'Load a heightmap or mask from an 8/16-bit PNG (grey or colour) into a heightfield layer.',
299
- description: 'Houdini: HeightField File. One sample per pixel; image column = X, row = Z with row 0 at the field\'s min Z (the layout export png16 writes, so a round trip lines up). Values 0..1 map to height_min..height_max (use the numbers from the export sidecar; 0 and 1 for masks). With a heightfield connected, the image is stretched over that field and written into `layer` instead of creating a new field.',
318
+ description: 'Houdini: HeightField File. One sample per pixel; image column = X, row = Z with row 0 at the field\'s min Z (the layout export png16 writes, so a round trip lines up). Values 0..1 map to height_min..height_max (use the numbers from the export sidecar; 0 and 1 for masks). The image covers size.x metres along X (or (pixels − 1) × resolution) around center, Z following its aspect. With a heightfield connected, the image is written into `layer` of that field instead of creating one: placed in the world the same way (fit world: every sample reads the image at its own X/Z, bilinear, so a tile reads the same values as the whole map; samples outside the image keep the layer), or stretched over the connected field (fit field, which depends on that field\'s extent).',
300
319
  aliases: ['heightfield_file', 'heightmap_import', 'hf_from_image', 'heightfield_image'],
301
- inputs: [{ name: 'heightfield', desc: 'optional: write the image into this field (stretched over its extent)', optional: true }],
320
+ inputs: [{ name: 'heightfield', desc: 'optional: write the image into this field', optional: true }],
302
321
  params: {
303
- path: { type: 'path', default: '', desc: 'PNG file (relative to the workspace) or URL', aliases: ['file', 'filename'] },
322
+ path: { type: 'path', default: '', desc: 'PNG file or URL; a relative path reads from the package folder (nearest .topo file), else the graph\'s folder', aliases: ['file', 'filename'] },
304
323
  layer: layerParam('height', 'layer to write'),
305
324
  height_min: { type: 'float', default: 0, desc: 'value for black (0)', aliases: ['min', 'low'] },
306
325
  height_max: { type: 'float', default: 10, desc: 'value for white (1)', aliases: ['max', 'high'] },
307
326
  channel: { type: 'enum', options: ['luminance', 'average', 'r', 'g', 'b', 'a'], default: 'luminance', desc: 'which channel of a colour image' },
308
- size: { type: 'vec2', default: [20, 20], desc: 'new field: extent in X and Z (metres)' },
309
- resolution: { type: 'float', default: 0, min: 0, desc: 'new field: cell size; > 0 overrides size (extent = (pixels - 1) × resolution)' },
327
+ size: { type: 'vec2', default: [20, 20], desc: 'image extent along X (metres; Z follows the image aspect): a new field\'s size, or where the image lies over a connected field (fit world)' },
328
+ resolution: { type: 'float', default: 0, min: 0, desc: 'pixel spacing (metres); > 0 overrides size (extent = (pixels - 1) × resolution)' },
310
329
  center: centerParam(),
330
+ fit: { type: 'enum', options: ['world', 'field'], default: 'world', desc: 'with a heightfield connected: world = the image lies at center/size in the world and each sample reads it at its X/Z; field = stretch the image over the connected field (depends on its extent)', aliases: ['placement'] },
311
331
  flip_z: { type: 'bool', default: false, desc: 'image row 0 at max Z instead of min Z' },
312
332
  name: { type: 'string', default: 'heightfield', desc: 'new field name' },
313
333
  },
314
- signatureExtra: (p, engine) => engine.host.fileStamp(p.path),
334
+ // relative paths read the scope's folder
335
+ signatureExtra: (p, scope) => scope.files.fileStamp(p.path),
315
336
  outputs: 'the layer (a new field also gets height and mask)',
316
337
  example: { type: 'heightfield_from_image', params: { path: 'terrain.png', size: [100, 100], height_min: 0, height_max: 25 } },
317
- async cook({ hasInput, input, p, engine, type }) {
338
+ async cook(ctx) {
339
+ const { hasInput, input, p, scope, type } = ctx;
318
340
  if (!p.path)
319
341
  throw new NodeError(`${type}: path is empty`);
320
342
  checkName(p.layer, type);
321
- const bytes = await engine.host.readFile(p.path).catch((e) => { throw new NodeError(`${type}: cannot read "${p.path}": ${e.message}`); });
343
+ const bytes = await scope.files.readFile(p.path).catch((e) => { throw new NodeError(`${type}: cannot read "${p.path}": ${e.message}`); });
322
344
  let img;
323
345
  try {
324
346
  img = decodePNG(bytes);
@@ -332,30 +354,48 @@ defineNode({
332
354
  const at = (fx, fz) => lo + (hi - lo) * bilinear(v, iw, ih, fx, p.flip_z ? ih - 1 - fz : fz);
333
355
  if (iw < 2 || ih < 2)
334
356
  throw new NodeError(`${type}: image is ${iw} × ${ih}; need at least 2 × 2 pixels`);
357
+ // where the image lies in the world: pixel (0, 0) at x0, z0, pixels `cell` metres apart (a new field's grid)
358
+ const cell = p.resolution > 0 ? p.resolution : p.size[0] / (iw - 1);
359
+ if (!(cell > 0))
360
+ throw new NodeError(`${type}: size must be > 0`);
361
+ const x0 = p.center[0] - ((iw - 1) * cell) / 2, z0 = p.center[2] - ((ih - 1) * cell) / 2;
335
362
  if (hasInput(0)) {
336
363
  const g = input(0).clone();
337
- let n = 0;
364
+ let n = 0, missed = 0;
365
+ const eps = 1e-6;
338
366
  for (let k = 0; k < g.volumes.length; k++) {
339
367
  const vol = g.volumes[k];
340
368
  if (!isHeightfield(vol))
341
369
  continue;
342
370
  const hf = asHeightfield(vol);
343
371
  const out = hf.writable(p.layer);
372
+ let inside = 0;
344
373
  for (let j = 0; j < hf.height; j++)
345
- for (let i = 0; i < hf.width; i++)
346
- out[j * hf.width + i] = at((i / (hf.width - 1)) * (iw - 1), (j / (hf.height - 1)) * (ih - 1));
374
+ for (let i = 0; i < hf.width; i++) {
375
+ if (p.fit === 'field') {
376
+ out[j * hf.width + i] = at((i / (hf.width - 1)) * (iw - 1), (j / (hf.height - 1)) * (ih - 1));
377
+ continue;
378
+ }
379
+ const fx = (hf.x(i) - x0) / cell, fz = (hf.z(j) - z0) / cell;
380
+ if (fx < -eps || fz < -eps || fx > iw - 1 + eps || fz > ih - 1 + eps)
381
+ continue;
382
+ out[j * hf.width + i] = at(fx, fz);
383
+ inside++;
384
+ }
385
+ if (p.fit !== 'field' && !inside)
386
+ missed++;
347
387
  g.volumes[k] = hf;
348
388
  n++;
349
389
  }
350
390
  if (!n)
351
391
  throw new NodeError(`${type}: input has no heightfield`, NO_FIELD);
392
+ const m = (x) => +x.toPrecision(6);
393
+ if (missed)
394
+ ctx.warn(`the image (${m((iw - 1) * cell)} × ${m((ih - 1) * cell)} m around ${m(p.center[0])}, ${m(p.center[2])}) does not overlap ${missed === n ? 'the heightfield' : `${missed} of ${n} heightfields`}; set size/center to where it lies, or fit field to stretch it over the field`);
352
395
  return g;
353
396
  }
354
397
  checkGrid(iw, ih, type);
355
- const cell = p.resolution > 0 ? p.resolution : p.size[0] / (iw - 1);
356
- if (!(cell > 0))
357
- throw new NodeError(`${type}: size must be > 0`);
358
- const hf = new Heightfield(iw, ih, cell, [p.center[0] - ((iw - 1) * cell) / 2, p.center[2] - ((ih - 1) * cell) / 2], undefined, p.name || 'heightfield');
398
+ const hf = new Heightfield(iw, ih, cell, [x0, z0], undefined, p.name || 'heightfield');
359
399
  const out = new Float32Array(iw * ih);
360
400
  for (let j = 0; j < ih; j++)
361
401
  for (let i = 0; i < iw; i++)
@@ -387,7 +427,7 @@ defineNode({
387
427
  step: { type: 'int', default: 1, min: 1, max: 64, desc: 'use every Nth sample (2 = a quarter of the quads)', aliases: ['decimate', 'lod'] },
388
428
  layers: { type: 'bool', default: true, desc: 'copy every layer to a point float attribute' },
389
429
  normals: { type: 'bool', default: true, desc: 'point N from the field gradient' },
390
- uv: { type: 'bool', default: true, desc: 'point uv 0..1 over the field' },
430
+ uv: { type: 'bool', default: true, desc: 'point uv 0..1 over the field (over its own extent: a tile gets its own 0..1)' },
391
431
  color: { type: 'enum', options: ['none', 'mask', 'height', 'terrain'], default: 'none', desc: 'point Cd from the layers' },
392
432
  keep_heightfield: { type: 'bool', default: false, desc: 'keep the heightfield volume alongside the mesh' },
393
433
  },
@@ -411,7 +451,7 @@ defineNode({
411
451
  aliases: ['heightfield_convert_sdf', 'hf_to_sdf', 'sdf_from_heightfield'],
412
452
  inputs: [{ name: 'heightfield', desc: 'geometry with heightfields' }],
413
453
  params: {
414
- depth: { type: 'float', default: 1, min: 0, desc: 'solid thickness below the lowest point (metres)', aliases: ['thickness'] },
454
+ depth: { type: 'float', default: 1, min: 0, desc: 'solid thickness below the field\'s lowest point (metres; that point depends on the field\'s extent, so tiles get their own bottoms)', aliases: ['thickness'] },
415
455
  closed: { type: 'bool', default: true, desc: 'cap the sides and the bottom (a finite block); false = an infinite slab clipped by the bounds' },
416
456
  keep_heightfield: { type: 'bool', default: false, desc: 'keep the heightfield volume' },
417
457
  name: { type: 'string', default: 'terrain_sdf', desc: 'SDF volume name' },
@@ -464,15 +504,15 @@ function heightfieldSdf(hf, depth, closed, name) {
464
504
  defineNode({
465
505
  type: 'heightfield_remap',
466
506
  category: 'heightfield',
467
- summary: 'Remap a layer\'s values: fit an input range to an output range through a ramp (normalise, invert, shape heights or masks).',
468
- description: 'Houdini: HeightField Remap. t = (value − input_min) / (input_max − input_min) (auto_range uses the layer\'s own min/max), then value = output_min + ramp(t) × (output_max − output_min). A ramp like [[0,0],[0.5,0.2],[1,1]] flattens valleys and sharpens peaks.',
507
+ summary: 'Remap a layer\'s values: fit an input range to an output range through a ramp (invert, shape heights or masks).',
508
+ description: 'Houdini: HeightField Remap. t = (value − input_min) / (input_max − input_min), then value = output_min + ramp(t) × (output_max − output_min). The input range is absolute, so a tile remaps exactly like the same area of the whole map; auto_range uses the layer\'s own min/max instead, which depend on the field\'s extent (a tile or a cropped field remaps differently). A ramp like [[0,0],[0.5,0.2],[1,1]] flattens valleys and sharpens peaks.',
469
509
  aliases: ['hf_remap'],
470
510
  inputs: [{ name: 'heightfield', desc: 'geometry with a heightfield' }],
471
511
  params: {
472
512
  layer: layerParam(),
473
- auto_range: { type: 'bool', default: true, desc: 'use the layer\'s min/max as the input range' },
474
- input_min: { type: 'float', default: 0, desc: 'input range start (when auto_range is off)' },
475
- input_max: { type: 'float', default: 1, desc: 'input range end (when auto_range is off)' },
513
+ input_min: { type: 'float', default: 0, desc: 'input value for t = 0 (e.g. the lowest height in metres)' },
514
+ input_max: { type: 'float', default: 1, desc: 'input value for t = 1' },
515
+ auto_range: { type: 'bool', default: false, desc: 'use the layer\'s own min/max as the input range instead (depends on the field\'s extent)' },
476
516
  output_min: { type: 'float', default: 0, desc: 'output for t = 0', aliases: ['min'] },
477
517
  output_max: { type: 'float', default: 1, desc: 'output for t = 1', aliases: ['max'] },
478
518
  ramp: { type: 'ramp', default: [[0, 0], [1, 1]], desc: 'shape: [[t, value], ...] with t and value 0..1' },
@@ -480,13 +520,13 @@ defineNode({
480
520
  mask_layer: maskParam(),
481
521
  },
482
522
  outputs: 'the layer',
483
- example: { nodes: { hf: { type: 'heightfield' }, n: { type: 'heightfield_noise', in: ['hf'], params: { amplitude: 3 } }, r: { type: 'heightfield_remap', in: ['n'], params: { output_min: 0, output_max: 6, ramp: [[0, 0], [0.6, 0.25], [1, 1]] } } }, output: 'r' },
523
+ example: { nodes: { hf: { type: 'heightfield' }, n: { type: 'heightfield_noise', in: ['hf'], params: { amplitude: 3 } }, r: { type: 'heightfield_remap', in: ['n'], params: { input_min: -3, input_max: 3, output_min: 0, output_max: 6, ramp: [[0, 0], [0.6, 0.25], [1, 1]] } } }, output: 'r' },
484
524
  cook: (ctx) => {
485
525
  const { p } = ctx;
486
526
  return eachField(ctx, (hf) => {
487
527
  const a = layerOf(hf, p.layer, ctx.type);
488
- const st = layerStats(a);
489
- const lo = p.auto_range ? st.min : p.input_min, hi = p.auto_range ? st.max : p.input_max;
528
+ const st = p.auto_range ? layerStats(a) : null;
529
+ const lo = st ? st.min : p.input_min, hi = st ? st.max : p.input_max;
490
530
  const span = hi - lo;
491
531
  const mask = maskOf(hf, p.mask_layer, ctx.type);
492
532
  writeLayer(hf, p.layer, mask, (_k, old) => {
@@ -545,15 +585,18 @@ defineNode({
545
585
  defineNode({
546
586
  type: 'heightfield_terrace',
547
587
  category: 'heightfield',
548
- summary: 'Terrace a heightfield: quantise heights into flat steps (rice terraces, mesas, strata), with rounded risers.',
549
- description: 'Houdini: HeightField Terrace. Levels are base + n × step (step = (max − min) / steps unless step_height is set). rounding 0 = flat steps with vertical risers, 1 = smooth S-shaped risers across the whole step.',
588
+ summary: 'Terrace a heightfield: quantise heights into flat steps at absolute levels (rice terraces, mesas, strata), with rounded risers.',
589
+ description: 'Houdini: HeightField Terrace. levels step (default): terraces at base + n × step_height, absolute heights, so a tile gets the same levels as the whole map. levels range: steps equal terraces from range_min to range_max (also absolute). levels layer: steps terraces between the layer\'s own min and max, which depend on the field\'s extent (a tile or a cropped field gets other levels than the whole map). rounding 0 = flat steps with vertical risers, 1 = smooth S-shaped risers across the whole step.',
550
590
  aliases: ['hf_terrace'],
551
591
  inputs: [{ name: 'heightfield', desc: 'geometry with a heightfield' }],
552
592
  params: {
553
593
  layer: layerParam(),
554
- steps: { type: 'int', default: 8, min: 1, max: 1000, desc: 'number of terraces between the layer\'s min and max', aliases: ['count', 'levels'] },
555
- step_height: { type: 'float', default: 0, min: 0, desc: 'terrace height (metres); > 0 overrides steps', aliases: ['height', 'spacing'] },
556
- offset: { type: 'float', default: 0, desc: 'shift the terrace levels (metres)', aliases: ['shift'] },
594
+ levels: { type: 'enum', options: ['step', 'range', 'layer'], default: 'step', desc: 'where the terraces sit: step = base + n × step_height; range = steps terraces from range_min to range_max; layer = steps terraces between the layer\'s own min and max (depends on the field\'s extent)', aliases: ['mode'] },
595
+ step_height: { type: 'float', default: 1, min: 0, desc: 'levels step: terrace height (metres)', aliases: ['height', 'spacing'] },
596
+ base: { type: 'float', default: 0, desc: 'levels step: the height of one terrace level (metres); the others are base ± n × step_height' },
597
+ steps: { type: 'int', default: 8, min: 1, max: 1000, desc: 'levels range and layer: number of terraces', aliases: ['count'] },
598
+ range_min: { type: 'float', default: 0, desc: 'levels range: height of the lowest terrace level (metres)' },
599
+ range_max: { type: 'float', default: 10, desc: 'levels range: height the steps reach (metres)' },
557
600
  rounding: { type: 'float', default: 0.2, min: 0, max: 1, desc: 'riser width as a fraction of the step: 0 = sharp, 1 = smooth', aliases: ['smoothness', 'sharpness'] },
558
601
  mask_layer: maskParam(),
559
602
  },
@@ -563,11 +606,25 @@ defineNode({
563
606
  const { p } = ctx;
564
607
  return eachField(ctx, (hf) => {
565
608
  const a = layerOf(hf, p.layer, ctx.type);
566
- const st = layerStats(a);
567
- const step = p.step_height > 0 ? p.step_height : (st.max - st.min) / p.steps;
568
- if (!(step > 0))
609
+ let base, step;
610
+ if (p.levels === 'layer') {
611
+ const st = layerStats(a);
612
+ base = st.min;
613
+ step = (st.max - st.min) / p.steps;
614
+ }
615
+ else if (p.levels === 'range') {
616
+ base = p.range_min;
617
+ step = (p.range_max - p.range_min) / p.steps;
618
+ }
619
+ else {
620
+ base = p.base;
621
+ step = p.step_height;
622
+ }
623
+ if (!(step > 0)) {
624
+ if (p.levels !== 'layer')
625
+ ctx.warn(p.levels === 'range' ? `range_max (${p.range_max}) must be above range_min (${p.range_min}); the layer is unchanged` : 'step_height is 0; the layer is unchanged');
569
626
  return;
570
- const base = (p.step_height > 0 ? 0 : st.min) + p.offset;
627
+ }
571
628
  const w = p.rounding;
572
629
  writeLayer(hf, p.layer, maskOf(hf, p.mask_layer, ctx.type), (_k, old) => {
573
630
  const s = (old - base) / step, f = Math.floor(s), t = s - f;
@@ -662,7 +719,7 @@ defineNode({
662
719
  type: 'heightfield_layer',
663
720
  category: 'heightfield',
664
721
  summary: 'Layer operations: compute a layer from an expression over layers ("height * mask + 2"), copy, rename, delete or fill.',
665
- description: 'Houdini: HeightField Layer / Copy Layer / Layer Clear, plus a volume wrangle for heightfields. Expression variables: every layer by name (height, mask, flow …), value (the target layer\'s current value), x z (world position), i j (sample indices), u v (0..1 over the field), cell (cell size), vars.*, b_<layer> = a layer of the heightfield in input 1 sampled at x, z, and all wrangle helpers (clamp fit smoothstep noise min max pow …). A body with "return" works too.',
722
+ description: 'Houdini: HeightField Layer / Copy Layer / Layer Clear, plus a volume wrangle for heightfields. Expression variables: every layer by name (height, mask, flow …), value (the target layer\'s current value), x z (world position), i j (sample indices), u v (0..1 over the field), cell (cell size), b_<layer> = a layer of the heightfield in input 1 sampled at x, z, the graph vars by their bare name (a layer or sample variable of the same name comes first, with a warning), and all wrangle helpers (clamp fit smoothstep noise min max pow …). A body with "return" works too. Write expressions in x z (and layers) to get the same values on a tile as on the whole map: i j u v count from the field\'s own corner and extent.',
666
723
  aliases: ['heightfield_copylayer', 'heightfield_layerclear', 'hf_layer', 'heightfield_wrangle', 'heightfield_expr'],
667
724
  inputs: [{ name: 'heightfield', desc: 'geometry with a heightfield' }, { name: 'other', desc: 'optional second heightfield: its layers as b_<name>', optional: true }],
668
725
  params: {
@@ -673,7 +730,7 @@ defineNode({
673
730
  value: { type: 'float', default: 0, desc: 'fill value' },
674
731
  mask_layer: maskParam(),
675
732
  },
676
- usesVars: true,
733
+ usesVars: (p) => (p.operation === 'expression' ? String(p.expression ?? '') : ''),
677
734
  outputs: 'the target layer',
678
735
  example: { nodes: { hf: { type: 'heightfield' }, n: { type: 'heightfield_noise', in: ['hf'], params: { amplitude: 2, range: 'positive' } }, l: { type: 'heightfield_layer', in: ['n'], params: { layer: 'snow', expression: 'smoothstep(1.2, 1.8, height)' } } }, output: 'l' },
679
736
  cook: (ctx) => {
@@ -682,7 +739,8 @@ defineNode({
682
739
  const other = hasInput(1) ? heightfieldsOf(input(1))[0] ?? null : null;
683
740
  if (hasInput(1) && !other)
684
741
  throw new NodeError(`${ctx.type}: input 1 has no heightfield`, NO_FIELD);
685
- return eachField(ctx, (hf) => {
742
+ const hiddenVars = new Set();
743
+ const out = eachField(ctx, (hf) => {
686
744
  const mask = maskOf(hf, p.mask_layer, ctx.type);
687
745
  switch (p.operation) {
688
746
  case 'delete':
@@ -727,6 +785,16 @@ defineNode({
727
785
  decl.push(`const ${id} = __B[${JSON.stringify(name)}](x, z);`);
728
786
  }
729
787
  }
788
+ // the graph vars the expression names: constants around the per-sample function, so a layer or a sample
789
+ // variable of the same name comes first (and the cook says so)
790
+ const own = new Set([...reserved, ...Object.keys(L), ...Object.keys(B).map((n) => 'b_' + n)]);
791
+ const varNames = [];
792
+ for (const n of codeVarNames(code, vars)) {
793
+ if (own.has(n))
794
+ hiddenVars.add(n);
795
+ else
796
+ varNames.push(n);
797
+ }
730
798
  const body = /\breturn\b/.test(code) ? code : `return (${code});`;
731
799
  // run like a wrangle: the body is parsed on its own first (a complete function body cannot close the wrapper
732
800
  // it is pasted into, so nothing runs while compiling), and the whole layer is computed under the host's time
@@ -736,12 +804,12 @@ defineNode({
736
804
  throw new NodeError(`${ctx.type}: expression syntax error: ${syntax.message}${code.includes('\n') ? ` (line ${syntax.line})` : ''}`);
737
805
  let make;
738
806
  try {
739
- make = engine.host.compile(`(function(__L, __B, vars){ "use strict"; return function(k, i, j, x, z, u, v, cell, value){ ${decl.join(' ')}\n${body}\n}; })`);
807
+ make = engine.host.compile(`(function(__L, __B, __vars, __varsGuard){ "use strict"; ${codeVarDecl(varNames)}\nreturn function(k, i, j, x, z, u, v, cell, value){ ${decl.join(' ')}\n${body}\n}; })`);
740
808
  }
741
809
  catch (e) {
742
810
  throw new NodeError(`${ctx.type}: expression syntax error: ${e.message}`);
743
811
  }
744
- const f = make(L, B, vars);
812
+ const f = make(L, B, codeVarValues(vars, varNames), scriptVarsGuard(engine.host));
745
813
  const old = hf.read(p.layer);
746
814
  const res = new Float32Array(hf.count);
747
815
  let bad = 0, failed;
@@ -782,13 +850,18 @@ defineNode({
782
850
  if (failed !== undefined) {
783
851
  const missing = /^(\w+) is not defined$/.exec(failed);
784
852
  if (missing)
785
- throw new NodeError(`${ctx.type}: "${missing[1]}" is not a layer of this heightfield (layers: ${[...hf.layers.keys()].join(', ')}) and not an expression variable`, 'Compute the layer upstream, or connect the heightfield that has it as input 1 and read it as b_' + missing[1] + '.');
853
+ throw new NodeError(`${ctx.type}: "${missing[1]}" is not a layer of this heightfield (layers: ${[...hf.layers.keys()].join(', ')}), a graph var or an expression variable`, 'Compute the layer upstream, or connect the heightfield that has it as input 1 and read it as b_' + missing[1] + '.');
786
854
  throw new NodeError(`${ctx.type}: ${failed}`);
787
855
  }
788
856
  if (bad)
789
857
  ctx.warn(`${bad} sample(s) gave NaN or infinity; written as 0`);
790
858
  writeLayer(hf, p.layer, mask, (k) => res[k]);
791
859
  });
860
+ if (hiddenVars.size) {
861
+ const n = [...hiddenVars].sort(), one = n.length === 1;
862
+ ctx.warn(`${n.join(', ')} in the expression ${one ? 'is' : 'are'} this node's own (a layer or a sample variable), not the graph var${one ? '' : 's'} of that name; rename the var to read it here`);
863
+ }
864
+ return out;
792
865
  },
793
866
  });
794
867
  // ---------------------------------------------------------------- masks
@@ -1052,7 +1125,7 @@ defineNode({
1052
1125
  type: 'heightfield_erode',
1053
1126
  category: 'heightfield',
1054
1127
  summary: 'Droplet or virtual-pipe hydraulic erosion with thermal talus relaxation and optional stream-power incision.',
1055
- description: 'Houdini: HeightField Erode. The default droplet/js path retains the original seeded droplet model and outputs. Droplets erode below carrying capacity and deposit as they slow or dry; each iteration also relaxes slopes above thermal_talus_angle. Kernel droplet uses the same parameters and layer meanings. Pipe uses four-direction shallow-water flux, velocity-based carrying capacity, sediment transport, rainfall and evaporation, with a CFL-limited timestep; stream_power adds K × drainage^m × slope^n incision. Pipe methods require backend kernel, or auto after the kernels have been loaded. Closed boundaries conserve terrain material. Open boundaries let water leave; droplet also loses carried sediment, while pipe retains sediment and settles it on return. Layers: height, nonnegative deposited sediment and thermal debris (added to existing layers), flow (0..1). Droplet water is a normalised resting-water mask; pipe water is remaining depth in metres. An existing lake layer supplies initial standing water to pipe/stream_power; lake is updated to the same final depth within its original footprint, while water includes every wet sample. Kernel backends also write cumulative wear (eroded depth). Pipe rainfall is uniform and deterministic; its seed is reserved for API consistency. Use flow/sediment/debris with heightfield_mask_by_feature or heightfield_to_mesh color terrain.',
1128
+ description: 'Houdini: HeightField Erode. method droplet (the default; backend js, or kernel for the same model in WASM): seeded droplets erode below their carrying capacity and deposit as they slow or dry; each iteration also relaxes slopes above thermal_talus_angle. Droplet settings are in metres, so the same params erode the same terrain alike at any spacing (an 8 m preview like the 2 m map, finer detail aside): rain_density counts droplets per m² per iteration, max_distance and erosion_radius are metres, and erosion_rate, deposition_rate, evaporation, inertia, gravity and thermal_rate act per droplet step of a third of erosion_radius, with sediment_capacity a volume in those steps cubed; the node converts them to the field\'s cells (a cell of a third of the radius takes them as given: the defaults at 0.1 m). For a terrain λ times larger keep the rest and multiply erosion_radius and max_distance by λ and divide rain_density by λ² (a 4 km map at 2 m: erosion_radius 6, max_distance 60, rain_density 0.005). Erosion is not local: droplets and water cross tile borders and start at seeded positions over the whole field, so a tile with a margin erodes like the same area of the map only statistically. Pipe uses four-direction shallow-water flux, velocity-based carrying capacity, sediment transport, rainfall and evaporation, with a CFL-limited timestep; stream_power adds K × drainage^m × slope^n incision. Pipe methods require backend kernel, or auto after the kernels have been loaded; their rates are per second, and their iterations are time steps that the cell size limits (CFL), so finer fields simulate less time per iteration unless time_step is below the limit of every spacing. Closed boundaries conserve terrain material. Open boundaries let water leave; droplet also loses carried sediment, while pipe retains sediment and settles it on return. Layers: height, nonnegative deposited sediment and thermal debris (added to existing layers), flow (0..1, normalised over the field: droplet on a log scale against its mean and 99th percentile, pipe by its maximum). Droplet water is a normalised resting-water mask; pipe water is remaining depth in metres. An existing lake layer supplies initial standing water to pipe/stream_power; lake is updated to the same final depth within its original footprint, while water includes every wet sample. Kernel backends also write cumulative wear (eroded depth). Pipe rainfall is uniform and deterministic; its seed is reserved for API consistency. Use flow/sediment/debris with heightfield_mask_by_feature or heightfield_to_mesh color terrain.',
1056
1129
  aliases: ['hf_erode', 'erosion', 'heightfield_erosion', 'heightfield_hydro_erode'],
1057
1130
  inputs: [{ name: 'heightfield', desc: 'geometry with a heightfield' }],
1058
1131
  params: {
@@ -1060,19 +1133,19 @@ defineNode({
1060
1133
  backend: { type: 'enum', options: ['auto', 'kernel', 'js'], default: 'js', desc: 'js preserves the original droplet result; kernel loads WASM; auto uses WASM only if already loaded, otherwise js (pipe methods require WASM)' },
1061
1134
  iterations: { type: 'int', default: 50, min: 0, max: 5000, desc: 'rain passes; pipe methods use thermal_interval to schedule thermal passes', aliases: ['iter', 'steps'] },
1062
1135
  seed: P.seed(),
1063
- erosion_rate: { type: 'float', default: 0.3, min: 0, max: 1, desc: 'fraction of free capacity picked up per droplet step, or erosion rate per second for pipe', aliases: ['erodability', 'erode_rate', 'erosion'] },
1064
- deposition_rate: { type: 'float', default: 0.3, min: 0, max: 1, desc: 'fraction of excess sediment deposited per droplet step, or deposition rate per second for pipe', aliases: ['deposit_rate', 'deposition'] },
1065
- sediment_capacity: { type: 'float', default: 1, min: 0, desc: 'how much sediment fast, steep water can carry (higher = deeper gullies, bigger fans)', aliases: ['capacity'] },
1066
- evaporation: { type: 'float', default: 0.1, min: 0, max: 1, desc: 'water fraction lost per droplet step, or evaporation rate per second for pipe', aliases: ['evaporation_rate'] },
1136
+ erosion_rate: { type: 'float', default: 0.3, min: 0, max: 1, desc: 'droplet: fraction of the free capacity picked up per droplet step (a third of erosion_radius); pipe: erosion rate per second', aliases: ['erodability', 'erode_rate', 'erosion'] },
1137
+ deposition_rate: { type: 'float', default: 0.3, min: 0, max: 1, desc: 'droplet: fraction of the excess sediment dropped per droplet step; pipe: deposition rate per second', aliases: ['deposit_rate', 'deposition'] },
1138
+ sediment_capacity: { type: 'float', default: 1, min: 0, desc: 'how much sediment fast, steep water can carry (higher = deeper gullies, bigger fans); droplet: a volume in droplet steps cubed, the same in metres at any spacing', aliases: ['capacity'] },
1139
+ evaporation: { type: 'float', default: 0.1, min: 0, max: 1, desc: 'droplet: water fraction lost per droplet step; pipe: evaporation rate per second', aliases: ['evaporation_rate'] },
1067
1140
  rain_amount: { type: 'float', default: 1, min: 0, desc: 'water per droplet; pipe rainfall depth in metres per second, multiplied by rain_layer if set', aliases: ['rain', 'water_amount'] },
1068
- rain_density: { type: 'float', default: 0.02, min: 0, max: 1, desc: 'droplet only: droplets per sample per iteration', aliases: ['droplets'] },
1069
- inertia: { type: 'float', default: 0.1, min: 0, max: 1, desc: 'droplet only: momentum, 0 = always steepest descent, higher = smoother, longer channels' },
1070
- gravity: { type: 'float', default: 4, min: 0, desc: 'acceleration on slopes' },
1141
+ rain_density: { type: 'float', default: 2, min: 0, desc: 'droplet only: droplets per square metre per iteration (at most one per sample: coarse fields cap it)', aliases: ['droplets'] },
1142
+ inertia: { type: 'float', default: 0.1, min: 0, max: 1, desc: 'droplet only: share of its heading a droplet keeps per droplet step; 0 = always steepest descent, higher = smoother, longer channels' },
1143
+ gravity: { type: 'float', default: 4, min: 0, desc: 'acceleration on slopes (droplet: speed² gained per droplet step of drop at slope 1; pipe: m/s²)' },
1071
1144
  min_slope: { type: 'float', default: 0.01, min: 0, desc: 'droplet only: minimum capacity (as a slope), keeps flats eroding a little' },
1072
- erosion_radius: { type: 'int', default: 3, min: 1, max: 8, desc: 'droplet only: erosion footprint radius (samples)', aliases: ['brush_radius'] },
1073
- max_lifetime: { type: 'int', default: 30, min: 1, max: 256, desc: 'droplet only: maximum steps per particle', aliases: ['lifetime', 'max_steps'] },
1145
+ erosion_radius: { type: 'float', default: 0.3, min: 0.001, desc: 'droplet only: erosion brush radius in metres (about a gully\'s half-width; at least one sample); a third of it is the droplet step the per-step settings refer to', aliases: ['brush_radius'] },
1146
+ max_distance: { type: 'float', default: 3, min: 0, desc: 'droplet only: how far a droplet travels at most (metres; at least one step)', aliases: ['travel_distance', 'droplet_distance'] },
1074
1147
  thermal_talus_angle: { type: 'float', default: 40, min: 0, max: 89, desc: 'thermal: angle of repose in degrees (steeper slopes shed material)', aliases: ['talus_angle', 'repose_angle', 'cut_angle'] },
1075
- thermal_rate: { type: 'float', default: 0.1, min: 0, max: 1, desc: 'thermal: fraction of the excess moved per thermal pass (0 = no thermal erosion)', aliases: ['thermal'] },
1148
+ thermal_rate: { type: 'float', default: 0.1, min: 0, max: 1, desc: 'thermal: fraction of the excess moved per thermal pass (droplet: on cells of a droplet step, scaled to the spacing; 0 = no thermal erosion)', aliases: ['thermal'] },
1076
1149
  thermal_interval: { type: 'int', default: 1, min: 1, max: 10000, desc: 'pipe/stream_power only: thermal pass every N iterations and on the final iteration; skips intervening relaxations without multiplying thermal_rate (1 preserves the default result)' },
1077
1150
  hardness_layer: { type: 'string', default: '', desc: 'optional 0..1 layer: 1 = rock that does not erode' },
1078
1151
  freeze_layer: { type: 'string', default: '', desc: 'optional 0..1 layer: 1 = frozen (unchanged), e.g. under buildings or roads' },
@@ -1106,21 +1179,31 @@ defineNode({
1106
1179
  let droplets = 0;
1107
1180
  // the time limit of long-running nodes: checked every iteration of the JS path; a big kernel run goes to a pool
1108
1181
  // worker that the limit can stop
1109
- const budget = simBudget(ctx, 'fewer iterations, a lower rain_density or max_lifetime, or a coarser field (heightfield_resample); or raise the limit');
1182
+ const budget = simBudget(ctx, 'fewer iterations, a lower rain_density or max_distance, or a coarser field (heightfield_resample); or raise the limit');
1183
+ // droplet settings in metres; dropletParams converts them to the kernels' per-sample params for each field's cells
1184
+ const settings = {
1185
+ rainDensity: p.rain_density, rainAmount: p.rain_amount, erosionRate: p.erosion_rate, depositionRate: p.deposition_rate,
1186
+ sedimentCapacity: p.sediment_capacity, evaporation: p.evaporation, inertia: p.inertia, gravity: p.gravity,
1187
+ minSlope: p.min_slope, erosionRadius: p.erosion_radius, maxDistance: p.max_distance,
1188
+ talusAngle: p.thermal_talus_angle, thermalRate: p.thermal_rate, boundary: p.boundary,
1189
+ };
1190
+ const m = (x) => +x.toPrecision(4);
1110
1191
  const out = await eachFieldAsync(ctx, async (hf) => {
1111
1192
  const H = layerOf(hf, 'height', ctx.type);
1112
1193
  const hard = maskOf(hf, p.hardness_layer, ctx.type), frz = maskOf(hf, p.freeze_layer, ctx.type);
1194
+ const { params, limited } = dropletParams(settings, hf.cellSize);
1113
1195
  if (p.method === 'droplet') {
1114
- const work = hf.count * p.rain_density * p.iterations * p.max_lifetime;
1196
+ const c = hf.cellSize, on = `on "${hf.name}" (${m(c)} m cells)`;
1197
+ if (limited.radius)
1198
+ ctx.warn(`erosion_radius ${m(p.erosion_radius)} m is more than 64 samples ${on}: the brush uses 64 samples (${m(64 * c)} m)`);
1199
+ if (limited.steps)
1200
+ ctx.warn(`max_distance ${m(p.max_distance)} m is more than 4096 steps ${on}: droplets stop after ${m(4096 * c)} m`);
1201
+ if (limited.density)
1202
+ ctx.warn(`rain_density ${m(p.rain_density)} per m² is more than one droplet per sample ${on}: using one per sample (${m(1 / (c * c))} per m²)`);
1203
+ const work = hf.count * params.rainDensity * p.iterations * params.maxLifetime;
1115
1204
  if (work > 4e9)
1116
- throw new NodeError(`${ctx.type}: ~${(work / 1e9).toFixed(1)}G droplet steps is too much; lower iterations, rain_density or max_lifetime, or resample the field`);
1205
+ throw new NodeError(`${ctx.type}: ~${(work / 1e9).toFixed(1)}G droplet steps is too much; lower iterations, rain_density or max_distance, or resample the field`);
1117
1206
  }
1118
- const params = {
1119
- rainDensity: p.rain_density, rainAmount: p.rain_amount, erosionRate: p.erosion_rate, depositionRate: p.deposition_rate,
1120
- sedimentCapacity: p.sediment_capacity, evaporation: p.evaporation, inertia: p.inertia, gravity: p.gravity,
1121
- minSlope: p.min_slope, erosionRadius: p.erosion_radius, maxLifetime: p.max_lifetime,
1122
- talusAngle: p.thermal_talus_angle, thermalRate: p.thermal_rate, boundary: p.boundary,
1123
- };
1124
1207
  if (kernels) {
1125
1208
  const grid = { w: hf.width, h: hf.height, cell: hf.cellSize, seed: p.seed };
1126
1209
  const result = await wasmCallUnderBudget(ctx, kernels, p.method === 'droplet'
@@ -1151,16 +1234,18 @@ defineNode({
1151
1234
  hf.layers.set('lake', lake);
1152
1235
  }
1153
1236
  if (p.method === 'droplet')
1154
- droplets += Math.round(p.rain_density * hf.count) * p.iterations;
1237
+ droplets += Math.round(params.rainDensity * hf.count) * p.iterations;
1155
1238
  return;
1156
1239
  }
1157
1240
  const field = makeErosionField(hf.width, hf.height, hf.cellSize, H, hard, frz);
1158
1241
  const r = rng(p.seed);
1242
+ // a stopped cook stops between iterations
1159
1243
  for (let it = 0; it < p.iterations; it++) {
1160
1244
  budget.check();
1245
+ await ctx.checkpoint();
1161
1246
  erodeStep(field, params, r);
1162
1247
  }
1163
- droplets += Math.round(p.rain_density * hf.count) * p.iterations;
1248
+ droplets += Math.round(params.rainDensity * hf.count) * p.iterations;
1164
1249
  hf.layers.set('height', Float32Array.from(field.h));
1165
1250
  for (const [name, delta] of [['sediment', field.sediment], ['debris', field.debris]]) {
1166
1251
  const prev = hf.layer(name), o = new Float32Array(hf.count);
@@ -1216,14 +1301,14 @@ defineNode({
1216
1301
  type: 'heightfield_flow',
1217
1302
  category: 'heightfield',
1218
1303
  summary: 'Compute downhill drainage accumulation and flow direction for river masks.',
1219
- description: 'Routes contributing cell area downhill without modifying height. D8 sends it to the steepest of eight neighbours; D-infinity splits flow between receivers on the steepest triangular facet. By default local minima retain drainage. fill_sinks routes over a priority-flood filled surface and resolves flats with stable receivers, without modifying the stored height or lake layers. The direction layer records the dominant receiver: E, SE, S, SW, W, NW, N, NE = 0..7, and 255 for a sink. Without normalise or log_scale, drainage is contributing area in square metres. Loads the erosion WASM kernel.',
1304
+ description: 'Routes contributing cell area downhill without modifying height. D8 sends it to the steepest of eight neighbours; D-infinity splits flow between receivers on the steepest triangular facet. By default local minima retain drainage. fill_sinks routes over a priority-flood filled surface and resolves flats with stable receivers, without modifying the stored height or lake layers. The direction layer records the dominant receiver: E, SE, S, SW, W, NW, N, NE = 0..7, and 255 for a sink. Drainage is contributing area in square metres, ln(1 + area) with log_scale (the default), so thresholds are absolute; normalise divides by the field\'s largest value instead, which depends on the field\'s extent. Drainage only counts area inside the field: a tile sees rivers that enter it as starting at its border, so route the whole map (or a tile with a margin that holds the catchments) and crop. Loads the erosion WASM kernel.',
1220
1305
  aliases: ['hf_flow', 'heightfield_drainage'],
1221
1306
  inputs: [{ name: 'heightfield', desc: 'geometry with a height layer' }],
1222
1307
  params: {
1223
1308
  method: { type: 'enum', options: ['d8', 'dinf'], default: 'dinf', desc: 'D8 chooses one steepest receiver; D-infinity splits contributing area between two downslope receivers' },
1224
1309
  fill_sinks: { type: 'bool', default: false, desc: 'route over a priority-flood filled surface with stable flat receivers, preserving the original height; false leaves local minima as sinks' },
1225
- normalise: { type: 'bool', default: true, desc: 'scale drainage to 0..1 after applying log_scale', aliases: ['normalize'] },
1226
- log_scale: { type: 'bool', default: true, desc: 'apply log(1 + drainage) to reveal small tributaries alongside main rivers' },
1310
+ normalise: { type: 'bool', default: false, desc: 'divide drainage by its largest value on the field (0..1, after log_scale); depends on the field\'s extent', aliases: ['normalize'] },
1311
+ log_scale: { type: 'bool', default: true, desc: 'write ln(1 + area in m²) to reveal small tributaries alongside main rivers' },
1227
1312
  },
1228
1313
  outputs: 'layers drainage and direction; all existing layers preserved',
1229
1314
  example: { nodes: { hf: { type: 'heightfield', params: { size: [20, 20], resolution: 0.5 } }, n: { type: 'heightfield_noise', in: ['hf'], params: { fractal: 'ridged', amplitude: 4 } }, f: { type: 'heightfield_flow', in: ['n'] } }, output: 'f' },
@@ -1508,7 +1593,7 @@ defineNode({
1508
1593
  type: 'heightfield_scatter',
1509
1594
  category: 'heightfield',
1510
1595
  summary: 'Scatter points on a heightfield by a mask layer\'s density: P on the surface, N from the slope (or straight up), height/slope/mask attributes, optional minimum distance. Feed copy_to_points.',
1511
- description: 'Houdini: HeightField Scatter. Count = density × area weighted by the mask (or count). Candidates are drawn by the mask (seeded), then thinned to even blue-noise spacing with relax (weighted sample elimination, as scatter, in chunks on the worker pool). Points sit exactly on the field\'s surface: bilinear between the samples (default), or with sample unreal_triangles the surface of an Unreal Landscape imported from this field\'s heightmap (export png16/r16): each cell split along its (0,0)–(1,1) diagonal in heightmap index space, column = X, row = Z (row 0 = min Z), which is how the Landscape triangulates its quads (vertex (x, y) = (column, row), Unreal Y = our Z), so instance bases land on the Landscape exactly. The modes agree at the samples and along cell edges and differ inside a cell by up to a quarter of its twist |h00 + h11 − h10 − h01|. N and slope come from central differences over one cell of the same surface; mask stays bilinear (Unreal samples weightmaps as textures). Attributes: height (Y), slope (degrees), mask (the density layer value at the point). N is the surface normal, and copy_to_points aims a copy\'s +Z along N (Houdini convention), which lays a Y-up tree down: align upright writes orient = identity so trees, houses and posts stand as modelled, align slope writes an orient that turns +Y onto the normal so rocks and shrubs lean with the terrain (orient wins over N in copy_to_points; random yaw goes on top with copy_to_points rotate_attrib). min_distance keeps every pair of points at least that far apart in XZ (exact dart throwing over the drawn candidates, replacing relax): building lots that never overlap; the count can come out lower when the masked area is full.',
1596
+ description: 'Houdini: HeightField Scatter. Count = density × area weighted by the mask (or count). Candidates are drawn by the mask (seeded), then thinned to even blue-noise spacing with relax (weighted sample elimination, as scatter, in chunks on the worker pool). Points sit exactly on the field\'s surface: bilinear between the samples (default), or with sample unreal_triangles the surface of an Unreal Landscape imported from this field\'s heightmap (export png16/r16): each cell split along its (0,0)–(1,1) diagonal in heightmap index space, column = X, row = Z (row 0 = min Z), which is how the Landscape triangulates its quads (vertex (x, y) = (column, row), Unreal Y = our Z), so instance bases land on the Landscape exactly. The modes agree at the samples and along cell edges and differ inside a cell by up to a quarter of its twist |h00 + h11 − h10 − h01|. N and slope come from central differences over one cell of the same surface; mask stays bilinear (Unreal samples weightmaps as textures). Attributes: height (Y), slope (degrees), mask (the density layer value at the point). N is the surface normal, and copy_to_points aims a copy\'s +Z along N (Houdini convention), which lays a Y-up tree down: align upright writes orient = identity so trees, houses and posts stand as modelled, align slope writes an orient that turns +Y onto the normal so rocks and shrubs lean with the terrain (orient wins over N in copy_to_points; random yaw goes on top with copy_to_points rotate_attrib). min_distance keeps every pair of points at least that far apart in XZ (exact dart throwing over the drawn candidates, replacing relax): building lots that never overlap; the count can come out lower when the masked area is full. Points are drawn over the whole field (density is per m², but the seeded draw, relax and min_distance see every sample), so a tile gets other points than the same area of the whole map: scatter on the whole map and keep the points inside the tile when tiles must match.',
1512
1597
  aliases: ['hf_scatter', 'heightfield_scatter_points'],
1513
1598
  inputs: [{ name: 'heightfield', desc: 'geometry with a heightfield' }],
1514
1599
  params: {
@@ -1634,7 +1719,7 @@ defineNode({
1634
1719
  type: 'heightfield_resample',
1635
1720
  category: 'heightfield',
1636
1721
  summary: 'Change a heightfield\'s resolution over the same extent (all layers, bilinear; pre-blurred when shrinking), e.g. to an Unreal size like 505 × 505.',
1637
- description: 'Houdini: HeightField Resample. Give the new cell size (resolution), exact sample counts (samples), or a factor on the sample count (2 = twice as many per side). The X extent is kept exactly; Z follows the new cell size.',
1722
+ description: 'Houdini: HeightField Resample. Give the new cell size (resolution), exact sample counts (samples), or a factor on the sample count (2 = twice as many per side). The X extent is kept exactly; Z follows the new cell size. The new grid starts at the field\'s corner and its cell is the X extent divided evenly, so tiles of a map resample onto one shared grid only when the resolution divides each tile\'s extent (heightfield_crop tiles of equal size do); shrinking pre-blurs, which needs a margin at tile borders.',
1638
1723
  aliases: ['hf_resample', 'heightfield_resize'],
1639
1724
  inputs: [{ name: 'heightfield', desc: 'geometry with a heightfield' }],
1640
1725
  params: {
@@ -1698,7 +1783,7 @@ defineNode({
1698
1783
  type: 'heightfield_transform',
1699
1784
  category: 'heightfield',
1700
1785
  summary: 'Move, scale, raise or turn (by 90° steps) heightfields: translate X/Z moves the grid, Y raises the heights; scale resizes the cells.',
1701
- description: 'Houdini: HeightField Transform. Heightfields stay axis-aligned grids: rotation snaps to multiples of 90°, scale is uniform in X/Z (it changes the cell size), height_scale multiplies heights about pivot Y. The generic transform node applies the same rules.',
1786
+ description: 'Houdini: HeightField Transform. Heightfields stay axis-aligned grids: rotation snaps to multiples of 90°, scale is uniform in X/Z (it changes the cell size), height_scale multiplies heights about pivot Y. Scale and rotation turn about pivot, a world point, so the tiles of a map move together; pivot_at_center turns each field about its own centre instead. The generic transform node applies the same rules.',
1702
1787
  aliases: ['heightfield_xform', 'hf_transform', 'heightfield_move'],
1703
1788
  inputs: [{ name: 'heightfield', desc: 'geometry with a heightfield' }],
1704
1789
  params: {
@@ -1707,7 +1792,7 @@ defineNode({
1707
1792
  height_scale: { type: 'float', default: 1, desc: 'multiply heights about pivot Y', aliases: ['scale_y', 'vertical_scale'] },
1708
1793
  rotate: { type: 'float', default: 0, desc: 'rotation about Y in degrees (snapped to 90° steps)', aliases: ['r', 'rot'] },
1709
1794
  pivot: { type: 'vec3', default: [0, 0, 0], desc: 'pivot for scale and rotation (X/Z ignored when pivot_at_center)' },
1710
- pivot_at_center: { type: 'bool', default: true, desc: 'use the field centre as the X/Z pivot' },
1795
+ pivot_at_center: { type: 'bool', default: false, desc: 'use the field\'s own centre as the X/Z pivot (depends on its extent: a tile turns about its own centre)' },
1711
1796
  },
1712
1797
  outputs: 'transformed heightfields',
1713
1798
  example: { nodes: { hf: { type: 'heightfield' }, n: { type: 'heightfield_noise', in: ['hf'] }, t: { type: 'heightfield_transform', in: ['n'], params: { translate: [20, 0, 0], height_scale: 2 } } }, output: 't' },
@@ -1723,3 +1808,89 @@ defineNode({
1723
1808
  });
1724
1809
  },
1725
1810
  });
1811
+ // ---------------------------------------------------------------- crop
1812
+ /** Inclusive sample range of tile t of n along an axis of `samples` samples: the cells split evenly, borders shared. */
1813
+ function tileRange(samples, n, t) {
1814
+ const cells = samples - 1;
1815
+ return [Math.floor((t * cells) / n), Math.floor(((t + 1) * cells) / n)];
1816
+ }
1817
+ defineNode({
1818
+ type: 'heightfield_crop',
1819
+ category: 'heightfield',
1820
+ summary: 'Crop heightfields (every layer) to world bounds or to one tile of a grid, with an optional margin; the samples stay exactly where they were (no resampling).',
1821
+ description: 'Cut a tile out of a whole map to preview or process it at full resolution, then build on the tile: nodes that work at world positions (noise, terrace, remap, masks by height or slope …) give the tile the same values as the same area of the map. mode tile: the field\'s cells are split evenly into tiles (nx, nz), tile (i, j) counting from min X / min Z, and neighbouring tiles share their border samples (as Unreal landscape tiles do). mode bounds: the samples covering min..max in X and Z (bounds between samples grow to the next sample; parts outside the field are dropped). margin keeps extra samples on every side (metres, rounded up to whole samples, or samples; less at the field\'s own border) for filters that read neighbours, such as blur, curvature, path and project. The crop is recorded in detail attributes: crop_core_min / crop_core_max (world X, Z of the tile or bounds without the margin: crop to them in mode bounds to drop the margin again), crop_margin (samples kept beyond the core on the −X, +X, −Z, +Z sides), crop_offset (the first sample\'s index in the input grid), crop_source_samples (the input\'s sample counts) and, in mode tile, crop_tile and crop_tiles (bounds mode keeps those of an earlier tile crop). With several heightfields each is cropped (tiles by its own grid) and the attributes describe the first. Other geometry passes through.',
1822
+ aliases: ['hf_crop', 'heightfield_tile', 'heightfield_cut_tile'],
1823
+ inputs: [{ name: 'heightfield', desc: 'geometry with a heightfield' }],
1824
+ params: {
1825
+ mode: { type: 'enum', options: ['tile', 'bounds'], default: 'tile', desc: 'tile = one tile of a tiles grid over the field; bounds = the samples covering min..max' },
1826
+ tiles: { type: 'ivec2', default: [2, 2], min: 1, max: 4096, desc: 'tile mode: number of tiles along X and Z', aliases: ['grid', 'tile_count'] },
1827
+ tile: { type: 'ivec2', default: [0, 0], min: 0, max: 4095, desc: 'tile mode: tile index [column along X, row along Z], counting from 0 at min X / min Z', aliases: ['index', 'tile_index'] },
1828
+ min: { type: 'vec2', default: [-5, -5], desc: 'bounds mode: world X and Z of the min corner (metres)', aliases: ['bounds_min'] },
1829
+ max: { type: 'vec2', default: [5, 5], desc: 'bounds mode: world X and Z of the max corner (metres)', aliases: ['bounds_max'] },
1830
+ margin: { type: 'float', default: 0, min: 0, desc: 'extra border kept on every side, in margin_unit (less at the field\'s own border): the reach of the filters that follow', aliases: ['padding', 'overlap'] },
1831
+ margin_unit: { type: 'enum', options: ['metres', 'samples'], default: 'metres', desc: 'margin in metres (rounded up to whole samples) or in samples', aliases: ['margin_units'] },
1832
+ },
1833
+ outputs: 'the cropped heightfields with all their layers; detail crop_core_min, crop_core_max, crop_margin, crop_offset, crop_source_samples (tile mode also crop_tile, crop_tiles)',
1834
+ example: {
1835
+ nodes: {
1836
+ map: { type: 'heightfield', params: { size: [40, 40], resolution: 0.25 } },
1837
+ tile: { type: 'heightfield_crop', in: ['map'], params: { tiles: [4, 4], tile: [1, 2], margin: 2 } },
1838
+ hills: { type: 'heightfield_noise', in: ['tile'], params: { amplitude: 3, element_size: 12 } },
1839
+ core: { type: 'heightfield_crop', in: ['hills'], params: { mode: 'bounds', min: [-10, 0], max: [0, 10] } },
1840
+ },
1841
+ output: 'core',
1842
+ },
1843
+ cook: (ctx) => {
1844
+ const { p, type } = ctx;
1845
+ const g = ctx.input(0).clone();
1846
+ const eps = 1e-6;
1847
+ let first = null;
1848
+ for (let k = 0; k < g.volumes.length; k++) {
1849
+ const v = g.volumes[k];
1850
+ if (!isHeightfield(v))
1851
+ continue;
1852
+ const hf = asHeightfield(v);
1853
+ // the core (tile or bounds) as inclusive sample ranges
1854
+ let i0, i1, j0, j1;
1855
+ if (p.mode === 'bounds') {
1856
+ if (!(p.max[0] > p.min[0] && p.max[1] > p.min[1]))
1857
+ throw new NodeError(`${type}: max [${p.max.join(', ')}] must be above min [${p.min.join(', ')}] in X and Z`);
1858
+ i0 = Math.max(0, Math.floor(hf.fx(p.min[0]) + eps));
1859
+ i1 = Math.min(hf.width - 1, Math.ceil(hf.fx(p.max[0]) - eps));
1860
+ j0 = Math.max(0, Math.floor(hf.fz(p.min[1]) + eps));
1861
+ j1 = Math.min(hf.height - 1, Math.ceil(hf.fz(p.max[1]) - eps));
1862
+ if (i1 - i0 < 1 || j1 - j0 < 1) {
1863
+ const b = hf.bounds, f = (x) => +x.toPrecision(6);
1864
+ throw new NodeError(`${type}: bounds [${p.min.join(', ')}] .. [${p.max.join(', ')}] cover ${i1 < i0 || j1 < j0 ? 'no' : 'fewer than 2 × 2'} samples of heightfield "${hf.name}"`, `the field spans X ${f(b.min[0])} .. ${f(b.max[0])}, Z ${f(b.min[2])} .. ${f(b.max[2])}`);
1865
+ }
1866
+ }
1867
+ else {
1868
+ const [nx, nz] = p.tiles, [ti, tj] = p.tile;
1869
+ if (nx > hf.width - 1 || nz > hf.height - 1)
1870
+ throw new NodeError(`${type}: tiles [${nx}, ${nz}] are more than the ${hf.width - 1} × ${hf.height - 1} cells of heightfield "${hf.name}"`, 'every tile needs at least one cell');
1871
+ if (ti >= nx || tj >= nz)
1872
+ throw new NodeError(`${type}: tile [${ti}, ${tj}] is outside the ${nx} × ${nz} tiles (indices count from 0)`);
1873
+ [i0, i1] = tileRange(hf.width, nx, ti);
1874
+ [j0, j1] = tileRange(hf.height, nz, tj);
1875
+ }
1876
+ const m = p.margin > 0 ? Math.ceil((p.margin_unit === 'samples' ? p.margin : p.margin / hf.cellSize) - eps) : 0;
1877
+ const c = [Math.max(0, i0 - m), Math.min(hf.width - 1, i1 + m), Math.max(0, j0 - m), Math.min(hf.height - 1, j1 + m)];
1878
+ g.volumes[k] = cropHeightfield(hf, c[0], c[1], c[2], c[3]);
1879
+ if (!first)
1880
+ first = { i0, i1, j0, j1, c, hf };
1881
+ }
1882
+ if (!first)
1883
+ throw new NodeError(`${type}: input has no heightfield`, NO_FIELD);
1884
+ const { i0, i1, j0, j1, c, hf } = first;
1885
+ g.detail.add('crop_core_min', 'float', 2).set(0, [hf.x(i0), hf.z(j0)]);
1886
+ g.detail.add('crop_core_max', 'float', 2).set(0, [hf.x(i1), hf.z(j1)]);
1887
+ g.detail.add('crop_margin', 'int', 4).set(0, [i0 - c[0], c[1] - i1, j0 - c[2], c[3] - j1]);
1888
+ g.detail.add('crop_offset', 'int', 2).set(0, [c[0], c[2]]);
1889
+ g.detail.add('crop_source_samples', 'int', 2).set(0, [hf.width, hf.height]);
1890
+ if (p.mode === 'tile') {
1891
+ g.detail.add('crop_tile', 'int', 2).set(0, p.tile);
1892
+ g.detail.add('crop_tiles', 'int', 2).set(0, p.tiles);
1893
+ }
1894
+ return g;
1895
+ },
1896
+ });