threedog 0.0.0-stage → 0.2.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 (506) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +39 -2
  4. package/core/Animator.js +268 -0
  5. package/core/Assets.js +256 -0
  6. package/core/Audio.js +267 -0
  7. package/core/Baked.js +72 -0
  8. package/core/Batching.js +247 -0
  9. package/core/Budget.js +221 -0
  10. package/core/Clock.js +94 -0
  11. package/core/Commits.js +77 -0
  12. package/core/DebugOverrides.js +143 -0
  13. package/core/Describe.js +145 -0
  14. package/core/Engine.js +184 -0
  15. package/core/Events.js +153 -0
  16. package/core/I18n.js +94 -0
  17. package/core/Input.js +245 -0
  18. package/core/Inspect.js +77 -0
  19. package/core/InspectScene.js +191 -0
  20. package/core/Jobs.js +146 -0
  21. package/core/Loading.js +149 -0
  22. package/core/MaterialInfo.js +32 -0
  23. package/core/Ops.js +256 -0
  24. package/core/Random.js +52 -0
  25. package/core/Rays.js +160 -0
  26. package/core/SaveStore.js +85 -0
  27. package/core/Saves.js +254 -0
  28. package/core/Stream.js +279 -0
  29. package/core/Threads.js +158 -0
  30. package/core/UrlState.js +94 -0
  31. package/core/Vars.js +35 -0
  32. package/core/Views.js +49 -0
  33. package/core/actor.js +23 -0
  34. package/core/assetEntry.js +89 -0
  35. package/core/assetLoad.js +190 -0
  36. package/core/assetManifest.js +35 -0
  37. package/core/assetReport.js +83 -0
  38. package/core/audioRules.js +121 -0
  39. package/core/audioVoice.js +225 -0
  40. package/core/batchGroups.js +116 -0
  41. package/core/canvasBox.js +63 -0
  42. package/core/catalog.js +169 -0
  43. package/core/checks.js +67 -0
  44. package/core/claims.js +51 -0
  45. package/core/dayTime.js +15 -0
  46. package/core/debugView.js +76 -0
  47. package/core/describeRender.js +45 -0
  48. package/core/describeText.js +143 -0
  49. package/core/easing.js +34 -0
  50. package/core/errorCodes.js +205 -0
  51. package/core/errorHints.js +208 -0
  52. package/core/errors.js +40 -0
  53. package/core/events.generated.js +84 -0
  54. package/core/ground.js +102 -0
  55. package/core/holds.js +106 -0
  56. package/core/inputContext.js +69 -0
  57. package/core/inputDefaults.js +22 -0
  58. package/core/inputPad.js +35 -0
  59. package/core/inputPointer.js +48 -0
  60. package/core/inputTouch.js +48 -0
  61. package/core/lifecycle.js +69 -0
  62. package/core/lightWatch.js +56 -0
  63. package/core/look/coreParts.js +112 -0
  64. package/core/look/layers.js +136 -0
  65. package/core/look/part.js +173 -0
  66. package/core/look/report.js +79 -0
  67. package/core/look/write.js +86 -0
  68. package/core/loop.js +200 -0
  69. package/core/math.js +33 -0
  70. package/core/modules.js +196 -0
  71. package/core/movement.js +19 -0
  72. package/core/mulberry32.js +14 -0
  73. package/core/opsAtomic.js +31 -0
  74. package/core/opsCheck.js +97 -0
  75. package/core/opsFail.js +20 -0
  76. package/core/opsGuard.js +26 -0
  77. package/core/opsHistory.js +27 -0
  78. package/core/opsRun.js +77 -0
  79. package/core/page.js +78 -0
  80. package/core/params.js +132 -0
  81. package/core/pureWorker.js +5 -0
  82. package/core/renamed.js +21 -0
  83. package/core/saveApply.js +128 -0
  84. package/core/saveFiles.js +139 -0
  85. package/core/saveIds.js +53 -0
  86. package/core/saveVersions.js +97 -0
  87. package/core/scatter.js +92 -0
  88. package/core/sceneMethods.js +100 -0
  89. package/core/screenToGround.js +39 -0
  90. package/core/services.js +73 -0
  91. package/core/session.js +171 -0
  92. package/core/shadowTypes.js +15 -0
  93. package/core/skip.js +104 -0
  94. package/core/startup.js +135 -0
  95. package/core/streamCells.js +24 -0
  96. package/core/streamSources.js +73 -0
  97. package/core/styleParts.js +96 -0
  98. package/core/targeting.js +64 -0
  99. package/core/thingExplain.js +68 -0
  100. package/core/thingOps.js +168 -0
  101. package/core/things.js +212 -0
  102. package/core/threadPure.js +120 -0
  103. package/core/threadServe.js +25 -0
  104. package/core/tier.js +11 -0
  105. package/core/util.js +11 -0
  106. package/core/validate.js +204 -0
  107. package/docs/AI.md +123 -0
  108. package/docs/API.md +83 -0
  109. package/docs/CODEMAP.md +347 -0
  110. package/docs/COMMANDS.md +108 -0
  111. package/docs/CONVENTIONS.md +145 -0
  112. package/docs/PERF.md +217 -0
  113. package/docs/THREE.md +86 -0
  114. package/docs/api/ambience.md +15 -0
  115. package/docs/api/assets.md +62 -0
  116. package/docs/api/audio.md +53 -0
  117. package/docs/api/budget.md +40 -0
  118. package/docs/api/cameraRig.md +120 -0
  119. package/docs/api/characters.md +144 -0
  120. package/docs/api/clock.md +7 -0
  121. package/docs/api/collision.md +39 -0
  122. package/docs/api/content.md +64 -0
  123. package/docs/api/dialogue.md +39 -0
  124. package/docs/api/engine.md +199 -0
  125. package/docs/api/entities.md +61 -0
  126. package/docs/api/events.md +95 -0
  127. package/docs/api/flow.md +27 -0
  128. package/docs/api/grids.md +11 -0
  129. package/docs/api/ground.md +16 -0
  130. package/docs/api/hlod.md +34 -0
  131. package/docs/api/hud.md +31 -0
  132. package/docs/api/i18n.md +10 -0
  133. package/docs/api/input.md +24 -0
  134. package/docs/api/interactions.md +31 -0
  135. package/docs/api/inventory.md +66 -0
  136. package/docs/api/jobs.md +10 -0
  137. package/docs/api/level.md +41 -0
  138. package/docs/api/lightPool.md +56 -0
  139. package/docs/api/music.md +34 -0
  140. package/docs/api/nav.md +26 -0
  141. package/docs/api/net.md +14 -0
  142. package/docs/api/openWorld.md +24 -0
  143. package/docs/api/particles.md +41 -0
  144. package/docs/api/photo.md +15 -0
  145. package/docs/api/post.md +10 -0
  146. package/docs/api/quests.md +36 -0
  147. package/docs/api/rays.md +26 -0
  148. package/docs/api/rigid.md +84 -0
  149. package/docs/api/saves.md +32 -0
  150. package/docs/api/settings.md +36 -0
  151. package/docs/api/sky.md +58 -0
  152. package/docs/api/stream.md +31 -0
  153. package/docs/api/style.md +134 -0
  154. package/docs/api/terrain.md +34 -0
  155. package/docs/api/timeline.md +39 -0
  156. package/docs/api/tools.md +57 -0
  157. package/docs/api/triggers.md +56 -0
  158. package/docs/api/vars.md +9 -0
  159. package/docs/api/vegetation.md +52 -0
  160. package/docs/api/water.md +48 -0
  161. package/docs/api/weather.md +29 -0
  162. package/docs/api/world.md +30 -0
  163. package/docs/recipes/01-new-game.md +148 -0
  164. package/docs/recipes/02-npc.md +167 -0
  165. package/docs/recipes/03-items-pickups.md +158 -0
  166. package/docs/recipes/04-quests.md +83 -0
  167. package/docs/recipes/05-props-bake.md +159 -0
  168. package/docs/recipes/06-clock-events.md +117 -0
  169. package/docs/recipes/07-flow-scenes-pause.md +132 -0
  170. package/docs/recipes/08-weather-sky.md +74 -0
  171. package/docs/recipes/09-style-pack.md +234 -0
  172. package/docs/recipes/10-blender-level.md +67 -0
  173. package/docs/recipes/11-vehicles.md +55 -0
  174. package/docs/recipes/12-navmesh.md +79 -0
  175. package/docs/recipes/13-animation.md +149 -0
  176. package/docs/recipes/14-custom-module.md +91 -0
  177. package/docs/recipes/15-perf.md +78 -0
  178. package/docs/recipes/16-dev-bridge.md +180 -0
  179. package/docs/recipes/18-world.md +185 -0
  180. package/docs/recipes/19-shooting-picking.md +76 -0
  181. package/docs/recipes/20-content-actions-save.md +176 -0
  182. package/docs/recipes/21-camera.md +153 -0
  183. package/docs/recipes/22-shop-gold.md +107 -0
  184. package/docs/recipes/23-ops.md +175 -0
  185. package/docs/recipes/26-ui-parts.md +138 -0
  186. package/docs/recipes/27-net.md +96 -0
  187. package/docs/recipes/28-terrain.md +80 -0
  188. package/docs/recipes/29-grid.md +87 -0
  189. package/docs/recipes/30-templates.md +131 -0
  190. package/docs/recipes/31-audio.md +126 -0
  191. package/docs/recipes/32-action-game.md +33 -0
  192. package/docs/recipes/33-stream-sources.md +37 -0
  193. package/docs/recipes/34-environment-lighting.md +36 -0
  194. package/docs/recipes/35-style-from-reference.md +89 -0
  195. package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
  196. package/docs/recipes/37-terrain-look-hooks.md +97 -0
  197. package/docs/recipes/38-environment-look-hooks.md +83 -0
  198. package/docs/recipes/40-scene.md +108 -0
  199. package/docs/recipes/41-thing-registry.md +93 -0
  200. package/docs/recipes/42-terrain-shape.md +64 -0
  201. package/docs/recipes/43-shader-patches-surface-looks.md +120 -0
  202. package/docs/recipes/44-water-weather-look-hooks.md +135 -0
  203. package/docs/recipes/45-cascaded-shadows.md +51 -0
  204. package/docs/recipes/46-blender-art-route.md +114 -0
  205. package/docs/recipes/47-island-snow-backdrop.md +44 -0
  206. package/docs/recipes/48-make-material.md +70 -0
  207. package/docs/recipes/49-game-module-contract.md +71 -0
  208. package/docs/recipes/50-own-renderer.md +12 -0
  209. package/docs/recipes/51-capability-catalog.md +63 -0
  210. package/docs/recipes/52-look.md +108 -0
  211. package/examples/action/DESIGN.md +3 -0
  212. package/examples/action/GAMEMAP.md +127 -0
  213. package/examples/action/content/actions.js +8 -0
  214. package/examples/action/content/audio.js +9 -0
  215. package/examples/action/content/index.js +10 -0
  216. package/examples/action/content/items.js +4 -0
  217. package/examples/action/content/places.js +4 -0
  218. package/examples/action/content/props.js +11 -0
  219. package/examples/action/content/templates.js +10 -0
  220. package/examples/action/content/views.js +6 -0
  221. package/examples/action/look.js +5 -0
  222. package/examples/action/main.js +137 -0
  223. package/examples/action/models.js +25 -0
  224. package/examples/sheepisland/GAMEMAP.md +107 -0
  225. package/examples/sheepisland/content/index.js +6 -0
  226. package/examples/sheepisland/content/props.js +19 -0
  227. package/examples/sheepisland/content/templates.js +5 -0
  228. package/examples/sheepisland/content/vegetation.js +8 -0
  229. package/examples/sheepisland/main.js +71 -0
  230. package/examples/sheepisland/params.js +25 -0
  231. package/examples/sheepisland/style/index.js +79 -0
  232. package/examples/sheepisland/style/models.js +59 -0
  233. package/examples/sheepisland/views.js +9 -0
  234. package/examples/styletest/GAMEMAP.md +135 -0
  235. package/examples/styletest/content/index.js +9 -0
  236. package/examples/styletest/content/items.js +8 -0
  237. package/examples/styletest/content/npcs.js +8 -0
  238. package/examples/styletest/content/places.js +5 -0
  239. package/examples/styletest/content/props.js +16 -0
  240. package/examples/styletest/content/templates.js +9 -0
  241. package/examples/styletest/content/vegetation.js +31 -0
  242. package/examples/styletest/look.js +11 -0
  243. package/examples/styletest/main.js +95 -0
  244. package/examples/styletest/models.js +87 -0
  245. package/examples/styletest/overrides.js +33 -0
  246. package/examples/styletest/panel.js +135 -0
  247. package/examples/styletest/params.js +32 -0
  248. package/examples/styletest/views.js +31 -0
  249. package/examples/world/DESIGN.md +5 -0
  250. package/examples/world/GAMEMAP.md +171 -0
  251. package/examples/world/content/actions.js +8 -0
  252. package/examples/world/content/audio.js +25 -0
  253. package/examples/world/content/bodies.js +12 -0
  254. package/examples/world/content/containers.js +4 -0
  255. package/examples/world/content/dialogues.js +33 -0
  256. package/examples/world/content/index.js +17 -0
  257. package/examples/world/content/items.js +10 -0
  258. package/examples/world/content/npcs.js +14 -0
  259. package/examples/world/content/pickups.js +11 -0
  260. package/examples/world/content/places.js +6 -0
  261. package/examples/world/content/props.js +12 -0
  262. package/examples/world/content/quests.js +15 -0
  263. package/examples/world/content/rules.js +23 -0
  264. package/examples/world/content/templates.js +5 -0
  265. package/examples/world/content/vegetation.js +32 -0
  266. package/examples/world/main.js +168 -0
  267. package/examples/world/models.js +28 -0
  268. package/index.d.ts +306 -0
  269. package/index.js +122 -0
  270. package/llms.txt +61 -0
  271. package/modules/ambience/Ambience.js +186 -0
  272. package/modules/camera/FirstPersonCamera.js +131 -0
  273. package/modules/camera/FixedCamera.js +162 -0
  274. package/modules/camera/FollowCamera.js +91 -0
  275. package/modules/camera/RtsCamera.js +132 -0
  276. package/modules/camera/common.js +182 -0
  277. package/modules/camera/index.js +11 -0
  278. package/modules/camera/projection.js +34 -0
  279. package/modules/characters/Character.js +235 -0
  280. package/modules/characters/NPC.js +242 -0
  281. package/modules/characters/assetModel.js +42 -0
  282. package/modules/characters/astar.js +66 -0
  283. package/modules/characters/behaviors.js +72 -0
  284. package/modules/characters/footsteps.js +13 -0
  285. package/modules/characters/index.js +215 -0
  286. package/modules/characters/moveHelpers.js +29 -0
  287. package/modules/characters/movers/common.js +62 -0
  288. package/modules/characters/movers/rapier.js +74 -0
  289. package/modules/characters/movers/simple.js +43 -0
  290. package/modules/characters/npcAvoid.js +129 -0
  291. package/modules/characters/npcSim.js +150 -0
  292. package/modules/characters/npcView.js +42 -0
  293. package/modules/characters/pathAsync.js +113 -0
  294. package/modules/characters/pathJob.js +62 -0
  295. package/modules/characters/pathWorker.js +7 -0
  296. package/modules/characters/playerStrings.js +12 -0
  297. package/modules/characters/proceduralRig.js +58 -0
  298. package/modules/characters/useModel.js +22 -0
  299. package/modules/characters/walkTo.js +58 -0
  300. package/modules/collision/Collision.js +274 -0
  301. package/modules/collision/grid.js +63 -0
  302. package/modules/content/explain.js +13 -0
  303. package/modules/content/ids.js +95 -0
  304. package/modules/content/index.js +154 -0
  305. package/modules/content/loader.js +190 -0
  306. package/modules/content/models.js +69 -0
  307. package/modules/content/packs.js +69 -0
  308. package/modules/content/props.js +89 -0
  309. package/modules/content/rules.js +134 -0
  310. package/modules/content/templates.js +189 -0
  311. package/modules/debug/DebugPanel.js +174 -0
  312. package/modules/entities/Entities.js +243 -0
  313. package/modules/entities/build.js +25 -0
  314. package/modules/entities/index.js +4 -0
  315. package/modules/flow/index.js +101 -0
  316. package/modules/gameplay/Container.js +227 -0
  317. package/modules/gameplay/Containers.js +89 -0
  318. package/modules/gameplay/Dialogue.js +219 -0
  319. package/modules/gameplay/Interactions.js +253 -0
  320. package/modules/gameplay/Inventory.js +224 -0
  321. package/modules/gameplay/Quests.js +205 -0
  322. package/modules/gameplay/boxOps.js +60 -0
  323. package/modules/gameplay/dialogueBox.js +48 -0
  324. package/modules/gameplay/interactionPrompt.js +28 -0
  325. package/modules/gameplay/inventoryOps.js +137 -0
  326. package/modules/gameplay/pickups.js +115 -0
  327. package/modules/gameplay/questLog.js +54 -0
  328. package/modules/gameplay/questSave.js +71 -0
  329. package/modules/grid/Grid.js +184 -0
  330. package/modules/grid/Layer.js +142 -0
  331. package/modules/grid/index.js +236 -0
  332. package/modules/grid/ops.js +73 -0
  333. package/modules/grid/preview.js +85 -0
  334. package/modules/grid/tiles.js +79 -0
  335. package/modules/hlod/index.js +167 -0
  336. package/modules/hud/index.js +167 -0
  337. package/modules/hud/parts.js +80 -0
  338. package/modules/level/geometry.js +46 -0
  339. package/modules/level/heightfield.js +160 -0
  340. package/modules/level/index.js +233 -0
  341. package/modules/level/nodes.js +84 -0
  342. package/modules/lights/index.js +227 -0
  343. package/modules/music/Music.js +294 -0
  344. package/modules/music/index.js +2 -0
  345. package/modules/music/rules.js +28 -0
  346. package/modules/nav/index.js +156 -0
  347. package/modules/nav/navPath.js +17 -0
  348. package/modules/net/Client.js +137 -0
  349. package/modules/net/Host.js +117 -0
  350. package/modules/net/Net.js +49 -0
  351. package/modules/net/index.js +77 -0
  352. package/modules/net/sync.js +114 -0
  353. package/modules/net/transports.js +118 -0
  354. package/modules/particles/Particles.js +179 -0
  355. package/modules/particles/effect.js +112 -0
  356. package/modules/particles/shaders.js +28 -0
  357. package/modules/photo/Photo.js +146 -0
  358. package/modules/rigid/RigidBodies.js +265 -0
  359. package/modules/rigid/Vehicles.js +97 -0
  360. package/modules/rigid/sync.js +158 -0
  361. package/modules/settings/Settings.js +297 -0
  362. package/modules/settings/apply.js +21 -0
  363. package/modules/settings/index.js +3 -0
  364. package/modules/settings/sections.js +156 -0
  365. package/modules/settings/strings.js +53 -0
  366. package/modules/settings/view.js +65 -0
  367. package/modules/sky/Sky.js +259 -0
  368. package/modules/sky/calendar.js +80 -0
  369. package/modules/sky/cascades.js +125 -0
  370. package/modules/sky/clouds.js +79 -0
  371. package/modules/sky/domeLayers.js +33 -0
  372. package/modules/sky/environment.js +141 -0
  373. package/modules/sky/fog.js +139 -0
  374. package/modules/sky/frame.js +77 -0
  375. package/modules/sky/layers.js +69 -0
  376. package/modules/sky/look.js +51 -0
  377. package/modules/sky/lookFog.js +80 -0
  378. package/modules/sky/lookShadow.js +50 -0
  379. package/modules/sky/lookSky.js +108 -0
  380. package/modules/sky/schedule.js +80 -0
  381. package/modules/sky/shader.js +96 -0
  382. package/modules/sky/shadow.js +74 -0
  383. package/modules/sky/skyModule.js +60 -0
  384. package/modules/terrain/ChunkManager.js +260 -0
  385. package/modules/terrain/chunkJob.js +19 -0
  386. package/modules/terrain/chunkLevels.js +40 -0
  387. package/modules/terrain/chunkQueries.js +42 -0
  388. package/modules/terrain/chunkWorker.js +5 -0
  389. package/modules/terrain/index.js +118 -0
  390. package/modules/terrain/lookGround.js +61 -0
  391. package/modules/terrain/mountTerrain.js +32 -0
  392. package/modules/terrain/terrainColorMap.js +41 -0
  393. package/modules/terrain/terrainDefaults.js +39 -0
  394. package/modules/terrain/terrainEdit.js +139 -0
  395. package/modules/terrain/terrainGen.js +155 -0
  396. package/modules/terrain/terrainIsland.js +131 -0
  397. package/modules/terrain/terrainMesh.js +92 -0
  398. package/modules/terrain/terrainShape.js +108 -0
  399. package/modules/terrain/terrainShapeMain.js +41 -0
  400. package/modules/terrain/terrainTexture.js +44 -0
  401. package/modules/timeline/Timeline.js +253 -0
  402. package/modules/timeline/Tween.js +114 -0
  403. package/modules/timeline/letterbox.js +24 -0
  404. package/modules/timeline/shots.js +90 -0
  405. package/modules/triggers/index.js +268 -0
  406. package/modules/vegetation/Vegetation.js +256 -0
  407. package/modules/vegetation/groundChunks.js +177 -0
  408. package/modules/vegetation/index.js +43 -0
  409. package/modules/vegetation/lookWind.js +37 -0
  410. package/modules/vegetation/modelGeometry.js +21 -0
  411. package/modules/water/Water.js +160 -0
  412. package/modules/water/look.js +80 -0
  413. package/modules/water/surface.js +88 -0
  414. package/modules/weather/Weather.js +242 -0
  415. package/modules/weather/look.js +75 -0
  416. package/modules/weather/particles.js +92 -0
  417. package/modules/weather/shaders.js +49 -0
  418. package/modules/weather/strings.js +15 -0
  419. package/modules/world/World.js +231 -0
  420. package/modules/world/cells.js +42 -0
  421. package/modules/world/explain.js +11 -0
  422. package/modules/world/index.js +71 -0
  423. package/modules/world/persist.js +107 -0
  424. package/modules/world/pos.js +20 -0
  425. package/modules/world/records.js +89 -0
  426. package/modules/world/sim.js +175 -0
  427. package/modules/world/simFar.js +82 -0
  428. package/modules/world/state.js +115 -0
  429. package/modules/world/thingSource.js +44 -0
  430. package/modules/world/views.js +182 -0
  431. package/package.json +66 -4
  432. package/presets.js +96 -0
  433. package/render/PostFX.js +240 -0
  434. package/render/detail.js +105 -0
  435. package/render/effects.js +144 -0
  436. package/render/engineUniforms.js +23 -0
  437. package/render/fuse.js +84 -0
  438. package/render/lighting.js +100 -0
  439. package/render/lights.js +18 -0
  440. package/render/lookSurface.js +161 -0
  441. package/render/materials.js +220 -0
  442. package/render/patches.js +252 -0
  443. package/render/postLook.js +86 -0
  444. package/render/surface.js +69 -0
  445. package/render/uniformDecl.js +29 -0
  446. package/types/common.d.ts +34 -0
  447. package/types/core.d.ts +1965 -0
  448. package/types/gameplay.d.ts +1822 -0
  449. package/types/generated/core/Audio.d.ts +200 -0
  450. package/types/generated/core/Batching.d.ts +47 -0
  451. package/types/generated/core/Budget.d.ts +90 -0
  452. package/types/generated/core/Commits.d.ts +31 -0
  453. package/types/generated/core/DebugOverrides.d.ts +52 -0
  454. package/types/generated/core/Events.d.ts +89 -0
  455. package/types/generated/core/I18n.d.ts +30 -0
  456. package/types/generated/core/Input.d.ts +118 -0
  457. package/types/generated/core/Jobs.d.ts +41 -0
  458. package/types/generated/core/Ops.d.ts +203 -0
  459. package/types/generated/core/Random.d.ts +49 -0
  460. package/types/generated/core/Rays.d.ts +49 -0
  461. package/types/generated/core/Saves.d.ts +162 -0
  462. package/types/generated/core/Stream.d.ts +93 -0
  463. package/types/generated/core/Threads.d.ts +82 -0
  464. package/types/generated/core/Views.d.ts +33 -0
  465. package/types/generated/core/audioVoice.d.ts +47 -0
  466. package/types/generated/core/page.d.ts +18 -0
  467. package/types/generated/core/session.d.ts +48 -0
  468. package/types/generated/modules/ambience/Ambience.d.ts +48 -0
  469. package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
  470. package/types/generated/modules/flow/index.d.ts +10 -0
  471. package/types/generated/modules/grid/Grid.d.ts +151 -0
  472. package/types/generated/modules/grid/Layer.d.ts +65 -0
  473. package/types/generated/modules/grid/index.d.ts +86 -0
  474. package/types/generated/modules/hlod/index.d.ts +11 -0
  475. package/types/generated/modules/hud/index.d.ts +10 -0
  476. package/types/generated/modules/lights/index.d.ts +13 -0
  477. package/types/generated/modules/music/Music.d.ts +111 -0
  478. package/types/generated/modules/net/Net.d.ts +34 -0
  479. package/types/generated/modules/net/index.d.ts +53 -0
  480. package/types/generated/modules/net/transports.d.ts +58 -0
  481. package/types/generated/modules/particles/Particles.d.ts +69 -0
  482. package/types/generated/modules/sky/Sky.d.ts +145 -0
  483. package/types/generated/modules/sky/skyModule.d.ts +10 -0
  484. package/types/generated/modules/timeline/Timeline.d.ts +51 -0
  485. package/types/generated/modules/water/Water.d.ts +29 -0
  486. package/types/generated/modules/weather/Weather.d.ts +62 -0
  487. package/types/generated/modules/world/World.d.ts +242 -0
  488. package/types/generated/modules/world/index.d.ts +15 -0
  489. package/types/generated/render/PostFX.d.ts +125 -0
  490. package/types/generated/render/materials.d.ts +100 -0
  491. package/types/generated/render/patches.d.ts +41 -0
  492. package/types/generated/ui/Focus.d.ts +11 -0
  493. package/types/generated/ui/LoadingScreen.d.ts +2 -0
  494. package/types/generated/ui/UI.d.ts +57 -0
  495. package/types/nav.d.ts +52 -0
  496. package/types/physics.d.ts +592 -0
  497. package/types/style.d.ts +638 -0
  498. package/types/worker.d.ts +11 -0
  499. package/types/world.d.ts +772 -0
  500. package/ui/Focus.js +51 -0
  501. package/ui/LoadingScreen.js +42 -0
  502. package/ui/Parts.js +199 -0
  503. package/ui/UI.js +167 -0
  504. package/ui/defaults.js +85 -0
  505. package/ui/theme.js +124 -0
  506. package/ui/touchPart.js +49 -0
