threedog 0.7.0 → 1.0.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 (593) hide show
  1. package/CHANGELOG.md +411 -1
  2. package/README.md +8 -11
  3. package/core/{Animator.js → assets/Animator.js} +30 -18
  4. package/core/{Assets.js → assets/Assets.js} +131 -56
  5. package/core/{Baked.js → assets/Baked.js} +4 -4
  6. package/core/assets/assetEntry.js +302 -0
  7. package/core/{assetHot.js → assets/assetHot.js} +9 -7
  8. package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
  9. package/core/assets/assetLod.js +113 -0
  10. package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
  11. package/core/{assetReport.js → assets/assetReport.js} +7 -14
  12. package/core/{namedModel.js → assets/namedModel.js} +17 -13
  13. package/core/{Audio.js → audio/Audio.js} +47 -25
  14. package/core/{audioRules.js → audio/audioRules.js} +8 -5
  15. package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
  16. package/core/{Events.js → base/Events.js} +3 -3
  17. package/core/{I18n.js → base/I18n.js} +15 -12
  18. package/core/{Random.js → base/Random.js} +7 -4
  19. package/core/{Vars.js → base/Vars.js} +14 -4
  20. package/core/{easing.js → base/easing.js} +1 -1
  21. package/core/{errorCodes.js → base/errorCodes.js} +151 -125
  22. package/core/{errorHints.js → base/errorHints.js} +17 -10
  23. package/core/{errors.js → base/errors.js} +12 -10
  24. package/core/{events.generated.js → base/events.generated.js} +11 -0
  25. package/core/base/follows.js +26 -0
  26. package/core/base/math.js +66 -0
  27. package/core/{params.js → base/params.js} +5 -6
  28. package/core/base/saveValues.js +81 -0
  29. package/core/base/sections.js +97 -0
  30. package/core/base/spelling.js +32 -0
  31. package/core/base/util.js +32 -0
  32. package/core/{validate.js → base/validate.js} +34 -34
  33. package/core/{Engine.js → engine/Engine.js} +137 -91
  34. package/core/{Loading.js → engine/Loading.js} +34 -5
  35. package/core/{copies.js → engine/copies.js} +4 -4
  36. package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
  37. package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
  38. package/core/{loop.js → engine/loop.js} +88 -49
  39. package/core/engine/moduleSlots.js +176 -0
  40. package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
  41. package/core/engine/modules.js +503 -0
  42. package/core/{page.js → engine/page.js} +59 -29
  43. package/core/{plugins.js → engine/plugins.js} +21 -12
  44. package/core/{services.js → engine/services.js} +50 -40
  45. package/core/{startup.js → engine/startup.js} +66 -54
  46. package/core/{Input.js → input/Input.js} +67 -39
  47. package/core/{inputContext.js → input/inputContext.js} +14 -5
  48. package/core/input/inputKeyboard.js +39 -0
  49. package/core/{inputPad.js → input/inputPad.js} +24 -3
  50. package/core/{inputPointer.js → input/inputPointer.js} +11 -3
  51. package/core/input/inputSeat.js +66 -0
  52. package/core/{inputTouch.js → input/inputTouch.js} +24 -7
  53. package/core/{Budget.js → inspect/Budget.js} +21 -20
  54. package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
  55. package/core/{Describe.js → inspect/Describe.js} +34 -26
  56. package/core/{Inspect.js → inspect/Inspect.js} +39 -10
  57. package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
  58. package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
  59. package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
  60. package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
  61. package/core/{UrlState.js → inspect/UrlState.js} +60 -24
  62. package/core/{catalog.js → inspect/catalog.js} +15 -8
  63. package/core/{checks.js → inspect/checks.js} +7 -5
  64. package/core/{debugView.js → inspect/debugView.js} +4 -4
  65. package/core/{describeRender.js → inspect/describeRender.js} +24 -22
  66. package/core/{describeText.js → inspect/describeText.js} +17 -8
  67. package/core/inspect/geometryWatch.js +38 -0
  68. package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
  69. package/core/inspect/metadata.generated.js +4140 -0
  70. package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
  71. package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
  72. package/core/inspect/toolDoor.js +21 -0
  73. package/core/inspect/valueHistory.js +35 -0
  74. package/core/{Ops.js → ops/Ops.js} +44 -14
  75. package/core/{control.js → ops/control.js} +57 -31
  76. package/core/ops/holds.js +140 -0
  77. package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
  78. package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
  79. package/core/{opsFail.js → ops/opsFail.js} +5 -7
  80. package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
  81. package/core/{opsRun.js → ops/opsRun.js} +9 -6
  82. package/core/{owned.js → ops/owned.js} +33 -19
  83. package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
  84. package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
  85. package/core/{stacks.js → ops/stacks.js} +34 -15
  86. package/core/{wrap.js → ops/wrap.js} +8 -6
  87. package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
  88. package/core/{Saves.js → saves/Saves.js} +171 -54
  89. package/core/saves/saveApply.js +312 -0
  90. package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
  91. package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
  92. package/core/saves/session.js +231 -0
  93. package/core/saves/stateReplace.js +184 -0
  94. package/core/{Rays.js → scene/Rays.js} +44 -30
  95. package/core/{Views.js → scene/Views.js} +16 -8
  96. package/core/{adaptive.js → scene/adaptive.js} +19 -9
  97. package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
  98. package/core/scene/compositeGround.js +72 -0
  99. package/core/scene/floor.js +17 -0
  100. package/core/{gameLights.js → scene/gameLights.js} +17 -7
  101. package/core/{grayMap.js → scene/grayMap.js} +8 -2
  102. package/core/{grid.js → scene/grid.js} +6 -4
  103. package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
  104. package/core/scene/ground.contract.js +14 -0
  105. package/core/scene/ground.js +139 -0
  106. package/core/{movement.js → scene/movement.js} +3 -3
  107. package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
  108. package/core/scene/pixel.js +154 -0
  109. package/core/scene/pixelRatio.js +167 -0
  110. package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
  111. package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
  112. package/core/scene/stepPoses.js +60 -0
  113. package/core/{targeting.js → scene/targeting.js} +4 -5
  114. package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
  115. package/core/{thingOps.js → scene/thingOps.js} +25 -16
  116. package/core/{things.js → scene/things.js} +18 -5
  117. package/core/{threePatches.js → scene/threePatches.js} +1 -1
  118. package/core/{tier.js → scene/tier.js} +10 -0
  119. package/core/scene/view.js +161 -0
  120. package/core/{Batching.js → stream/Batching.js} +85 -28
  121. package/core/{Stream.js → stream/Stream.js} +80 -38
  122. package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
  123. package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
  124. package/core/{scatter.js → stream/scatter.js} +7 -4
  125. package/core/{streamSources.js → stream/streamSources.js} +14 -8
  126. package/core/{Commits.js → threads/Commits.js} +17 -11
  127. package/core/{Jobs.js → threads/Jobs.js} +25 -13
  128. package/core/{Threads.js → threads/Threads.js} +21 -18
  129. package/core/{threadPure.js → threads/threadPure.js} +7 -5
  130. package/core/{threadServe.js → threads/threadServe.js} +3 -3
  131. package/core/{Clock.js → time/Clock.js} +20 -11
  132. package/core/{dayTime.js → time/dayTime.js} +5 -1
  133. package/core/{skip.js → time/skip.js} +28 -21
  134. package/core/{time.js → time/time.js} +32 -20
  135. package/core/{uiClock.js → time/uiClock.js} +4 -4
  136. package/docs/AI.md +92 -72
  137. package/docs/API.md +33 -28
  138. package/docs/CODEMAP.md +121 -200
  139. package/docs/COMMANDS.md +77 -70
  140. package/docs/CONVENTIONS.md +167 -24
  141. package/docs/MIGRATING-0.8.md +171 -0
  142. package/docs/MIGRATING-1.0.md +101 -0
  143. package/docs/THREE.md +140 -38
  144. package/docs/api/assets.md +12 -13
  145. package/docs/api/audio.md +6 -5
  146. package/docs/api/budget.md +4 -4
  147. package/docs/api/calendar.md +10 -11
  148. package/docs/api/cameraRig.md +32 -29
  149. package/docs/api/characters.md +35 -24
  150. package/docs/api/clock.md +1 -1
  151. package/docs/api/collider3d.md +9 -0
  152. package/docs/api/collision.md +12 -9
  153. package/docs/api/content.md +18 -17
  154. package/docs/api/dialogue.md +5 -4
  155. package/docs/api/engine.md +58 -54
  156. package/docs/api/events.md +17 -6
  157. package/docs/api/flow.md +1 -1
  158. package/docs/api/grids.md +1 -1
  159. package/docs/api/ground.md +6 -7
  160. package/docs/api/hud.md +2 -2
  161. package/docs/api/i18n.md +6 -6
  162. package/docs/api/input.md +9 -8
  163. package/docs/api/interactions.md +5 -5
  164. package/docs/api/inventory.md +10 -10
  165. package/docs/api/jobs.md +5 -5
  166. package/docs/api/level.md +10 -9
  167. package/docs/api/lightPool.md +1 -6
  168. package/docs/api/music.md +3 -3
  169. package/docs/api/nav.md +14 -12
  170. package/docs/api/openWorld.md +1 -1
  171. package/docs/api/particles.md +10 -7
  172. package/docs/api/photo.md +4 -2
  173. package/docs/api/pickups.md +3 -3
  174. package/docs/api/post.md +21 -5
  175. package/docs/api/quests.md +7 -5
  176. package/docs/api/rays.md +7 -7
  177. package/docs/api/rigid.md +29 -19
  178. package/docs/api/saves.md +13 -11
  179. package/docs/api/settings.md +9 -8
  180. package/docs/api/sky.md +8 -7
  181. package/docs/api/stream.md +8 -9
  182. package/docs/api/swarm.md +34 -0
  183. package/docs/api/terrain.md +6 -8
  184. package/docs/api/terrainDraw.md +2 -2
  185. package/docs/api/timeline.md +4 -4
  186. package/docs/api/tools.md +27 -22
  187. package/docs/api/triggers.md +2 -0
  188. package/docs/api/vars.md +1 -1
  189. package/docs/api/vegetation.md +4 -3
  190. package/docs/api/vegetationDraw.md +2 -2
  191. package/docs/api/water.md +7 -3
  192. package/docs/api/weather.md +27 -12
  193. package/docs/api/weatherDraw.md +4 -4
  194. package/docs/api/world.md +6 -6
  195. package/docs/recipes/01-new-game.md +28 -43
  196. package/docs/recipes/02-npc.md +21 -23
  197. package/docs/recipes/03-items-pickups.md +37 -53
  198. package/docs/recipes/04-quests.md +5 -4
  199. package/docs/recipes/05-props-bake.md +34 -44
  200. package/docs/recipes/06-clock-events.md +31 -22
  201. package/docs/recipes/07-flow-scenes-pause.md +30 -32
  202. package/docs/recipes/08-weather-sky.md +91 -37
  203. package/docs/recipes/09-materials-lights-models.md +25 -39
  204. package/docs/recipes/10-blender-level.md +22 -11
  205. package/docs/recipes/11-vehicles.md +44 -24
  206. package/docs/recipes/12-navmesh.md +60 -15
  207. package/docs/recipes/13-animation.md +70 -22
  208. package/docs/recipes/14-custom-module.md +33 -20
  209. package/docs/recipes/15-perf.md +51 -28
  210. package/docs/recipes/16-dev-bridge.md +39 -58
  211. package/docs/recipes/18-world.md +49 -28
  212. package/docs/recipes/19-shooting-picking.md +7 -4
  213. package/docs/recipes/20-content-actions-save.md +55 -40
  214. package/docs/recipes/21-camera.md +47 -25
  215. package/docs/recipes/22-shop-gold.md +21 -16
  216. package/docs/recipes/23-ops.md +28 -24
  217. package/docs/recipes/26-ui-parts.md +25 -14
  218. package/docs/recipes/27-net.md +3 -5
  219. package/docs/recipes/28-terrain.md +119 -23
  220. package/docs/recipes/29-grid.md +3 -3
  221. package/docs/recipes/30-templates.md +63 -30
  222. package/docs/recipes/31-audio.md +7 -7
  223. package/docs/recipes/32-action-game.md +21 -11
  224. package/docs/recipes/33-stream-sources.md +6 -3
  225. package/docs/recipes/34-environment-lighting.md +72 -25
  226. package/docs/recipes/35-picture-from-reference.md +20 -23
  227. package/docs/recipes/36-ground-plants.md +106 -0
  228. package/docs/recipes/40-scene.md +18 -21
  229. package/docs/recipes/43-shader-patches-surfaces.md +27 -48
  230. package/docs/recipes/44-water-weather-hooks.md +56 -50
  231. package/docs/recipes/45-cascaded-shadows.md +41 -20
  232. package/docs/recipes/46-blender-art-route.md +9 -10
  233. package/docs/recipes/49-game-module-contract.md +7 -6
  234. package/docs/recipes/50-own-renderer.md +3 -2
  235. package/docs/recipes/51-capability-catalog.md +14 -8
  236. package/docs/recipes/52-around-the-picture.md +56 -100
  237. package/docs/recipes/53-ground-up-close.md +61 -24
  238. package/docs/recipes/55-mods-time-wrap.md +17 -20
  239. package/docs/recipes/56-webgpu-tsl.md +28 -15
  240. package/docs/recipes/57-control.md +39 -12
  241. package/docs/recipes/58-input.md +15 -2
  242. package/docs/recipes/59-depth-post-effects.md +1 -1
  243. package/docs/recipes/60-judge-the-picture.md +30 -25
  244. package/docs/recipes/62-picture-code.md +129 -39
  245. package/docs/recipes/63-third-person-start.md +19 -5
  246. package/docs/recipes/64-particles.md +54 -5
  247. package/docs/recipes/65-swarm.md +140 -0
  248. package/docs/recipes/66-common-tasks.md +313 -0
  249. package/examples/action/.threedog/content-index.json +1 -1
  250. package/examples/action/GAMEMAP.md +5 -5
  251. package/examples/perf-island/.threedog/content-index.json +1 -0
  252. package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
  253. package/examples/{sheepisland → perf-island}/assets.js +1 -1
  254. package/examples/{sheepisland → perf-island}/main.js +8 -8
  255. package/examples/{sheepisland → perf-island}/models.js +1 -1
  256. package/examples/{sheepisland → perf-island}/params.js +1 -1
  257. package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
  258. package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
  259. package/examples/{sheepisland → perf-island}/views.js +1 -1
  260. package/examples/plain-picture/GAMEMAP.md +4 -1
  261. package/examples/rc2d/GAMEMAP.md +4 -3
  262. package/examples/rc2d/main.js +1 -3
  263. package/examples/rc2d/rc2d.js +1 -1
  264. package/examples/styletest/.threedog/content-index.json +1 -1
  265. package/examples/styletest/GAMEMAP.md +6 -5
  266. package/examples/techniques/contact-shadows/contactShadows.js +1 -1
  267. package/examples/techniques/contact-shadows/main.js +1 -1
  268. package/examples/techniques/interior-light/main.js +1 -1
  269. package/examples/techniques/modular-building/README.md +7 -6
  270. package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
  271. package/examples/techniques/procedural-animation/README.md +1 -1
  272. package/examples/webgpu-tsl/GAMEMAP.md +2 -1
  273. package/examples/world/.threedog/content-index.json +1 -1
  274. package/examples/world/GAMEMAP.md +9 -7
  275. package/examples/world/main.js +3 -3
  276. package/examples/world/picture/sky.js +1 -1
  277. package/index.d.ts +16 -12
  278. package/index.js +53 -32
  279. package/llms.txt +11 -14
  280. package/modules/ambience/Ambience.js +16 -11
  281. package/modules/calendar/Calendar.js +19 -19
  282. package/modules/calendar/index.js +18 -16
  283. package/modules/calendar/schedule.js +11 -6
  284. package/modules/calendar/seasons.js +7 -7
  285. package/modules/camera/FirstPersonCamera.js +5 -5
  286. package/modules/camera/FixedCamera.js +43 -30
  287. package/modules/camera/FollowCamera.js +24 -15
  288. package/modules/camera/RtsCamera.js +12 -11
  289. package/modules/camera/common.js +72 -37
  290. package/modules/camera/contract.js +1 -0
  291. package/modules/camera/pixelSnap.js +62 -0
  292. package/modules/characters/Character.js +166 -70
  293. package/modules/characters/NPC.js +84 -44
  294. package/modules/characters/assetModel.js +16 -12
  295. package/modules/characters/astar.js +48 -27
  296. package/modules/characters/behaviors.js +4 -5
  297. package/modules/characters/character.contract.js +21 -0
  298. package/modules/characters/contract.js +17 -3
  299. package/modules/characters/index.js +240 -226
  300. package/modules/characters/moveHelpers.js +88 -12
  301. package/modules/characters/mover.contract.js +14 -0
  302. package/modules/characters/movers/common.js +22 -18
  303. package/modules/characters/movers/manual.js +1 -1
  304. package/modules/characters/movers/rapier.js +18 -10
  305. package/modules/characters/movers/simple.js +26 -13
  306. package/modules/characters/movers/support.js +24 -13
  307. package/modules/characters/npcAvoid.js +19 -16
  308. package/modules/characters/npcSim.js +88 -32
  309. package/modules/characters/npcView.js +19 -11
  310. package/modules/characters/pathAsync.js +81 -29
  311. package/modules/characters/pathJob.js +38 -21
  312. package/modules/characters/pathWorker.js +1 -1
  313. package/modules/characters/player.js +120 -0
  314. package/modules/characters/playerStrings.js +2 -2
  315. package/modules/characters/proceduralRig.js +2 -2
  316. package/modules/characters/seat.js +56 -0
  317. package/modules/characters/useModel.js +3 -3
  318. package/modules/characters/vehicle.contract.js +8 -5
  319. package/modules/characters/walkTo.js +40 -33
  320. package/modules/collision/Collision.js +69 -45
  321. package/modules/collision/contract.js +15 -0
  322. package/modules/collision/grid.js +6 -1
  323. package/modules/content/explain.js +2 -3
  324. package/modules/content/fields.js +24 -3
  325. package/modules/content/ids.js +5 -3
  326. package/modules/content/index.js +132 -114
  327. package/modules/content/loader.js +117 -140
  328. package/modules/content/markers.js +25 -0
  329. package/modules/content/models.js +54 -17
  330. package/modules/content/packs.js +5 -4
  331. package/modules/content/parts.js +2 -2
  332. package/modules/content/places.js +36 -0
  333. package/modules/content/props.js +22 -17
  334. package/modules/content/rules.js +47 -61
  335. package/modules/content/stages.js +7 -7
  336. package/modules/content/templates.js +80 -49
  337. package/modules/content/words.js +47 -0
  338. package/modules/debug/DebugPanel.js +14 -45
  339. package/modules/flow/contract.js +2 -1
  340. package/modules/flow/index.js +30 -16
  341. package/modules/gameplay/Container.js +17 -13
  342. package/modules/gameplay/Containers.js +23 -6
  343. package/modules/gameplay/Dialogue.js +93 -34
  344. package/modules/gameplay/Interactions.js +93 -51
  345. package/modules/gameplay/Inventory.js +64 -22
  346. package/modules/gameplay/Quests.js +146 -30
  347. package/modules/gameplay/boxOps.js +8 -1
  348. package/modules/gameplay/dialogueBubbles.js +16 -12
  349. package/modules/gameplay/inventoryOps.js +11 -8
  350. package/modules/gameplay/pickups.js +63 -37
  351. package/modules/gameplay/questLog.js +4 -2
  352. package/modules/gameplay/questSave.js +9 -4
  353. package/modules/gameplay/quests.contract.js +1 -1
  354. package/modules/grid/Grid.js +2 -2
  355. package/modules/grid/Layer.js +12 -8
  356. package/modules/grid/index.js +28 -23
  357. package/modules/grid/ops.js +43 -46
  358. package/modules/grid/preview.js +7 -7
  359. package/modules/grid/tiles.js +6 -6
  360. package/modules/hlod/index.js +42 -57
  361. package/modules/hud/index.js +22 -14
  362. package/modules/hud/parts.js +8 -8
  363. package/modules/level/contract.js +16 -0
  364. package/modules/level/heightfield.js +29 -31
  365. package/modules/level/index.js +113 -161
  366. package/modules/level/load.js +196 -0
  367. package/modules/level/meshes.js +65 -0
  368. package/modules/level/nodes.js +40 -23
  369. package/modules/lights/index.js +33 -183
  370. package/modules/lights/slots.js +93 -0
  371. package/modules/lights/sources.js +90 -0
  372. package/modules/music/Music.js +34 -28
  373. package/modules/music/rules.js +1 -1
  374. package/modules/nav/contract.js +16 -0
  375. package/modules/nav/index.js +180 -49
  376. package/modules/nav/navPath.js +45 -10
  377. package/modules/net/Client.js +7 -7
  378. package/modules/net/Host.js +7 -7
  379. package/modules/net/Net.js +1 -1
  380. package/modules/net/index.js +6 -5
  381. package/modules/net/sync.js +2 -2
  382. package/modules/net/transports.js +2 -2
  383. package/modules/particles/Particles.js +95 -29
  384. package/modules/particles/effect.js +86 -32
  385. package/modules/particles/shaders.js +19 -1
  386. package/modules/photo/Photo.js +23 -23
  387. package/modules/rigid/RigidBodies.js +255 -89
  388. package/modules/rigid/Vehicles.js +17 -8
  389. package/modules/rigid/collider3d.contract.js +26 -0
  390. package/modules/rigid/ragdoll.js +298 -0
  391. package/modules/rigid/ragdollBones.js +209 -0
  392. package/modules/rigid/refresh.js +10 -0
  393. package/modules/rigid/sync.js +51 -20
  394. package/modules/settings/Settings.js +177 -61
  395. package/modules/settings/apply.js +20 -13
  396. package/modules/settings/sections.js +19 -14
  397. package/modules/settings/strings.js +2 -2
  398. package/modules/settings/view.js +3 -3
  399. package/modules/sky/Sky.js +29 -22
  400. package/modules/sky/clouds.js +7 -7
  401. package/modules/sky/dome.js +33 -20
  402. package/modules/sky/domeLayers.js +9 -9
  403. package/modules/sky/environment.js +6 -6
  404. package/modules/sky/frame.js +19 -10
  405. package/modules/sky/season.js +7 -1
  406. package/modules/sky/shader.js +24 -25
  407. package/modules/sky/skyModule.js +17 -28
  408. package/modules/sky/tint.js +1 -1
  409. package/modules/swarm/Swarm.js +356 -0
  410. package/modules/swarm/draw.js +68 -0
  411. package/modules/swarm/grid.js +63 -0
  412. package/modules/terrain/ChunkManager.js +71 -59
  413. package/modules/terrain/chunkQueries.js +7 -24
  414. package/modules/terrain/chunkWorker.js +1 -1
  415. package/modules/terrain/draw.js +14 -11
  416. package/modules/terrain/index.js +42 -42
  417. package/modules/terrain/terrainColorMap.js +6 -3
  418. package/modules/terrain/terrainDefaults.js +2 -1
  419. package/modules/terrain/terrainEdit.js +45 -29
  420. package/modules/terrain/terrainGen.js +19 -12
  421. package/modules/terrain/terrainIsland.js +2 -2
  422. package/modules/terrain/terrainMesh.js +7 -6
  423. package/modules/terrain/terrainShape.js +8 -10
  424. package/modules/terrain/terrainShapeMain.js +3 -3
  425. package/modules/timeline/Timeline.js +83 -43
  426. package/modules/timeline/Tween.js +25 -19
  427. package/modules/timeline/shots.js +24 -17
  428. package/modules/triggers/index.js +95 -28
  429. package/modules/vegetation/Vegetation.js +34 -26
  430. package/modules/vegetation/densityMap.js +4 -7
  431. package/modules/vegetation/draw.js +39 -18
  432. package/modules/vegetation/groundChunks.js +21 -38
  433. package/modules/vegetation/index.js +37 -12
  434. package/modules/vegetation/modelGeometry.js +3 -6
  435. package/modules/vegetation/nearFade.js +1 -1
  436. package/modules/water/Water.js +20 -16
  437. package/modules/water/surface.js +3 -3
  438. package/modules/weather/Weather.js +52 -40
  439. package/modules/weather/particles.js +8 -8
  440. package/modules/weather/weatherDraw.js +28 -23
  441. package/modules/world/World.js +28 -15
  442. package/modules/world/explain.js +1 -1
  443. package/modules/world/index.js +30 -17
  444. package/modules/world/persist.js +90 -27
  445. package/modules/world/pos.js +5 -5
  446. package/modules/world/records.js +37 -11
  447. package/modules/world/sim.js +78 -27
  448. package/modules/world/simFar.js +2 -2
  449. package/modules/world/state.js +43 -11
  450. package/modules/world/thingSource.js +20 -5
  451. package/modules/world/views.js +27 -14
  452. package/package.json +48 -7
  453. package/presets.js +1 -3
  454. package/render/PostFX.js +83 -53
  455. package/render/backend.js +31 -33
  456. package/render/cascades.js +17 -12
  457. package/render/cascades.tsl.js +5 -8
  458. package/render/daylight.js +20 -3
  459. package/render/detail.js +8 -7
  460. package/render/effects.js +28 -25
  461. package/render/fuse.js +3 -3
  462. package/render/fx/cloudShadow.tsl.js +3 -3
  463. package/render/fx/detail.tsl.js +1 -1
  464. package/render/fx/index.js +5 -10
  465. package/render/fx/library.tsl.js +11 -0
  466. package/render/fx/lighting.tsl.js +2 -1
  467. package/render/fx/nodeErrors.tsl.js +2 -2
  468. package/render/fx/objectOrigin.tsl.js +1 -2
  469. package/render/fx/particles.tsl.js +8 -6
  470. package/render/fx/patchNodes.tsl.js +5 -15
  471. package/render/fx/postWebGPU.tsl.js +30 -26
  472. package/render/fx/sky.tsl.js +15 -17
  473. package/render/fx/uniforms.tsl.js +4 -4
  474. package/render/fx/wind.tsl.js +1 -1
  475. package/render/fxNumbers.js +3 -0
  476. package/render/layers.js +2 -2
  477. package/render/lighting.js +5 -3
  478. package/render/lightmap.js +41 -21
  479. package/render/lights.js +6 -6
  480. package/render/lit.js +24 -0
  481. package/render/materials.js +8 -7
  482. package/render/mergeCommon.js +22 -0
  483. package/render/modeling.js +2 -2
  484. package/render/occlusion.js +62 -15
  485. package/render/ownFrame.js +4 -4
  486. package/render/patches.js +15 -15
  487. package/render/postWebGL.js +15 -12
  488. package/render/probes.js +41 -19
  489. package/render/recordSweep.js +117 -0
  490. package/render/shaderErrors.js +10 -9
  491. package/render/shadowCache.tsl.js +107 -0
  492. package/render/shadowTypes.js +9 -0
  493. package/{core → render}/shadows.js +59 -13
  494. package/render/slots.js +7 -7
  495. package/render/terms.js +22 -24
  496. package/render/uniformDecl.js +1 -1
  497. package/types/core.d.ts +336 -202
  498. package/types/gameplay.d.ts +254 -130
  499. package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
  500. package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
  501. package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
  502. package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +8 -16
  503. package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
  504. package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
  505. package/types/generated/core/{Input.d.ts → input/Input.d.ts} +28 -10
  506. package/types/generated/core/input/inputSeat.d.ts +26 -0
  507. package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
  508. package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
  509. package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
  510. package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
  511. package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
  512. package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
  513. package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
  514. package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
  515. package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
  516. package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
  517. package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
  518. package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
  519. package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
  520. package/types/generated/modules/calendar/Calendar.d.ts +10 -11
  521. package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
  522. package/types/generated/modules/grid/Grid.d.ts +1 -0
  523. package/types/generated/modules/grid/Layer.d.ts +1 -1
  524. package/types/generated/modules/grid/index.d.ts +3 -3
  525. package/types/generated/modules/music/Music.d.ts +7 -5
  526. package/types/generated/modules/particles/Particles.d.ts +5 -4
  527. package/types/generated/modules/sky/Sky.d.ts +21 -10
  528. package/types/generated/modules/swarm/Swarm.d.ts +80 -0
  529. package/types/generated/modules/timeline/Timeline.d.ts +7 -5
  530. package/types/generated/modules/water/Water.d.ts +1 -0
  531. package/types/generated/modules/weather/Weather.d.ts +14 -16
  532. package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
  533. package/types/generated/modules/world/World.d.ts +11 -7
  534. package/types/generated/render/PostFX.d.ts +21 -23
  535. package/types/generated/render/materials.d.ts +1 -0
  536. package/types/generated/render/occlusion.d.ts +9 -0
  537. package/types/generated/render/patches.d.ts +1 -0
  538. package/types/generated/ui/Focus.d.ts +1 -0
  539. package/types/generated/ui/UI.d.ts +1 -0
  540. package/types/nav.d.ts +47 -15
  541. package/types/physics.d.ts +150 -73
  542. package/types/pixel.d.ts +75 -0
  543. package/types/tsl.d.ts +37 -4
  544. package/types/world.d.ts +48 -75
  545. package/ui/Focus.js +10 -9
  546. package/ui/Parts.js +13 -5
  547. package/ui/UI.js +7 -7
  548. package/ui/defaults.js +3 -2
  549. package/ui/theme.js +7 -5
  550. package/core/assetEntry.js +0 -109
  551. package/core/engineCamera.js +0 -32
  552. package/core/ground.js +0 -104
  553. package/core/holds.js +0 -134
  554. package/core/math.js +0 -48
  555. package/core/moduleSlots.js +0 -100
  556. package/core/modules.js +0 -314
  557. package/core/saveApply.js +0 -210
  558. package/core/saveValues.js +0 -46
  559. package/core/session.js +0 -174
  560. package/core/shadowTypes.js +0 -16
  561. package/core/util.js +0 -17
  562. package/core/view.js +0 -43
  563. package/docs/MIGRATING-0.3.md +0 -248
  564. package/docs/MIGRATING-0.4.md +0 -320
  565. package/docs/MIGRATING-0.5.md +0 -68
  566. package/docs/MIGRATING-0.6.md +0 -126
  567. package/docs/PERF.md +0 -245
  568. package/docs/recipes/36-sky-ground-plants.md +0 -158
  569. package/docs/recipes/37-terrain-hooks.md +0 -115
  570. package/docs/recipes/38-environment-hooks.md +0 -67
  571. package/docs/recipes/42-terrain-shape.md +0 -64
  572. package/docs/recipes/47-island-snow-backdrop.md +0 -43
  573. package/docs/recipes/54-three-idioms.md +0 -88
  574. package/examples/plain-picture/FINDINGS.md +0 -53
  575. package/examples/sheepisland/.threedog/content-index.json +0 -1
  576. package/modules/camera/projection.js +0 -21
  577. /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
  578. /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
  579. /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
  580. /package/core/{actor.js → ops/actor.js} +0 -0
  581. /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
  582. /package/core/{saveIds.js → saves/saveIds.js} +0 -0
  583. /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
  584. /package/core/{cells.js → stream/cells.js} +0 -0
  585. /package/core/{streamCells.js → stream/streamCells.js} +0 -0
  586. /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
  587. /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
  588. /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
  589. /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
  590. /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
  591. /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
  592. /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
  593. /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
