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/Stream.js ADDED
@@ -0,0 +1,279 @@
1
+ // Spatial stream-in, engine.stream: entries are only registered, not built at once; build is called only near a full-detail stream source (the player, the
2
+ // camera focus, a teleport destination)
3
+ // and the result unloads when far from all of them. Ten thousand entries build only the nearby ones.
4
+ // const h = engine.stream.add({ position: [40, 0, -20], radius: 8, build: () => makeHouse() }); // the object build returns is added to the scene automatically
5
+ // engine.stream.setRadius(200); // how far from each stream source to build (meters); defaults to the terrain view distance, or the fog distance engine.fogFar
6
+ // without terrain
7
+ // h.remove(); // no longer needed (a built one is unloaded)
8
+ // Stream sources (stream.player, stream.camera, stream.source(...), stream.teleport(...)) are the one list every distance-based loader reads: stream entries,
9
+ // world models, terrain chunks, hlod and rigid colliders (the Source class is in streamSources.js).
10
+ // build runs in engine.jobs spread over frames (nearest first); when build returns an object synchronously it is attached to the scene on the spot inside that
11
+ // job (built / ready are already correct when engine.step returns),
12
+ // and a returned Promise is awaited before attaching. Unloads only beyond radius x unloadFactor (walking back and forth does not rebuild); keep: true never
13
+ // unloads.
14
+ // At startup start() waits for everything registered within radius to finish building before the loading screen goes away. The grid cell size cellSize is
15
+ // shared with hlod.
16
+ /** @import { StreamEntryOptions, StreamHandle, StreamSource, StreamSourceOptions } from '../types/core' */
17
+ import { checkOptions } from './validate.js';
18
+ import { xzOf } from './math.js';
19
+ import { reportError } from './errors.js';
20
+ import { codedError } from './errorHints.js';
21
+ import { Source, SOURCE_KEYS, SOURCE_STRINGS } from './streamSources.js';
22
+
23
+ const KEYS = ['position', 'radius', 'build', 'dispose', 'keep', 'priority'];
24
+ const FULL = { detail: 'full' };
25
+
26
+ /** engine.stream builds on demand by space: only entries near the focus get built. */
27
+ export class Stream {
28
+ /** @internal */
29
+ constructor(engine) {
30
+ /** @internal */ this.engine = engine;
31
+ /**
32
+ * Build radius in meters around each full-detail stream source (a source radius caps it); null = follow the terrain view distance (the fog distance
33
+ * engine.fogFar without terrain) @type {number | null}
34
+ */
35
+ this.radius = null;
36
+ /** Grid cell edge in meters, shared with hlod, default 64 */
37
+ this.cellSize = 64;
38
+ /** Unload only beyond radius x this (walking back and forth does not rebuild), default 1.25 */
39
+ this.unloadFactor = 1.25;
40
+ /** @internal */ this.entries = new Set();
41
+ /** @internal 'cx,cz' -> Set<handle> */ this.cells = new Map();
42
+ /** @internal Handles that are built or queued */ this.live = new Set();
43
+ /** @internal Number of queued builds */ this.queued = 0;
44
+ /** @internal */ this._cs = this.cellSize;
45
+ /** @internal Largest radius among entries (recomputed when the largest is removed) */ this._maxRadius = 0;
46
+ /** @internal */ this._radiusDirty = false;
47
+ /** @internal what the sources looked like at the last check */ this._memo = {};
48
+ /** @internal */ this._dirty = true;
49
+ /** @internal */ this._sources = new Set();
50
+ /** @internal Bumps when a source is added, removed or moved with at() */ this._version = 0;
51
+ /** @internal name -> (source) => boolean */ this._checks = new Map();
52
+ /** Built-in source at the gameplay anchor (world.anchor, else the player, else engine.focus): full detail and physics @type {StreamSource} */
53
+ this.player = this.source(() => engine.player?.position ?? engine.focus, { name: 'player' });
54
+ /** Built-in source at the camera focus engine.focus: full detail, no physics @type {StreamSource} */
55
+ this.camera = this.source(engine.focus, { name: 'camera', physics: false });
56
+ this.readyCheck('stream', s => s.detail !== 'full' || this.ready);
57
+ }
58
+ /** The build radius actually in use, in meters @returns {number} */
59
+ get activeRadius() {
60
+ return this.radius ?? this.engine.ground.viewRange?.() ?? this.engine.fogFar; // the ground's view range (terrain sets it), else the fog distance
61
+ }
62
+ /** @internal Key 'cx,cz' of the cell containing (x, z) (hlod shares the same grid) @param {number} x @param {number} z @returns {string} */
63
+ cellKey(x, z) { return Math.floor(x / this.cellSize) + ',' + Math.floor(z / this.cellSize); }
64
+
65
+ /**
66
+ * Register something to stream in (not built at once); an object returned by build with no parent is added to the scene automatically.
67
+ * @param {StreamEntryOptions} def
68
+ * @returns {StreamHandle}
69
+ * @example engine.stream.add({ position: [40, 0, 12], radius: 6, build: () => makeHouse() });
70
+ */
71
+ add(def) {
72
+ checkOptions('stream.add()', def, KEYS);
73
+ const [x, z] = xzOf(def.position);
74
+ /** @type {any} */
75
+ const h = { def, x, z, object: null, built: false, want: false, cell: null, remove: () => this._remove(h) };
76
+ this.entries.add(h);
77
+ this._insert(h);
78
+ this._maxRadius = Math.max(this._maxRadius, def.radius ?? 0);
79
+ this._dirty = true;
80
+ return h;
81
+ }
82
+ /** @internal Clear all entries and drop added sources (called by engine.dispose; built objects are released with the scene; the two built-in sources stay) */
83
+ dispose() {
84
+ this.entries.clear(); this.cells.clear(); this.live.clear(); this.queued = 0;
85
+ for (const s of [...this._sources]) if (s !== this.player && s !== this.camera) s.remove();
86
+ this._checks.clear();
87
+ }
88
+ /** Set the build radius in meters @param {number} m */
89
+ setRadius(m) { this.radius = m; this._dirty = true; }
90
+ /** Everything registered within radius is built (start() waits for it before the loading screen goes away) @returns {boolean} */
91
+ get ready() { return this.queued === 0; }
92
+ /** entries is the registered count, built the built count, queued the queued count @returns {{ entries: number, built: number, queued: number }} */
93
+ get stats() { return { entries: this.entries.size, built: this.live.size - this.queued, queued: this.queued }; }
94
+
95
+ /**
96
+ * Add a stream source: the world around position is loaded (terrain chunks, colliders, nearby models, stream entries) until remove() or until.
97
+ * position may be live (an Object3D or Vector3 that moves) or a function. detail 'simple' loads only terrain and hlod proxies (a far view);
98
+ * physics defaults to true for 'full'; pass false for a camera that only needs a picture. radius caps every loader's range (default: each loader's own
99
+ * range).
100
+ * until: a Promise (removed when it settles) or a function checked every frame (removed when it returns true).
101
+ * @example const dest = engine.stream.source([800, 0, 300], { radius: 64 }); await dest.whenReady; engine.player.placeAt([800, 0, 300]); dest.remove();
102
+ * @example engine.stream.source(photoCam, { physics: false, until: () => !photoMode.active }); // follows a camera, no colliders
103
+ * @param {any} position
104
+ * @param {StreamSourceOptions} [opts]
105
+ * @returns {StreamSource}
106
+ * @experimental
107
+ */
108
+ source(position, opts = {}) {
109
+ checkOptions('stream.source()', opts, SOURCE_KEYS);
110
+ if (opts.detail != null && opts.detail !== 'full' && opts.detail !== 'simple') throw codedError('stream-option', SOURCE_STRINGS.detail.replace('{got}', JSON.stringify(opts.detail)));
111
+ const s = new Source(this, position, opts);
112
+ this._sources.add(s); this._version++;
113
+ return /** @type {any} */ (s);
114
+ }
115
+
116
+ /**
117
+ * Load the destination first, then move: resolves after the player (engine.focus without one) is placed. Until the destination is ready
118
+ * (terrain chunks, collision, nearby models) the player stays where it is. move replaces the default placement (for a vehicle or a custom character).
119
+ * timeout (seconds of frame time, default 60; Infinity waits forever): when the destination is still not ready, the Promise rejects (code stream-timeout,
120
+ * naming the loaders still waiting) and the player is not moved.
121
+ * @example await engine.stream.teleport([800, 0, 300]);
122
+ * @example await engine.stream.teleport(door.target, { radius: 40, move: p => engine.player.placeAt(p) });
123
+ * @param {any} position
124
+ * @param {{ radius?: number, move?: (position: any) => void, timeout?: number }} [opts]
125
+ * @returns {Promise<void>}
126
+ * @experimental
127
+ */
128
+ async teleport(position, opts = {}) {
129
+ checkOptions('stream.teleport()', opts, ['radius', 'move', 'timeout']);
130
+ const e = this.engine, s = this.source(position, { radius: opts.radius ?? 64, name: 'teleport' }), limit = opts.timeout ?? 60;
131
+ let waited = 0;
132
+ const watch = e.onFrame(dt => {
133
+ if ((waited += dt) <= limit || s.ready) return;
134
+ const checks = [...this._checks].filter(([, fn]) => !fn(s)).map(([n]) => n).join(', ') || 'one more frame';
135
+ s._settle(codedError('stream-timeout', SOURCE_STRINGS.timeout.replace('{x}', s.x.toFixed(1)).replace('{z}', s.z.toFixed(1)).replace('{t}', String(limit)).replace('{checks}', checks)));
136
+ });
137
+ try {
138
+ await s.whenReady;
139
+ if (opts.move) opts.move(position);
140
+ else if (e.player) e.player.placeAt(position);
141
+ else { const [x, z] = xzOf(position); e.focus.set(x, e.surface(x, z), z); }
142
+ } finally { watch.remove(); s.remove(); } // the player (or camera) source covers the place from now on
143
+ }
144
+
145
+ /**
146
+ * Register a readiness check for loaders: fn(source) returns whether this loader finished what that source asks for.
147
+ * For module authors whose loader reads stream sources; games only read source.ready.
148
+ * @example engine.stream.readyCheck('props', s => s.detail !== 'full' || props.queued === 0)
149
+ * @param {string} name
150
+ * @param {(source: StreamSource) => boolean} fn
151
+ * @returns {{ remove(): void }}
152
+ * @experimental
153
+ */
154
+ readyCheck(name, fn) { this._checks.set(name, fn); return { remove: () => { if (this._checks.get(name) === fn) this._checks.delete(name); } }; }
155
+
156
+ /**
157
+ * Sources with fresh positions, filtered: { detail: 'full' } for models and stream entries, { physics: true } for colliders, no filter for terrain
158
+ * @param {{ detail?: 'full' | 'simple', physics?: boolean }} [pick]
159
+ * @returns {StreamSource[]}
160
+ * @experimental
161
+ */
162
+ sources(pick) {
163
+ const out = [];
164
+ for (const s of this._sources) {
165
+ if (pick?.detail && s.detail !== pick.detail) continue;
166
+ if (pick?.physics != null && s.physics !== pick.physics) continue;
167
+ out.push(s.sync());
168
+ }
169
+ return /** @type {any} */ (out);
170
+ }
171
+ /**
172
+ * @internal For loaders that skip work while nothing moves: true when the picked sources were added / removed or one moved more than eps since the last
173
+ * marked call.
174
+ * memo is the loader's own object; mark false only peeks (for a ready getter).
175
+ */
176
+ changed(memo, eps, pick, mark = true) {
177
+ let diff = memo.v !== this._version || !memo.at, i = 0;
178
+ if (!diff) for (const s of this._sources) { // walks the sources in place: no array while nothing moved (every loader asks every frame)
179
+ if ((pick?.detail && s.detail !== pick.detail) || (pick?.physics != null && s.physics !== pick.physics)) continue;
180
+ const a = memo.at[i++]; s.sync();
181
+ if (!a || (s.x - a.x) ** 2 + (s.z - a.z) ** 2 > eps * eps) { diff = true; break; }
182
+ }
183
+ if (!diff && i !== memo.at.length) diff = true;
184
+ if (diff && mark) { memo.v = this._version; memo.at = this.sources(pick).map(s => ({ x: s.x, z: s.z, s })); }
185
+ return diff;
186
+ }
187
+
188
+ /** @internal End of every frame (after loaders ran): until, readiness, whenReady. A source counts only after one full frame, so every loader has seen it. */
189
+ _settle() {
190
+ // snapshot because remove() / waiter callbacks change the set; the array is reused (this runs every frame), taken out while in use for re-entrancy
191
+ const snap = this._snap || [];
192
+ this._snap = null; snap.length = 0;
193
+ for (const s of this._sources) snap.push(s);
194
+ for (let i = 0; i < snap.length; i++) {
195
+ const s = snap[i];
196
+ if (typeof s.until === 'function' && s.until()) { s.remove(); continue; }
197
+ if (s.age++ < 1) continue;
198
+ s.sync();
199
+ let ok = true;
200
+ for (const fn of this._checks.values()) if (!fn(s)) { ok = false; break; }
201
+ s._ready = ok;
202
+ if (ok && s._waiters.length) s._settle(null);
203
+ }
204
+ snap.length = 0; this._snap = snap;
205
+ }
206
+ /** @internal */
207
+ _insert(h) {
208
+ h.cell = this.cellKey(h.x, h.z);
209
+ let s = this.cells.get(h.cell); if (!s) this.cells.set(h.cell, s = new Set());
210
+ s.add(h);
211
+ }
212
+ /** @internal */
213
+ _remove(h) {
214
+ if (!this.entries.delete(h)) return;
215
+ this.cells.get(h.cell)?.delete(h);
216
+ if ((h.def.radius ?? 0) >= this._maxRadius) this._radiusDirty = true;
217
+ this._unload(h);
218
+ }
219
+
220
+ /** @internal Called by the engine each frame (after the frame hooks, before jobs). Skips re-checking while no stream source moved more than 1/8 of a cell. */
221
+ _update() {
222
+ if (this._cs !== this.cellSize) { this._cs = this.cellSize; this.cells.clear(); for (const h of this.entries) this._insert(h); this._dirty = true; }
223
+ if (!this.entries.size) return;
224
+ if (this._radiusDirty) {
225
+ this._radiusDirty = false; this._maxRadius = 0;
226
+ for (const h of this.entries) this._maxRadius = Math.max(this._maxRadius, h.def.radius ?? 0);
227
+ }
228
+ const cs = this.cellSize;
229
+ if (!this.changed(this._memo, cs / 8, FULL) && !this._dirty) return;
230
+ this._dirty = false;
231
+ // full-detail sources only: a 'simple' source (far view) gets terrain and hlod proxies, not props
232
+ const src = this.sources(FULL), R = this.activeRadius;
233
+ // distance past each source's reach, shifted so it compares against R (a source radius below R shrinks its reach)
234
+ const dist = h => { let d = Infinity; for (const s of src) d = Math.min(d, Math.hypot(h.x - s.x, h.z - s.z) - (h.def.radius ?? 0) - s.reach(R) + R); return d; };
235
+ // unload what is far from every source
236
+ for (const h of this.live) if (!h.def.keep && dist(h) > R * this.unloadFactor) this._unload(h);
237
+ // build what is near: look only at cells within each source's reach
238
+ for (const s of src) {
239
+ const r = s.reach(R), n = Math.ceil((r + this._maxRadius) / cs), cx = Math.floor(s.x / cs), cz = Math.floor(s.z / cs);
240
+ for (let i = -n; i <= n; i++) for (let j = -n; j <= n; j++) {
241
+ const cell = this.cells.get((cx + i) + ',' + (cz + j)); if (!cell) continue;
242
+ for (const h of cell) if (!h.want) { const d = dist(h); if (d < R) this._build(h, d / R); }
243
+ }
244
+ }
245
+ }
246
+
247
+ /** @internal */
248
+ _build(h, near) {
249
+ h.want = true;
250
+ if (this.live.has(h)) return; // still queued (was cancelled earlier, then came back in range)
251
+ this.live.add(h); this.queued++;
252
+ // a failed build is tried again the next time a stream source moves (want goes back to false); reported once, the game goes on without it
253
+ const fail = err => { this.queued--; this.live.delete(h); h.want = false; reportError(this.engine, err, 'stream build', { soft: true }); };
254
+ this.engine.jobs.add(() => {
255
+ if (!h.want || !this.entries.has(h)) return this._built(h, null);
256
+ const t0 = performance.now(), r = h.def.build(); // measure: the 'stream' stage of engine.budget.cost
257
+ this.engine.budget.cost.end('stream', t0);
258
+ if (r && typeof r.then === 'function') return r.then(obj => this._built(h, obj), fail);
259
+ this._built(h, r); // synchronous build: attach to the scene on the spot
260
+ }, { priority: (h.def.priority ?? 0) - near }).catch(fail);
261
+ }
262
+ /** @internal Build finished (obj null means nothing was built): discard it if no longer wanted, otherwise attach to the scene */
263
+ _built(h, obj) {
264
+ this.queued--;
265
+ if (!h.want || !this.entries.has(h)) { if (obj) this._dispose(h, obj); this.live.delete(h); return; }
266
+ h.object = obj; h.built = true;
267
+ if (obj && !obj.parent) this.engine.add(obj, { owner: 'stream' });
268
+ }
269
+ /** @internal */
270
+ _unload(h) {
271
+ h.want = false;
272
+ if (!h.built) return; // still queued: discard it when the build finishes and it is found unwanted
273
+ const obj = h.object; h.object = null; h.built = false;
274
+ this.live.delete(h);
275
+ if (obj) this._dispose(h, obj);
276
+ }
277
+ /** @internal */
278
+ _dispose(h, obj) { if (h.def.dispose) h.def.dispose(obj); else this.engine.remove(obj); }
279
+ }
@@ -0,0 +1,158 @@
1
+ // engine.threads: a small worker pool. createEngine({ threads: 'auto' | number | false }) sets how many workers each lane may use (default 'auto').
2
+ // const lane = engine.threads.lane({ create: () => new Worker(new URL('./myWorker.js', import.meta.url), { type: 'module' }), local: makeHandler });
3
+ // lane.broadcast({ type: 'init', cfg }, 'init'); // every worker (and the local handler) gets it, also workers started later
4
+ // const r = await lane.run({ type: 'job', x: 1 }); // least busy worker answers
5
+ // The worker file is two lines: import { serve } from 'threedog/worker'; serve(makeHandler()); (the worker-safe entry: serve and compilePure, no three.js or DOM)
6
+ // makeHandler() returns msg => reply, the SAME code runs on the main thread when there are no workers (threads: false, Worker unsupported, or the worker crashed),
7
+ // so callers never write a second code path. Typed arrays in a reply are transferred (no copy).
8
+ // Gameplay must not depend on when a reply arrives: hand results to engine.commits (fixed-tick effect, main-thread fallback), see Commits.js.
9
+ // Workers start lazily on the first run / broadcast, so threads: 'auto' costs nothing in a game that never uses a lane; threads: false never creates one.
10
+ // shared: true when the page is cross-origin isolated (COOP/COEP headers); then array() hands out SharedArrayBuffer-backed arrays every worker reads without a copy.
11
+ import { compilePure, pureHandler } from './threadPure.js';
12
+ import { codedError, coded } from './errorHints.js';
13
+
14
+ const STRINGS = { crashed: '[threads] a worker failed ({msg}); its lane now runs on the main thread (same code, slower)',
15
+ transfer: 'lane.run(): the worker died after this task moved its buffers (transfer), so it cannot rerun on the main thread with the same data; send it again',
16
+ bad: 'createEngine({ threads }): use \'auto\', a worker count (0 = none) or false; got {v}' };
17
+
18
+ /** Resolve the threads option to a worker count per lane. 'auto' leaves one core for the main thread, capped at 4 (more rarely helps a browser game and costs memory). */
19
+ function threadCount(v = 'auto') {
20
+ if (v === false || v === 0) return 0;
21
+ if (v === 'auto' || v === true) return Math.max(1, Math.min(4, (globalThis.navigator?.hardwareConcurrency || 2) - 1));
22
+ if (typeof v === 'number' && v >= 0) return Math.floor(v);
23
+ throw codedError('threads-option', STRINGS.bad.replace('{v}', JSON.stringify(v)));
24
+ }
25
+
26
+ /**
27
+ * One kind of worker (one script), up to engine.threads.size instances. run() goes to the least busy one; with no workers the local handler answers on a microtask.
28
+ */
29
+ class Lane {
30
+ /** @internal construct through engine.threads.lane() (the class stays in the declarations because lane() returns it) */
31
+ constructor(threads, { create, local, max = Infinity }) {
32
+ this.threads = threads; this.create = create; this.local = local;
33
+ this.max = Math.min(threads.size, max);
34
+ /** @type {{ w: Worker, busy: number }[]} */ this.workers = [];
35
+ this.handler = null; // the main-thread handler, built when first needed
36
+ this.tasks = new Map(); // id -> { msg, transfer, res, rej, slot }
37
+ this.bcast = new Map(); // key -> message, replayed to workers started later and to the local handler
38
+ this._id = 0; this._k = 0;
39
+ }
40
+ /** Workers actually running in this lane (0 = main thread) @returns {number} */
41
+ get size() { return this.workers.length; }
42
+ _start() {
43
+ if (this.workers.length || this.handler || this.max <= 0) return;
44
+ try {
45
+ for (let i = 0; i < this.max; i++) {
46
+ const slot = { w: this.create(), busy: 0 };
47
+ slot.w.onmessage = e => this._reply(slot, e.data);
48
+ slot.w.onerror = e => { e.preventDefault?.(); this._crash(e.message || 'error'); };
49
+ for (const m of this.bcast.values()) slot.w.postMessage({ id: 0, data: m });
50
+ this.workers.push(slot);
51
+ }
52
+ } catch (err) { this._crash(err.message); }
53
+ }
54
+ _reply(slot, { id, data, error }) {
55
+ const t = this.tasks.get(id); if (!t) return;
56
+ this.tasks.delete(id); slot.busy--;
57
+ if (error) t.rej(new Error(error)); else t.res(data);
58
+ }
59
+ /** A worker died: stop them all and finish every open task on the main thread (results are the same, only slower); a task that transferred buffers rejects instead (its data is gone) */
60
+ _crash(msg) {
61
+ if (!this.workers.length && this.handler) return;
62
+ console.warn(coded('threads-crash', STRINGS.crashed.replace('{msg}', msg)));
63
+ for (const s of this.workers) s.w.terminate();
64
+ this.workers = []; this.max = 0;
65
+ for (const [id, t] of this.tasks) { this.tasks.delete(id); if (t.moved) t.rej(codedError('threads-transfer', STRINGS.transfer)); else this._runLocal(t.msg).then(t.res, t.rej); }
66
+ }
67
+ _local() {
68
+ if (!this.handler) { this.handler = this.local(); for (const m of this.bcast.values()) this.handler(structuredClone(m)); }
69
+ return this.handler;
70
+ }
71
+ // The message is cloned like postMessage would, so a handler that changes its input behaves the same in both places
72
+ _runLocal(msg) { return Promise.resolve().then(() => this._local()(structuredClone(msg))); }
73
+ /**
74
+ * Send a task; resolves with the handler's reply. Typed arrays you list in transfer move to the worker (unusable here afterwards);
75
+ * if that worker then crashes, the task rejects (code threads-transfer) instead of rerunning on the main thread with emptied buffers.
76
+ * @param {any} msg plain data
77
+ * @param {Transferable[]} [transfer]
78
+ * @returns {Promise<any>}
79
+ */
80
+ run(msg, transfer) {
81
+ this._start();
82
+ if (!this.workers.length) return this._runLocal(msg);
83
+ let slot = this.workers[0];
84
+ for (const s of this.workers) if (s.busy < slot.busy) slot = s;
85
+ const id = ++this._id;
86
+ slot.busy++;
87
+ return new Promise((res, rej) => {
88
+ this.tasks.set(id, { msg, res, rej, slot, moved: !!transfer?.length });
89
+ slot.w.postMessage({ id, data: msg }, transfer || []);
90
+ });
91
+ }
92
+ /**
93
+ * Send setup data to every worker (no reply). With a key, a later broadcast of the same key replaces it for workers started afterwards.
94
+ * @param {any} msg
95
+ * @param {string} [key]
96
+ */
97
+ broadcast(msg, key = '#' + this._k++) {
98
+ this.bcast.delete(key); this.bcast.set(key, msg);
99
+ this._start();
100
+ for (const s of this.workers) s.w.postMessage({ id: 0, data: msg });
101
+ if (this.handler) this.handler(structuredClone(msg));
102
+ }
103
+ /** Stop the workers; open tasks never settle */
104
+ dispose() { for (const s of this.workers) s.w.terminate(); this.workers = []; this.tasks.clear(); this.max = 0; this.threads.lanes.delete(this); }
105
+ }
106
+
107
+ /**
108
+ * engine.threads: worker pool behind createEngine({ threads }). Lanes start their workers lazily; size 0 means everything runs on the main thread.
109
+ * @experimental
110
+ */
111
+ export class Threads {
112
+ /** @internal */
113
+ constructor(opt) {
114
+ /** Workers per lane (0 = main thread only) */
115
+ this.size = threadCount(opt);
116
+ /** True when SharedArrayBuffer can be shared with workers (page is cross-origin isolated) */
117
+ this.shared = this.size > 0 && globalThis.crossOriginIsolated === true && typeof SharedArrayBuffer === 'function';
118
+ /** @internal */ this.lanes = new Set();
119
+ /** @internal */ this._pure = null;
120
+ }
121
+ /**
122
+ * A lane of workers running one script. create must contain the literal new Worker(new URL('./file.js', import.meta.url), { type: 'module' }) so bundlers find the file.
123
+ * local builds the same handler on the main thread (used when there are no workers).
124
+ * @param {{ create: () => Worker, local: () => (msg: any) => any, max?: number }} opts
125
+ * @returns {Lane}
126
+ * @example
127
+ * const lane = engine.threads.lane({ create: () => new Worker(new URL('./chunkWorker.js', import.meta.url), { type: 'module' }), local: chunkHandler });
128
+ * lane.run({ cx: 0, cz: 0 }).then(r => engine.commits ...);
129
+ */
130
+ lane(opts) { const l = new Lane(this, opts); this.lanes.add(l); return l; }
131
+ /**
132
+ * A typed array other threads can read without a copy: on a SharedArrayBuffer when shared, else an ordinary one (postMessage then copies it).
133
+ * @template {Float32ArrayConstructor | Int32ArrayConstructor | Uint8ArrayConstructor | Uint16ArrayConstructor | Float64ArrayConstructor} T
134
+ * @param {T} Type
135
+ * @param {number} length
136
+ * @returns {InstanceType<T>}
137
+ * @example const heights = engine.threads.array(Float32Array, 256 * 256);
138
+ */
139
+ array(Type, length) {
140
+ const bytes = length * Type.BYTES_PER_ELEMENT;
141
+ return /** @type {any} */ (new Type(this.shared ? new SharedArrayBuffer(bytes) : new ArrayBuffer(bytes)));
142
+ }
143
+ /**
144
+ * Turn a self-contained function into one that can run in a worker. It is recompiled from its source text, so it sees only its parameters and globals like Math:
145
+ * a closure variable fails with a ReferenceError naming it, on the main thread too (threads on or off behave the same). Used by world.simulate(kind, { far, worker: true }).
146
+ * @param {Function} fn
147
+ * @param {string} label where it came from, used in error messages
148
+ * @returns {{ fn: Function, src: string, label: string }}
149
+ * @example const grow = engine.threads.pure((rec, dt) => { rec.growth = Math.min(1, rec.growth + dt / 600); }, "world.simulate('crop') far");
150
+ */
151
+ pure(fn, label) { return compilePure(fn, label); }
152
+ /** @internal the shared lane that runs pure functions (core/pureWorker.js) */
153
+ pureLane() {
154
+ return this._pure ??= this.lane({ create: () => new Worker(new URL('./pureWorker.js', import.meta.url), { type: 'module' }), local: pureHandler });
155
+ }
156
+ /** @internal engine.dispose calls it */
157
+ dispose() { for (const l of [...this.lanes]) l.dispose(); this._pure = null; }
158
+ }
@@ -0,0 +1,94 @@
1
+ // Reproduce a scenario in one call: engine.applyState({ time, season, weather, pos, save, wait, cutscene, state }), engine.defineState(name, params).
2
+ // In dev (or with createEngine({ urlState: true })) URL parameters are read automatically: /?time=18:30&weather=rain&pos=40,-20&cutscene=skip&wait=3&state=name
3
+ //
4
+ // Who handles which key: core handles save (saves.load), pos (player.placeAt, or sets the focus without a player) and wait (advances with engine.step);
5
+ // the rest go to the module hook applyState(e, params) (written like the describe hook): sky -> time and season, weather -> weather, timeline -> cutscene.
6
+ // Two phases, both called from start():
7
+ // early(): before modules are ready, applies save, pos, time, weather (terrain is generated directly at the new position)
8
+ // late(): after engine:ready, view (engine.views), cutscene ('skip' skips the opening cutscene), sets weather once more, advances wait seconds, aligns time again, then emits state:applied
9
+ // In a game, await engine.applyState({...}) at any time runs both phases back to back.
10
+ import { checkOptions, warnMissing } from './validate.js';
11
+ import { xzOf } from './math.js';
12
+
13
+ const KEYS = ['state', 'time', 'season', 'weather', 'pos', 'save', 'wait', 'cutscene', 'view'];
14
+
15
+ export class UrlState {
16
+ constructor(engine, { fromUrl = false } = {}) {
17
+ this.engine = engine;
18
+ this.fromUrl = fromUrl;
19
+ this.states = new Map(); // name -> params
20
+ this.pending = null; // URL parameters (used by start())
21
+ this.applied = false; // URL parameters are fully applied (npm run shot waits for it)
22
+ }
23
+ define(name, params) { this.states.set(name, params); }
24
+
25
+ /** Expand the state name, check spelling, and turn strings from the URL into numbers */
26
+ _expand(params) {
27
+ let p = { ...params };
28
+ if (p.state != null) {
29
+ const s = this.states.get(p.state);
30
+ if (!s) warnMissing('state', p.state, [...this.states.keys()]);
31
+ p = { ...s, ...p };
32
+ delete p.state;
33
+ }
34
+ checkOptions('applyState()', p, KEYS);
35
+ if (typeof p.pos === 'string') { const [x, z] = p.pos.split(',').map(Number); p.pos = { x, z }; }
36
+ if (p.wait != null) p.wait = +p.wait;
37
+ return p;
38
+ }
39
+ _hooks(p, keys) {
40
+ const part = {}; for (const k of keys) if (p[k] != null) part[k] = p[k];
41
+ if (!Object.keys(part).length) return [];
42
+ return [...this.engine.modules.values()].filter(m => m.applyState).map(m => m.applyState(this.engine, part));
43
+ }
44
+ /** Wait for modules to be ready (terrain chunks must generate after a teleport); in headless mode advance frames ourselves */
45
+ async _settle() {
46
+ const e = this.engine;
47
+ for (let i = 0; i < 600; i++) {
48
+ if (![...e.modules.values()].some(m => m.isReady && !m.isReady(e)) && e.stream.ready) return;
49
+ if (e.headless) e.step(1 / 30, { render: false, describe: false });
50
+ await new Promise(r => setTimeout(r, 16)); // main-loop: yield to the browser (background threads, Promise continuations) without advancing game time
51
+ }
52
+ }
53
+ async _early(p) {
54
+ const e = this.engine;
55
+ if (p.save != null) await e.saves.load(String(p.save));
56
+ if (p.pos) { const [x, z] = xzOf(p.pos); if (e.player) e.player.placeAt({ x, z }); else e.focus.set(x, e.surface(x, z), z); }
57
+ await Promise.all(this._hooks(p, ['time', 'season', 'weather']));
58
+ }
59
+ async _late(p) {
60
+ const e = this.engine;
61
+ await Promise.all(this._hooks(p, ['cutscene', 'weather'])); // set weather once more: the opening auto-weather or settings in engine:ready may have changed it
62
+ if (p.wait > 0) for (let s = p.wait; s > 1e-6; s -= 0.5) { // advance in small slices so Promises (the next cutscene segment) and background threads continue between them
63
+ e.step(Math.min(0.5, s), { render: false, describe: false });
64
+ await new Promise(r => setTimeout(r, 0)); // main-loop: yield to the browser (background threads, Promise continuations) without advancing game time
65
+ }
66
+ await Promise.all(this._hooks(p, ['time', 'season'])); // advancing moves time and the day, so align them last
67
+ if (p.view && e.views.list().length) e.views.show(p.view); // a page with its own ?view= (no engine.views declared) handles it itself
68
+ this.applied = true;
69
+ e.events.emit('state:applied', p);
70
+ }
71
+
72
+ /** Apply a set of parameters (usable any time in a game; both phases run back to back) */
73
+ apply(params) {
74
+ const p = this._expand(params);
75
+ this.applied = false;
76
+ // setting up a scenario is not a gameplay action: the ops guard lets its writes through until it finishes
77
+ return this.engine.ops.allow(async () => { await this._early(p); await this._settle(); await this._late(p); });
78
+ }
79
+ /** In start(), before modules are ready: read the URL parameters and apply save/pos/time/weather */
80
+ early() {
81
+ if (!this.fromUrl) return;
82
+ const q = new URLSearchParams(location.search), raw = {};
83
+ for (const k of KEYS) if (q.has(k)) raw[k] = q.get(k);
84
+ if (!Object.keys(raw).length) return;
85
+ this.pending = this._expand(raw);
86
+ return this._early(this.pending);
87
+ }
88
+ /** In start(), after engine:ready: cutscene, wait, align time again, then emit state:applied */
89
+ late() {
90
+ if (!this.pending) { this.applied = true; return; }
91
+ const p = this.pending;
92
+ return this.engine.ops.allow(async () => { await this._settle(); await this._late(p); });
93
+ }
94
+ }
package/core/Vars.js ADDED
@@ -0,0 +1,35 @@
1
+ // Story flags and counters, engine.vars (saved automatically under the save key vars):
2
+ // engine.vars.setFlag('metBaker'); engine.vars.flag('metBaker') // true
3
+ // engine.vars.bump('fish', 2); engine.vars.counter('fish') // 2
4
+ // Dialogue state.flags and quest counter/bump all point here. Writes go through the ops guard (dev): outside loading, fixed steps and ops they are reported. Loading replaces the contents in place; the flags / counters objects themselves stay the same.
5
+
6
+ import { DEV } from './validate.js';
7
+
8
+ export class Vars {
9
+ constructor(engine) {
10
+ this.engine = engine;
11
+ this.flags = {};
12
+ this.counters = {};
13
+ engine.saves.register('vars', {
14
+ atomic: true,
15
+ save: () => ({ flags: { ...this.flags }, counters: { ...this.counters } }), // copy: save data must not share objects with the live state
16
+ load: d => { this.replace(d?.flags, d?.counters); },
17
+ });
18
+ }
19
+ /** Read a flag */
20
+ flag(k) { return this.flags[k]; }
21
+ /** Set a flag (default true) */
22
+ setFlag(k, v = true) { DEV && this.engine.ops.guard('vars.setFlag'); this.flags[k] = v; }
23
+ /** Read a counter (0 if absent) */
24
+ counter(k) { return this.counters[k] ?? 0; }
25
+ /** Add n to a counter (default 1) and return the new value */
26
+ bump(k, n = 1) { DEV && this.engine.ops.guard('vars.bump'); return (this.counters[k] = this.counter(k) + n); }
27
+ /** @internal Replace wholesale (for loading and net sync); a kind passed as undefined stays unchanged */
28
+ replace(flags, counters) {
29
+ DEV && this.engine.ops.guard('vars.replace');
30
+ // same object: already it, skip (clearing first would lose the data). Own keys only, never "__proto__": a save must not swap the prototype
31
+ const set = (o, v) => { if (o === v) return; for (const k of Object.keys(o)) delete o[k]; for (const k of Object.keys(v || {})) if (k !== '__proto__') o[k] = v[k]; };
32
+ if (flags !== undefined) set(this.flags, flags);
33
+ if (counters !== undefined) set(this.counters, counters);
34
+ }
35
+ }
package/core/Views.js ADDED
@@ -0,0 +1,49 @@
1
+ // Named fixed camera views declared by the game, so a screenshot of "the same place" can be taken again after any change:
2
+ // engine.views.define('gate', { position: [10, 4, 12], target: [0, 1, 0], fov: 50 });
3
+ // engine.views.show('gate'); // or the URL ?view=gate, or `npm run shot -- -w my-game --view gate`
4
+ // A view takes over the camera with engine.takeCamera('views') (the same claim cutscenes use) until release() or the handle's remove(): a cutscene that
5
+ // held the camera before gets it back, instead of the camera going to nobody. It is a diagnostic aid, not a camera mode.
6
+ import { checkOptions, warnMissing } from './validate.js';
7
+ import { codedError, renamed } from './errorHints.js';
8
+
9
+ const vec3 = a => Array.isArray(a) && a.length === 3 && a.every(Number.isFinite);
10
+
11
+ export class Views {
12
+ /** @param {any} engine */
13
+ constructor(engine) { this.engine = engine; this.map = new Map(); this.current = null; this._cam = null; }
14
+ /**
15
+ * Declare a view. position and target are [x, y, z]; fov (degrees) is optional (the camera's own when left out). Returns { remove() } (undeclares it).
16
+ * @param {string} name @param {{ position: number[], target?: number[], fov?: number }} v
17
+ * @returns {{ remove(): void }}
18
+ */
19
+ define(name, v) {
20
+ if (v && v.pos !== undefined) renamed('viewsPos', `views.define('${name}', { pos })`);
21
+ checkOptions(`views.define('${name}')`, v, ['position', 'target', 'fov']);
22
+ if (!vec3(v.position)) throw codedError('views-define', `views.define('${name}'): position must be [x, y, z], got ${JSON.stringify(v.position)}`);
23
+ if (v.target !== undefined && !vec3(v.target)) throw codedError('views-define', `views.define('${name}'): target must be [x, y, z], got ${JSON.stringify(v.target)}`);
24
+ const rec = { position: v.position, target: v.target ?? [0, 0, 0], fov: v.fov };
25
+ this.map.set(name, rec);
26
+ return { remove: () => { if (this.map.get(name) === rec) { if (this.current === name) this.release(); this.map.delete(name); } } };
27
+ }
28
+ /** @param {string} name */
29
+ has(name) { return this.map.has(name); }
30
+ /** @returns {string[]} the declared view names */
31
+ list() { return [...this.map.keys()]; }
32
+ /**
33
+ * Put the camera on a view and keep it there (the camera rigs leave it alone) until release() or the returned handle's remove(); null for an unknown name
34
+ * @param {string} name @returns {{ remove(): void } | null}
35
+ */
36
+ show(name) {
37
+ const v = this.map.get(name);
38
+ if (!v) { warnMissing('view', name, this.list()); return null; }
39
+ const e = this.engine, c = e.camera;
40
+ this._cam = e.takeCamera('views');
41
+ c.position.fromArray(v.position); c.lookAt(...v.target);
42
+ if (v.fov != null && c.isPerspectiveCamera) { c.fov = v.fov; c.updateProjectionMatrix(); }
43
+ c.updateMatrixWorld(true);
44
+ this.current = name;
45
+ return { remove: () => { if (this.current === name) this.release(); } };
46
+ }
47
+ /** Give the camera back (to the previous holder, e.g. a running cutscene, or to the rig) */
48
+ release() { this._cam?.remove(); this._cam = null; this.current = null; }
49
+ }
package/core/actor.js ADDED
@@ -0,0 +1,23 @@
1
+ // Who acts for the local user (part of Engine, mixed into Engine.prototype). engine.actor is a world record id, default 'player'.
2
+ // Modules that ask "who is interacting / standing in a trigger zone / being guided by a marker" read engine.actorPosition() instead of engine.player,
3
+ // so a game hands control to a vehicle, another squad member or a selected unit by setting engine.actor, and ops default ctx.actor to it.
4
+
5
+ export const actorMethods = {
6
+ /**
7
+ * Where an actor is now: the player's live position for 'player' (engine.focus when there is no player), else its model or world record position.
8
+ * null when the id is unknown. Defaults to engine.actor, the one the local user controls.
9
+ * @example engine.actor = 'boat_1'; // the player boards a boat: interactions, trigger zones and markers now measure from the boat
10
+ * const p = engine.actorPosition(); // { x, y, z } of the boat
11
+ * @param {string} [id]
12
+ * @returns {{ x: number, y: number, z: number } | null}
13
+ */
14
+ actorPosition(id = this.actor) {
15
+ // without any player (builder, strategy view) the camera focus stands in for 'player'
16
+ return this._actorObject(id)?.position ?? this._things.source(id)?.get(id).position ?? (id === 'player' ? this.focus : null);
17
+ },
18
+ /** @internal The actor's three.js object right now (player root, or the world model when built); null when it has none */
19
+ _actorObject(id = this.actor) {
20
+ if (id === 'player' && this.player) return this.player.root;
21
+ return this._things.source(id)?.view?.(id) ?? null;
22
+ },
23
+ };