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
package/core/Budget.js ADDED
@@ -0,0 +1,221 @@
1
+ // Performance budget, engine.budget: the game sets limits (only categories given are checked); on overrun it reports which category and who uses the most.
2
+ // createEngine({ budget: { drawCalls: 250, fps: 55 } }) or engine.budget.enable({ drawCalls: 250 })
3
+ // engine.budget.report() // { ok, over: [{ category, value, limit, top }] }; null when off
4
+ // Off by default; when off, sample() returns immediately and costs nothing. The engine presets no limit numbers.
5
+ // Categories: drawCalls, triangles, textures, cpuMs, fps, low1 (the last two are lower bounds) + module-registered metrics (chunkApplyMs, rigidBodies...)
6
+ // + the apply-cost stages (applyTransitMs, applyBuildMs, applyColliderMs, applyUploadMs, applyStreamMs: ms per frame, see ApplyCost).
7
+ // "Who uses the most": draw calls are estimated by the userData.budgetTag of an object (or its parent); untagged counts as 'other'.
8
+ /** @import { Handle } from '../types/common' */
9
+ /** @import { BudgetLimits, BudgetReport, BudgetTagStat } from '../types/world' */
10
+ import { coded } from './errorHints.js';
11
+ import { fmt } from './validate.js';
12
+ import { r1 } from './math.js';
13
+ import { SHADOW_TYPES } from './shadowTypes.js';
14
+ import * as THREE from 'three';
15
+
16
+ const STRINGS = {
17
+ startup: 'Startup took {value} ms, over budget startupMs {limit} ms; slowest module: {top}',
18
+ module: 'Module {name} took {value} ms to start, over budget moduleMs {limit} ms (init + waiting for ready)',
19
+ over: 'Performance budget exceeded: {category} = {value} ({dir} {limit}). Most draw calls: {top}',
20
+ min: 'minimum', max: 'maximum',
21
+ };
22
+ const LOWER = new Set(['fps', 'low1']); // these two are lower bounds ("not below")
23
+ const WINDOW = 300; // how many recent frames the frame-rate stats use
24
+
25
+ /** Cost stages of bringing a background result into the frame, in the order a chunk goes through them */
26
+ const STAGES = ['transit', 'build', 'collider', 'upload', 'stream'];
27
+ const EMA = 0.1; // per-frame smoothing, the same factor chunkApplyMs always used
28
+
29
+ /**
30
+ * engine.budget.cost: where the main thread pays for background results (terrain chunks, vegetation, colliders, stream builds), split in stages.
31
+ * Always on (a few performance.now() calls per applied result). Stages: transit = worker round trip minus the worker's own compute (queueing,
32
+ * structured clone, waiting for a busy main thread: an async wait, not main-thread blocking, so it is an approximation); build = creating the
33
+ * three.js objects (geometry, meshes, instanced meshes); collider = physics colliders; upload = GPU upload and shader compile, approximated as the
34
+ * extra render time of frames that first draw new objects over the average render time of other frames; stream = the synchronous part of a stream
35
+ * build() callback.
36
+ */
37
+ export class ApplyCost {
38
+ /** @internal */
39
+ constructor() {
40
+ /** @internal */ this.t = {};
41
+ for (const k of STAGES) this.t[k] = { n: 0, totalMs: 0, maxMs: 0, frameMs: 0, bytes: 0, _cur: 0 };
42
+ /** @internal */ this._fresh = 0;
43
+ /** @internal */ this._base = -1;
44
+ }
45
+ /** @internal Add ms to a stage (bytes: payload size, transit only) */
46
+ add(stage, ms, bytes = 0) {
47
+ const s = this.t[stage];
48
+ s.n++; s.totalMs += ms; s._cur += ms; s.bytes += bytes;
49
+ if (ms > s.maxMs) s.maxMs = ms;
50
+ }
51
+ /** @internal Close a span started with performance.now(); build and stream spans create objects the next render uploads */
52
+ end(stage, t0) {
53
+ this.add(stage, performance.now() - t0); // measure
54
+ if (stage === 'build' || stage === 'stream') this._fresh++;
55
+ }
56
+ /** @internal A worker result arrived: t0 is when its job was sent, r.ms what the worker spent computing it */
57
+ transit(t0, r) {
58
+ const t = r.terrain, bytes = t ? t.pos.byteLength + t.nor.byteLength + t.col.byteLength + t.uv.byteLength : 0;
59
+ this.add('transit', Math.max(0, performance.now() - t0 - (r.ms ?? 0)), bytes); // measure
60
+ }
61
+ /** @internal One render finished (ms): a frame that drew new objects pays the upload, the others set the baseline. Also rolls the per-frame smoothing */
62
+ rendered(ms) {
63
+ if (this._fresh) { if (this._base >= 0) this.add('upload', Math.max(0, ms - this._base)); this._fresh = 0; }
64
+ else this._base = this._base < 0 ? ms : this._base + (ms - this._base) * EMA;
65
+ for (const k of STAGES) { const s = this.t[k]; s.frameMs += (s._cur - s.frameMs) * EMA; s._cur = 0; }
66
+ }
67
+ /**
68
+ * Per stage: n results, totalMs, maxMs of one result, frameMs (smoothed ms per frame), bytes (transit only)
69
+ * @returns {Record<string, { n: number, totalMs: number, maxMs: number, frameMs: number, bytes: number }>}
70
+ * @example engine.budget.cost.report().build // { n: 12, totalMs: 9.4, maxMs: 1.8, frameMs: 0.2, bytes: 0 }
71
+ */
72
+ report() {
73
+ const out = /** @type {any} */ ({});
74
+ for (const k of STAGES) { const s = this.t[k]; out[k] = { n: s.n, totalMs: r1(s.totalMs), maxMs: r1(s.maxMs), frameMs: r1(s.frameMs), bytes: s.bytes }; }
75
+ return out;
76
+ }
77
+ /** Forget what was counted so far (to measure one scene on its own) */
78
+ reset() { for (const k of STAGES) Object.assign(this.t[k], { n: 0, totalMs: 0, maxMs: 0, frameMs: 0, bytes: 0, _cur: 0 }); }
79
+ }
80
+
81
+ /** engine.budget: performance budget (turned on by createEngine({ budget }) or enable(); off by default, costs nothing). */
82
+ export class Budget {
83
+ /** @internal */
84
+ constructor(engine) {
85
+ /** @internal */ this.engine = engine;
86
+ /** Is it on? */
87
+ this.enabled = false;
88
+ /** Current limits @type {BudgetLimits} */
89
+ this.limits = {};
90
+ /** @internal Module-defined categories: name -> { read, limit } @type {Map<string, { read: () => number, limit?: number }>} */
91
+ this.metrics = new Map();
92
+ /** @internal */ this._dts = [];
93
+ /** @internal */ this._cpu = [];
94
+ /** @internal */ this._t = 0;
95
+ /** @internal @type {any} */ this._last = null;
96
+ /** Cost of applying background results, split in stages (see ApplyCost) */
97
+ this.cost = new ApplyCost();
98
+ for (const k of STAGES) this.metric('apply' + k[0].toUpperCase() + k.slice(1) + 'Ms', () => this.cost.t[k].frameMs);
99
+ /** @internal */ this._warned = new Set();
100
+ /** @internal */ this._frustum = new THREE.Frustum();
101
+ /** @internal */ this._m = new THREE.Matrix4();
102
+ }
103
+ /**
104
+ * Turn on and set limits (only categories given are checked)
105
+ * @param {BudgetLimits} [limits]
106
+ * @returns {this}
107
+ * @example engine.budget.enable({ drawCalls: 250, fps: 55 });
108
+ */
109
+ enable(limits = {}) { this.enabled = true; this.limits = { ...limits }; this._dts = []; this._cpu = []; this._last = null; return this; }
110
+ /** Turn off */
111
+ disable() { this.enabled = false; this._last = null; }
112
+ /**
113
+ * Module-defined category: read() returns the current value, opts.limit is the limit (the game's enable() takes precedence). Returns a handle { remove() }
114
+ * @param {string} name
115
+ * @param {() => number} read
116
+ * @param {{ limit?: number }} [opts]
117
+ * @returns {Handle}
118
+ */
119
+ metric(name, read, opts = {}) {
120
+ const m = { read, limit: opts.limit };
121
+ this.metrics.set(name, m);
122
+ return { remove: () => { if (this.metrics.get(name) === m) this.metrics.delete(name); } };
123
+ }
124
+ /** Limit of a category; undefined if none was given (not checked) @param {string} name @returns {number | undefined} */
125
+ limitOf(name) { return this.limits[name] ?? this.metrics.get(name)?.limit; }
126
+
127
+ /** @internal Called by the engine after each rendered frame: records frame time, checks once a second, and warns once per category over its limit */
128
+ sample(dt) {
129
+ if (!this.enabled) return;
130
+ this._dts.push(dt); this._cpu.push(this.engine.cpuMs ?? 0);
131
+ if (this._dts.length > WINDOW) { this._dts.shift(); this._cpu.shift(); }
132
+ if ((this._t += dt) < 1) return;
133
+ this._t = 0;
134
+ const r = this._last = this._evaluate();
135
+ for (const o of r.over) {
136
+ if (this._warned.has(o.category)) continue;
137
+ this._warned.add(o.category);
138
+ console.warn(coded('budget-over', fmt(STRINGS.over, { ...o, dir: LOWER.has(o.category) ? STRINGS.min : STRINGS.max, top: o.top.map(t => `${t.tag} ${t.drawCalls}`).join(', ') })));
139
+ }
140
+ }
141
+ /** Budget report; null when off. In the real-time loop it returns the last second's result; in step() mode it is computed on demand @returns {BudgetReport | null} */
142
+ report() {
143
+ if (!this.enabled) return null;
144
+ return this._last && this._dts.length ? this._last : this._evaluate();
145
+ }
146
+ /**
147
+ * Called by the engine when startup finishes: warns if startupMs / moduleMs is exceeded and returns the offenders (empty array if none)
148
+ * @param {{ totalMs: number, modules: Record<string, { init?: number, ready?: number }> }} s
149
+ * @returns {{ category: 'startupMs' | 'moduleMs', value: number, limit: number, top: { tag: string, ms: number }[] }[]}
150
+ */
151
+ checkStartup(s) {
152
+ if (!this.enabled) return [];
153
+ const { startupMs, moduleMs } = this.limits, /** @type {any[]} */ over = [];
154
+ const mods = Object.entries(s.modules).map(([tag, v]) => ({ tag, ms: (v.init ?? 0) + (v.ready ?? 0) })).sort((a, b) => b.ms - a.ms);
155
+ const top = mods.slice(0, 3);
156
+ if (startupMs != null && s.totalMs > startupMs) {
157
+ console.warn(coded('budget-over', fmt(STRINGS.startup, { value: s.totalMs, limit: startupMs, top: top.map(t => `${t.tag} ${t.ms}`).join(', ') })));
158
+ over.push({ category: 'startupMs', value: s.totalMs, limit: startupMs, top });
159
+ }
160
+ if (moduleMs != null) for (const m of mods) if (m.ms > moduleMs) {
161
+ console.warn(coded('budget-over', fmt(STRINGS.module, { name: m.tag, value: m.ms, limit: moduleMs })));
162
+ over.push({ category: 'moduleMs', value: m.ms, limit: moduleMs, top: [m] });
163
+ }
164
+ return over;
165
+ }
166
+ /** Current value per category (fps/low1/cpuMs exist only once there are frame times) @returns {Record<string, number>} */
167
+ values() {
168
+ const info = this.engine.renderer.info, v = /** @type {Record<string, number>} */ ({ drawCalls: info.render.calls, triangles: info.render.triangles, textures: info.memory.textures });
169
+ const d = this._dts;
170
+ if (d.length) {
171
+ const sum = d.reduce((a, b) => a + b, 0), worst = d.slice().sort((a, b) => b - a), n = Math.max(1, Math.floor(d.length * 0.01));
172
+ v.fps = r1(d.length / sum);
173
+ v.low1 = r1(n / worst.slice(0, n).reduce((a, b) => a + b, 0));
174
+ v.cpuMs = r1(this._cpu.reduce((a, b) => a + b, 0) / this._cpu.length);
175
+ }
176
+ for (const [name, m] of this.metrics) v[name] = r1(m.read());
177
+ return v;
178
+ }
179
+ /** @internal */
180
+ _evaluate() {
181
+ const v = this.values(), over = [];
182
+ let top = null;
183
+ for (const [category, value] of Object.entries(v)) {
184
+ const limit = this.limitOf(category);
185
+ if (limit == null || value == null) continue;
186
+ if (LOWER.has(category) ? value >= limit : value <= limit) continue;
187
+ over.push({ category, value, limit, top: top ??= this.byTag().slice(0, 5) });
188
+ }
189
+ return { ok: !over.length, over };
190
+ }
191
+ /**
192
+ * Estimate draw calls and triangles by userData.budgetTag (visible meshes inside the frustum; shadow casters count a second shadow draw).
193
+ * Returns [{ tag, drawCalls, triangles }], largest first. Called only on overrun (at most once a second) or when debugging
194
+ * @returns {BudgetTagStat[]}
195
+ */
196
+ byTag() {
197
+ const e = this.engine, cam = e.camera, out = new Map(), shadows = e.renderer.shadowMap.enabled, shadowCost = SHADOW_TYPES[e.shadowType]?.cost ?? 1;
198
+ // shadow passes a caster is drawn in: one per shadow-casting light (cascaded shadows add a light per cascade), six for a point light
199
+ let passes = 0;
200
+ e.scene.traverseVisible(o => { if (o.isLight && o.castShadow) passes += o.isPointLight ? 6 : 1; });
201
+ passes = Math.max(1, passes);
202
+ cam.updateMatrixWorld();
203
+ this._frustum.setFromProjectionMatrix(this._m.multiplyMatrices(cam.projectionMatrix, cam.matrixWorldInverse));
204
+ const walk = (o, tag) => {
205
+ if (!o.visible) return;
206
+ tag = o.userData.budgetTag ?? tag;
207
+ if ((o.isMesh || o.isPoints || o.isLine || o.isSprite) && (!o.frustumCulled || this._frustum.intersectsObject(o))) {
208
+ const g = o.geometry, groups = Array.isArray(o.material) ? Math.max(1, g?.groups.length ?? 1) : 1;
209
+ // a caster adds a shadow draw, scaled by the filter's rough cost (estimate: vsm ~1.6x, basic ~0.8x of pcf), once per pass
210
+ // (an upper bound: each light culls to its own shadow box, so a near cascade skips most of the scene)
211
+ const calls = groups * (shadows && o.castShadow ? 1 + shadowCost * passes : 1);
212
+ const n = g ? (g.index ? g.index.count : g.attributes.position?.count ?? 0) : 0;
213
+ const s = out.get(tag) || out.set(tag, { tag, drawCalls: 0, triangles: 0 }).get(tag);
214
+ s.drawCalls += calls; s.triangles += o.isMesh ? Math.round(n / 3) * (o.count ?? 1) : 0;
215
+ }
216
+ for (const c of o.children) walk(c, tag);
217
+ };
218
+ walk(e.scene, 'other');
219
+ return [...out.values()].sort((a, b) => b.drawCalls - a.drawCalls);
220
+ }
221
+ }
package/core/Clock.js ADDED
@@ -0,0 +1,94 @@
1
+ // Game clock, engine.clock: game seconds `now` + "after a delay / every interval" timers.
2
+ // Game seconds = fixed-step seconds x clock.timeScale (default 1; the sky's time of day follows it too); it does not run while paused / frozen, and is saved with the save;
3
+ // a sky day = sky.dayLength game seconds, so one sky hour = dayLength / 24 game seconds (independent of timeScale: the time scale only makes game seconds run faster).
4
+ // Clock-time / season timers (daily 18:00, time-window switches, season change) belong to the sky: engine.sky.at / between / daily / onSeason.
5
+ // engine.clock.after(120, 'bread:ready') // emit an event after 120 game seconds (saveable: still fires after a load)
6
+ // engine.clock.after(5, () => door.close()) // a function works too, but functions cannot be saved
7
+ // engine.clock.every(30, () => spawnBird()) // every 30 game seconds
8
+ // For fixed seconds (ignore the time scale; cooldowns, action timing): accumulate dt in engine.onFixed(dt => ...). Which time to use for what: the table in recipes/06-clock-events.md. All timers return a handle { remove() }.
9
+ // A timer callback that throws is a gameplay error (errors.js: frozen with engine.error in dev); the other timers still run.
10
+ import { reportError } from './errors.js';
11
+ import { codedError } from './errorHints.js';
12
+
13
+ const STRINGS = {
14
+ after: 'clock.after(seconds): seconds must be a finite number of game seconds, got {got}',
15
+ every: 'clock.every(seconds): seconds must be a finite number of game seconds > 0, got {got}; for every fixed step use engine.onFixed(dt => ...)',
16
+ where: 'clock timer',
17
+ };
18
+
19
+ export class Clock {
20
+ constructor(engine) {
21
+ this.engine = engine;
22
+ this.now = 0; // game seconds
23
+ /** Game seconds per fixed-step second: 0 stops game time (sky included), 60 = a minute per second. Fixed-step dt and engine.elapsed ignore it @type {number} */
24
+ this.timeScale = 1;
25
+ /** @internal after / every: { due, fn?, event?, data?, every? } */ this._timers = [];
26
+ /** @internal earliest due among the timers (ticks with nothing due return early) */ this._next = Infinity;
27
+ engine.saves.register('clock', {
28
+ save: () => ({ now: this.now, timers: this._timers.filter(t => t.event).map(({ due, event, data }) => ({ due, event, data })) }),
29
+ // On load: event timers use the saved due time; function timers (not saveable, still attached to the running game) are shifted onto the new clock by their remaining time
30
+ load: d => {
31
+ const old = this.now;
32
+ this.now = d?.now ?? 0;
33
+ const fnTimers = this._timers.filter(t => !t.event);
34
+ for (const t of fnTimers) t.due = this.now + (t.due - old);
35
+ this._set(fnTimers.concat((d?.timers || []).map(t => ({ ...t }))));
36
+ },
37
+ });
38
+ }
39
+
40
+ /** Call fn after `seconds` game seconds; when fnOrEvent is an event name, emit that event (with data) when due, which can be saved */
41
+ after(seconds, fnOrEvent, data) {
42
+ if (!Number.isFinite(seconds)) throw codedError('clock-interval', STRINGS.after.replace('{got}', String(seconds)));
43
+ const t = typeof fnOrEvent === 'string' ? { due: this.now + seconds, event: fnOrEvent, data } : { due: this.now + seconds, fn: fnOrEvent };
44
+ return this._add(t);
45
+ }
46
+ /** Call fn every `seconds` game seconds (seconds > 0) */
47
+ every(seconds, fn) {
48
+ if (!(seconds > 0) || !Number.isFinite(seconds)) throw codedError('clock-interval', STRINGS.every.replace('{got}', String(seconds)));
49
+ return this._add({ due: this.now + seconds, fn, every: seconds });
50
+ }
51
+ /** @internal */
52
+ _add(t) {
53
+ this._timers.push(t);
54
+ if (t.due < this._next) this._next = t.due;
55
+ return { remove: () => { this._set(this._timers.filter(x => x !== t)); } };
56
+ }
57
+ /** @internal replace the timer list and recompute the next due time */
58
+ _set(list) { this._timers = list; this._next = Infinity; for (const t of list) if (t.due < this._next) this._next = t.due; }
59
+ /** Game seconds until the next timer is due (Infinity with none); engine.skip ends a segment there so timers fire in time order @internal */
60
+ untilNext() { return Math.max(0, this._next - this.now); }
61
+ /** Number of registered timers (after / every), used by engine.counts() */
62
+ get size() { return this._timers.length; }
63
+ /** Clear all timers (engine.dispose calls it) */
64
+ dispose() { this._set([]); }
65
+ /**
66
+ * @internal For engine.session: the function timers now, each with its remaining delay (what a new playthrough starts with).
67
+ * @returns {{ t: object, rem: number }[]}
68
+ */
69
+ snapshotFnTimers() { return this._timers.filter(t => !t.event).map(t => ({ t, rem: t.due - this.now })); }
70
+ /**
71
+ * @internal For engine.session: keep the event timers (they came with the save) and put back exactly the snapshotted function timers, each with its original delay.
72
+ * A function timer removed during play comes back too: a new playthrough starts as if the page had just opened.
73
+ * @param {{ t: object, rem: number }[]} list
74
+ */
75
+ restoreFnTimers(list) { this._set(this._timers.filter(t => t.event).concat(list.map(({ t, rem }) => Object.assign(t, { due: this.now + rem })))); }
76
+
77
+ /** @internal Called by the engine every fixed step (after module hooks) */
78
+ tick(dt) {
79
+ this.now += dt * this.timeScale;
80
+ if (this._next <= this.now) this._runTimers();
81
+ }
82
+ /** @internal */
83
+ _runTimers() {
84
+ const due = this._timers.filter(t => t.due <= this.now).sort((a, b) => a.due - b.due);
85
+ for (const t of due) {
86
+ if (t.every) { while (t.due <= this.now) { t.due += t.every; this._call(t); } continue; }
87
+ this._timers = this._timers.filter(x => x !== t);
88
+ if (t.event) this.engine.events.emit(t.event, t.data); else this._call(t);
89
+ }
90
+ this._set(this._timers);
91
+ }
92
+ /** @internal a callback that throws is a gameplay error; the other timers still run */
93
+ _call(t) { try { t.fn(); } catch (err) { reportError(this.engine, err, STRINGS.where); } }
94
+ }
@@ -0,0 +1,77 @@
1
+ // How background results take effect: engine.commits.
2
+ // Background results that affect gameplay (chunk collision, spread-over-frames jobs that change gameplay state, future navmesh, entity spawns...) do not take effect "whenever they finish" --
3
+ // that depends on machine speed and background-thread queueing -- but on a fixed-step tick decided when the request is made:
4
+ // const t = engine.commits.request({ apply: r => change gameplay state with the result, fallback: () => compute the same result on the main thread now, valid: () => still wanted? });
5
+ // when the background work finishes: t.resolve(result); when no longer wanted: t.remove()
6
+ // At the due tick (engine.tick at request + lag, default 30 steps = 0.5 s) requests take effect in a stable order (due tick, then request order):
7
+ // finished -> apply(result); not finished -> apply(fallback()) (stats.late +1; a background result that arrives later is ignored); valid() false -> dropped.
8
+ // A save load or level change (invalidate) drops the requests that have no valid: they were made for the old world. A request with valid decides itself
9
+ // (terrain colliders survive a load because the terrain is the same; pass valid when your result belongs to state a load replaces).
10
+ // So sync, async, delayed or out-of-order returns all give the same gameplay state at the same tick for the same input. Fixed steps do not run while frozen, so due time stops too.
11
+ // Requests registered during loading (before engine.ready): start() calls rebase() when done and timing restarts from the playable moment (load time varies by machine and must not count); lag 0 takes effect right then.
12
+ // Results that only affect visuals (model upload, far scenery, particles) need not go through here; show them when ready.
13
+ const STRINGS = { noFallback: 'commits.request() needs a fallback: it is computed on the main thread when due and the result is not ready (so the outcome never depends on machine speed); pass fallback: () => ...' };
14
+
15
+ /**
16
+ * engine.commits: background results that affect gameplay take effect on a fixed-step tick decided at request time, in a stable order; if not finished when due, the fallback is computed on the main thread.
17
+ * Sync, async, delayed and out-of-order returns give the same gameplay state at the same tick for the same input. Results that only affect visuals need not go through here.
18
+ */
19
+ import { codedError } from './errorHints.js';
20
+
21
+ export class Commits {
22
+ /** @internal */
23
+ constructor(engine) {
24
+ /** @internal */ this.engine = engine;
25
+ /** Default delay (fixed steps); 30 = 0.5 s */
26
+ this.lag = 30;
27
+ /** @internal sorted by due, then seq */ this.queue = [];
28
+ /** @internal */ this._seq = 0;
29
+ /** @internal bumped by invalidate (save load, level change); requests without valid from an older epoch are dropped */ this.epoch = 0;
30
+ /** Totals: applied, fallbacks used because not finished when due, dropped because valid() was false */
31
+ this.stats = { applied: 0, late: 0, dropped: 0 };
32
+ }
33
+ /** Number of requests not yet applied @returns {number} */
34
+ get pending() { return this.queue.length; }
35
+ /**
36
+ * Register a request: resolve(result) when the background work finishes, remove() if no longer wanted. apply changes gameplay state with the result; fallback computes the same result on the main thread (required); valid says whether it is still wanted when due
37
+ * @template [T=any]
38
+ * @param {{ apply: (result: T) => void, fallback: () => T, valid?: (() => boolean) | null, lag?: number }} opts
39
+ * @returns {{ due: number, resolve: (result: T) => void, remove: () => void }}
40
+ * @example const t = engine.commits.request({ apply: r => { state.path = r; }, fallback: () => computePath() });
41
+ * pathWorker.then(r => t.resolve(r));
42
+ */
43
+ request(opts) {
44
+ const { apply, fallback, valid = null, lag = this.lag } = opts;
45
+ if (typeof fallback !== 'function') throw codedError('commit-fallback', STRINGS.noFallback);
46
+ const t = { due: this.engine.tick + Math.max(1, lag), lag, seq: this._seq++, apply, fallback, valid, epoch: this.epoch, done: false, result: undefined, canceled: false };
47
+ this._insert(t);
48
+ const remove = () => { t.canceled = true; };
49
+ return { due: t.due, resolve: r => { if (!t.done) { t.done = true; t.result = r; } }, remove };
50
+ }
51
+ /** @internal */
52
+ _insert(t) {
53
+ let i = this.queue.length;
54
+ while (i > 0 && (this.queue[i - 1].due > t.due || (this.queue[i - 1].due === t.due && this.queue[i - 1].seq > t.seq))) i--;
55
+ this.queue.splice(i, 0, t);
56
+ }
57
+ /** @internal Called by the engine at the start of each fixed step: due requests take effect in order */
58
+ tick(now) {
59
+ while (this.queue.length && this.queue[0].due <= now) {
60
+ const t = this.queue.shift();
61
+ if (t.canceled || (t.valid ? !t.valid() : t.epoch !== this.epoch)) { this.stats.dropped++; continue; }
62
+ if (!t.done) { t.result = t.fallback(); t.done = true; this.stats.late++; }
63
+ t.apply(t.result);
64
+ this.stats.applied++;
65
+ }
66
+ }
67
+ /** @internal Called when start() finishes loading: pending requests restart timing from now (due = now + lag); lag 0 takes effect immediately */
68
+ rebase() {
69
+ const now = this.engine.tick, list = this.queue.splice(0);
70
+ for (const t of list) { t.due = now + t.lag; this._insert(t); }
71
+ this.tick(now);
72
+ }
73
+ /** @internal Drop all requests (engine.dispose calls it) */
74
+ dispose() { this.queue.length = 0; }
75
+ /** @internal A save load or level change replaced the world: results requested for the old one must not land on the new one (counted as dropped) */
76
+ invalidate() { this.epoch++; }
77
+ }
@@ -0,0 +1,143 @@
1
+ // engine.debug: diagnostic overrides with an owner ("show me this without X") and the diagnostic view modes. They change only what the screen shows,
2
+ // never the game state or a save, and describe().scene.overrides lists them so an AI knows the picture is not the real state. Why an owner: a tool
3
+ // (view mode, probe, AI session) removes everything it set with one clear(owner), whatever it forgot to remove(); a tool never touches another owner's.
4
+ // Generic on purpose: a patch is { visible?, material?, apply? }, and apply(obj) -> undo covers any other look (the view modes in debugView.js use it).
5
+ // All of engine.debug is core (it works without the debug panel); the F3 panel module only adds engine.debug.panel next to it (composition).
6
+ // One chain: every material / visibility change, from override() and from a view, is an entry in this._l. Removing any entry undoes the whole chain
7
+ // in reverse and re-applies the rest in order, so a view and an override on the same mesh can never restore each other's stale material, and nothing
8
+ // here disposes a material it did not create (stand-ins are cached on the original, so the original is never touched).
9
+ import { codedError } from './errorHints.js';
10
+ import { DebugView } from './debugView.js';
11
+
12
+ const KEYS = ['visible', 'material', 'apply'];
13
+ const MATERIALS = ['flat', 'wire'];
14
+
15
+ /** Drawable parts under obj (obj itself included) */
16
+ function meshes(obj) { const out = []; obj.traverse(o => { if (o.isMesh || o.isPoints || o.isLine) out.push(o); }); return out; }
17
+ const patchInfo = p => ({ ...p, ...(p.apply && { apply: 'function' }) });
18
+
19
+ export class DebugOverrides {
20
+ /** @internal */
21
+ constructor(e) {
22
+ /** @internal */ this.e = e;
23
+ /** @internal the override chain, in apply order */ this._l = [];
24
+ /** @internal */ this._view = new DebugView(e, this);
25
+ /** The F3 debug panel (the debug() module), or null when it is not installed @type {any} */
26
+ this.panel = null;
27
+ // a load can replace the objects a thing id names: an override still holding the old object would show on nothing and lie in describe
28
+ e.events?.on?.('save:loaded', () => this._prune());
29
+ }
30
+ /**
31
+ * Diagnostic view: 'albedo' | 'lighting' | 'shadow' | 'normals' to look at one part of the render, 'off' to restore. Temporary and owner-scoped; never saved
32
+ * (describe().render says which view is active, so it is not mistaken for the real look). While one owner's view is on, another owner can neither switch it
33
+ * nor turn it off without force: true; engine.debug.clear(owner) turns that owner's view off too.
34
+ * @example engine.debug.view('normals'); // look at the screenshot, then engine.debug.view('off')
35
+ * @param {'albedo' | 'lighting' | 'shadow' | 'normals' | 'off'} mode @param {{ owner?: string, force?: boolean }} [opts]
36
+ * @returns {{ mode: string, owner: string | null, what?: string, note?: string }}
37
+ */
38
+ view(mode, opts) { return this._view.set(mode, opts); }
39
+ /** The active view ({ mode: 'off', owner: null } when none) @returns {{ mode: string, owner: string | null, what?: string }} */
40
+ viewState() { return this._view.state(); }
41
+
42
+ /**
43
+ * Change how an object looks for diagnosis, owned by `owner`. Returns { remove() }. Never saved, never part of the game state; listed in
44
+ * describe().scene.overrides while active. A thing id is remembered as the id: when that thing is removed, or a load replaces it, the override is dropped.
45
+ * @param {string} owner who sets it (a tool or session name); engine.debug.clear(owner) removes all of that owner's overrides
46
+ * @param {string | import('three').Object3D} target a thing id (engine.thing), an object name or any Object3D, or a look part id ('look.tone'): then patch is that part's set() values, written on its debug layer above every game owner
47
+ * @param {{ visible?: boolean, material?: 'flat' | 'wire', apply?: (obj: any) => (() => void) | void }} patch flat = unlit base colour, wire = wireframe, apply = your own change (return its undo)
48
+ * @example const h = engine.debug.override('ai-session', 'windmill', { material: 'flat' }); h.remove(); // or engine.debug.clear('ai-session')
49
+ */
50
+ override(owner, target, patch) {
51
+ if (!owner || typeof owner !== 'string') throw codedError('debug-override', "engine.debug.override(owner, target, patch): owner is a non-empty string naming who sets it, e.g. 'ai-session', so engine.debug.clear(owner) can remove it");
52
+ if (typeof target === 'string' && target.startsWith('look.')) return this._look(owner, target, patch);
53
+ for (const k of Object.keys(patch ?? {})) if (!KEYS.includes(k)) throw codedError('debug-override', `engine.debug.override: unknown field '${k}'. Fields: ${KEYS.join(', ')}, e.g. { visible: false } or { material: 'flat' }`);
54
+ if (patch.material !== undefined && !MATERIALS.includes(patch.material)) throw codedError('debug-override', `engine.debug.override: material must be ${MATERIALS.map(m => `'${m}'`).join(' or ')} (unlit base colour / wireframe), got ${JSON.stringify(patch.material)}`);
55
+ const byId = typeof target === 'string';
56
+ const obj = /** @type {any} */ (target)?.isObject3D ? target : this.e.thing(target).object;
57
+ const id = byId ? target : this.e._things.entryOf(obj)?.[0].id ?? (obj.name || obj.type);
58
+ return this._add({ owner, id, byId, obj, patch: { ...patch }, undo: null });
59
+ }
60
+ /**
61
+ * Remove every override of one owner (nothing else), its look-part debug values and its view; returns how many were removed
62
+ * @param {string} owner
63
+ */
64
+ clear(owner) {
65
+ const mine = this._l.filter(o => o.owner === owner && !o.view);
66
+ if (mine.length) this._rebuild(() => { this._l = this._l.filter(o => !mine.includes(o)); });
67
+ let looks = 0;
68
+ for (const p of Object.values(this.e.look ?? {})) if (p._owners.debug.has(owner)) { p._drop('debug', owner); looks++; }
69
+ const view = this._view.releaseOwner(owner) ? 1 : 0;
70
+ return mine.length + looks + view;
71
+ }
72
+ /** Active overrides as plain data (describe().scene.overrides) */
73
+ overrides() {
74
+ this._prune();
75
+ const looks = Object.values(this.e.look ?? {}).flatMap(p => [...p._owners.debug].map(([owner, r]) => ({ owner, target: p.id, ...Object.fromEntries(r.values) })));
76
+ return [...this._l.filter(o => !o.view).map(o => ({ owner: o.owner, target: o.id, ...patchInfo(o.patch) })), ...looks];
77
+ }
78
+ /** A look part's debug layer (look/part.js): same validation as set(), describe().look tags the keys 'debug:<owner>' */
79
+ _look(owner, id, values) {
80
+ const p = this.e.look?.[id.slice(5)];
81
+ if (!p) throw codedError('debug-override', `engine.debug.override: no look part '${id}'; parts: ${Object.keys(this.e.look ?? {}).map(k => 'look.' + k).join(', ') || 'none'}`);
82
+ return p._setOn('debug', owner, values ?? {}); // one path with set(): normalize, flatten, check (look/part.js, review M8)
83
+ }
84
+ /** Active overrides on one object, for engine.thing(id).explain() */
85
+ overridesOn(obj) { this._prune(); return this._l.filter(o => o.obj === obj && !o.view).map(o => ({ owner: o.owner, ...patchInfo(o.patch) })); }
86
+ /** Undo everything, drop / restore what the views put back, re-apply */
87
+ dispose() { this._rebuild(() => { this._l = []; }); this._view.active = null; }
88
+
89
+ /** @internal Add one entry at the end of the chain: applied all-or-nothing, pushed only once it applied */
90
+ _add(o) {
91
+ this._apply(o); // throws with nothing left changed (see _apply)
92
+ this._l.push(o);
93
+ return { remove: () => this._drop(o) };
94
+ }
95
+ /** @internal */
96
+ _drop(o) { if (this._l.includes(o)) this._rebuild(() => { this._l = this._l.filter(x => x !== o); }); }
97
+ /** @internal Undo the whole chain newest first, change the list, re-apply in order: no entry ever restores a value another entry set after it */
98
+ _rebuild(change) {
99
+ for (const x of [...this._l].reverse()) { x.undo?.(); x.undo = null; }
100
+ change();
101
+ const keep = [];
102
+ for (const x of this._l) { try { this._apply(x); keep.push(x); } catch { /* an apply that throws now (its object was disposed) is dropped */ } }
103
+ this._l = keep;
104
+ }
105
+ /** @internal Drop overrides set by thing id whose thing is gone: removed (detached from the scene) or the id now names another object (a load rebuilt it) */
106
+ _prune() {
107
+ const live = id => this.e._things?.live?.(id);
108
+ const gone = this._l.filter(o => o.byId && (!inScene(o.obj, this.e.scene) || (live(o.id) ?? o.obj) !== o.obj));
109
+ if (gone.length) this._rebuild(() => { this._l = this._l.filter(o => !gone.includes(o)); });
110
+ }
111
+ /** @internal Apply one entry; when a step throws, the steps already done are undone before the error goes on (all-or-nothing) */
112
+ _apply(o) {
113
+ const { patch, obj } = o, undos = [];
114
+ const undo = () => { for (const u of undos.reverse()) u(); };
115
+ try {
116
+ if (patch.visible !== undefined) { const was = obj.visible; obj.visible = patch.visible; undos.push(() => { obj.visible = was; }); }
117
+ if (patch.material) {
118
+ for (const m of meshes(obj)) {
119
+ const was = m.material;
120
+ if (!was) continue;
121
+ m.material = Array.isArray(was) ? was.map(x => this._stand(x, patch.material)) : this._stand(was, patch.material);
122
+ undos.push(() => { m.material = was; });
123
+ }
124
+ }
125
+ if (patch.apply) { const u = patch.apply(obj); if (typeof u === 'function') undos.push(u); }
126
+ } catch (err) { undo(); throw err; }
127
+ o.undo = undo;
128
+ }
129
+ /** @internal One cached unlit stand-in per material and kind, kept on the original's userData (we created it; the original is never disposed here) */
130
+ _stand(m, kind) {
131
+ if (m.userData._dbgOf) m = m.userData._dbgOf; // already a stand-in (a view under an override): derive from the original, never stack copies
132
+ const cache = m.userData._dbg ??= {};
133
+ if (cache[kind]) return cache[kind];
134
+ // a plain material on purpose: a diagnostic stand-in must not depend on the style pack it is diagnosing (rule 1 allows dev-only debug overlays)
135
+ const s = new this.e.THREE.MeshBasicMaterial({ color: m.color ?? 0xffffff, map: m.map ?? null, alphaMap: m.alphaMap ?? null, vertexColors: !!m.vertexColors,
136
+ transparent: !!m.transparent, opacity: m.opacity ?? 1, side: m.side, alphaTest: m.alphaTest ?? 0, wireframe: kind === 'wire', fog: false });
137
+ s.name = `debug:${kind}:${m.name || ''}`; s.userData._dbgOf = m;
138
+ return cache[kind] = s;
139
+ }
140
+ }
141
+
142
+ /** True while obj hangs under the scene (a removed thing is detached) */
143
+ function inScene(obj, scene) { for (let o = obj; o; o = o.parent) if (o === scene) return true; return !scene; }