package/docs/PERF.md DELETED
@@ -1,245 +0,0 @@
1
- # Performance comparison (PERF)
2
-
3
- > Sections 1-5 come from a cloud environment without a GPU (Chromium + SwiftShader software rendering, 1280x720, pixel ratio 1; section 6 is a real GPU). Use them only for
4
- **relative comparison**; they do not represent real-device frame rates.
5
- > Reproduce: `node packages/tools/perf.mjs [frames]` (default 60 frames; it builds first, then opens
6
- > `packages/engine/tests/perf/index.html` in a headless browser; both are in the engine repository, not the npm package).
7
- > Startup time is also printed in the "startup time" item of `npm test` (reported only, no threshold).
8
- > **Latest run (2026-10-30, wrap-up)**: cloud container with a 2-core CPU and 7 GB memory, no GPU; `npm run perf` (60 frames) run alone (not at the
9
- same time as `npm test`).
10
- > This machine is about 1.5-2x slower overall than the one behind the old numbers (the same plain three.js scene takes 9.6-12.2 ms, the old one 9.9
11
- ms); compare across runs only through relations within the same run. Old numbers are kept in the "previous run" rows of each table.
12
-
13
- ## 0. Real-device baseline
14
-
15
- Measured 2026-10-31 on the open-world example, before the stage 2 changes, with the in-game F3 panel "20-second stress test" (view distance 256 m, density 1x).
16
-
17
- | Machine | Avg fps | 1% low fps | Longest frame | Chunks generated during the run |
18
- |---|---|---|---|---|
19
- | AMD Ryzen 7 **integrated GPU** (desktop), browser not recorded | 60.0 (vsync cap) | 53.8 | 21.0 ms | 6366 |
20
-
21
- The average is capped by the display refresh rate, so this shows headroom exists, not how much. Not yet measured: the same machine's discrete GPU (RTX
22
- 5060), `npm run perf` on this machine, phones and laptop integrated GPUs.
23
-
24
- ## How it was measured
25
-
26
- - Test page (engine repository) `packages/engine/tests/perf/index.html?mode=...`:
27
- - `native`: plain three.js, 2000 cubes (shared geometry and material) + a ground + 1 directional light with shadows (2048 pixels, covering +-70 m) +
28
- a hemisphere light, `renderer.render` every frame.
29
- - `engine`: the same scene inside `createEngine()` (**no modules installed**), running the same sequence as the real-time loop each frame: fixed
30
- step -> frame hooks (including stream/jobs) -> render -> budget sampling -> afterRender.
31
- - `world`: `openWorld()` plus the gameplay modules (interactions, dialogue, inventory, quests, timeline, triggers,
32
- particles, hud; debug panel, music and ambience off), with the same seed, the same flat ground and the same vegetation as the open-world example,
33
- without NPCs/quests or other content; `engine.profile()` times `fixed/frame/afterRender` for each module.
34
- - `props`: `n` repeated props over 4 models placed through `world.present`, with a directional shadow; `batch=0` turns `engine.batching` off (section 3c).
35
- - `city`: used by the C group of feature tests (HLOD, scenario parameters, settings freeze); not timed.
36
- - Shadows: `renderer.shadowMap.render` is wrapped to count "how many times shadows were really updated" and the draw calls per update.
37
- - Each item runs 3 times and the median is taken; native/engine alternate for two rounds, and every page uses a freshly opened browser (the
38
- software-rendering GPU process carries the backlog of the previous page into the next; the first version of the script did not do this and the same
39
- item varied 2x).
40
-
41
- ## 1. Plain three.js vs engine (no modules), 60 frames
42
-
43
- | | CPU ms/frame | Render ms/frame | Draw calls | Triangles | Shadow draw calls |
44
- |---|---|---|---|---|---|
45
- | Plain three.js (round 1) | 9.55 | 9.55 | 3723 | 44666 | 1848 |
46
- | Engine (round 1) | 9.87 | 9.81 | 3723 | 44666 | 1848 |
47
- | Plain three.js (round 2) | 12.2 | 12.2 | 3723 | 44666 | 1848 |
48
- | Engine (round 2) | 10.95 | 10.89 | 3723 | 44666 | 1848 |
49
- | Previous run: plain three.js (two rounds) | 9.98 / 9.88 | | | | |
50
- | Previous run: engine (two rounds) | 9.67 / 9.89 | | | | |
51
-
52
- Between the two rounds plain three.js itself differs by 2.6 ms (software-rendering noise), and the engine falls between the two plain rounds.
53
- Conclusion: draw calls and triangles are identical; the engine core's per-frame cost beyond rendering is about 0.05 ms (fixed step, frame hooks,
54
- jobs/stream, budget sampling returns immediately when off), within measurement error. The engine adds no extra draws (with bloom/ambient occlusion
55
- off, PostFX renders directly).
56
-
57
- ## 2. openWorld fully on, per-module cost per frame (60 frames, player moving forward at 6 m/s)
58
-
59
- Whole frame 3.99 ms, of which rendering (submitting draw commands) 2.97 ms; 74 draw calls, 67k triangles (previous run: whole frame 1.84 ms, rendering
60
- 1.38 ms, 66 draw calls, 84k triangles).
61
-
62
- | Module | ms/frame (this run) | Previous run |
63
- |---|---|---|
64
- | rigid (Rapier physics) | 0.56 | 0.23 |
65
- | sky | 0.12 | 0.02 |
66
- | cameraRig | 0.09 | 0.03 |
67
- | terrain (chunk streaming, LOD, frustum) | 0.04 | 0.06 |
68
- | weather | 0.02 | < 0.01 |
69
- | characters / interactions / particles | 0.01 each | < 0.01-0.01 |
70
- | triggers, quests, timeline, water, dialogue, settings, hud, inventory | 0 | < 0.01 |
71
-
72
- Conclusion: module logic totals about 0.9 ms/frame (a quarter of the frame), and the biggest part is still Rapier; every item rose together with the
73
- slower whole frame (slower machine), and no single module became slower.
74
- particles: group X once measured 0.21 ms/frame, and this run alone it is 0.01. The world scene has no particle effects (no emit/attach); particles per
75
- frame only computes one point-size ratio and then iterates an empty effect table,
76
- so it cannot cost 0.2 ms; that was noise from competing for CPU with another process (the full test run), not a regression, and no code was changed.
77
- The real cost is in rendering (on real devices mostly the GPU, which cannot be measured here).
78
-
79
- ## 3. Shadow parameter comparison (openWorld, 60 frames, player moving forward at 6 m/s)
80
-
81
- | updateEvery | snap | Shadow updates | Draw calls per shadow | CPU ms/frame | Render ms/frame |
82
- |---|---|---|---|---|---|
83
- | 1 (default) | 0.5 (default) | 60/60 | 27 | 2.17 | 1.74 |
84
- | 3 | 0.5 | 20/60 | 27 | 1.56 | 1.14 |
85
- | 1 | 'texel' | 60/60 | 27 | 2.53 | 1.93 |
86
- | 3 | 'texel' | 21/60 | 27 | 1.00 | 0.75 |
87
-
88
- - `updateEvery: 3` cuts shadow drawing from 60 to 20 times per second (in this scene 27 draw calls each time -> about 1080 fewer draws per second).
89
- The difference in the CPU column is hidden by software-rendering noise (the same configuration can differ by 0.5 ms between two runs), so rely on
90
- "shadow updates x draw calls per update".
91
- - Early update while moving: only when the shadow center is more than 1/4 of the coverage radius away from the last update point (default 17.5 m;
92
- teleporting or fast movement) is the update brought forward. The first version updated "whenever the snapped cell changed", and with 'texel' (cell
93
- only 0.07 m) it updated almost every frame (27/30), which saves nothing; that was changed.
94
- - `snap: 'texel'` does not save performance by itself; it keeps shadow edges from flickering while moving (aligned to shadow pixels).
95
-
96
- ## 3b. HLOD (`npm test -- HLOD`, test block of 7x7 buildings + ground)
97
-
98
- With the focus at the block center: 93 draw calls (including shadows); with the focus moved 400 m away and everything switched to proxies: 16; moving
99
- back restores 93.
100
-
101
- ## 3c. Automatic batching (engine.batching), 2026-10-31
102
-
103
- `npm run perf -- --only=props`: 3000 repeated props over 4 models (a lamp of 2 meshes, a fence, a crate, an AC unit; 3750 meshes), each a world record
104
- presented as a clone of its model, spread over about 143 x 143 m (16 cells of 64 m), one directional light with shadows, 60 frames, headless Chromium
105
- with ANGLE SwiftShader
106
- on the user's Windows machine (plain `--use-gl=swiftshader` does not start WebGL there, which is why section 5 shows 0 draw calls; perf.mjs has since
107
- moved to the hardware GPU when headless reaches one, so later runs of this table are GPU numbers: the first output line names the renderer).
108
-
109
- | | CPU ms/frame | Render ms/frame | Draw calls (incl. shadow) | Shadow draw calls | Batches | Instances |
110
- |---|---|---|---|---|---|---|
111
- | batching off (round 1) | 77.36 | 76.09 | 6742 | 3333 | 0 | 0 |
112
- | batching on (round 1) | 7.91 | 6.26 | 156 | 79 | 56 | 3694 |
113
- | batching off (round 2) | 43.77 | 42.63 | 6742 | 3333 | 0 | 0 |
114
- | batching on (round 2) | 9.14 | 7.10 | 156 | 79 | 56 | 3694 |
115
-
116
- Draw calls fall 43x (6742 -> 156); 56 of the 79 (cell, geometry, material) groups reached the threshold of 8, the other 23 (cell-edge strips) stay plain meshes.
117
- The batching bookkeeping itself costs about 0.46 ms/frame with 3000 batched objects and nothing moving (a transform check per batched object plus a
118
- 256-object round robin that looks for parts changed behind its back). With nothing repeating it only checks a few transforms.
119
-
120
- ## 4. Open to playable (engine.startup)
121
-
122
- > Dated: the tables below predate the 2026-11-02 cold-start change (no scene render before ready, `compileAsync` for the real render target, the
123
- > room environment built only when a material reads it, Rapier / Recast loading from install). After it a test game measured 2.9 s cold start with
124
- > 2.46 s of long tasks before ready (Radeon 780M, headless); the open-world rows have not been remeasured.
125
-
126
- | Example | Open to playable ms | start() to playable ms | Asset preload ms | First-screen chunks (terrain ready) ms | Slowest module |
127
- |---|---|---|---|---|---|
128
- | Open world (`/`), before optimization | 7036 | 6778 | 0 | 4319 | terrain 4319 |
129
- | Open world (`/`), after optimization (median of 5) | 3067 | 2798 | 0 | 377 | rigid 2420 (Rapier download and initialization) |
130
- | Small city (`/tests/city/index.html`), previous run | 2103 | 1866 | 0 | — | rigid 1863 (Rapier download and initialization) |
131
- | Open world, this run (perf.mjs) | 4392 | 4116 | 0 | 1281 | rigid 2834 |
132
- | Open world, this run (npm test "startup time") | 4057 | 3176 | 0 | 940 | rigid 2235 |
133
- | Small city, this run (perf.mjs / npm test) | 2470 / 3094 | 2246 / 1846 | 0 | — | rigid 1511 |
134
-
135
- This run is about 1 second slower than "after optimization", with first-screen chunks 377 -> 940-1281 ms: this machine has only 2 cores, and the
136
- background chunk threads, the Rapier wasm compilation and the main thread compete for them; rigid (Rapier) is still the slowest item.
137
-
138
- With software rendering, shader compilation and chunk upload are very slow and real devices will be much faster; use it to see "who is slowest" and
139
- the change before/after a modification.
140
-
141
- ### Where the open-world startup is slow (per-frame record of chunk count, in-flight tasks, pending upload results)
142
-
143
- Background-thread generation itself is not slow (measured in node: terrain 7 ms/chunk, all vegetation about 8 ms/chunk). The slowness is **a single
144
- very long main-thread frame** (0.5-1.8 seconds per frame during loading under software rendering, longer while Rapier compiles), and the chunk
145
- pipeline advances "per frame" everywhere:
146
-
147
- 1. **Dispatch per frame**: at most 4 tasks at the same time, and a result has to wait for the next frame's update before the next one is dispatched.
148
- With a 1-second main-thread frame, the background thread finishes 4 (tens of milliseconds) and then idles.
149
- 2. **Upload limited per frame**: a 3 ms upload budget per frame; during loading results pile up to 8-14 in the queue and only about 4 are uploaded per frame.
150
- 3. **Ready check one frame late**: start() checks readiness with a timer every 20 ms, but the timer is often scheduled after the next frame, so after
151
- all chunks are in place one more whole frame (about 1 second) is rendered before it notices.
152
- 4. The isReadyAround radius is 1 ring (3x3 = 9 chunks), which is reasonable and was not changed; the stream registry is empty here (0 ms); there is no
153
- duplicate generation (the rebuilds of registerSpecies all happen before start).
154
-
155
- The fixes (effective only while the loading screen is still up; behavior after entering the game is unchanged, view distance and density unchanged):
156
-
157
- - ChunkManager: dispatch the next task as soon as a result returns (`_pump`); when the engine is not ready, do not limit the number of concurrent
158
- tasks (send all to the background threads to queue, nearest first).
159
- - ChunkManager: when the engine is not ready, the ring of chunks around the player (needed for the first screen) is not limited by the 3 ms upload
160
- budget and is uploaded entirely within one frame; the rest still follow the budget.
161
- - Engine.start: besides the timer, the real-time loop also checks readiness at the end of every frame.
162
-
163
- Step-by-step effect (first-screen chunks ms, 2-3 runs each): originally 4254-4591 -> dispatch on result return 4359-4779 (the real bottleneck was the
164
- main thread not receiving replies) -> send everything while loading 2897-3185 -> first-screen chunks without budget 2960-3185 -> check readiness at
165
- the end of each frame 332-1927. The biggest remainder is rigid (Rapier wasm compilation, about 2.4 seconds), which runs in parallel with chunk generation.
166
-
167
- ## 5. Worker pool (engine.threads), 2026-10-31
168
-
169
- Measured on the user's Windows machine (16 logical cores, so `threads: 'auto'` = 4 workers), headless Chromium. **WebGL did not start in this headless run**
170
- (0 draw calls everywhere), so only CPU module timings and startup are comparable; render numbers are meaningless. Not a real-device GPU measurement.
171
-
172
- `npm run perf`, before -> after the change (terrain moved from its own single worker to a 4-worker lane):
173
-
174
- | | Before | After |
175
- |---|---|---|
176
- | openWorld whole frame ms | 0.54 | 0.61 |
177
- | terrain module ms/frame | 0.06 | 0.08 |
178
- | rigid module ms/frame | 0.24 | 0.27 |
179
- | open world: open to playable / start() to playable ms | 821 / 340 | 1211 / 538 |
180
- | town: open to playable / start() to playable ms | 804 / 358 | 947 / 394 |
181
-
182
- The slowest item in both runs is rigid (Rapier), which this change does not touch, and it moved 339 -> 537 ms by itself: the differences are run-to-run noise,
183
- not a regression. Terrain's per-frame cost stays under 0.1 ms.
184
-
185
- World far simulation in workers (`npm test -- "threads:"`, 460 records, far every 0.05 s, 240 steps): main-thread ms per fixed step
186
- threads 0 = 1.34-1.41, threads 2 = 0.95-1.10. The main thread still copies each batch (structuredClone) and diffs the result, so the gain grows with how heavy
187
- `far` is; a trivial far gains little. Records are bit-identical between threads 0 and 2 at every checkpoint;
188
- with threads 2 every batch used the worker result (0 late).
189
-
190
- ## 5b. Pathfinding in workers (`findPathAsync`), 2026-10-31
191
-
192
- Same machine (16 logical cores), headless Chromium, `npm test -- "paths: findPathAsync main"`. Two headless engines get the same 300 requests;
193
- "main-thread ms" is the total time of the fixed steps until every answer landed, minus the same number of steps without requests. Workers were already started
194
- and held the mesh (a game pays that start-up once). Before = the synchronous `findPath` loop that NPCs used until now.
195
-
196
- | 300 paths | Before: sync `findPath` | `findPathAsync`, threads 0 | `findPathAsync`, threads 2 |
197
- |---|---|---|---|
198
- | A* (40 boxes, 140 m area) | 218-266 ms | 254-294 ms | 78-90 ms (2 of 10 batches late) |
199
- | Navmesh (40x40 maze) | 8-17 ms | 11-35 ms | 3 ms (0 late) |
200
-
201
- Paths and landing steps are identical between threads 0 and 2 (also across a collider change and a crashed worker). The A* main-thread time that remains is
202
- sampling the ground raster (water / slope, cached 5 s) and the batches that came back late; with real frame gaps (16 ms instead of the test's 2-4 ms)
203
- fewer are late.
204
- threads 0 costs a little more than the sync loop (batch building plus the raster), so `findPath` stays the call for one-off paths.
205
-
206
- ## 6. Load budget (`threedog stress`), 2026-11-02
207
-
208
- **Machine: `ANGLE (AMD, AMD Radeon 780M Graphics (0x00001900) Direct3D11 vs_5_0 ps_5_0, D3D11)`** (AMD Ryzen 7 integrated GPU, headless Chromium on
209
- the hardware GPU), 1280x720, pixel ratio 1, 30 frames per step, medians. Other headless browsers were running on the machine at the same time: expect
210
- 10-20% noise. The same machine's discrete GPU (RTX 5060) is measured separately by the user (key B on the WebGPU compare page); add its row here.
211
-
212
- Each axis alone on the neutral page `tests/stress/` (gray ground, the engine's default lights, 400 boxes under the light / shadow / post axes). frame =
213
- CPU + waiting for the GPU to finish, no overlap: an upper bound of the real frame. "≈" is log-interpolated between the two steps around the crossing.
214
-
215
- | Axis (unit) | Fits 16.7 ms | Fits 33 ms | CPU / GPU / frame ms at the 16.7 ms load | Stopped by |
216
- |---|---|---|---|---|
217
- | triangles (1M-triangle tiles, few draws) | ≈ 45M | ≈ 100M | 0.6 / 10.1 / 11.9 | 33 ms |
218
- | draw calls (separate meshes, one material) | ≈ 2400 | ≈ 4800 | 8.6 / 4.5 / 13.1 | 33 ms |
219
- | instances (one InstancedMesh of boxes) | ≈ 3.2M | ≈ 7.3M | 0.3 / 15.0 / 16.6 | 33 ms |
220
- | point + spot lights (no shadow) | ≥ 128 | ≥ 128 | 2.3 / 10.3 / 13.6 | shader compile fails at 256 (uniform limit) |
221
- | shadow-casting spot lights (1024²) | ≥ 8 | ≥ 8 | 2.7 / 2.8 / 6.6 | shader compile fails at 16 (texture units) |
222
- | sun shadow map size | ≈ 9700² (8192² fits) | ≈ 13000² | 2.7 / 2.8 / 6.3 at 8192² | 33 ms (16384²: 45 ms GPU) |
223
- | overlapping full-view transparent quads | ≈ 58 | ≈ 113 | 0.4 / 8.2 / 9.3 | 33 ms |
224
- | point particles (4 px, additive) | ≈ 1.7M | ≈ 3.8M | 0.3 / 14.6 / 15.8 | 33 ms |
225
- | post effects, cumulative: bloom, vignette, grain, lut, chromatic, outline, ao, dof | 7 (all but dof) | all 8 (17.1 ms) | 4.1 / 9.7 / 15.0 | ladder end |
226
- | skinned characters (24 bones, 2352 triangles, own mixer) | ≈ 230 | ≈ 440 | 4.9 / 2.7 / 9.2 | 33 ms |
227
-
228
- Reading it: on this iGPU draw calls and skinned characters are CPU-bound (main thread), everything else is GPU-bound; ao (GTAO) is the costliest
229
- single post effect (+5 ms GPU, it redraws the scene for normals). Real scenes combine axes, so take a game's limit well below one axis' crossing.
230
-
231
- ## Limitations
232
-
233
- - SwiftShader does the GPU's work on the CPU, but WebGL commands are submitted asynchronously: "render ms" in the tables is mostly the time three.js
234
- spends traversing the scene + submitting commands, and **does not include** the time to actually draw pixels. Fragment-heavy things (shadow map
235
- resolution, bloom, ambient occlusion, transparent overdraw) show no difference here; measure them with `threedog stress` on the GPU (section 6).
236
- - Noise: the same configuration run repeatedly can differ by 10-30%; draw no conclusion from smaller differences.
237
- - The `world` mode has no NPCs, pickups or other content, so it has fewer draw calls than the open-world example; to see the example itself, open
238
- `npm run dev` and run the stress test with F3.
239
- - The budget monitor (`engine.budget`) is off by default; when on, each frame adds one array write and a check once per second, and only when over the
240
- limit does it traverse the scene to count by `userData.budgetTag`.
241
-
242
- ## Per-module timing
243
-
244
- The core ships `engine.profile(true)` to turn it on and `engine.profile()` to read `{ moduleName: average milliseconds per rendered frame }` and
245
- reset; the test page uses it instead of wrapping hooks itself.
@@ -1,158 +0,0 @@
1
- # Sky, ground and plants
2
-
3
- ```js
4
- engine.use(terrain({ ...terrainPreset(), colors: { grass: 0x6a8a3a, rock: 0x777066 }, biomeColors: { meadow: ['grass'], cliff: ['rock'] } }));
5
- engine.terrain.material.flatShading = true; // the ground's picture is a plain three.js material
6
- engine.terrain.recolor({ colors: { grass: 0xa8a050, rock: 0x777066 } }); // what the workers baked in, changed at run time
7
- engine.terrain.material = applyEffects(new THREE.MeshToonMaterial({ vertexColors: true }), { patches: engine.terrain.patches }); // your own, effects kept
8
- engine.vegetation.material = applyEffects(new THREE.MeshToonMaterial({ vertexColors: true }), { patches: engine.vegetation.patches });
9
- ```
10
-
11
- For an AI that wants the sky, the ground or the plants to look a way the defaults do not. Each section lists the engine default; code that sets nothing
12
- gets it. None of these settings moves a hill, a river or a species list. The order of work from a reference picture is in `35-picture-from-reference.md`.
13
-
14
- ## Sky clouds: `sky({ clouds })` (at run time `engine.uniforms.uCloudCover.value`, `uCloudColor`, `uCloudShade`, `uSkyCloudScale`, `uSkyCloudSpeed`, `uCloudOpacity`, `uCloudSoft`)
15
- | Key | Meaning | Default |
16
- |---|---|---|
17
- | `color`, `shade`, `coverage`, `scale`, `speed` | lit color, shaded color, cover (multiplies the weather's cloud amount), size, drift speed | |
18
- | `kind` | `'plane'` cheap, 3 noise samples. `'cumulus'` billowy, 8 noise samples per cloudy sky pixel, flatter projection (clouds fill the whole sky instead of crowding at the horizon), the sun side of each cloud is lit and the underside shaded | `'plane'` |
19
- | `horizon` | added to `dir.y` before projecting; smaller = clouds shrink and crowd more towards the horizon | plane 0.08, cumulus 0.5 |
20
- | `fade` | `[from, to]` in `dir.y`: invisible below `from`, full above `to` | plane `[0, 0.18]`, cumulus `[0, 0.12]` |
21
- | `opacity`, `softness` | cloud alpha; width of the cloud edge | 0.9 / 0.3 (cumulus 0.95 / 0.35) |
22
- | `noise` | plane only: `{ scales: [2.7, 6.1], weights: [0.6, 0.3, 0.1] }`, the two finer layers' frequency and the mix of the three | as shown |
23
- | `relief` | cumulus only: contrast of the sun-side light | 5 |
24
-
25
- Why a thin band at the horizon with `plane`: the plane projection divides by height, so near the horizon one screen pixel covers a lot of cloud plane
26
- and the noise is dense and small; overhead one pixel covers little and the same coverage looks sparse. For a sky full of big clouds use
27
- `kind: 'cumulus'`, or raise `horizon` (0.3-0.6) and lower `scale`. Cost: both are one 2D pass over the dome (no ray marching); cumulus is about
28
- 2.7x the noise work of plane on the cloudy pixels (pixels below the horizon or with no cloud cover skip it). Cloud shadows on the ground
29
- (the signal `engine.uniforms.uCloudShadow`, a separate setting) follow the same weather cover, so more clouds still means more shadow.
30
-
31
- ```js fragment
32
- sky: { clouds: { kind: 'cumulus', coverage: 1, scale: 0.45, color: 0xfff4e4, shade: 0x8a9cb8, speed: [0.003, 0.001] } }
33
- ```
34
-
35
- ### Your own cloud function
36
- `engine.sky.clouds(glsl | { glsl, tsl, uniforms })` is the one way in (a `glsl` key in `sky({ clouds })` throws and names it). The GLSL must define this function; the dome calls it for every upper-hemisphere pixel with cover above 0.01, then does `mix(sky, rgb, a)`:
37
- ```glsl
38
- vec4 threedogClouds(vec3 dir, float time, vec3 sunDir, float night, vec3 lit, vec3 shade, float cover)
39
- // dir: unit view direction, dir.y > 0. sunDir: towards the sun (the moon is opposite). night: 0 day .. 1 night.
40
- // lit / shade: clouds.color / clouds.shade. cover: weather cloud amount * clouds.coverage.
41
- // return: rgb = final cloud color (dim it at night yourself), a = opacity (apply your own horizon fade).
42
- ```
43
- In scope: the GLSL noise helpers `float threedogHash(vec2 p)` and `float threedogNoise(vec2 p)`, the built-in cloud uniforms (`uCloudScale`, `uCloudSpeed`, `uCloudHorizon`, `uCloudFade`...) and
44
- the patch's `uniforms` (declared for you; number, `THREE.Color`, `THREE.Vector2/3/4`, array of 2-4 numbers, or `THREE.Texture`). Change one later
45
- with `engine.sky.dome.material.uniforms.uEdge.value = 0.1`. A bad `kind`, GLSL without the function, or an unsupported uniform value throws with the fix.
46
- Flat painted cloud blobs with a hard edge, multiplied by a texture:
47
- ```js
48
- // sky({ clouds: { color: 0xfff1dc, shade: 0x9aa8c4 } }) gives lit and shade; the function goes through the hook
49
- engine.sky.clouds({ uniforms: { uPaper: paperTexture, uEdge: 0.06 }, // paperTexture: any THREE.Texture, repeat wrapping
50
- glsl: `vec4 threedogClouds(vec3 d, float time, vec3 sunDir, float night, vec3 lit, vec3 shade, float cover){
51
- vec2 p = d.xz / (d.y + 0.5) * 0.4 + vec2(0.004, 0.002) * time;
52
- float n = threedogNoise(p) * 0.65 + threedogNoise(p * 2.3 + 5.0) * 0.35;
53
- float a = smoothstep(1.0 - cover, 1.0 - cover + uEdge, n); // hard edge
54
- float up = clamp(0.5 + (n - threedogNoise(p + sunDir.xz * 0.1)) * 6.0, 0.0, 1.0); // sun side
55
- vec3 c = mix(shade, lit, up) * texture2D(uPaper, p * 3.0).rgb * (0.35 + 0.65 * (1.0 - night));
56
- return vec4(c, a * smoothstep(0.0, 0.1, d.y));
57
- }` });
58
- ```
59
-
60
- ## Ground color: `terrain({ colors, biomeColors, steep, variation })`
61
- Terrain colors are baked by the (worker) generator: two colors blended by a noise, a small brightness grain, and an optional layer of large patches.
62
- `colors` names the colors, `biomeColors` gives each ground type one or two of those names, `steep` overrides them on slopes. A ground type with no
63
- color is neutral gray. The `variation` defaults are shown (plain data, so it travels to the workers; unknown keys throw):
64
- ```js fragment
65
- terrain({ colors: { ... }, biomeColors: { ... },
66
- variation: {
67
- blend: { size: 33, strength: 1 }, // wavelength in m of the two-color noise; strength > 1 = harder contrast, < 1 = flatter
68
- jitter: { size: 0.33, min: 0.92, range: 0.12 }, // grain cell in m; darkest multiplier; how much brighter it can get (0 range = no grain)
69
- patches: { size: 90, strength: 0.15, levels: 0, tint: 0xb59a5a }, // optional (example values): a second, large layer of color blocks
70
- } })
71
- ```
72
- `patches` is off unless given. It is a noise much larger than `blend`; `levels: 4` snaps it to 4 flat steps (hard-edged color blocks instead of a
73
- soft blend); without `tint` it lightens and darkens the ground, with `tint` it pulls the color towards the tint where the noise is high. Vertex colors
74
- interpolate across a chunk cell (4 m at the default resolution), so blocks smaller than that blur; for crisp blocks use `shading: 'texture'`
75
- (recipe 37) or a texture (next). Which combination fits which picture, and ground that looks wrong up close: recipe 53.
76
-
77
- ### Changing it at run time: `engine.terrain.recolor`
78
- ```js fragment
79
- engine.terrain.recolor({ colors, biomeColors, steep, variation, shading, normals }); // every chunk is rebuilt; edits stay, collision does not change
80
- engine.terrain.recolor({ detail: { noise: 'paper', strength: 0.2 } }); // only the material: no chunk is rebuilt
81
- ```
82
- Each value is given whole, not merged, and `null` takes it out (`shading: null` goes back to what `terrain({...})` was given). Keys left out stay.
83
- `recolor` throws under a picture that replaced `'terrain-draw'`, which draws the ground its own way.
84
-
85
- ### Your own ground material
86
- `engine.terrain.material` is what every chunk draws with: a plain three.js material, neutral gray with vertex colors until you change it. Write to it, or
87
- set your own at any time; `terrain({ material })` (a Material or `(engine) => Material`) does the same from the start. Setting it swaps the material on
88
- every loaded chunk, regenerates nothing and adds nothing: a material of yours is drawn as given. To keep the cloud shadow, the season tint and the
89
- detail layer, hand it `engine.terrain.patches`. `terrain({ material })` adds them for you unless `effects: false`. After a later `recolor({ detail })`
90
- patch your material again; the engine only rebuilds its own.
91
-
92
- Chunk geometry has `position`, `normal`, `color` and `uv = world xz / chunk size`, continuous across chunk borders (checked by
93
- `tests/specs/appearance.mjs`), so a repeating texture is seamless whatever chunk it lands in. `texture.repeat.set(8, 8)` = 8 tiles per chunk. Without
94
- UVs (steep sides stretch a top-down map), project from the world position in a patch instead (`needs.patches: ['world']` gives `vThreedogWorld`):
95
- ```js
96
- engine.terrain.material = applyEffects(new THREE.MeshLambertMaterial({ vertexColors: true }), { clouds: false, patches: [{
97
- name: 'triplanar', needs: { patches: ['world'] }, uniforms: { uTex: { value: groundTexture }, uTexScale: { value: 0.1 } }, // groundTexture: repeat wrapping
98
- glsl: { fragment: { pars: 'uniform sampler2D uTex; uniform float uTexScale;',
99
- color_fragment: `vec3 n = abs(normalize(cross(dFdx(vThreedogWorld), dFdy(vThreedogWorld)))); n /= n.x + n.y + n.z;
100
- diffuseColor.rgb *= texture2D(uTex, vThreedogWorld.zy * uTexScale).rgb * n.x + texture2D(uTex, vThreedogWorld.xz * uTexScale).rgb * n.y
101
- + texture2D(uTex, vThreedogWorld.xy * uTexScale).rgb * n.z;` } } }] });
102
- ```
103
- A procedural noise texture is a `THREE.DataTexture` filled in a loop (`wrapS = wrapT = THREE.RepeatWrapping`, `colorSpace = THREE.SRGBColorSpace`,
104
- `needsUpdate = true`).
105
-
106
- ### Detail layer
107
- The lighter alternative, with no material of your own: `terrain({ detail })`, or `engine.terrain.recolor({ detail })` at run time. It takes
108
- `noise: 'grain' | 'paper' | 'stroke' | 'dabs'`, or `texture: 'name'`, or your own `glsl`, and `scale`, `strength`, `fade` ... (keys in recipe 43; here
109
- `scale` defaults to 0.25 and `strength` to 0.35). `engine.terrain.uniforms` are its `{ value }` objects, written directly and live:
110
- `engine.terrain.uniforms.uDetailStrength.value = 0.2`. Which to pick: recipe 53.
111
-
112
- ## Plants and wind
113
- ```js
114
- engine.vegetation.define('oak', { model: await engine.assets.model('oak'), wind: 0.02 }); // per species: its own material, wind, fade
115
- engine.vegetation.define('fern', { geometry, material: new THREE.MeshToonMaterial({ vertexColors: true }), wind: 0.08 });
116
- engine.vegetation.material = applyEffects(new THREE.MeshToonMaterial({ vertexColors: true }), { patches: engine.vegetation.patches }); // the shared default
117
- engine.uniforms.uWindAmp.value = 0.5; engine.uniforms.uWindFreq.value = 2; // how hard and how fast: plain signals, live
118
- ```
119
- `engine.vegetation.material` is what every species with no material or model of its own draws. Set it and it is drawn as given, on plants already
120
- planted too: nothing is added behind it, so hand it `engine.vegetation.patches` (season tint, sway at one amplitude, the `color()` code) to keep those.
121
- `null` gives the neutral default back. A species' own amplitude and near fade need a material of its own: `define(name, { material })` adds wind, cloud
122
- shadows, season tint and the fade to it unless `effects: false`. Each species' live material is `engine.vegetationDraw.kind(name).material`.
123
-
124
- What the vegetation code fixes, split into mechanism (stays) and picture:
125
-
126
- | Where | What | Kind |
127
- |---|---|---|
128
- | `Vegetation.define` | per species: `wind` amplitude, `rule`, `positions`, `densityMap`, `lodRing`, `maxRing`, `nearOnly`, `castShadow`, `shadowRing`, `material`, `effects` | already options (game content) |
129
- | `GroundChunks`, `VegetationDraw` (`modules/vegetation/draw.js`) | one InstancedMesh per species per chunk; rings decide LOD swap, draw distance, shadow distance; 3 ms placement budget; collision lag | mechanism, stays (the whole picture is replaceable: recipe 28 section 6) |
130
- | wind sway shape | two sines (speed `1.2 + 0.6*uWind` and `2.9`, spatial phase from the instance origin), height-weighted, lean with wind strength | picture: **`engine.vegetation.sway(glsl)`** replaces it for every species whose `wind` is a number, planted ones too |
131
- | wind speed, strength | `uWindFreq`, `uWindAmp` | signals: `engine.uniforms.uWindFreq.value`, `uWindAmp.value` (0 = plants stand still) |
132
- | color | vertex and instance colors, season tint | picture: **`engine.vegetation.color(glsl \| { glsl, tsl })`** puts code in the `color` slot of every species, live |
133
- | season tint | `diffuseColor.rgb *= tint` (default) or a blend towards the tint; colors from `engine.sky.seasonTints` | `engine.sky.seasonTints = { mode: 'multiply' \| 'mix', strength, autumn: { foliage: 0xffb070 } }`; see recipe 43 |
134
- | defaults | `castShadow` = not `nearOnly`, `shadowRing` 1, `lodRing` 1 | per-species options, set them in the species |
135
-
136
- ```js
137
- engine.vegetation.sway({ uniforms: { uSteps: 3 }, // stepped sway: plants snap between 3 poses instead of a smooth sine
138
- glsl: `void threedogWind(inout vec3 transformed, vec3 ip, vec3 position){
139
- float s = floor(sin(uTime * uWindFreq + ip.x * 0.3 + ip.z * 0.2) * uSteps) / uSteps;
140
- transformed.x += s * max(position.y, 0.0) * THREEDOG_WIND_AMP * uWind;
141
- }` });
142
- ```
143
- `threedogWind` receives the vertex (`transformed`, object space), `ip` (world position of this plant's origin, so each plant has its own phase) and
144
- `position`; `uTime`, `uWind` (weather), `uWindFreq` and `THREEDOG_WIND_AMP` (the species' amplitude) are in scope. It applies to every material made by
145
- `vegetation.define` whose `wind` is a number, and the shadow sways with it. A missing function throws with the signature. WebGPU needs the `tsl` form: `{ glsl, tsl }`.
146
- `sway(null)` gives the built-in sway back. A shared material the game set keeps what it was built with: apply the new `engine.vegetation.patches` to it. The same object works in code:
147
- `applyEffects(mat, { wind: { amplitude: 0.03, glsl, uniforms } })`.
148
-
149
- Two entries, two scopes: `sway()` is the default shape for all plants, and `vegetation.define(name, { wind: { amplitude, glsl, tsl, uniforms } })` is one species' own
150
- sway. When both are set the species' own wins, and `sway()` and `sway(null)` leave it as it is. Use one `sway()` for the world and a `wind` object for the plant that moves differently.
151
-
152
- Cost, measured with software rendering (relative numbers only): 10,000 grass blades of 6 triangles in one InstancedMesh draw in 1 call; per frame
153
- about 120 ms with no wind, default wind and a custom sway alike, so the sway function is not where grass time goes (vertex count and fill are).
154
- Reduce grass cost with `rule.perChunk`, `maxRing` and `nearOnly`, not the wind.
155
-
156
- ## What is still fixed
157
- Cloud *shadows* on the ground (`threedog_clouds_pars_fragment`) keep their two-noise shape; strength, scale and speed are the signals
158
- `engine.uniforms.uCloudShadow`, `uCloudScale`, `uCloudSpeed`. Grass has no billboard or blade-shape setting: give `vegetation.define` your own `geometry` or `model`.
@@ -1,115 +0,0 @@
1
- # Crisp ground color borders, terrain normals, height from a grid
2
-
3
- For an AI that wants the ground to look a way the defaults do not: crisp color borders (a river bank, a path edge), a coarse low-poly mesh with
4
- fine color, a different triangle cut, custom lighting normals, height read from a grid or image. Terrain basics are in `28-terrain.md`, ground
5
- color noise in `36-sky-ground-plants.md`, the ground up close (detail, variation, symptoms) in `53-ground-up-close.md`. Each knob names its
6
- default (`tests/specs/terrain-draw.mjs` pins them). Each knob has three exits: a parameter, a small pure function, or replacing the whole ground material.
7
-
8
- ## Why the bank is jagged: color lived on the mesh
9
- With `shading: 'smooth'` or `'flat'` a color is computed at a grid point (or triangle center) and blended across the triangle. At the default
10
- `resolution: 16` on a 64 m chunk that is one color sample per 4 m, so any border between two ground types can only run along triangle edges.
11
- Raising `resolution` fixes it at the price of triangles (and collision, and edit granularity). `shading: 'texture'` cuts the link: color is
12
- computed per pixel into a per-chunk image, the mesh stays as coarse as you like.
13
-
14
- ## 1. `shading: 'texture'` (and `colorResolution`)
15
- ```js
16
- engine.use(terrain({ ...terrainPreset(), shading: 'texture', colorResolution: 128 }));
17
- ```
18
- - A worker computes a `(colorResolution + 2)^2` RGBA image per chunk with the same rules as the vertex colors (`faceColor`: ground type from your
19
- `groundType`, `biomeColors` two-color noise blend, `steep` slope colors, `variation` blend / jitter / patches, painted cells).
20
- The main thread uploads it as a `DataTexture` (sRGB, mipmaps, anisotropy 4). The `+ 2` is a 1 pixel border computed from world coordinates, so
21
- neighboring chunks hold identical values at the seam and no seam shows (checked byte for byte).
22
- - Vertex colors are plain white in this mode (they carry no color). The material samples the image by world xz (the `world` patch), so `uv`
23
- stays free (`world xz / chunk size`, for your own textures). Each chunk gets its own clone of the terrain material (same patches, one compiled
24
- program), so a change you make to the terrain material object after chunks exist does not reach loaded chunks; pass it through `terrain({ material })`.
25
- - Painted cells (`terrain.edit(..., { paint })`) keep their whole-cell color; the image of every chunk touched by an edit is re-uploaded in place.
26
- - Steep-slope colors test a normal interpolated between grid points, so they no longer follow single triangles either.
27
- - Independent of `resolution`: `resolution` still sets mesh, collision and edit granularity, `colorResolution` only the color detail
28
- (64 m chunk: 128 = 0.5 m per pixel, 256 = 0.25 m).
29
-
30
- Numbers (resolution 16, 64 m chunk, a curved ground-type border, rendered top-down in the real engine, error against the true curve):
31
-
32
- | shading | border RMS error | border jaggedness (RMS 2nd difference) |
33
- | --- | --- | --- |
34
- | smooth | 1.12 m | 0.48 |
35
- | texture, colorResolution 128 | 0.14 m | 0.10 |
36
-
37
- Cost (software-rendered machine, relative values only):
38
- - worker time per chunk: about 9 ms for `texture` at 128 (calculation is mostly your `groundType` called once per pixel) against 1.1 ms for smooth
39
- (measured in Node, the worker runs the same code); 64 costs a quarter, 256 four times that.
40
- - memory: 130 x 130 x 4 = 68 KB per chunk plus mipmaps (about 90 KB; 23 KB at 64). 69 loaded chunks = about 6 MB at 128.
41
- - `threedog perf --only=stream --shading=texture` against the default: frame CPU average 5.5 ms both; worst frame 64 ms -> 88 ms (one-time shader
42
- program compile plus first uploads, it lands once, not per chunk); upload stage total 41 ms -> 112 ms over 69 chunks.
43
- - Low-tier devices (`engine.tier === 'low'`, see `core/tier.js`): if you did not set `colorResolution`, the terrain module uses 64 there. To skip the
44
- color map completely on low tier, choose the shading yourself: `shading: engine.tier === 'low' ? 'smooth' : 'texture'` in your terrain() call.
45
- - With `terrain({ shape })` (an outline, `42-terrain-shape.md`) the map covers the top only: void pixels keep the color of the ground under them
46
- (no seam at the rim) with alpha 0, and island sides and bottom draw with vertex colors (or `shape.side.material`).
47
-
48
- ## 2. Lighting normals: `normals` and `normalFn`
49
- - `shading: 'smooth'` lights with one normal per grid point, `'flat'` one per triangle. In texture mode choose: `normals: 'smooth'` (default) or
50
- `'flat'` (faceted light, fine color: a low-poly shape with crisp borders).
51
- - `normalFn(i, j, h, cell) => [nx, ny, nz]` replaces the smooth normal at grid point `(i, j)`; `h(i, j)` reads a grid-point height, `cell` is the
52
- spacing in meters. Pure like `height` / `groundType` (only its parameters, `Math`; a function you pass travels to workers as source text and an
53
- outside variable throws naming it). The engine normalizes the result. Default: central difference of the four neighbors.
54
- ```js
55
- terrain({ normalFn: (i, j, h, cell) => [(h(i - 1, j) - h(i + 1, j)) / cell, 4, (h(i, j - 1) - h(i, j + 1)) / cell] }) // gentler lighting on slopes
56
- ```
57
- `normals` and `normalFn` change light only, never height or collision. `engine.terrain.recolor({ normals: 'flat' })` changes it at run time (rebuilds the chunks).
58
-
59
- ## 3. `diagonal`: how a cell is cut into triangles
60
- ```js
61
- terrain({ diagonal: 'adaptive' }) // 'fixed' (default) | 'adaptive' | 'alternate'
62
- ```
63
- `fixed` cuts every cell the same way. `adaptive` cuts along the diagonal with the smaller height difference, which removes
64
- the zigzag ridges a fixed cut leaves on a slope; `alternate` flips every other cell (no directional bias on flat low-poly facets). `engine.surface`,
65
- collision and vegetation heights follow the chosen cut, so nothing floats. It changes the walkable shape, so `recolor` does not take it.
66
-
67
- ## 4. `boundsPad`: the chunk bounding sphere margin
68
- `boundsPad: { up: 3, radius: 8 }` (meters, the defaults) is the margin of the culling sphere: the center is raised by `up`, the radius grows
69
- by `radius`. Raise it if a shader moves vertices far (wind on tall ground cover, a vertex-displacement patch) and chunks pop out at the screen edge.
70
-
71
- ## 5. Relation to `variation`
72
- `variation` shapes *what* color a point gets; `shading` decides *where* it is evaluated. In vertex modes every variation is limited to cell size; in
73
- texture mode it is sampled per pixel, so `patches: { size: 20, levels: 4 }` gives hard-edged color blocks, and a `jitter.size` below the pixel size
74
- (0.5 m at `colorResolution: 128`) comes out as one grain per pixel, coarser than asked. Choosing a combination, and ground that looks wrong up close: recipe 53.
75
-
76
- ## 6. Example: a river bank
77
- ```js
78
- engine.use(terrain({
79
- shading: 'texture', colorResolution: 192, resolution: 16,
80
- height: (x, z) => 0,
81
- // the border is a curve; the ground type is evaluated per pixel
82
- groundType: (x, z) => z > 32 + 14 * Math.sin(x * 0.09) ? 'grass' : 'sand',
83
- colors: { grass: 0x5a8a3a, sand: 0xd8c690 }, biomeColors: { grass: ['grass'], sand: ['sand'] },
84
- }));
85
- ```
86
- Using a preset (`riverAt` of `@threedog/terrain-noise`) the same switch gives crisp banks without more triangles: `terrain({ ...terrainPreset(), shading: 'texture' })`.
87
-
88
- ## 7. Height from a grid or image
89
- `sampleGrid(data, { width, height, size | cellSize, origin, interp })` turns numbers laid out on a regular grid into a function `(x, z) => value`;
90
- `await engine.assets.gridFromImage(nameOrUrl, { channel, range, bits })` reads such a grid from an image (PNG at full 8 or 16 bits, jpg/webp at 8;
91
- `channel` is `'r'`/`'g'`/`'b'`/`'a'`; `range: [min, max]` maps the pixel values to world units, default `[0, 1]`). Samples sit on the grid nodes, so
92
- `width` samples span `width - 1` cells; outside the grid the edge value is used, or `outside: v`. The grid is just a field: height, moisture, a
93
- ground-type weight, spawn density, a walkable mask, danger, travel cost.
94
-
95
- `interp` is the picture between nodes; none of them is the right one:
96
- - `'nearest'`: flat steps, one value per cell. Terraces, blocky or voxel-like ground, tile masks, numbers that are ids.
97
- - `'linear'` (default): plain bilinear blend; smooth enough for most fields, never leaves the range of its four corners.
98
- - `'cubic'`: smooth slopes without cell creases (rolling hills, soft gradients). It can overshoot beside a sharp step; `clamp: true` keeps the
99
- result inside the four corner values.
100
-
101
- ```js
102
- const g = await engine.assets.gridFromImage('/maps/height16.png', { range: [-5, 60] }); // meters, 16-bit file
103
- const heightAt = sampleGrid(g.data, { ...g, size: [512, 512], origin: [-256, -256], interp: 'cubic', clamp: true });
104
- heightAt(10, 20); // gameplay side: where to put a camp, a mine, a lighthouse
105
- const wet = sampleGrid(moisture, { width: 32, height: 32, cellSize: 8 }); // a hand-made field: wetter ground grows reeds, rice, moss
106
- const walk = sampleGrid(mask, { width: 64, height: 64, cellSize: 1, interp: 'nearest', outside: 0 }); // 0 / 1 per tile; off the map: not walkable
107
- ```
108
- A terrain `height` function is recompiled in a worker and cannot capture `heightAt`, so the terrain reads the same image through its own
109
- `heightmap` (bilinear, centered on `center`): `terrain({ heightmap: { ...g, size: [512, 512], min: -5, max: 60 } })` with `g` from `gridFromImage`
110
- using the default `range` (it expects 0-1 values; `min`/`max` scale them). Use `sampleGrid` for everything outside the terrain module; when you need
111
- a picture the terrain's bilinear read does not give (terraces: `nearest`), bake it into the data first or write the step in a `height` function.
112
-
113
- ## Whole replacement
114
- Anything beyond this: `terrain({ material })` (or `engine.terrain.material = m`) swaps the ground material and `engine.terrain.T.buildChunk(cx, cz)` returns the
115
- raw arrays (`pos`, `nor`, `col`, `uv`, and `tex: { data, size }` in texture mode) if you build chunk meshes yourself.
@@ -1,67 +0,0 @@
1
- # Lights, fog and exposure
2
-
3
- Lights, fog and exposure are your own three.js code ([recipe 62](62-picture-code.md)): the sky computes signals and draws its dome, it writes none of them. This page covers what is left around
4
- that: the placeholder lights, fog, the tone curve, extra sky layers. Sky basics are in `08-weather-sky.md`, clouds and ground color in
5
- `36-sky-ground-plants.md`, environment lighting in `34-environment-lighting.md`.
6
-
7
-
8
- ## Lights: the placeholders, and your own
9
- The engine has one directional light (`engine.lights.sun`) and one hemisphere (`engine.lights.hemi`): still white placeholders (sun 2 at (40, 80, 30) with soft shadows, hemi 1.2), so a scene
10
- with no picture code is neutral gray and not black. Nothing moves them, with or without a sky.
11
-
12
- ```js
13
- const engine = createEngine({ canvas, lights: false }); // the placeholders stay out of the scene
14
- const sun = new THREE.DirectionalLight(0xffd0a0, 2); engine.scene.add(sun, sun.target); // add your own lights before engine.start()
15
- engine.onRender(() => { sun.position.copy(engine.uniforms.uSunDir.value).multiplyScalar(100); sun.intensity = 2 * engine.uniforms.uDaylight.value * engine.uniforms.uWeatherLight.value; });
16
- const torch = new THREE.PointLight(0xffa040, 6, 12); engine.add(torch);
17
- ```
18
-
19
- - `createEngine({ lights: false })`: the default sun and hemisphere are never put in the scene, `engine.lights.sun` / `hemi`
20
- stay as detached objects so nothing reads `undefined`. Use it for a scene lit entirely by your own lights.
21
- - Shadows: only the engine sun's box is managed. Your own `castShadow` lights work as in three.js, each costing its
22
- own shadow pass; `engine.shadows` (recipe 45) takes them when you hand them in, and `engine.shadows.enabled = false` turns every shadow off.
23
- - Add or remove lights before `engine.start()`; what a change costs mid-play, and many lamps with `lightPool`: recipe 09 "Lights and stalls".
24
-
25
- ## Fog: plain three.js, signals, your own math
26
- ```js
27
- const fog = engine.scene.fog = new THREE.Fog(0x99bbbb, 60, 220); // or new THREE.FogExp2(color, density)
28
- engine.onRender(() => { // a fog that follows the day and the weather: your picture/ code
29
- fog.color.copy(engine.uniforms.uSkyHorizon.value);
30
- fog.far = 220 / engine.uniforms.uWeatherFog.value;
31
- });
32
- ```
33
- There is no fog until your code makes one, and nothing writes it after that.
34
-
35
- - Signals to read: `uSkyHorizon` is the color at the horizon, so fog in that color hides the line where the dome meets the ground; `uWeatherFog` is what the weather asks for, a
36
- multiplier your code applies; `uViewDistance` says how far the world is meant to be seen (`terrain({ viewFog: true })` writes it).
37
- - Color, near, far and density are live. Adding or removing `scene.fog`, or changing its type, recompiles materials once: do it at a scene change, not every frame.
38
- - Materials with `fog: false` (the dome) are not fogged.
39
- - Your own fog math (height fog, a warm far haze): the `fogPars` and `fog` slots on a material, WebGL only (recipe 43), or your own `ShaderMaterial`:
40
- `applyEffects(material, { patches: [{ name: 'haze', slot: 'fog', glsl: 'float f = 1.0 - exp(-fogDensity * vFogDepth); gl_FragColor.rgb = mix(gl_FragColor.rgb, vec3(1.0, 0.85, 0.7), f * 0.3);' }] })`.
41
- - Check the result with `engine.describe('picture').picture.fog`; `threedog shot` says how much of the picture the fog makes up.
42
-
43
- ## Exposure and the tone curve
44
- ```js
45
- engine.renderer.toneMappingExposure = 1.3;
46
- engine.onRender(() => { engine.renderer.toneMappingExposure = 1 + 0.5 * (1 - engine.uniforms.uDaylight.value); }); // over the day: your picture/ code
47
- engine.renderer.toneMapping = THREE.NeutralToneMapping; // the curve; materials recompile on their next draw
48
- ```
49
- The engine picks no curve: `renderer.toneMapping` stays three.js's default (`NoToneMapping`) until your code writes it. A curve of your own is a post effect in the `'tone'` slot (recipe 52).
50
-
51
- ## Extra sky layers: rainbow, aurora, color bands
52
- `engine.sky.layer(name, spec)`, drawn on the dome after clouds and stars; none by default:
53
-
54
- ```js
55
- engine.sky.layer('aurora', { blend: 'add', uniforms: { uAurora: [0.2, 1, 0.6] }, glsl: `vec4 threedogSkyLayer(vec3 d, float time, vec3 sunDir, float night){
56
- float band = smoothstep(0.25, 0.45, d.y) * (1.0 - smoothstep(0.55, 0.8, d.y));
57
- float n = threedogNoise(vec2(d.x * 4.0 + time * 0.05, d.z * 2.0));
58
- return vec4(uAurora, band * n * night); }` });
59
- ```
60
- Signature `vec4 threedogSkyLayer(vec3 dir, float time, vec3 sunDir, float night)` returns (rgb, amount). `blend: 'mix'` (default) or `'add'`;
61
- `order` sorts layers (smaller first); `uniforms` like `clouds.uniforms`, live in `engine.sky.dome.material.uniforms.uAurora.value`. Each layer's function is
62
- renamed (`threedogSkyLayer0`, `1`, ...), so layers from different parts of the game never clash. Whole replacement: `engine.sky.replace(panorama)` or
63
- hide `engine.sky.dome` and add your own background.
64
-
65
- ## Water and weather particles
66
- Water depth color, crest foam, wave / surface GLSL, reflections; rain and snow shape, size, density and shaders, the lightning picture, and
67
- particles for the game's own weather (`engine.weather.define`): `44-water-weather-hooks.md`.