@@ -0,0 +1,260 @@
1
+ // Chunk streaming: chunks around the engine.stream sources (player, camera focus, teleport destination...) are generated on engine.threads workers,
2
+ // uploaded to the GPU when in view, released when far from all sources.
3
+ // LOD is split by ring from the nearest source: the chunk a source stands in plus the one ring around it is ring 1, and so on.
4
+ // Visuals and gameplay take effect separately: a finished model is uploaded and shown at once; tree collision (forEachCollider, chunkCollision) only takes
5
+ // effect at the tick set by engine.commits (c.solid),
6
+ // and is generated on the main thread on the spot if not done by then -- machine speed never changes whether the player bumps into a tree (see
7
+ // core/Commits.js).
8
+ import * as THREE from 'three';
9
+ import { createTerrain } from './terrainGen.js';
10
+ import { chunkHandler } from './chunkJob.js';
11
+ import { TerrainEdits } from './terrainEdit.js';
12
+ import { terrainMaterial } from '../../render/materials.js';
13
+ import { chunkRing } from '../../core/streamSources.js';
14
+ import { chunkQueries } from './chunkQueries.js';
15
+ import { chunkLevels, NO_VEG } from './chunkLevels.js';
16
+ import { mountTerrain } from './mountTerrain.js';
17
+ import { disposeColorMap } from './terrainTexture.js';
18
+
19
+ const COLLIDER_LAG = 30; // base delay before chunk collision takes effect (fixed steps, 30 = 0.5 s), multiplied by (1 + ring)
20
+
21
+ export class ChunkManager {
22
+ constructor(engine, terrainCfg, material = null) {
23
+ this.engine = engine;
24
+ this.T = createTerrain(terrainCfg); // main-thread copy: height queries for the character and camera
25
+ this.chunks = new Map();
26
+ this.viewChunks = 4; // unit: chunks
27
+ this.density = 1;
28
+ this.applyBudgetMs = 3; // max ms per frame spent uploading results to the GPU
29
+ this.maxInFlight = 4;
30
+ this.inFlight = 0;
31
+ this.ready = [];
32
+ this._want = []; // chunks not yet dispatched (nearest first)
33
+ // +1 when the chunk table is cleared / deleted from (update uses it to decide whether to rebuild the pending list)
34
+ this._ver = 0;
35
+ this._wantFor = [-1, -1]; // view distance and _ver the pending list was last built for
36
+ this.gen = 0;
37
+ this.stats = { builtThisFrame: 0, applyMs: 0, queued: 0 };
38
+ this.terrainMat = terrainMaterial(typeof material === 'function' ? material(engine) : material, engine);
39
+ this.centers = []; // stream sources in chunk units: { cx, cz, R, simple } (set by update)
40
+ this.sideMat = null; // shape.side.material: island sides and bottoms
41
+ this.lowest = 0; // lowest island point loaded (default voidY)
42
+ this._frustum = new THREE.Frustum();
43
+ this._m = new THREE.Matrix4();
44
+
45
+ // one lane of chunk workers (engine.threads); with threads: false or no Worker the same handler runs on the main thread, and a crashed worker falls back to
46
+ // it
47
+ this.lane = engine.threads.lane({ create: () => new Worker(new URL('./chunkWorker.js', import.meta.url), { type: 'module' }), local: chunkHandler });
48
+ this.lane.broadcast({ type: 'init', terrain: terrainCfg, species: {} }, 'init');
49
+ /** @internal edit records (saved with the save) */ this.edits = new TerrainEdits(engine, this);
50
+ }
51
+
52
+ get CHUNK() { return this.T.CHUNK; }
53
+ /**
54
+ * Below it the player or a moving body fell out of the world (terrain:void): shape.voidY, else 50 m under the lowest island
55
+ * chunk loaded (at most -50); -Infinity without a shape
56
+ * @example engine.events.on('terrain:void', ({ who }) => { if (who === engine.player) engine.player.placeAt(home); });
57
+ */
58
+ get voidY() { return this.T.shape ? this.T.shape.voidY ?? Math.min(0, this.lowest) - 50 : -Infinity; }
59
+ /** Grid spacing (meters): edits snap to it, and paint colors whole cells of this size. Set by chunkSize / resolution */
60
+ get cellSize() { return this.T.CELL; }
61
+ /**
62
+ * Change the ground: dig, raise, flatten, or paint the ground type. Call it from an op or a fixed step (it is saved gameplay state).
63
+ * Heights snap to grid points and paint to cells (cellSize); the nearest one is taken when the shape is smaller than a cell.
64
+ * engine.surface / slope / groundType, collision, paths and vegetation (what grew there is removed) follow at once; it is saved,
65
+ * and a chunk unloaded and generated again comes back edited. Paint colors come from biomeColors[type] (gray when the game's style has none).
66
+ * @param {import('three').Vector3 | {x:number,z:number} | number[]} position
67
+ * @param {{ radius?: number, shape?: 'circle' | 'square', raise?: number, lower?: number, flatten?: number, paint?: string | null }} opts
68
+ * radius meters (default half a cell); one of raise / lower (meters) / flatten (target height); paint a type name, null gives back the generated type
69
+ * @returns {{ heights: number, cells: number }} how many grid points and cells changed (0 and 0 off a shape outline)
70
+ * @example
71
+ * engine.ops.define('farm.till', { args: { at: 'position' },
72
+ * run(e, a) { e.terrain.edit(a.at, { shape: 'square', radius: e.terrain.cellSize / 2, paint: 'tilled' }); } });
73
+ * engine.terrain.edit(pos, { radius: 3, lower: 1.5 }); // dig a pit
74
+ * engine.terrain.edit(pos, { shape: 'square', radius: 6, flatten: engine.surface(pos) }); // level a foundation
75
+ */
76
+ edit(position, opts) { return this.edits.edit(position, opts); }
77
+
78
+ /** @internal vegetation plumbing */
79
+ registerSpecies(name, rule) {
80
+ this.lane.broadcast({ type: 'species', name, rule }, 'species:' + name);
81
+ this.rebuild();
82
+ }
83
+ /** Replace the terrain config in every worker (height map loaded); species is the full rule table */
84
+ reinit(terrainCfg, species) {
85
+ this.T = createTerrain(terrainCfg);
86
+ this.edits.attach();
87
+ this.lane.broadcast({ type: 'init', terrain: terrainCfg, species }, 'init');
88
+ this.rebuild();
89
+ }
90
+
91
+ // dispatch the next task as soon as a result returns: a worker need not wait for the next frame to get work (a frame can be very long while loading)
92
+ _send(job) {
93
+ this.inFlight++;
94
+ const t0 = performance.now(); // measure
95
+ this.lane.run(job).then(r => { this.inFlight--; this.engine.budget.cost.transit(t0, r); this.ready.push(r); this._pump(); });
96
+ }
97
+
98
+ /**
99
+ * View distance (in chunks). Also moves the camera far plane out to it; the fog distance follows only with terrain({ viewFog: true }) (the game's fog is its
100
+ * own)
101
+ */
102
+ setViewChunks(n) {
103
+ this.viewChunks = n;
104
+ const d = (n - 0.3) * this.T.CHUNK, e = this.engine;
105
+ if (this.viewFog) e.setFogFar(d);
106
+ else if (e.camera.far < d + 150) { e.camera.far = d + 150; e.camera.updateProjectionMatrix(); } // chunks in view must not be clipped
107
+ }
108
+ /** Vegetation density multiplier (rebuilds all chunks) */
109
+ setDensity(d) { this.density = d; this.rebuild(); }
110
+
111
+ rebuild() {
112
+ for (const c of this.chunks.values()) this._dispose(c);
113
+ this.chunks.clear();
114
+ this.ready = [];
115
+ this._want = [];
116
+ this.gen++; this._ver++;
117
+ }
118
+
119
+ /** Ring of a chunk from the nearest stream source; a 'simple' source counts as the outer ring (far look, no near detail) */
120
+ _ring(c) { return chunkRing(c.cx, c.cz, this.centers, this.viewChunks); }
121
+
122
+ /**
123
+ * Build a queued chunk entry and register the tick when its collision takes effect. Registered when the chunk is first needed (decided by stream source
124
+ * positions),
125
+ * not when actually sent to the worker (which depends on how busy the worker is) -- so the effect time depends on gameplay only.
126
+ * Effect delay: ring 1, which the loading screen waits for, takes effect the moment play starts (lag 0); farther rings get more worker time, so on-the-spot
127
+ * generation is rarely needed
128
+ */
129
+ _queue(cx, cz, key) {
130
+ const c = { cx, cz, key, state: 'queued', group: null, veg: {}, colliders: {}, pendingDetail: false, detailDone: new Set(), level: -1, sphere: null, solid: false, gen: this.gen };
131
+ this.chunks.set(key, c);
132
+ const ring = this._ring(c);
133
+ c.ticket = this.engine.commits.request({
134
+ lag: !this.engine.ready && ring <= 1 ? 0 : COLLIDER_LAG * (1 + ring),
135
+ // collision counts from this step on (a new token makes the physics module build this chunk's collision)
136
+ apply: () => { c.solid = true; c.colToken = {}; },
137
+ fallback: () => this._forceReady(c),
138
+ valid: () => this.chunks.get(c.key) === c && c.gen === this.gen,
139
+ });
140
+ return c;
141
+ }
142
+ /**
143
+ * Dispatch tasks from the queue until maxInFlight are running; while the loading screen is up send all of them (a main-thread frame is long, waiting for
144
+ * replies would idle the worker)
145
+ */
146
+ _pump() {
147
+ const species = (this.engine.vegetation || NO_VEG).baseNames(), max = this.engine.ready ? Math.max(this.maxInFlight, 2 * this.lane.size) : Infinity;
148
+ while (this.inFlight < max && this._want.length) {
149
+ const c = this._want.shift();
150
+ if (c.state !== 'queued' || this.chunks.get(c.key) !== c) continue; // already generated on the spot, or released
151
+ c.state = 'pending';
152
+ this._send(this._job(c, true, species));
153
+ }
154
+ }
155
+
156
+ /** sources: engine.stream.sources() (every stream source; a source radius caps the view distance) */
157
+ update(sources, camera) {
158
+ const CH = this.T.CHUNK, V = this.viewChunks;
159
+ // centers are reused objects compared field by field: nothing is allocated on a frame where no source changed chunk
160
+ const C = this.centers;
161
+ let changed = C.length !== sources.length || this._wantFor[0] !== V || this._wantFor[1] !== this._ver;
162
+ C.length = sources.length;
163
+ for (let i = 0; i < sources.length; i++) {
164
+ const s = sources[i], cx = Math.floor(s.x / CH), cz = Math.floor(s.z / CH), simple = s.detail === 'simple';
165
+ const R = s.radius == null ? V : Math.min(V, Math.max(1, Math.ceil(s.radius / CH))), c = C[i] ??= { cx: NaN, cz: 0, R: 0, simple: false };
166
+ if (c.cx !== cx || c.cz !== cz || c.R !== R || c.simple !== simple) { c.cx = cx; c.cz = cz; c.R = R; c.simple = simple; changed = true; }
167
+ }
168
+
169
+ // 1. queue chunks any source needs; release those far from all.
170
+ // Skip when source chunks, view distance and chunk table are unchanged (don't rebuild lists and key strings every frame)
171
+ if (changed) {
172
+ this._wantFor[0] = V; this._wantFor[1] = this._ver;
173
+ const d2 = c => { let m = Infinity; for (const s of this.centers) m = Math.min(m, (c.cx - s.cx) ** 2 + (c.cz - s.cz) ** 2); return m; };
174
+ const want = new Map();
175
+ for (const s of this.centers) {
176
+ const R = s.R, lim = R * R + R;
177
+ for (let dz = -R; dz <= R; dz++) for (let dx = -R; dx <= R; dx++) {
178
+ const cx = s.cx + dx, cz = s.cz + dz, key = cx + ',' + cz;
179
+ if (dx * dx + dz * dz <= lim && !this.chunks.has(key)) want.set(key, { cx, cz, key });
180
+ }
181
+ }
182
+ // re-sort queued chunks (not released) plus new ones by distance to the nearest source: nearest first
183
+ const fresh = [...want.values()].sort((a, b) => d2(a) - d2(b)).map(w => this._queue(w.cx, w.cz, w.key));
184
+ this._want = this._want.filter(c => c.state === 'queued' && this.chunks.get(c.key) === c).concat(fresh).sort((a, b) => d2(a) - d2(b));
185
+ const kept = c => this.centers.some(s => (c.cx - s.cx) ** 2 + (c.cz - s.cz) ** 2 <= (s.R + 1) * (s.R + 1) + s.R + 1);
186
+ for (const [key, c] of this.chunks) if (!kept(c)) { this._dispose(c); this.chunks.delete(key); }
187
+ }
188
+ this._pump();
189
+ this.stats.queued = this._want.length;
190
+
191
+ // 2. upload worker results within the time budget; while the loading screen is up, first-screen chunks (the ring around the player) ignore the budget and
192
+ // all upload in one frame
193
+ const t0 = performance.now(), loading = !this.engine.ready, later = []; // measure: upload budget
194
+ let built = 0;
195
+ for (const r of this.ready) {
196
+ const c = this.chunks.get(r.cx + ',' + r.cz);
197
+ if (!c || r.gen !== this.gen || this._stale(c, r)) continue;
198
+ if (built > 0 && performance.now() - t0 >= this.applyBudgetMs // measure
199
+ && !(loading && this._ring(c) <= 1)) { later.push(r); continue; }
200
+ if (r.terrain) { if (c.state === 'ready') continue; this._applyTerrain(c, r.terrain); c.ticket?.resolve(true); }
201
+ else if (c.state !== 'ready') continue;
202
+ for (const name in r.veg) this._applyVeg(c, name, r.veg[name]);
203
+ if (!r.terrain) { c.pendingDetail = false; for (const name in r.veg) c.detailDone.add(name); }
204
+ c.level = -1; built++;
205
+ }
206
+ this.ready = later;
207
+ this.stats.builtThisFrame = built;
208
+ this.stats.applyMs += ((performance.now() - t0) - this.stats.applyMs) * 0.1; // measure
209
+
210
+ // 3. LOD + frustum culling
211
+ camera.updateMatrixWorld();
212
+ this._m.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
213
+ this._frustum.setFromProjectionMatrix(this._m);
214
+ let visible = 0, instances = 0;
215
+ for (const c of this.chunks.values()) {
216
+ if (c.state !== 'ready') continue;
217
+ const ring = this._ring(c);
218
+ this._setLevel(c, ring);
219
+ const v = ring <= 1 || this._frustum.intersectsSphere(c.sphere);
220
+ c.group.visible = v;
221
+ if (v) { visible++; for (const n in c.veg) if (c.veg[n].visible) instances += c.veg[n].count; }
222
+ }
223
+ this.stats.visible = visible; this.stats.loaded = this.chunks.size; this.stats.instances = instances;
224
+ return built;
225
+ }
226
+
227
+ /** Due but chunk not ready: if the worker result already arrived, upload it now, else generate on the main thread (same code as the worker, same result) */
228
+
229
+ _job(c, terrain, species) {
230
+ const ev = this.edits.version(c.key), edits = this.edits.forChunk(c.cx, c.cz);
231
+ return { type: 'job', cx: c.cx, cz: c.cz, terrain, species, density: this.density, gen: this.gen, ev, edits };
232
+ }
233
+ // result built before a later edit near this chunk: drop it and ask again (a loaded chunk was already rebuilt by the edit)
234
+ _stale(c, r) {
235
+ if (r.ev === this.edits.version(c.key)) return false;
236
+ if (r.terrain && c.state === 'pending') { c.state = 'queued'; this._want.unshift(c); }
237
+ else if (!r.terrain) { c.pendingDetail = false; c.level = -1; }
238
+ return true;
239
+ }
240
+
241
+ _applyTerrain(c, t) { mountTerrain(this, c, t); }
242
+
243
+ // the InstancedMesh of one species in a chunk is built by vegetation (the same code builds its chunks on any other ground)
244
+ _applyVeg(c, name, r) { this.engine.vegetation.mount(c, name, r); }
245
+
246
+
247
+ /** Stop the chunk workers (called by terrain dispose; in-flight results are discarded) */
248
+ dispose() { this.lane.dispose(); this.ready.length = 0; }
249
+ /** @internal vegetation / settings plumbing */
250
+ refreshLevels() { for (const c of this.chunks.values()) c.level = -1; }
251
+
252
+ _dispose(c) {
253
+ if (c.state !== 'ready') return;
254
+ this.engine.scene.remove(c.group);
255
+ c.terrain.geometry.dispose();
256
+ disposeColorMap(c);
257
+ for (const n in c.veg) c.veg[n].dispose();
258
+ }
259
+ }
260
+ Object.assign(ChunkManager.prototype, chunkQueries, chunkLevels);
@@ -0,0 +1,19 @@
1
+ // Chunk generation handler: the same code answers in the terrain worker (chunkWorker.js) and on the main thread when there are no workers (engine.threads lane fallback).
2
+ // Runs in a Worker: must not import three.js (see CONVENTIONS "Worker limits"); vegetation rules arrive as plain data.
3
+ import { createTerrain } from './terrainGen.js';
4
+
5
+ /** @returns {(msg: any) => any} handler for { type: 'init' | 'species' | 'job' } messages */
6
+ export function chunkHandler() {
7
+ let T = null, species = {};
8
+ return d => {
9
+ if (d.type === 'init') { T = createTerrain(d.terrain); species = d.species || {}; return null; }
10
+ if (d.type === 'species') { species[d.name] = d.rule; return null; }
11
+ const t0 = performance.now(); // measure
12
+ T.setEdits(d.edits); // only the edits around this chunk travel with the job (null when there are none)
13
+ const out = { gen: d.gen, ev: d.ev, cx: d.cx, cz: d.cz, terrain: d.terrain ? T.buildChunk(d.cx, d.cz) : null, veg: {}, ms: 0 };
14
+ for (const name of d.species) out.veg[name] = T.place(d.cx, d.cz, species[name], d.density);
15
+ // compute time: the main thread subtracts it from the round trip to get the transit cost (Budget.js ApplyCost)
16
+ out.ms = performance.now() - t0; // measure
17
+ return out;
18
+ };
19
+ }
@@ -0,0 +1,40 @@
1
+ // Chunk loading detail: forcing one chunk ready now and choosing per-species detail level by ring (mixed into ChunkManager.prototype).
2
+ // Split out of ChunkManager.js; the methods use the manager state (chunks, ready, edits, T, density) through this.
3
+
4
+ /** Stand-in for engine.vegetation when the vegetation module is not installed */
5
+ export const NO_VEG = { baseNames: () => [], nearNames: () => [], list: () => [], get: () => null };
6
+
7
+ export const chunkLevels = {
8
+ _forceReady(c) {
9
+ if (c.state === 'ready') return true;
10
+ const i = this.ready.findIndex(r => r.terrain && r.cx === c.cx && r.cz === c.cz && r.gen === c.gen && r.ev === this.edits.version(c.key));
11
+ let r = i >= 0 ? this.ready.splice(i, 1)[0] : null;
12
+ if (!r) {
13
+ const veg = this.engine.vegetation || NO_VEG;
14
+ r = { terrain: this.T.buildChunk(c.cx, c.cz), veg: {} };
15
+ for (const name of veg.baseNames()) r.veg[name] = this.T.place(c.cx, c.cz, veg.get(name).rule, this.density);
16
+ }
17
+ this._applyTerrain(c, r.terrain);
18
+ for (const name in r.veg) this._applyVeg(c, name, r.veg[name]);
19
+ c.level = -1;
20
+ return true;
21
+ },
22
+
23
+ _setLevel(c, ring) {
24
+ if (c.level === ring) return;
25
+ c.level = ring;
26
+ const veg = this.engine.vegetation || NO_VEG;
27
+ for (const sp of veg.list()) {
28
+ const im = c.veg[sp.name];
29
+ if (sp.nearOnly) {
30
+ // detailDone: this species was already placed here and came back empty; without it the empty result would reset the level and re-ask forever
31
+ if (ring <= sp.maxRing && !im && !c.pendingDetail && !c.detailDone.has(sp.name)) {
32
+ c.pendingDetail = true;
33
+ this._send(this._job(c, false, veg.nearNames()));
34
+ } else if (ring > sp.maxRing + 1 && im) { veg.unmount(c, sp.name); c.detailDone.delete(sp.name); }
35
+ continue;
36
+ }
37
+ if (im) veg.levelOf(im, sp, ring);
38
+ }
39
+ },
40
+ };
@@ -0,0 +1,42 @@
1
+ // Readiness and collision queries on loaded chunks (mixed into ChunkManager.prototype), read by loading and by the collision and physics
2
+ // modules through the ground API.
3
+ import { xzOf } from '../../core/math.js';
4
+
5
+ export const chunkQueries = {
6
+ /** Whether chunks within `rings` rings (default 1) of a position are generated (for the loading screen); solid: also their collision has taken effect */
7
+ isReadyAround(position, { rings = 1, solid = false } = {}) {
8
+ const [x, z] = xzOf(position), CH = this.T.CHUNK, pcx = Math.floor(x / CH), pcz = Math.floor(z / CH);
9
+ for (let dz = -rings; dz <= rings; dz++) for (let dx = -rings; dx <= rings; dx++) {
10
+ const c = this.chunks.get((pcx + dx) + ',' + (pcz + dz));
11
+ if (!c || c.state !== 'ready' || solid && !c.solid) return false;
12
+ }
13
+ return true;
14
+ },
15
+
16
+ /** @internal Iterate collision circles near (x,z): fn(cx, cz, r). Only queries loaded chunks near the player */
17
+ forEachCollider(x, z, range, fn) {
18
+ const CH = this.T.CHUNK, x0 = Math.floor((x - range) / CH), x1 = Math.floor((x + range) / CH), z0 = Math.floor((z - range) / CH), z1 = Math.floor((z + range) / CH);
19
+ for (let cz = z0; cz <= z1; cz++) for (let cx = x0; cx <= x1; cx++) {
20
+ const c = this.chunks.get(cx + ',' + cz);
21
+ if (!c?.solid) continue;
22
+ for (const n in c.colliders) {
23
+ const k = c.colliders[n];
24
+ for (let i = 0; i < k.length; i += 3) {
25
+ const dx = k[i] - x, dz = k[i + 1] - z, rr = range + k[i + 2];
26
+ if (dx * dx + dz * dz < rr * rr) fn(k[i], k[i + 1], k[i + 2]);
27
+ }
28
+ }
29
+ }
30
+ },
31
+
32
+ /** @internal Collision data of a chunk (for the physics module): terrain triangles (chunk-local coordinates) + vegetation collision circles. Returns null if not generated.
33
+ * token tells whether the chunk was regenerated */
34
+ chunkCollision(cx, cz) {
35
+ const c = this.chunks.get(cx + ',' + cz);
36
+ if (!c || c.state !== 'ready' || !c.solid) return null; // collision's effective tick not reached yet
37
+ // when the token changes the physics module rebuilds this chunk's collision; edits such as felling a tree issue a new colToken
38
+ // an island chunk (terrain({ shape })) leaves out its bottom: a body falls past the underside instead of landing on it from below
39
+ const p = c.terrain.geometry.attributes.position.array, positions = c.solidCount == null ? p : p.subarray(0, c.solidCount * 3);
40
+ return { token: c.colToken ?? c, positions, ox: cx * this.T.CHUNK, oz: cz * this.T.CHUNK, circles: Object.values(c.colliders) };
41
+ },
42
+ };
@@ -0,0 +1,5 @@
1
+ // Terrain worker: generates chunk meshes and vegetation placement off the main thread (one per engine.threads slot).
2
+ import { serve } from '../../core/threadServe.js';
3
+ import { chunkHandler } from './chunkJob.js';
4
+
5
+ serve(chunkHandler());
@@ -0,0 +1,118 @@
1
+ // Terrain module: chunked, streamed ground built from a height function (or a height map), with edits, workers and ground types.
2
+ // After install: engine.terrain is the chunk manager; engine.surface()/slope()/groundType() come from it.
3
+ //
4
+ // The engine ships no landform and no ground types: terrain() alone is flat gray ground at y = 0 (a placeholder, with a dev warning).
5
+ // A game passes a generator: its own pure functions, or a preset such as terrainPreset() from @threedog/terrain-noise:
6
+ // engine.use(terrain({ seed: 7, ...terrainPreset(), flatten: [{ x: 0, z: 0, radius: 20 }] }));
7
+ // engine.use(terrain({ height: (x, z, n) => 10 * n.fbm(x * 0.01, z * 0.01), groundType: (x, z, h) => h > 8 ? 'rock' : 'grass' }));
8
+ // Both run in workers, so they are pure (threads.pure rules: only parameters and globals like Math; an outside variable throws here, naming it).
9
+ // Settings a function needs travel as params (plain data, read as n.params). The engine still does chunks, streaming, collision, flatten and edits on top.
10
+ // Height map: terrain({ heightmap: { url: '/textures/height.png', size: [1024, 1024], min: -5, max: 60 } }), a grayscale image, whiter is higher, read at startup.
11
+ // Colors come from the style pack style.terrain (colors palette, biomeColors per ground type, steep); a type without a color is neutral gray.
12
+ // Shading: 'smooth' | 'flat' | 'texture' (per-chunk color map, colors independent of the mesh; see recipes/37-terrain-look-hooks.md).
13
+ // Material: terrain({ material }) or style.terrain.material, a Material or (engine) => Material; chunks carry position, normal, color
14
+ // and uv (world xz / chunk size, continuous across chunks). Cloud shadows and season tint are added to it.
15
+ // Edits: engine.terrain.edit(pos, { radius: 2, lower: 1 }) digs; { paint: 'tilled' } paints a ground type (its color: style.terrain.biomeColors). Saved, see terrainEdit.js.
16
+
17
+ // Outline: terrain({ shape: { mask: (x, z, n) => 40 - Math.hypot(x, z), side: { depth: 2 } } }) keeps ground only where mask > 0 (an island
18
+ // with cliff sides); off it engine.surface is -Infinity, engine.ground.has false, and a fall emits terrain:void. See recipes/42-terrain-shape.md.
19
+
20
+ /** Read a grayscale image into a 0-1 array (height map, outline mask) */
21
+ async function loadGray(url) {
22
+ const img = new Image(); img.src = url; await img.decode();
23
+ const c = document.createElement('canvas'); c.width = img.width; c.height = img.height;
24
+ const g = c.getContext('2d'); g.drawImage(img, 0, 0);
25
+ const px = g.getImageData(0, 0, c.width, c.height).data, data = new Float32Array(c.width * c.height);
26
+ for (let i = 0; i < data.length; i++) data[i] = px[i * 4] / 255;
27
+ return { data, width: c.width, height: c.height };
28
+ }
29
+ import { ChunkManager } from './ChunkManager.js';
30
+ import { DEFAULT_TERRAIN } from './terrainGen.js';
31
+ import { checkOptions } from '../../core/validate.js';
32
+ import { readParams, keysSchema } from '../../core/params.js';
33
+ import { compilePure } from '../../core/threadPure.js';
34
+ import { warnOnce } from '../../core/validate.js';
35
+ import { prepareShape, voidWatcher } from './terrainShapeMain.js';
36
+ import { defineGroundLook } from './lookGround.js';
37
+
38
+ const NO_HEIGHT = 'terrain(): no height function or height map was given, so the ground is flat gray at y = 0 (a placeholder, not a look). '
39
+ + 'Pass terrain({ height, groundType }) or a preset, e.g. terrain({ ...terrainPreset() }) with terrainPreset from @threedog/terrain-noise';
40
+
41
+ export { createTerrain, DEFAULT_TERRAIN } from './terrainGen.js';
42
+
43
+ const TERRAIN_PARAMS = keysSchema(['viewChunks', 'density', 'material', 'viewFog', ...Object.keys(DEFAULT_TERRAIN)], { ...DEFAULT_TERRAIN, viewChunks: 4, density: 1, viewFog: false }); // defaults shown in the catalog; createTerrain applies the real ones
44
+
45
+ export function terrain(opts = {}) {
46
+ readParams('terrain', TERRAIN_PARAMS, opts);
47
+ const { viewChunks = 4, density = 1, material, viewFog = false, ...cfg } = opts;
48
+ let w = null, watchVoid = null;
49
+ return {
50
+ name: 'terrain', label: 'Terrain', params: TERRAIN_PARAMS, options: opts, noSkip: 'void-fall watch only; nothing accumulates over time', optional: ['vegetation'], stage: 'world',
51
+ install(e) {
52
+ const style = e.style.terrain || {};
53
+ for (const k in cfg) if (cfg[k] === undefined) delete cfg[k];
54
+ // a game's generator functions go to the workers as source text: checked here (outside variables name themselves) so the error points at this call
55
+ const terrainCfg = { ...(style.config || {}), ...cfg, colors: { ...(style.colors || {}), ...(cfg.colors || {}) } };
56
+ for (const k of ['height', 'groundType', 'normalFn']) if (typeof terrainCfg[k] === 'function') terrainCfg[k] = compilePure(terrainCfg[k], `terrain({ ${k} })`).src; // also a style's normalFn
57
+ // low-tier devices start with a coarser color map (a quarter of the pixels and upload); the game's own colorResolution wins
58
+ if (terrainCfg.shading === 'texture' && terrainCfg.colorResolution == null && e.tier === 'low') terrainCfg.colorResolution = 64;
59
+ if (style.biomeColors) terrainCfg.biomeColors = { ...style.biomeColors, ...(cfg.biomeColors || {}) };
60
+ if (style.steep && !cfg.steep) terrainCfg.steep = style.steep;
61
+ if (style.variation) { // look only (plain data), so it rides along to the workers
62
+ checkOptions('style.terrain.variation', style.variation, ['blend', 'jitter', 'patches']);
63
+ checkOptions('style.terrain.variation.blend', style.variation.blend || {}, ['size', 'strength']);
64
+ checkOptions('style.terrain.variation.jitter', style.variation.jitter || {}, ['size', 'min', 'range']);
65
+ checkOptions('style.terrain.variation.patches', style.variation.patches || {}, ['size', 'strength', 'levels', 'tint']);
66
+ terrainCfg.variation = style.variation;
67
+ }
68
+ if (!terrainCfg.height && !terrainCfg.heightmap) warnOnce(NO_HEIGHT);
69
+ const sideMat = terrainCfg.shape ? prepareShape(terrainCfg) : null;
70
+ w = new ChunkManager(e, terrainCfg, material ?? style.material);
71
+ if (sideMat) w.sideMat = typeof sideMat === 'function' ? sideMat(e) : sideMat;
72
+ if (terrainCfg.shape) watchVoid = voidWatcher(e, w);
73
+ w.density = density;
74
+ w.viewFog = viewFog; // opt-in: the fog ends where the chunks end (hides the edge); otherwise createEngine({ fogFar }) / the game's fog stays
75
+ this._cfg = terrainCfg;
76
+ // look.ground: what terrain({...}) itself was given goes on the game layer (owner 'terrain()'); the style's values are the style layer
77
+ defineGroundLook(e, w, { cfg: () => this._cfg, setCfg: c => { this._cfg = c; },
78
+ game: { colors: cfg.colors && terrainCfg.colors, biomeColors: cfg.biomeColors && terrainCfg.biomeColors, steep: cfg.steep, shading: cfg.shading, material } });
79
+ e.setGround({
80
+ height: (x, z) => w.T.surface(x, z),
81
+ slope: (x, z) => w.T.slope(x, z),
82
+ type: (x, z) => w.T.biomeAt(x, z, w.T.surface(x, z), w.T.slope(x, z)), // 'void' outside terrain({ shape })
83
+ waterLevel: w.T.waterLevel,
84
+ // public collision API: the collision and physics modules read terrain only through these, never chunk internals
85
+ forEachCollider: (x, z, range, fn) => w.forEachCollider(x, z, range, fn),
86
+ chunkSize: w.T.CHUNK,
87
+ viewRange: () => w.viewChunks * w.T.CHUNK, // stream entries build within the terrain view by default
88
+ chunkCollision: (cx, cz) => w.chunkCollision(cx, cz),
89
+ has: (x, z) => w.T.has(x, z),
90
+ voidY: () => w.voidY, // the physics module reports its own bodies falling below it (terrain:void)
91
+ });
92
+ w.setViewChunks(viewChunks);
93
+ // a source is ready when the ring around it is generated, and for a physics source its collision has taken effect (chunkCollision non-null)
94
+ e.stream.readyCheck('terrain', s => w.isReadyAround(s, { rings: 1 }) && (!s.physics || w.isReadyAround(s, { rings: 1, solid: true })));
95
+ e.events.on('settings:shadows', () => w.refreshLevels());
96
+ e.budget.metric('chunkApplyMs', () => w.stats.applyMs); // chunk upload ms per frame (the limit comes from the game's budget)
97
+ return w;
98
+ },
99
+ frame(dt, e) { w.update(e.stream.sources(), e.camera); }, // chunks load around every engine.stream source
100
+ fixed() { watchVoid?.(); }, // terrain({ shape }) only: falls below voidY are gameplay, so they are seen on the fixed step
101
+ describe(e, ctx) { ctx.out.perf.chunks = { loaded: w.stats.loaded ?? 0, visible: w.stats.visible ?? 0, queued: w.stats.queued }; },
102
+ // height map / mask image wait for the image: after it loads, rebuild terrain with the new config (both the main-thread copy and the workers)
103
+ critical: true, // a missing height map would start the game on flat ground: stop start() with the reason instead
104
+ async init(e) {
105
+ const hm = this._cfg.heightmap, mk = this._cfg.shape?.mask;
106
+ const needH = hm?.url && !hm.data, needM = mk?.url && !mk.data;
107
+ if (!needH && !needM) return;
108
+ const cfg2 = { ...this._cfg };
109
+ this._cfg = cfg2; // look.ground rebuilds from the current config
110
+ if (needH) cfg2.heightmap = { ...hm, ...await loadGray(hm.url), url: undefined };
111
+ if (needM) cfg2.shape = { ...cfg2.shape, mask: { ...mk, ...await loadGray(mk.url), url: undefined } };
112
+ const species = {}; for (const sp of e.vegetation?.list() || []) species[sp.name] = sp.rule;
113
+ w.reinit(cfg2, species);
114
+ },
115
+ isReady(e) { return e.stream.sources().every(s => w.isReadyAround(s)); },
116
+ dispose() { w.dispose(); },
117
+ };
118
+ }
@@ -0,0 +1,61 @@
1
+ // look.ground: how the terrain looks (colors, variation, shading, detail layer, material). Registered by the terrain module.
2
+ // set({ colors, biomeColors, steep, variation, shading, detail })
3
+ // colors / biomeColors / steep / variation / shading are baked into the chunks by the workers: a change rebuilds every chunk (cost 'rebuild';
4
+ // edits stay). colors / biomeColors / steep are given whole (they replace the style's table), variation / detail are objects (style.terrain.*).
5
+ // patch('detail', glsl) the detail layer's `vec4 threedogDetailSample(vec2 p)` (render/detail.js); a detail object must be set too
6
+ // replace(Material | (engine) => Material) the ground material (terrain({ material }) / style.terrain.material is the first one); null gives it back
7
+ // Why not in ChunkManager.js: that file is at its size cap, and every ground option below already reached it as config before; this only
8
+ // writes the same config again when a verb changes it.
9
+ import { defineLookPart, REPLACE } from '../../core/look/part.js';
10
+ import { terrainMaterial } from '../../render/materials.js';
11
+
12
+ const GEN = ['colors', 'biomeColors', 'steep', 'variation', 'shading'];
13
+ const isObj = v => (v && typeof v === 'object' ? null : 'must be an object');
14
+
15
+ /**
16
+ * @param {any} e @param {any} w the ChunkManager
17
+ * @param {{ cfg: () => any, setCfg: (c: any) => void, game: Record<string, any> }} h the module's current terrain config, and what terrain({...}) itself passed (written as owner 'terrain()')
18
+ */
19
+ export function defineGroundLook(e, w, h) {
20
+ const st = e.style.terrain ?? {}, cfg0 = h.cfg();
21
+ const rebuild = 'rebuild';
22
+ const part = defineLookPart(e, {
23
+ id: 'ground', group: 'surface', module: 'terrain', object: () => w.terrainMat, applyAtStart: false, docs: ['recipes/52-look.md'],
24
+ params: {
25
+ colors: { type: 'any', default: {}, neutral: true, cost: rebuild, check: isObj, desc: 'palette name -> color; the whole table (a ground type without a color is neutral gray)' },
26
+ biomeColors: { type: 'any', default: {}, neutral: true, cost: rebuild, check: isObj, desc: 'ground type -> palette name(s); the whole table' },
27
+ steep: { type: 'array', default: [], neutral: true, cost: rebuild, desc: 'slope colors [{ maxNormalY, colors }]' },
28
+ variation: { type: 'any', default: null, neutral: true, cost: rebuild, check: isObj, desc: '{ blend, jitter, patches } color variation (style.terrain.variation); null = none' },
29
+ shading: { type: 'string', values: ['smooth', 'flat', 'texture'], default: 'smooth', cost: rebuild,
30
+ why: 'terrain colors are blended per grid point (smooth) so the ground has no visible facets', off: "look.ground.set({ shading: 'flat' }) for one color per triangle, or 'texture' for a per-chunk color map" },
31
+ detail: { type: 'any', default: null, neutral: true, cost: 'recompile', check: isObj, desc: '{ texture | noise | glsl, scale, strength ... } detail layer over the ground (style.terrain.detail); null = none' },
32
+ },
33
+ style: () => ({ colors: st.colors, biomeColors: st.biomeColors, steep: st.steep, variation: st.variation, shading: st.config?.shading, detail: st.detail, [REPLACE]: st.material }),
34
+ read: () => ({}),
35
+ hooks: { detail: { signature: 'vec4 threedogDetailSample(vec2 p) // rgb + height 0-1', scope: ['fragment'], example: "engine.look.ground.patch('detail', glsl)" } },
36
+ replace: { accepts: 'a Material, or (engine) => Material; null gives the style\'s back', loses: ['the style\'s terrain material (cloud shadows and season tint are added to the new one)'] },
37
+ applyReplace: () => material(), applyHook: () => material(),
38
+ apply(v, changed) {
39
+ if (changed.has('detail')) material();
40
+ if (!GEN.some(k => changed.has(k))) return;
41
+ const next = { ...h.cfg() };
42
+ for (const k of GEN) if (changed.has(k)) { if (v[k] == null) delete next[k]; else next[k] = v[k]; }
43
+ if (!next.shading) next.shading = cfg0.shading;
44
+ h.setCfg(next);
45
+ const species = {}; for (const sp of e.vegetation?.list() || []) species[sp.name] = sp.rule;
46
+ w.reinit(next, species);
47
+ },
48
+ });
49
+ // what terrain({ colors, shading, material ... }) itself was given sits on the game layer under the owner 'terrain()', so describe shows it
50
+ const given = {};
51
+ for (const k of GEN) if (h.game[k] !== undefined) given[k] = h.game[k];
52
+ if (h.game.material !== undefined) given[REPLACE] = h.game.material;
53
+ if (Object.keys(given).length) part.write('terrain()', given);
54
+ /** Rebuild the ground material from the resolved replace / detail, then every chunk picks it up */
55
+ function material() {
56
+ const impl = part.value(REPLACE) ?? null;
57
+ w.terrainMat = terrainMaterial(typeof impl === 'function' ? impl(e) : impl, e);
58
+ w.rebuild();
59
+ }
60
+ return part;
61
+ }
@@ -0,0 +1,32 @@
1
+ // Upload a generated terrain chunk (helper of ChunkManager.js): geometry from the worker's arrays, one mesh in a group at the chunk origin, added to the scene.
2
+ // `m` is the ChunkManager; c is the chunk record it keeps.
3
+ import * as THREE from 'three';
4
+ import { mountColorMap } from './terrainTexture.js';
5
+
6
+ export function mountTerrain(m, c, t) {
7
+ const t0 = performance.now(); // measure: the 'build' stage of engine.budget.cost
8
+ const g = new THREE.BufferGeometry();
9
+ g.setAttribute('position', new THREE.BufferAttribute(t.pos, 3));
10
+ g.setAttribute('normal', new THREE.BufferAttribute(t.nor, 3));
11
+ g.setAttribute('color', new THREE.BufferAttribute(t.col, 3));
12
+ g.setAttribute('uv', new THREE.BufferAttribute(t.uv, 2));
13
+ let mat = t.tex ? mountColorMap(m, c, t.tex, c.cx * m.T.CHUNK, c.cz * m.T.CHUNK) : m.terrainMat; // texture shading: a material with this chunk's color map
14
+ if (t.top != null) { // island chunk (terrain({ shape })): vertices are top, side, bottom
15
+ const rest = t.pos.length / 3 - t.top;
16
+ // the color map is sampled by world xz, so it would smear down the sides: sides and bottom keep vertex colors (or the game's material)
17
+ if (rest && (t.tex || m.sideMat)) { g.addGroup(0, t.top, 0); g.addGroup(t.top, rest, 1); mat = [mat, m.sideMat ?? m.terrainMat]; }
18
+ c.solidCount = t.solid; // collision takes top and sides, not the bottom
19
+ m.lowest = Math.min(m.lowest, t.minH);
20
+ }
21
+ const mesh = new THREE.Mesh(g, mat);
22
+ mesh.receiveShadow = true; mesh.frustumCulled = false; mesh.matrixAutoUpdate = false;
23
+ c.group = new THREE.Group();
24
+ c.group.userData.budgetTag = 'terrain';
25
+ c.group.position.set(c.cx * m.T.CHUNK, 0, c.cz * m.T.CHUNK);
26
+ c.group.add(mesh); c.terrain = mesh;
27
+ c.group.updateMatrixWorld(true);
28
+ c.sphere = new THREE.Sphere(new THREE.Vector3(t.sphere[0], t.sphere[1], t.sphere[2]), t.sphere[3]);
29
+ c.state = 'ready';
30
+ m.engine.scene.add(c.group);
31
+ m.engine.budget.cost.end('build', t0);
32
+ }
@@ -0,0 +1,41 @@
1
+ // Terrain color map (shading: 'texture'): one RGBA8 image per chunk, colored pixel by pixel with the same rules as the vertex colors
2
+ // (faceColor: ground type, steep slopes, noise blend, jitter, patches; painted cells), so a color border (a river bank) is no longer
3
+ // confined to triangle edges. Pure computation, no three.js: runs in the Worker next to buildChunk.
4
+ //
5
+ // Layout: (R + 2)^2 pixels, R = colorResolution. Pixel k (0..R+1) sits at world x = chunkOrigin + (k - 1 + 0.5) * CHUNK / R, so the
6
+ // image has a 1-pixel border around the chunk. A border pixel is computed from world coordinates, which means the neighbor chunk
7
+ // computes the identical value at the same place: linear filtering at the chunk edge then reads the same numbers on both sides (no seam).
8
+ // Values are stored sRGB-encoded (the texture is uploaded with colorSpace sRGB), which keeps dark greens from banding in 8 bits.
9
+
10
+ const toSRGB = c => (c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055);
11
+
12
+ /** @returns {(cx: number, cz: number) => { data: Uint8Array, size: number }} */
13
+ // inside(x, z) (terrain({ shape }) only): a void pixel keeps the color of the ground under it (so filtering at the rim stays seamless)
14
+ // and gets alpha 0, which a game's own shader may read
15
+ export function makeColorMap({ cfg, CHUNK, CELL, surface, faceColor, paintColor, cellType, gridNormal, inside = null }) {
16
+ const R = Math.max(2, Math.round(cfg.colorResolution)), S = R + 2, step = CHUNK / R;
17
+ // sRGB encode through a table: 4096 steps are finer than 8 bits can show
18
+ const LUT = new Uint8Array(4097);
19
+ for (let i = 0; i <= 4096; i++) LUT[i] = Math.round(255 * toSRGB(i / 4096));
20
+ const enc = v => LUT[v <= 0 ? 0 : v >= 1 ? 4096 : (v * 4096 + 0.5) | 0];
21
+ return function colorMap(cx, cz) {
22
+ const data = new Uint8Array(S * S * 4), tmp = [0, 0, 0], ox = cx * CHUNK, oz = cz * CHUNK;
23
+ const ny = new Map(); // grid-point normal.y, shared by the pixels of a cell
24
+ const gny = (i, j) => { const k = i * 100003 + j; let v = ny.get(k); if (v === undefined) ny.set(k, v = gridNormal(i, j)[1]); return v; };
25
+ let o = 0;
26
+ for (let pj = 0; pj < S; pj++) {
27
+ const z = oz + (pj - 0.5) * step, j = Math.floor(z / CELL), fz = z / CELL - j;
28
+ for (let pi = 0; pi < S; pi++, o += 4) {
29
+ const x = ox + (pi - 0.5) * step, i = Math.floor(x / CELL), fx = x / CELL - i, pt = cellType(i, j);
30
+ if (pt !== undefined) paintColor(pt, (i + 0.5) * CELL, (j + 0.5) * CELL, tmp); // a painted cell is one color, like its vertices
31
+ else {
32
+ // steep-slope tests use the normal interpolated between the 4 grid points, so they do not follow triangle edges either
33
+ const n = (gny(i, j) * (1 - fx) + gny(i + 1, j) * fx) * (1 - fz) + (gny(i, j + 1) * (1 - fx) + gny(i + 1, j + 1) * fx) * fz;
34
+ faceColor(surface(x, z), n, x, z, tmp);
35
+ }
36
+ data[o] = enc(tmp[0]); data[o + 1] = enc(tmp[1]); data[o + 2] = enc(tmp[2]); data[o + 3] = inside && !inside(x, z) ? 0 : 255;
37
+ }
38
+ }
39
+ return { data, size: S };
40
+ };
41
+ }