threedog 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (506) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +39 -2
  4. package/core/Animator.js +268 -0
  5. package/core/Assets.js +256 -0
  6. package/core/Audio.js +267 -0
  7. package/core/Baked.js +72 -0
  8. package/core/Batching.js +247 -0
  9. package/core/Budget.js +221 -0
  10. package/core/Clock.js +94 -0
  11. package/core/Commits.js +77 -0
  12. package/core/DebugOverrides.js +143 -0
  13. package/core/Describe.js +145 -0
  14. package/core/Engine.js +184 -0
  15. package/core/Events.js +153 -0
  16. package/core/I18n.js +94 -0
  17. package/core/Input.js +245 -0
  18. package/core/Inspect.js +77 -0
  19. package/core/InspectScene.js +191 -0
  20. package/core/Jobs.js +146 -0
  21. package/core/Loading.js +149 -0
  22. package/core/MaterialInfo.js +32 -0
  23. package/core/Ops.js +256 -0
  24. package/core/Random.js +52 -0
  25. package/core/Rays.js +160 -0
  26. package/core/SaveStore.js +85 -0
  27. package/core/Saves.js +254 -0
  28. package/core/Stream.js +279 -0
  29. package/core/Threads.js +158 -0
  30. package/core/UrlState.js +94 -0
  31. package/core/Vars.js +35 -0
  32. package/core/Views.js +49 -0
  33. package/core/actor.js +23 -0
  34. package/core/assetEntry.js +89 -0
  35. package/core/assetLoad.js +190 -0
  36. package/core/assetManifest.js +35 -0
  37. package/core/assetReport.js +83 -0
  38. package/core/audioRules.js +121 -0
  39. package/core/audioVoice.js +225 -0
  40. package/core/batchGroups.js +116 -0
  41. package/core/canvasBox.js +63 -0
  42. package/core/catalog.js +169 -0
  43. package/core/checks.js +67 -0
  44. package/core/claims.js +51 -0
  45. package/core/dayTime.js +15 -0
  46. package/core/debugView.js +76 -0
  47. package/core/describeRender.js +45 -0
  48. package/core/describeText.js +143 -0
  49. package/core/easing.js +34 -0
  50. package/core/errorCodes.js +205 -0
  51. package/core/errorHints.js +208 -0
  52. package/core/errors.js +40 -0
  53. package/core/events.generated.js +84 -0
  54. package/core/ground.js +102 -0
  55. package/core/holds.js +106 -0
  56. package/core/inputContext.js +69 -0
  57. package/core/inputDefaults.js +22 -0
  58. package/core/inputPad.js +35 -0
  59. package/core/inputPointer.js +48 -0
  60. package/core/inputTouch.js +48 -0
  61. package/core/lifecycle.js +69 -0
  62. package/core/lightWatch.js +56 -0
  63. package/core/look/coreParts.js +112 -0
  64. package/core/look/layers.js +136 -0
  65. package/core/look/part.js +173 -0
  66. package/core/look/report.js +79 -0
  67. package/core/look/write.js +86 -0
  68. package/core/loop.js +200 -0
  69. package/core/math.js +33 -0
  70. package/core/modules.js +196 -0
  71. package/core/movement.js +19 -0
  72. package/core/mulberry32.js +14 -0
  73. package/core/opsAtomic.js +31 -0
  74. package/core/opsCheck.js +97 -0
  75. package/core/opsFail.js +20 -0
  76. package/core/opsGuard.js +26 -0
  77. package/core/opsHistory.js +27 -0
  78. package/core/opsRun.js +77 -0
  79. package/core/page.js +78 -0
  80. package/core/params.js +132 -0
  81. package/core/pureWorker.js +5 -0
  82. package/core/renamed.js +21 -0
  83. package/core/saveApply.js +128 -0
  84. package/core/saveFiles.js +139 -0
  85. package/core/saveIds.js +53 -0
  86. package/core/saveVersions.js +97 -0
  87. package/core/scatter.js +92 -0
  88. package/core/sceneMethods.js +100 -0
  89. package/core/screenToGround.js +39 -0
  90. package/core/services.js +73 -0
  91. package/core/session.js +171 -0
  92. package/core/shadowTypes.js +15 -0
  93. package/core/skip.js +104 -0
  94. package/core/startup.js +135 -0
  95. package/core/streamCells.js +24 -0
  96. package/core/streamSources.js +73 -0
  97. package/core/styleParts.js +96 -0
  98. package/core/targeting.js +64 -0
  99. package/core/thingExplain.js +68 -0
  100. package/core/thingOps.js +168 -0
  101. package/core/things.js +212 -0
  102. package/core/threadPure.js +120 -0
  103. package/core/threadServe.js +25 -0
  104. package/core/tier.js +11 -0
  105. package/core/util.js +11 -0
  106. package/core/validate.js +204 -0
  107. package/docs/AI.md +123 -0
  108. package/docs/API.md +83 -0
  109. package/docs/CODEMAP.md +347 -0
  110. package/docs/COMMANDS.md +108 -0
  111. package/docs/CONVENTIONS.md +145 -0
  112. package/docs/PERF.md +217 -0
  113. package/docs/THREE.md +86 -0
  114. package/docs/api/ambience.md +15 -0
  115. package/docs/api/assets.md +62 -0
  116. package/docs/api/audio.md +53 -0
  117. package/docs/api/budget.md +40 -0
  118. package/docs/api/cameraRig.md +120 -0
  119. package/docs/api/characters.md +144 -0
  120. package/docs/api/clock.md +7 -0
  121. package/docs/api/collision.md +39 -0
  122. package/docs/api/content.md +64 -0
  123. package/docs/api/dialogue.md +39 -0
  124. package/docs/api/engine.md +199 -0
  125. package/docs/api/entities.md +61 -0
  126. package/docs/api/events.md +95 -0
  127. package/docs/api/flow.md +27 -0
  128. package/docs/api/grids.md +11 -0
  129. package/docs/api/ground.md +16 -0
  130. package/docs/api/hlod.md +34 -0
  131. package/docs/api/hud.md +31 -0
  132. package/docs/api/i18n.md +10 -0
  133. package/docs/api/input.md +24 -0
  134. package/docs/api/interactions.md +31 -0
  135. package/docs/api/inventory.md +66 -0
  136. package/docs/api/jobs.md +10 -0
  137. package/docs/api/level.md +41 -0
  138. package/docs/api/lightPool.md +56 -0
  139. package/docs/api/music.md +34 -0
  140. package/docs/api/nav.md +26 -0
  141. package/docs/api/net.md +14 -0
  142. package/docs/api/openWorld.md +24 -0
  143. package/docs/api/particles.md +41 -0
  144. package/docs/api/photo.md +15 -0
  145. package/docs/api/post.md +10 -0
  146. package/docs/api/quests.md +36 -0
  147. package/docs/api/rays.md +26 -0
  148. package/docs/api/rigid.md +84 -0
  149. package/docs/api/saves.md +32 -0
  150. package/docs/api/settings.md +36 -0
  151. package/docs/api/sky.md +58 -0
  152. package/docs/api/stream.md +31 -0
  153. package/docs/api/style.md +134 -0
  154. package/docs/api/terrain.md +34 -0
  155. package/docs/api/timeline.md +39 -0
  156. package/docs/api/tools.md +57 -0
  157. package/docs/api/triggers.md +56 -0
  158. package/docs/api/vars.md +9 -0
  159. package/docs/api/vegetation.md +52 -0
  160. package/docs/api/water.md +48 -0
  161. package/docs/api/weather.md +29 -0
  162. package/docs/api/world.md +30 -0
  163. package/docs/recipes/01-new-game.md +148 -0
  164. package/docs/recipes/02-npc.md +167 -0
  165. package/docs/recipes/03-items-pickups.md +158 -0
  166. package/docs/recipes/04-quests.md +83 -0
  167. package/docs/recipes/05-props-bake.md +159 -0
  168. package/docs/recipes/06-clock-events.md +117 -0
  169. package/docs/recipes/07-flow-scenes-pause.md +132 -0
  170. package/docs/recipes/08-weather-sky.md +74 -0
  171. package/docs/recipes/09-style-pack.md +234 -0
  172. package/docs/recipes/10-blender-level.md +67 -0
  173. package/docs/recipes/11-vehicles.md +55 -0
  174. package/docs/recipes/12-navmesh.md +79 -0
  175. package/docs/recipes/13-animation.md +149 -0
  176. package/docs/recipes/14-custom-module.md +91 -0
  177. package/docs/recipes/15-perf.md +78 -0
  178. package/docs/recipes/16-dev-bridge.md +180 -0
  179. package/docs/recipes/18-world.md +185 -0
  180. package/docs/recipes/19-shooting-picking.md +76 -0
  181. package/docs/recipes/20-content-actions-save.md +176 -0
  182. package/docs/recipes/21-camera.md +153 -0
  183. package/docs/recipes/22-shop-gold.md +107 -0
  184. package/docs/recipes/23-ops.md +175 -0
  185. package/docs/recipes/26-ui-parts.md +138 -0
  186. package/docs/recipes/27-net.md +96 -0
  187. package/docs/recipes/28-terrain.md +80 -0
  188. package/docs/recipes/29-grid.md +87 -0
  189. package/docs/recipes/30-templates.md +131 -0
  190. package/docs/recipes/31-audio.md +126 -0
  191. package/docs/recipes/32-action-game.md +33 -0
  192. package/docs/recipes/33-stream-sources.md +37 -0
  193. package/docs/recipes/34-environment-lighting.md +36 -0
  194. package/docs/recipes/35-style-from-reference.md +89 -0
  195. package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
  196. package/docs/recipes/37-terrain-look-hooks.md +97 -0
  197. package/docs/recipes/38-environment-look-hooks.md +83 -0
  198. package/docs/recipes/40-scene.md +108 -0
  199. package/docs/recipes/41-thing-registry.md +93 -0
  200. package/docs/recipes/42-terrain-shape.md +64 -0
  201. package/docs/recipes/43-shader-patches-surface-looks.md +120 -0
  202. package/docs/recipes/44-water-weather-look-hooks.md +135 -0
  203. package/docs/recipes/45-cascaded-shadows.md +51 -0
  204. package/docs/recipes/46-blender-art-route.md +114 -0
  205. package/docs/recipes/47-island-snow-backdrop.md +44 -0
  206. package/docs/recipes/48-make-material.md +70 -0
  207. package/docs/recipes/49-game-module-contract.md +71 -0
  208. package/docs/recipes/50-own-renderer.md +12 -0
  209. package/docs/recipes/51-capability-catalog.md +63 -0
  210. package/docs/recipes/52-look.md +108 -0
  211. package/examples/action/DESIGN.md +3 -0
  212. package/examples/action/GAMEMAP.md +127 -0
  213. package/examples/action/content/actions.js +8 -0
  214. package/examples/action/content/audio.js +9 -0
  215. package/examples/action/content/index.js +10 -0
  216. package/examples/action/content/items.js +4 -0
  217. package/examples/action/content/places.js +4 -0
  218. package/examples/action/content/props.js +11 -0
  219. package/examples/action/content/templates.js +10 -0
  220. package/examples/action/content/views.js +6 -0
  221. package/examples/action/look.js +5 -0
  222. package/examples/action/main.js +137 -0
  223. package/examples/action/models.js +25 -0
  224. package/examples/sheepisland/GAMEMAP.md +107 -0
  225. package/examples/sheepisland/content/index.js +6 -0
  226. package/examples/sheepisland/content/props.js +19 -0
  227. package/examples/sheepisland/content/templates.js +5 -0
  228. package/examples/sheepisland/content/vegetation.js +8 -0
  229. package/examples/sheepisland/main.js +71 -0
  230. package/examples/sheepisland/params.js +25 -0
  231. package/examples/sheepisland/style/index.js +79 -0
  232. package/examples/sheepisland/style/models.js +59 -0
  233. package/examples/sheepisland/views.js +9 -0
  234. package/examples/styletest/GAMEMAP.md +135 -0
  235. package/examples/styletest/content/index.js +9 -0
  236. package/examples/styletest/content/items.js +8 -0
  237. package/examples/styletest/content/npcs.js +8 -0
  238. package/examples/styletest/content/places.js +5 -0
  239. package/examples/styletest/content/props.js +16 -0
  240. package/examples/styletest/content/templates.js +9 -0
  241. package/examples/styletest/content/vegetation.js +31 -0
  242. package/examples/styletest/look.js +11 -0
  243. package/examples/styletest/main.js +95 -0
  244. package/examples/styletest/models.js +87 -0
  245. package/examples/styletest/overrides.js +33 -0
  246. package/examples/styletest/panel.js +135 -0
  247. package/examples/styletest/params.js +32 -0
  248. package/examples/styletest/views.js +31 -0
  249. package/examples/world/DESIGN.md +5 -0
  250. package/examples/world/GAMEMAP.md +171 -0
  251. package/examples/world/content/actions.js +8 -0
  252. package/examples/world/content/audio.js +25 -0
  253. package/examples/world/content/bodies.js +12 -0
  254. package/examples/world/content/containers.js +4 -0
  255. package/examples/world/content/dialogues.js +33 -0
  256. package/examples/world/content/index.js +17 -0
  257. package/examples/world/content/items.js +10 -0
  258. package/examples/world/content/npcs.js +14 -0
  259. package/examples/world/content/pickups.js +11 -0
  260. package/examples/world/content/places.js +6 -0
  261. package/examples/world/content/props.js +12 -0
  262. package/examples/world/content/quests.js +15 -0
  263. package/examples/world/content/rules.js +23 -0
  264. package/examples/world/content/templates.js +5 -0
  265. package/examples/world/content/vegetation.js +32 -0
  266. package/examples/world/main.js +168 -0
  267. package/examples/world/models.js +28 -0
  268. package/index.d.ts +306 -0
  269. package/index.js +122 -0
  270. package/llms.txt +61 -0
  271. package/modules/ambience/Ambience.js +186 -0
  272. package/modules/camera/FirstPersonCamera.js +131 -0
  273. package/modules/camera/FixedCamera.js +162 -0
  274. package/modules/camera/FollowCamera.js +91 -0
  275. package/modules/camera/RtsCamera.js +132 -0
  276. package/modules/camera/common.js +182 -0
  277. package/modules/camera/index.js +11 -0
  278. package/modules/camera/projection.js +34 -0
  279. package/modules/characters/Character.js +235 -0
  280. package/modules/characters/NPC.js +242 -0
  281. package/modules/characters/assetModel.js +42 -0
  282. package/modules/characters/astar.js +66 -0
  283. package/modules/characters/behaviors.js +72 -0
  284. package/modules/characters/footsteps.js +13 -0
  285. package/modules/characters/index.js +215 -0
  286. package/modules/characters/moveHelpers.js +29 -0
  287. package/modules/characters/movers/common.js +62 -0
  288. package/modules/characters/movers/rapier.js +74 -0
  289. package/modules/characters/movers/simple.js +43 -0
  290. package/modules/characters/npcAvoid.js +129 -0
  291. package/modules/characters/npcSim.js +150 -0
  292. package/modules/characters/npcView.js +42 -0
  293. package/modules/characters/pathAsync.js +113 -0
  294. package/modules/characters/pathJob.js +62 -0
  295. package/modules/characters/pathWorker.js +7 -0
  296. package/modules/characters/playerStrings.js +12 -0
  297. package/modules/characters/proceduralRig.js +58 -0
  298. package/modules/characters/useModel.js +22 -0
  299. package/modules/characters/walkTo.js +58 -0
  300. package/modules/collision/Collision.js +274 -0
  301. package/modules/collision/grid.js +63 -0
  302. package/modules/content/explain.js +13 -0
  303. package/modules/content/ids.js +95 -0
  304. package/modules/content/index.js +154 -0
  305. package/modules/content/loader.js +190 -0
  306. package/modules/content/models.js +69 -0
  307. package/modules/content/packs.js +69 -0
  308. package/modules/content/props.js +89 -0
  309. package/modules/content/rules.js +134 -0
  310. package/modules/content/templates.js +189 -0
  311. package/modules/debug/DebugPanel.js +174 -0
  312. package/modules/entities/Entities.js +243 -0
  313. package/modules/entities/build.js +25 -0
  314. package/modules/entities/index.js +4 -0
  315. package/modules/flow/index.js +101 -0
  316. package/modules/gameplay/Container.js +227 -0
  317. package/modules/gameplay/Containers.js +89 -0
  318. package/modules/gameplay/Dialogue.js +219 -0
  319. package/modules/gameplay/Interactions.js +253 -0
  320. package/modules/gameplay/Inventory.js +224 -0
  321. package/modules/gameplay/Quests.js +205 -0
  322. package/modules/gameplay/boxOps.js +60 -0
  323. package/modules/gameplay/dialogueBox.js +48 -0
  324. package/modules/gameplay/interactionPrompt.js +28 -0
  325. package/modules/gameplay/inventoryOps.js +137 -0
  326. package/modules/gameplay/pickups.js +115 -0
  327. package/modules/gameplay/questLog.js +54 -0
  328. package/modules/gameplay/questSave.js +71 -0
  329. package/modules/grid/Grid.js +184 -0
  330. package/modules/grid/Layer.js +142 -0
  331. package/modules/grid/index.js +236 -0
  332. package/modules/grid/ops.js +73 -0
  333. package/modules/grid/preview.js +85 -0
  334. package/modules/grid/tiles.js +79 -0
  335. package/modules/hlod/index.js +167 -0
  336. package/modules/hud/index.js +167 -0
  337. package/modules/hud/parts.js +80 -0
  338. package/modules/level/geometry.js +46 -0
  339. package/modules/level/heightfield.js +160 -0
  340. package/modules/level/index.js +233 -0
  341. package/modules/level/nodes.js +84 -0
  342. package/modules/lights/index.js +227 -0
  343. package/modules/music/Music.js +294 -0
  344. package/modules/music/index.js +2 -0
  345. package/modules/music/rules.js +28 -0
  346. package/modules/nav/index.js +156 -0
  347. package/modules/nav/navPath.js +17 -0
  348. package/modules/net/Client.js +137 -0
  349. package/modules/net/Host.js +117 -0
  350. package/modules/net/Net.js +49 -0
  351. package/modules/net/index.js +77 -0
  352. package/modules/net/sync.js +114 -0
  353. package/modules/net/transports.js +118 -0
  354. package/modules/particles/Particles.js +179 -0
  355. package/modules/particles/effect.js +112 -0
  356. package/modules/particles/shaders.js +28 -0
  357. package/modules/photo/Photo.js +146 -0
  358. package/modules/rigid/RigidBodies.js +265 -0
  359. package/modules/rigid/Vehicles.js +97 -0
  360. package/modules/rigid/sync.js +158 -0
  361. package/modules/settings/Settings.js +297 -0
  362. package/modules/settings/apply.js +21 -0
  363. package/modules/settings/index.js +3 -0
  364. package/modules/settings/sections.js +156 -0
  365. package/modules/settings/strings.js +53 -0
  366. package/modules/settings/view.js +65 -0
  367. package/modules/sky/Sky.js +259 -0
  368. package/modules/sky/calendar.js +80 -0
  369. package/modules/sky/cascades.js +125 -0
  370. package/modules/sky/clouds.js +79 -0
  371. package/modules/sky/domeLayers.js +33 -0
  372. package/modules/sky/environment.js +141 -0
  373. package/modules/sky/fog.js +139 -0
  374. package/modules/sky/frame.js +77 -0
  375. package/modules/sky/layers.js +69 -0
  376. package/modules/sky/look.js +51 -0
  377. package/modules/sky/lookFog.js +80 -0
  378. package/modules/sky/lookShadow.js +50 -0
  379. package/modules/sky/lookSky.js +108 -0
  380. package/modules/sky/schedule.js +80 -0
  381. package/modules/sky/shader.js +96 -0
  382. package/modules/sky/shadow.js +74 -0
  383. package/modules/sky/skyModule.js +60 -0
  384. package/modules/terrain/ChunkManager.js +260 -0
  385. package/modules/terrain/chunkJob.js +19 -0
  386. package/modules/terrain/chunkLevels.js +40 -0
  387. package/modules/terrain/chunkQueries.js +42 -0
  388. package/modules/terrain/chunkWorker.js +5 -0
  389. package/modules/terrain/index.js +118 -0
  390. package/modules/terrain/lookGround.js +61 -0
  391. package/modules/terrain/mountTerrain.js +32 -0
  392. package/modules/terrain/terrainColorMap.js +41 -0
  393. package/modules/terrain/terrainDefaults.js +39 -0
  394. package/modules/terrain/terrainEdit.js +139 -0
  395. package/modules/terrain/terrainGen.js +155 -0
  396. package/modules/terrain/terrainIsland.js +131 -0
  397. package/modules/terrain/terrainMesh.js +92 -0
  398. package/modules/terrain/terrainShape.js +108 -0
  399. package/modules/terrain/terrainShapeMain.js +41 -0
  400. package/modules/terrain/terrainTexture.js +44 -0
  401. package/modules/timeline/Timeline.js +253 -0
  402. package/modules/timeline/Tween.js +114 -0
  403. package/modules/timeline/letterbox.js +24 -0
  404. package/modules/timeline/shots.js +90 -0
  405. package/modules/triggers/index.js +268 -0
  406. package/modules/vegetation/Vegetation.js +256 -0
  407. package/modules/vegetation/groundChunks.js +177 -0
  408. package/modules/vegetation/index.js +43 -0
  409. package/modules/vegetation/lookWind.js +37 -0
  410. package/modules/vegetation/modelGeometry.js +21 -0
  411. package/modules/water/Water.js +160 -0
  412. package/modules/water/look.js +80 -0
  413. package/modules/water/surface.js +88 -0
  414. package/modules/weather/Weather.js +242 -0
  415. package/modules/weather/look.js +75 -0
  416. package/modules/weather/particles.js +92 -0
  417. package/modules/weather/shaders.js +49 -0
  418. package/modules/weather/strings.js +15 -0
  419. package/modules/world/World.js +231 -0
  420. package/modules/world/cells.js +42 -0
  421. package/modules/world/explain.js +11 -0
  422. package/modules/world/index.js +71 -0
  423. package/modules/world/persist.js +107 -0
  424. package/modules/world/pos.js +20 -0
  425. package/modules/world/records.js +89 -0
  426. package/modules/world/sim.js +175 -0
  427. package/modules/world/simFar.js +82 -0
  428. package/modules/world/state.js +115 -0
  429. package/modules/world/thingSource.js +44 -0
  430. package/modules/world/views.js +182 -0
  431. package/package.json +66 -4
  432. package/presets.js +96 -0
  433. package/render/PostFX.js +240 -0
  434. package/render/detail.js +105 -0
  435. package/render/effects.js +144 -0
  436. package/render/engineUniforms.js +23 -0
  437. package/render/fuse.js +84 -0
  438. package/render/lighting.js +100 -0
  439. package/render/lights.js +18 -0
  440. package/render/lookSurface.js +161 -0
  441. package/render/materials.js +220 -0
  442. package/render/patches.js +252 -0
  443. package/render/postLook.js +86 -0
  444. package/render/surface.js +69 -0
  445. package/render/uniformDecl.js +29 -0
  446. package/types/common.d.ts +34 -0
  447. package/types/core.d.ts +1965 -0
  448. package/types/gameplay.d.ts +1822 -0
  449. package/types/generated/core/Audio.d.ts +200 -0
  450. package/types/generated/core/Batching.d.ts +47 -0
  451. package/types/generated/core/Budget.d.ts +90 -0
  452. package/types/generated/core/Commits.d.ts +31 -0
  453. package/types/generated/core/DebugOverrides.d.ts +52 -0
  454. package/types/generated/core/Events.d.ts +89 -0
  455. package/types/generated/core/I18n.d.ts +30 -0
  456. package/types/generated/core/Input.d.ts +118 -0
  457. package/types/generated/core/Jobs.d.ts +41 -0
  458. package/types/generated/core/Ops.d.ts +203 -0
  459. package/types/generated/core/Random.d.ts +49 -0
  460. package/types/generated/core/Rays.d.ts +49 -0
  461. package/types/generated/core/Saves.d.ts +162 -0
  462. package/types/generated/core/Stream.d.ts +93 -0
  463. package/types/generated/core/Threads.d.ts +82 -0
  464. package/types/generated/core/Views.d.ts +33 -0
  465. package/types/generated/core/audioVoice.d.ts +47 -0
  466. package/types/generated/core/page.d.ts +18 -0
  467. package/types/generated/core/session.d.ts +48 -0
  468. package/types/generated/modules/ambience/Ambience.d.ts +48 -0
  469. package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
  470. package/types/generated/modules/flow/index.d.ts +10 -0
  471. package/types/generated/modules/grid/Grid.d.ts +151 -0
  472. package/types/generated/modules/grid/Layer.d.ts +65 -0
  473. package/types/generated/modules/grid/index.d.ts +86 -0
  474. package/types/generated/modules/hlod/index.d.ts +11 -0
  475. package/types/generated/modules/hud/index.d.ts +10 -0
  476. package/types/generated/modules/lights/index.d.ts +13 -0
  477. package/types/generated/modules/music/Music.d.ts +111 -0
  478. package/types/generated/modules/net/Net.d.ts +34 -0
  479. package/types/generated/modules/net/index.d.ts +53 -0
  480. package/types/generated/modules/net/transports.d.ts +58 -0
  481. package/types/generated/modules/particles/Particles.d.ts +69 -0
  482. package/types/generated/modules/sky/Sky.d.ts +145 -0
  483. package/types/generated/modules/sky/skyModule.d.ts +10 -0
  484. package/types/generated/modules/timeline/Timeline.d.ts +51 -0
  485. package/types/generated/modules/water/Water.d.ts +29 -0
  486. package/types/generated/modules/weather/Weather.d.ts +62 -0
  487. package/types/generated/modules/world/World.d.ts +242 -0
  488. package/types/generated/modules/world/index.d.ts +15 -0
  489. package/types/generated/render/PostFX.d.ts +125 -0
  490. package/types/generated/render/materials.d.ts +100 -0
  491. package/types/generated/render/patches.d.ts +41 -0
  492. package/types/generated/ui/Focus.d.ts +11 -0
  493. package/types/generated/ui/LoadingScreen.d.ts +2 -0
  494. package/types/generated/ui/UI.d.ts +57 -0
  495. package/types/nav.d.ts +52 -0
  496. package/types/physics.d.ts +592 -0
  497. package/types/style.d.ts +638 -0
  498. package/types/worker.d.ts +11 -0
  499. package/types/world.d.ts +772 -0
  500. package/ui/Focus.js +51 -0
  501. package/ui/LoadingScreen.js +42 -0
  502. package/ui/Parts.js +199 -0
  503. package/ui/UI.js +167 -0
  504. package/ui/defaults.js +85 -0
  505. package/ui/theme.js +124 -0
  506. package/ui/touchPart.js +49 -0
@@ -0,0 +1,135 @@
1
+ // Startup (part of Engine, mixed into Engine.prototype): start() initializes modules, preloads assets, applies scenario parameters, waits for the world to be ready, and records startup timing in engine.startup.
2
+ // Every step is a task in engine.loading, so the loading screen, describe().loading and `threedog loading` name the same current item.
3
+ // A critical asset (manifest critical: true) that fails stops start() with the reason instead of starting a broken game.
4
+
5
+ import { reportError } from './errors.js';
6
+ import { catalogSnap, catalogClaim } from './catalog.js';
7
+ import { codedError } from './errorHints.js';
8
+ import { touchStart } from './inputTouch.js';
9
+ import { Loading, failureText } from './Loading.js';
10
+
11
+ const DEV_STRINGS = {
12
+ initFailed: 'init of module {name}',
13
+ blocked: 'Startup blocked: {n} critical item(s) failed to load, the game cannot start:\n {list}',
14
+ stalled: 'Startup stalled: still waiting after {s} s for: {list}. A module\'s isReady(e) keeps returning false (or the world never finished its nearby builds); fix that module, or raise engine.loading.timeoutMs if the load is just slow',
15
+ disposed: 'engine.start() stopped: engine.dispose() was called while it was loading ({at}); a disposed engine cannot start, create a new one',
16
+ };
17
+
18
+ export const startupMethods = {
19
+ /**
20
+ * What loading is doing now: tasks with phase / error / source, view() for the summary describe().loading shows.
21
+ * @type {Loading}
22
+ * @example engine.loading.view().waiting // 'decoding model "hero" (/models/hero.glb, manifest "main")'
23
+ */
24
+ get loading() { return this._loading ||= new Loading(this); },
25
+
26
+ /** Start the game: init modules, preload, apply scenario parameters, wait until the world is ready. A second call returns the first call's Promise. */
27
+ start() { return (this._starting ??= this._start()); },
28
+
29
+ /** @internal stop when dispose() ran during an await of start() */
30
+ _alive(at) { if (this.disposed) throw codedError('engine-disposed', DEV_STRINGS.disposed.replace('{at}', at)); },
31
+
32
+ /** @internal */
33
+ async _start() {
34
+ // Dev server only (npm run dev): if main.js forgot window.engine = engine, set it so the dev bridge and console can find the engine; leave an existing one alone (including tests with several engines)
35
+ if (import.meta.env?.DEV && typeof window !== 'undefined' && !window.engine) window.engine = this;
36
+ await this.saves.whenReady; // read the save index into memory (IndexedDB is async) so saves.list / check are synchronous afterwards
37
+ this._alive('reading saves');
38
+ this._checkOptional(); // optional dependencies that affect gameplay are missing: warn once in dev (modules.js)
39
+ if (!this.headless) this._loop();
40
+ this.ui._check(); // a UI part name the game set but no module declared is a typo: fail now, not silently
41
+ touchStart(this.input); // on-screen stick / buttons are a UI part too, so they are drawn only once the parts are settled
42
+ const ls = this.ui.get('loading'), t0 = performance.now(), L = this.loading; // measure
43
+ const ms = t => Math.round(performance.now() - t); // measure
44
+ const timing = {}; // module name -> { init, ready } in ms (ready = time spent waiting for isReady)
45
+ for (const m of this.modules.values()) if (m.init) {
46
+ const task = L._begin(m.name, 'module', { critical: !!m.critical });
47
+ task.phase('build');
48
+ ls?.update({ progress: 0.1, text: this.t('common.preparing', { name: this.moduleName(m) }) });
49
+ const t = performance.now(); // measure
50
+ this._setModState(m, 'initializing'); // no hooks until init succeeded (modules.js)
51
+ const snap = catalogSnap(this); // what init registers belongs to this module in engine.catalog()
52
+ try { await m.init(this); catalogClaim(this, m.name, snap); L._done(task); this._setModState(m, 'running'); }
53
+ catch (e) {
54
+ L._fail(task, e); this._setModState(m, 'failed');
55
+ // a critical module stops start() with the reason (below); any other failure is reported by severity and start() goes on
56
+ if (!m.critical) reportError(this, e, DEV_STRINGS.initFailed.replace('{name}', m.name), { module: m });
57
+ }
58
+ if (this._fatal().length) return this._blocked(this._fatal());
59
+ timing[m.name] = { init: ms(t) };
60
+ this._alive('init of ' + m.name);
61
+ }
62
+ this._started = true; // a module installed from now on runs its init at once (modules.js)
63
+ const tp = performance.now(); // measure
64
+ const progress = p => ls?.update({ progress: 0.2 + p * 0.3, text: L.text() ?? this.t('common.loadingAssets') });
65
+ // fonts the UI look names (style.ui.fonts: asset names) load with the preload, so the first menu never flashes the fallback font;
66
+ // an unknown name rejects here with the manifest line to add
67
+ await Promise.all([this.assets.preload(progress), ...(this.style.ui?.fonts || []).map(n => this.assets.font(n))]);
68
+ const preloadMs = ms(tp), tr = performance.now(); // measure
69
+ this._alive('preloading assets');
70
+ if (this._fatal().length) return this._blocked(this._fatal());
71
+ let streamMs = null; // time until the "required nearby" builds in the stream registry finished
72
+ await this._urlState.early(); // scenario parameters: save, position, time, weather
73
+ this._alive('applying scenario parameters');
74
+ ls?.update({ progress: 0.5, text: this.t('common.generating', { name: this.t('common.world') }) });
75
+ await this._waitReady(timing, tr, ms, v => { streamMs = v; }, () => streamMs).catch(why => Array.isArray(why) ? this._blocked(why) : Promise.reject(why));
76
+ // Compile every visible material for the current lights now, behind the loading screen, instead of stalling the first frame that shows it
77
+ // (async where the browser has KHR_parallel_shader_compile). A later change in the number of lights compiles again: see recipes/09 "Lights and stalls"
78
+ const tc = performance.now(); // measure
79
+ await this.renderer.compileAsync(this.scene, this.camera);
80
+ const compileMs = ms(tc);
81
+ this._alive('compiling shaders');
82
+ this.ready = true;
83
+ this.commits.rebase(); // background results registered during loading restart timing from now (see Commits.js)
84
+ // Startup timing: totalMs from page open to playable, startMs from start() to playable
85
+ this.startup = { totalMs: Math.round(performance.now()), startMs: ms(t0), preloadMs, streamMs, compileMs, modules: timing }; // measure
86
+ this.budget.checkStartup(this.startup);
87
+ ls?.update({ progress: 1, text: '' }); ls?.hide();
88
+ this.ops.allow(() => this.events.emit('engine:ready')); // engine:ready listeners finish setting up the game; still loading for the ops guard
89
+ this.session._capture(); // the state engine.session.newGame() returns to: set up, nothing played yet
90
+ this.ui.open('title'); // the title screen, only when the game turned it on (createEngine({ ui: { title: {...} } }))
91
+ await this._urlState.late(); // scenario parameters: skip the cutscene, wait, align the time, then emit state:applied
92
+ return this;
93
+ },
94
+
95
+ /** Critical items that failed: assets, track() steps and modules declared critical: true (a non-critical module's init error goes through reportError instead) */
96
+ _fatal() { return this.loading.list({ phase: 'failed' }).filter(t => t.critical); },
97
+
98
+ /** A critical item failed: keep the loading screen up with the failure, log it (errors.log in dev) and reject start() with every reason */
99
+ _blocked(fatal) {
100
+ const err = codedError(fatal.some(t => t.kind === 'module') ? 'module-critical' : 'asset-critical', DEV_STRINGS.blocked.replace('{n}', String(fatal.length)).replace('{list}', fatal.map(failureText).join('\n ')));
101
+ this.ui.get('loading')?.update({ progress: 1, text: this.t('loading.failed', { name: fatal.map(t => t.name).join(', ') }), failed: fatal });
102
+ console.error(err.message);
103
+ throw err;
104
+ },
105
+
106
+ // Check every 20 ms and also at the end of each real-time frame (a software-rendered frame is long, so a timer alone often waits a whole extra frame)
107
+ _waitReady(timing, tr, ms, setStream, getStream) {
108
+ const ls = this.ui.get('loading');
109
+ return new Promise((res, rej) => {
110
+ let done = false;
111
+ const t0 = performance.now(); // measure: wall clock, so a module that never turns ready ends the wait instead of hanging
112
+ const check = () => {
113
+ if (done) return;
114
+ if (this.disposed) { done = true; rej(codedError('engine-disposed', DEV_STRINGS.disposed.replace('{at}', 'waiting for the world'))); return; }
115
+ // Headless mode has no real-time loop: run one frame by hand (time does not advance, jobs ignore real time) so terrain and other modules keep loading
116
+ if (this.headless) this._frameHooks(0, true);
117
+ const waiting = [...this.modules.values()].filter(m => m.isReady && !m.isReady(this));
118
+ for (const m of this.modules.values()) if (m.isReady && !waiting.includes(m) && timing[m.name]?.ready == null) (timing[m.name] ||= {}).ready = ms(tr);
119
+ if (this.stream.ready && getStream() == null) setStream(ms(tr));
120
+ const fatal = this._fatal(); // a critical step tracked by a module can fail while we wait
121
+ if (fatal.length || (!waiting.length && getStream() != null)) { done = true; this._afterTick = null; if (fatal.length) rej(fatal); else res(); return; }
122
+ if (performance.now() - t0 > this.loading.timeoutMs) { // measure
123
+ done = true; this._afterTick = null;
124
+ const who = [...waiting.map(m => m.name), ...(this.stream.ready ? [] : ['the stream (required nearby builds)'])];
125
+ rej(codedError('module-not-ready', DEV_STRINGS.stalled.replace('{s}', String(Math.round(this.loading.timeoutMs / 1000))).replace('{list}', who.join(', '))));
126
+ return;
127
+ }
128
+ ls?.update({ progress: 0.5 + 0.5 * (1 - waiting.length / this.modules.size), text: this.loading.text() ?? this.t('common.generating', { name: this.t('common.world') }) });
129
+ };
130
+ const poll = () => { check(); if (!done) setTimeout(poll, 20); }; // main-loop: poll for readiness while loading (a dispose rejects on the next check)
131
+ this._afterTick = check;
132
+ poll();
133
+ });
134
+ },
135
+ };
@@ -0,0 +1,24 @@
1
+ // Per-chunk view of stream sources for loaders that sync whole chunks (physics terrain): has any picked source crossed a chunk border since the last call.
2
+
3
+ /**
4
+ * Refresh memo (a flat array of [cx, cz, ring, ...] per picked source; chunk size `size`, ring capped at `maxRing`) in place and return true when it
5
+ * differs from the previous call. Builds no array or string while nothing crosses a border, so it can run every fixed step.
6
+ * @param {import('./Stream.js').Stream} stream
7
+ * @param {number[]} memo
8
+ * @param {number} size
9
+ * @param {number} maxRing
10
+ * @param {{ detail?: string, physics?: boolean }} [pick]
11
+ * @internal
12
+ */
13
+ export function cellsChanged(stream, memo, size, maxRing, pick) {
14
+ let n = 0, same = true;
15
+ for (const s of stream._sources) {
16
+ if ((pick?.detail && s.detail !== pick.detail) || (pick?.physics != null && s.physics !== pick.physics)) continue;
17
+ s.sync();
18
+ const cx = Math.floor(s.x / size), cz = Math.floor(s.z / size), r = Math.min(maxRing, s.radius == null ? Infinity : Math.max(1, Math.ceil(s.radius / size)));
19
+ if (memo[n] !== cx || memo[n + 1] !== cz || memo[n + 2] !== r) { same = false; memo[n] = cx; memo[n + 1] = cz; memo[n + 2] = r; }
20
+ n += 3;
21
+ }
22
+ if (memo.length !== n) { same = false; memo.length = n; }
23
+ return !same;
24
+ }
@@ -0,0 +1,73 @@
1
+ // Stream sources (internal half of engine.stream): the places the world must be loaded around (the streaming-source idea of Unreal World Partition).
2
+ // Every distance-based loader reads this list and nothing else: stream entries, world models (present), terrain chunks, hlod near/far and rigid-body terrain colliders.
3
+ // engine.stream.player built in: the gameplay anchor (world.anchor, else the player, else engine.focus); full detail + physics
4
+ // engine.stream.camera built in: engine.focus; full detail, no physics (a cutscene or photo camera far away gets a picture, not colliders)
5
+ // const s = engine.stream.source([800, 0, 300], { radius: 64 }); await s.whenReady; ... s.remove();
6
+ // await engine.stream.teleport([800, 0, 300]); // the player moves only after the destination is loaded (terrain, collision, nearby models)
7
+ // Display, physics and world data are three separate things: a source decides what is shown and what has colliders; world records are never deleted by unloading,
8
+ // and near / far simulation follows world.anchor (recipe 18). Readiness is per source: each loader registers a check with readyCheck.
9
+ import { checkOptions } from './validate.js';
10
+ import { xzOf } from './math.js';
11
+ import { codedError } from './errorHints.js';
12
+
13
+ export const SOURCE_KEYS = ['radius', 'detail', 'physics', 'until', 'name'];
14
+ export const SOURCE_STRINGS = {
15
+ detail: 'stream.source(): detail must be \'full\' (models, stream entries, physics) or \'simple\' (terrain and hlod proxies only), got {got}',
16
+ removed: 'stream source "{name}" was removed before it was ready (remove() or its until); nothing waits for it any more',
17
+ timeout: 'stream.teleport(): the destination ({x}, {z}) was not ready after {t} s; still waiting on: {checks}. The player was not moved',
18
+ };
19
+
20
+ /** One stream source (returned by engine.stream.source) @internal */
21
+ export class Source {
22
+ constructor(stream, position, o) {
23
+ /** @internal */ this.stream = stream;
24
+ /** @internal */ this.pos = position;
25
+ /** Label shown in describe and errors @type {string} */ this.name = o.name ?? 'source';
26
+ /** Reach in meters; null = each loader's own range (terrain view distance, present radius...). A number caps every loader at it @type {number | null} */ this.radius = o.radius ?? null;
27
+ /** 'full' or 'simple' @type {'full' | 'simple'} */ this.detail = o.detail ?? 'full';
28
+ /** Whether colliders are built around it @type {boolean} */ this.physics = o.physics ?? this.detail === 'full';
29
+ /** Current horizontal position (refreshed by every list call) @type {number} */ this.x = 0;
30
+ /** @type {number} */ this.z = 0;
31
+ /** @internal */ this.age = 0;
32
+ /** @internal */ this._ready = false;
33
+ /** @internal */ this._waiters = [];
34
+ /** @internal */ this.removed = false;
35
+ this.until = o.until ?? null;
36
+ if (typeof this.until?.then === 'function') this.until.then(() => this.remove(), () => this.remove());
37
+ this.sync();
38
+ }
39
+ /** @internal Read the live position (an Object3D / Vector3 that moves, or a function) */
40
+ sync() { const p = typeof this.pos === 'function' ? this.pos() : this.pos; [this.x, this.z] = xzOf(p); return this; }
41
+ /** Everything this source asks for is loaded (checked once per frame, at the end of the frame) @type {boolean} */
42
+ get ready() { return this._ready; }
43
+ /** Promise that resolves when ready becomes true @type {Promise<void>} */
44
+ get whenReady() { return this._ready ? Promise.resolve() : new Promise((res, rej) => this._waiters.push({ res, rej })); }
45
+ /** @internal settle every waiter: resolve, or reject with err */
46
+ _settle(err) { for (const w of this._waiters.splice(0)) if (err) w.rej(err); else w.res(); }
47
+ /**
48
+ * Move the source (a live Object3D / Vector3, a function returning a position, or a fixed one); ready is checked again
49
+ * @example engine.stream.camera.at(photoCamera)
50
+ * @param {any} position
51
+ * @returns {this}
52
+ */
53
+ at(position) { this.pos = position; this.sync(); this._ready = false; this.age = 0; this.stream._version++; return this; }
54
+ /** A loader's range for this source: the loader's own range, capped by the source radius @param {number} range @returns {number} */
55
+ reach(range) { return this.radius == null ? range : Math.min(this.radius, range); }
56
+ /** Stop loading for this source (what nobody else asks for unloads) @returns {void} */
57
+ remove() {
58
+ if (this.removed) return;
59
+ this.removed = true; this.stream._sources.delete(this); this.stream._version++;
60
+ this._settle(codedError('stream-removed', SOURCE_STRINGS.removed.replace('{name}', this.name))); // an await on whenReady never hangs
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Ring of a chunk (cx, cz) from the nearest stream source, in chunk units. `centers` are the sources in chunk units ({ cx, cz, simple }); a simple
66
+ * source counts as the outer ring (far look, no near detail). Shared by the terrain and vegetation chunk tables so both rings mean the same.
67
+ * @internal
68
+ */
69
+ export function chunkRing(cx, cz, centers, viewChunks) {
70
+ let r = Infinity;
71
+ for (const s of centers) r = Math.min(r, Math.max(Math.abs(cx - s.cx), Math.abs(cz - s.cz), s.simple ? viewChunks : 0));
72
+ return r;
73
+ }
@@ -0,0 +1,96 @@
1
+ // A style built from parts: createEngine({ style: [lowpoly, { sky: mySky }, toonMaterials] }) merges the parts left to right into engine.style.
2
+ // Why parts and not one object: a look is often borrowed piecemeal (one pack's materials, another's sky, the game's own UI colors), and a
3
+ // spread `{ ...lowpoly, sky }` loses lowpoly's other sky fields; a deep merge keeps them. Rules (one place; recipes/09-style-pack.md "Composing"):
4
+ // - parts merge left to right, later wins; nested arrays are flattened (a pack may itself be a list of parts); null / undefined / false parts are skipped
5
+ // - plain objects ({ } literals) merge key by key, recursively: { sky: { sunSize: 600 } } changes only sunSize
6
+ // - anything else replaces whole: arrays (sky.keyframes, post, terrain.steep), functions, numbers, strings, three.js objects and class instances
7
+ // - a key set to undefined is ignored; a key set to null removes it (e.g. { post: null } = no post effects from earlier parts)
8
+ // - parts are never mutated; plain objects are copied, functions and three.js objects are shared by reference
9
+ // - post is the one list you often edit rather than replace: postAdd(effect) / postRemove(name) are parts that change the list built so far
10
+ // Zero cost when unused: a single object (not a list) is used as it is, engine.style === that object.
11
+ // Looks only: a style never holds world state (water level, sea, terrain shape); checkStyleLooks throws in dev.
12
+ import { DEV } from './validate.js';
13
+ import { isPlainObject as plain, getPath } from './util.js';
14
+
15
+
16
+ // A post edit is a function carrying this mark: mergeInto calls it with the list built so far instead of replacing the list
17
+ const EDIT = Symbol('threedog.postEdit');
18
+ const edit = fn => ({ post: Object.assign(fn, { [EDIT]: true }) });
19
+
20
+ /**
21
+ * A style part that adds post effects to the ones before it (a plain { post: [...] } would replace the whole list). An effect with the same name as
22
+ * an earlier one replaces it in place; names are the effects' own ('bloom', 'ao', 'outline', or your own).
23
+ * @example createEngine({ style: [lowpoly, postAdd(myGrain, bloom({ strength: 0.6 }))] }) // grain added, lowpoly's bloom swapped for yours
24
+ * @param {...import('../render/PostFX.js').PostEffect} effects
25
+ * @returns {{ post: any }}
26
+ */
27
+ export function postAdd(...effects) {
28
+ return edit(list => {
29
+ const out = [...(list ?? [])];
30
+ for (const e of effects) { const i = out.findIndex(o => o.name === e.name); if (i >= 0) out[i] = e; else out.push(e); }
31
+ return out;
32
+ });
33
+ }
34
+
35
+ /**
36
+ * A style part that removes post effects by name from the ones before it.
37
+ * @example createEngine({ style: [lowpoly, postRemove('ao', 'outline')] })
38
+ * @param {...string} names
39
+ * @returns {{ post: any }}
40
+ */
41
+ export function postRemove(...names) {
42
+ return edit(list => (list ?? []).filter(e => !names.includes(e.name)));
43
+ }
44
+
45
+ function mergeInto(out, part) {
46
+ for (const [k, v] of Object.entries(part)) {
47
+ if (v === undefined) continue;
48
+ if (v?.[EDIT]) out[k] = v(out[k]);
49
+ else if (v === null) delete out[k];
50
+ else if (plain(v)) out[k] = mergeInto(plain(out[k]) ? out[k] : {}, v);
51
+ else out[k] = v;
52
+ }
53
+ return out;
54
+ }
55
+
56
+ /**
57
+ * The style object engine.style is built from: a single style object as is, or a list of parts deep-merged (rules at the top of this file)
58
+ * @param {any} style
59
+ * @returns {Record<string, any>}
60
+ * @internal
61
+ */
62
+ export function styleFrom(style) {
63
+ let out = style ?? {};
64
+ if (Array.isArray(style)) {
65
+ out = {};
66
+ for (const part of style.flat(Infinity)) {
67
+ if (!part) continue;
68
+ if (!plain(part)) throw new Error(`createEngine({ style: [...] }): each part must be a plain object (a style pack or { key: value }), got ${typeof part}`);
69
+ // copy the part's plain objects too, so a later part never writes into an earlier pack
70
+ mergeInto(out, part);
71
+ }
72
+ }
73
+ if (DEV) checkStyleLooks(out);
74
+ return out;
75
+ }
76
+
77
+ // World state a style must not carry: [style path, is this key world state, where it goes instead]. Why: with the same map and rules, swapping
78
+ // the style may only change how things look; a style that moved the sea or reshaped the hills would make "same game, new look" impossible
79
+ const WORLD = [
80
+ ['water', k => ['level', 'sea', 'size'].includes(k), 'engine.use(water({ level, sea, size })) (WaterOptions); without level the terrain waterLevel is used'],
81
+ // looks of the ground: shading, colorResolution, normals, normalFn; diagonal moves engine.surface, so it is the game's
82
+ ['terrain.config', k => !['shading', 'colorResolution', 'normals', 'normalFn'].includes(k), "terrain({ ... }) (TerrainConfig: seed, chunkSize, resolution, diagonal, waterLevel, height...); only shading, colorResolution, normals, normalFn are looks"],
83
+ ];
84
+ function checkStyleLooks(style) {
85
+ for (const [path, isWorld, where] of WORLD) {
86
+ const obj = getPath(style, path);
87
+ if (!obj || typeof obj !== 'object') continue;
88
+ for (const k of Object.keys(obj))
89
+ if (isWorld(k)) throw new Error(`style.${path}.${k} is world state, not a look: swapping the style would change the map or the rules. Set it where the world is made: ${where}`);
90
+ }
91
+ }
92
+
93
+ // Dev warning when createEngine gets no style pack (shown once from Engine.js)
94
+ export const NO_STYLE = 'createEngine(): no style pack given, so everything is a neutral gray placeholder: plain lights (one white hemisphere + one neutral '
95
+ + 'directional light, no shadows, no tone mapping), gray background, ground, capsule characters and box props. This is not a look. '
96
+ + "Pass one: import lowpoly from '@threedog/style-lowpoly'; createEngine({ canvas, style: lowpoly }) (or your own pack, recipes/09-style-pack.md)";
@@ -0,0 +1,64 @@
1
+ // Target selection: pure functions (no camera, input or engine state), for lock-on, aim assist, "talk to whoever I'm facing", select the nearest unit.
2
+ // Why a score and not just "nearest": the player wants what they are looking at; an enemy pressed against their back should not steal the lock.
3
+ // The caller keeps the current target (in a world record, a module, a variable) and decides when to pick; these functions only answer "which one".
4
+ import { xzOf } from './math.js';
5
+ import { codedError } from './errorHints.js';
6
+
7
+ const wrap = a => Math.atan2(Math.sin(a), Math.cos(a));
8
+ const KEYS = ['radius', 'cone', 'close', 'angleWeight', 'blocked', 'at'];
9
+ const yawOf = view => typeof view === 'number' ? view : Math.atan2(view.x, view.z);
10
+ /** Candidate position: an Object3D / NPC / Character / world record has .position; a Vector3 / { x, z } / [x, y, z] is the position itself */
11
+ const posOf = c => c.position ?? c;
12
+ function check(fn, opts) {
13
+ if ('range' in opts) throw codedError('unknown-option', `${fn}(): the distance option is radius (meters), as in entities.nearest / world.query: write { radius: ${opts.range} }`);
14
+ for (const k of Object.keys(opts)) if (!KEYS.includes(k)) throw codedError('unknown-option', `${fn}(): unknown option '${k}'; available: ${KEYS.join(', ')}`);
15
+ }
16
+
17
+ /**
18
+ * Pick the best target: within `radius` meters and within `cone` radians either side of the view, lowest "distance + angle off the view × angleWeight" wins.
19
+ * Inside `close` meters the angle is ignored (surrounded: still lock something). Returns the candidate itself, or null.
20
+ * - from: the picker's position (Object3D / Vector3 / { x, z })
21
+ * - view: horizontal look direction { x, z } (engine.cameraRig.forward()) or a facing angle in radians (character.facing)
22
+ * - candidates: anything with a position (Object3D, NPC, Character, world record, Vector3, { x, z }); opts.at(c) reads another field
23
+ * - opts: radius 15, cone 1.4 (≈ 80°), close 2.5, angleWeight 6, blocked(c) => true to skip a candidate (occlusion, e.g. a raycast hits a wall first)
24
+ * @example
25
+ * const enemies = engine.world.query({ kind: 'enemy', near: player.position, radius: 20 });
26
+ * lock = pickTarget(player, engine.cameraRig.forward(), enemies, { blocked: r => wallBetween(player, r) });
27
+ */
28
+ export function pickTarget(from, view, candidates, opts = {}) {
29
+ check('pickTarget', opts);
30
+ const { radius = 15, cone = 1.4, close = 2.5, angleWeight = 6, blocked = null, at = posOf } = opts;
31
+ const [fx, fz] = xzOf(posOf(from)), yaw = yawOf(view);
32
+ let best = null, bestScore = Infinity;
33
+ for (const c of candidates) {
34
+ const [x, z] = xzOf(at(c)), d = Math.hypot(x - fx, z - fz);
35
+ if (d > radius) continue;
36
+ const off = Math.abs(wrap(Math.atan2(x - fx, z - fz) - yaw));
37
+ if (off > cone && d > close) continue;
38
+ const score = d + off * angleWeight;
39
+ if (score < bestScore && !blocked?.(c)) { bestScore = score; best = c; }
40
+ }
41
+ return best;
42
+ }
43
+
44
+ /**
45
+ * Switch to the neighbour of `current`: side 1 = the next one to the right, -1 = to the left (as seen along view), wrapping round at the end.
46
+ * Considers candidates within radius (default 15 m) that are not blocked; current missing or gone → the leftmost. Returns a candidate or null.
47
+ * @example lock = switchTarget(player, engine.cameraRig.forward(), lock, enemies, input.axis.x > 0 ? 1 : -1);
48
+ */
49
+ export function switchTarget(from, view, current, candidates, side, opts = {}) {
50
+ check('switchTarget', opts);
51
+ if (side !== 1 && side !== -1) throw codedError('engine-misuse', `switchTarget(): side must be 1 (right) or -1 (left), got ${side}`);
52
+ const { radius = 15, blocked = null, at = posOf } = opts;
53
+ const [fx, fz] = xzOf(posOf(from)), yaw = yawOf(view);
54
+ // right of the view is the negative angle direction (facing grows toward +X, the screen's right is at -yaw), so negate to sort left → right
55
+ const list = [];
56
+ for (const c of candidates) {
57
+ const [x, z] = xzOf(at(c));
58
+ if (Math.hypot(x - fx, z - fz) <= radius && !blocked?.(c)) list.push({ c, a: -wrap(Math.atan2(x - fx, z - fz) - yaw) });
59
+ }
60
+ if (!list.length) return null;
61
+ list.sort((p, q) => p.a - q.a);
62
+ const i = list.findIndex(p => p.c === current);
63
+ return i < 0 ? list[0].c : list[(i + side + list.length) % list.length].c;
64
+ }
@@ -0,0 +1,68 @@
1
+ // engine.thing(id).explain(): everything known about one id in one plain object (JSON-able, same for the CLI `threedog thing <id>`, MCP and tests).
2
+ // Why one object: an AI asked "why is this crate here, blocking me, and how do I change it?" otherwise joins thing(), world.origin, material info, the
3
+ // template, collision settings and the op list by hand. Each part reads an existing source; nothing here is stored or changes any state.
4
+ import { materialInfo } from './MaterialInfo.js';
5
+
6
+ const MAT_MAX = 8;
7
+ const safe = f => { try { return f(); } catch { return null; } };
8
+
9
+ /** Unique materials under obj with role / name / where the spec came from */
10
+ function materialsOf(obj) {
11
+ const seen = new Set(), out = [];
12
+ obj?.traverse?.(o => {
13
+ for (const m of [o.material].flat()) {
14
+ if (!m || seen.has(m)) continue;
15
+ seen.add(m);
16
+ if (out.length < MAT_MAX) { const i = materialInfo(m, o); out.push({ role: i.role, name: m.name || null, from: i.from, keys: i.keys, type: i.type, color: i.color, mesh: o.name || null }); }
17
+ }
18
+ });
19
+ if (seen.size > MAT_MAX) out.push({ more: seen.size - MAT_MAX });
20
+ return out;
21
+ }
22
+
23
+ /** Ops whose definition says (targets) they are for this id, kind or template; thing.set / thing.remove target '*' */
24
+ function opsFor(e, t) {
25
+ const keys = new Set([t.id, t.kind, t.template].filter(Boolean));
26
+ return [...e.ops.defs.values()].filter(d => d.targets != null && [d.targets].flat().some(x => x === '*' || keys.has(x)))
27
+ .map(d => ({ op: d.name, desc: d.desc ?? null, args: d.args ?? null }));
28
+ }
29
+
30
+ /** What core knows about how the thing takes part in movement / picking: the size of its model. Template and record rules come from a module's explainer (below) */
31
+ function rulesOf(e, t, obj) {
32
+ const out = {};
33
+ if (obj) {
34
+ const T = e.THREE, size = new T.Box3().setFromObject(obj).getSize(new T.Vector3());
35
+ if (isFinite(size.y)) out.height = Math.round(size.y * 100) / 100;
36
+ }
37
+ return out;
38
+ }
39
+
40
+ /**
41
+ * @param {any} e @param {any} t the thing (engine.thing result) @internal
42
+ */
43
+ export function explainThing(e, t) {
44
+ const obj = t.object, T = e._things;
45
+ const over = e.debug.overridesOn(obj);
46
+ const state = obj ? { position: obj.position.toArray().map(v => Math.round(v * 100) / 100), visible: obj.visible, scale: obj.scale.toArray() } : {};
47
+ const saved = { tier: t.saved, keeps: t.keeps, loses: t.loses, ...(t.saved === 'code' && { overridden: T.over.has(t.id), removed: T.removed.has(t.id) }) };
48
+ const out = {
49
+ id: t.id, kind: t.kind, owner: t.owner,
50
+ definition: { at: t.definedAt ?? t.at ?? null, template: t.template ?? null, templateAt: t.templateAt ?? null, ...(t.level && { level: t.level, node: t.node }), ...(t.spawned && { spawned: t.spawned }) },
51
+ model: t.model ?? null,
52
+ materials: materialsOf(obj),
53
+ state,
54
+ rules: rulesOf(e, t, obj),
55
+ ops: opsFor(e, t),
56
+ saved,
57
+ change: {
58
+ runtime: `game state changes through ops: engine.ops.run('<op>', { id: '${t.id}' }); thing.set / thing.remove move, show or remove it (undoable)`,
59
+ permanent: t.edit ?? 'no source known: edit the code or content line that creates it, then reload',
60
+ diagnostic: `engine.debug.override(owner, '${t.id}', { visible, material: 'flat' | 'wire' }) changes the screen only (never saved); engine.debug.clear(owner) removes it`,
61
+ },
62
+ ...(over.length && { overrides: over, warning: 'diagnostic overrides are active on this thing: what is drawn is not its real state' }),
63
+ };
64
+ // Explain contributions (arch #6): a module that owns records or templates adds to the object with e._things.explainers.push((e, t, out) => { ... }),
65
+ // so core never reads their shapes. A throwing explainer is skipped: explain is a diagnostic and must not fail because of one part.
66
+ for (const f of T.explainers) safe(() => f(e, t, out));
67
+ return out;
68
+ }
@@ -0,0 +1,168 @@
1
+ // engine.thing and the two built-in ops on things (thing.set / thing.remove), plus the 'scene' save part and describe().scene.
2
+ // One query and one way to change for both kinds of things: a world record (template instance, prop, pickup, NPC) and a plain three.js object added with
3
+ // engine.add. Why both go through ops: a change then has undo, lands in the op log and is checked by can(), whichever system owns the object.
4
+ // For a record the ops turn into world.set / world.move / world.remove (the model follows the record); for a plain object they write the transform and,
5
+ // when the object has a stable id and is rebuilt by code at setup, record it as an override in the 'scene' save part (things.js).
6
+ import { Things, snap, write } from './things.js';
7
+ import { closest } from './validate.js';
8
+ import { codedError } from './errorHints.js';
9
+ import { explainThing } from './thingExplain.js';
10
+
11
+ const SAY = {
12
+ record: { keeps: ['record fields and position (world save part)'], loses: ['the built model itself: it is rebuilt from its template / present after a load'] },
13
+ code: { keeps: ['position, rotation, scale, visibility and removal made with thing.set / thing.remove (scene save part)'],
14
+ loses: ['geometry and material changes', 'children added later', 'userData', 'closure state (onFrame callbacks)', 'changes written directly (mesh.position.x = 3)'] },
15
+ session: { keeps: [], loses: ['everything: it exists only in this session and does not come back after a load'] },
16
+ engine: { keeps: [], loses: ['changes written directly: the engine module that owns it rewrites them'] },
17
+ };
18
+
19
+ /** How to change it for good, one line */
20
+ function editText(en, tier, rec) {
21
+ if (tier === 'record') return `${rec ?? 'world record'} · thing.set turns into world.set / world.move`;
22
+ const at = en.at ? ` at ${en.at}` : '';
23
+ if (tier === 'engine') return `managed by ${en.owner}: change it through that module, not directly`;
24
+ if (tier === 'code') return `added by code${at} (id '${en.id}'): to change it for good edit that line; thing.set changes are saved as overrides`;
25
+ if (!en.stable) return `added by code${at} without an id: give it one at setup (engine.add(obj, { id: 'name' })) to save thing.set changes; now they last this session only`;
26
+ return `made during play${en.op ? ` by op ${en.op}` : ''}${at}: to keep it, make it a template and create it inside the op with engine.spawn(name, at)`;
27
+ }
28
+
29
+ /** thing.explain(): the whole story of the id in one object (thingExplain.js); a method, not a field, so the thing stays small */
30
+ const withExplain = (e, t) => Object.defineProperty(t, 'explain', { value: () => explainThing(e, t), enumerable: false });
31
+
32
+ /** A registered plain object as a thing (same shape as hit.thing); `object` is a non-enumerable getter so the result stays JSON-able */
33
+ function nativeThing(e, en, root) {
34
+ const tier = e._things.tier(en), say = SAY[tier];
35
+ const out = { id: en.id, kind: root.type, owner: en.owner, at: en.at, phase: en.phase, ...(en.op && { op: en.op, tick: en.tick }), saved: tier,
36
+ keeps: say.keeps, loses: say.loses, edit: editText(en, tier), removed: e._things.gone.has(en.id),
37
+ template: null, definedAt: null, model: null, fields: {} };
38
+ return withExplain(e, Object.defineProperty(out, 'object', { get: () => root, enumerable: false }));
39
+ }
40
+
41
+ /**
42
+ * The thing for a record id (from a source, see Things.addSource), a registered id / name, or any Object3D (its
43
+ * registered ancestor). null when nothing matches.
44
+ * @internal
45
+ */
46
+ export function findThing(e, q) {
47
+ const T = e._things;
48
+ if (typeof q === 'string') {
49
+ if (T.source(q)) return recordAsThing(e, q);
50
+ const o = T.live(q) ?? e.scene.getObjectByName(q);
51
+ return native(e, o && T.entryOf(o));
52
+ }
53
+ if (!q?.isObject3D) return null;
54
+ const id = T.idOf(q);
55
+ return id ? recordAsThing(e, id) : native(e, T.entryOf(q));
56
+ }
57
+ /** A world-owned entry that world no longer answers for is a torn-down model (template models are only detached): not a thing */
58
+ const native = (e, hit) => hit && hit[0].owner !== 'world' ? nativeThing(e, hit[0], hit[1]) : null;
59
+ function recordAsThing(e, id) {
60
+ const src = e._things.source(id), r = src.explain(id);
61
+ const out = { ...r, owner: 'world', at: r.definedAt ?? null, phase: r.spawned ? 'play' : 'setup', saved: 'record', ...SAY.record, edit: editText(null, 'record', r.edit) };
62
+ return withExplain(e, Object.defineProperty(out, 'object', { get: () => src.view(id), enumerable: false }));
63
+ }
64
+ /** Every id engine.thing knows (for "did you mean") */
65
+ function thingIds(e) { return [...e._things.recordIds(), ...e._things.byId.keys()]; }
66
+ export const hintThing = (e, id) => { const c = closest(String(id), thingIds(e)); return c ? ` (did you mean '${c}'?)` : ''; };
67
+
68
+ /** Normalise thing.set args into a patch of arrays (rotation as a number = yaw; scale as a number = uniform) */
69
+ function patchOf(o, a) {
70
+ const p = {};
71
+ if (a.position) p.position = Array.isArray(a.position) ? [...a.position] : [a.position.x, a.position.y ?? o.position.y, a.position.z];
72
+ if (a.rotation != null) p.rotation = typeof a.rotation === 'number' ? [o.rotation.x, a.rotation, o.rotation.z] : [...a.rotation];
73
+ if (a.scale != null) p.scale = typeof a.scale === 'number' ? [a.scale, a.scale, a.scale] : [...a.scale];
74
+ if (a.visible != null) p.visible = a.visible;
75
+ return p;
76
+ }
77
+ const xyz = p => Array.isArray(p) ? { x: p[0], y: p[1], z: p[2] } : p;
78
+ const yaw = r => typeof r === 'number' ? r : r[1];
79
+ const uni = s => typeof s === 'number' ? s : s[0];
80
+
81
+ /** Register the registry, engine.thing's ops, the 'scene' save part and the session:start setup window (called once by the Engine constructor) */
82
+ export function installThings(e) {
83
+ const T = e._things = new Things(e);
84
+ T.explainers = []; // explain contributions from modules (see thingExplain.js)
85
+ /**
86
+ * Add a contribution to engine.thing(id).explain(): fn(engine, thing, out) may fill out.state / out.rules (or add keys) for the things its module owns.
87
+ * For module authors: core never reads another module's record or template shape, the module hands it over here. A throwing fn is skipped.
88
+ * @param {(e: any, t: any, out: any) => void} fn
89
+ * @example engine.explainWith((e, t, out) => { const r = e.myRecords.get(t.id); if (r) out.state = { ...r }; });
90
+ */
91
+ e.explainWith = fn => { T.explainers.push(fn); };
92
+ // content() replaces this; without it a bare "spawn is not a function" would not say which module to install
93
+ e.spawn = () => { throw new Error("engine.spawn needs the content module: add content() to engine.use(...) (import { content } from 'threedog')"); };
94
+ e.saves.register('scene', { atomic: true, save: () => T.save(), load: d => T.load(d) });
95
+ const kindOf = id => T.source(id) ? 'record' : T.live(id) ? T.tier(T.byObj.get(T.live(id))) : null;
96
+ const reasons = {
97
+ noThing: 'no world record or engine.add object has this id (engine.thing(id) suggests the closest one)',
98
+ engineOwned: 'an engine module manages this object (water, particles, physics…); change it through that module',
99
+ recordVisible: 'a world record has no visible flag: hide its model with present({ show: rec => … }) and a field set by world.set',
100
+ };
101
+ e.ops.define('thing.set', {
102
+ targets: '*',
103
+ desc: 'Move / turn / scale / show or hide a thing: a world record (via world.set / move) or an engine.add object (saved as an override when it has an id)',
104
+ args: { id: 'string', position: 'any?', rotation: 'any?', scale: 'any?', visible: 'bool?' },
105
+ can: (_, a) => { const k = kindOf(a.id); return !k ? 'noThing' : k === 'engine' ? 'engineOwned' : k === 'record' && a.visible != null ? 'recordVisible' : true; },
106
+ run(eng, a) {
107
+ if (kindOf(a.id) === 'record') {
108
+ const patch = { ...(a.position && { position: xyz(a.position) }), ...(a.rotation != null && { rot: yaw(a.rotation) }), ...(a.scale != null && { scale: uni(a.scale) }) };
109
+ return { record: true, before: T.source(a.id).set(a.id, patch) };
110
+ }
111
+ const obj = T.live(a.id), p = patchOf(obj, a);
112
+ if (T.tier(T.byObj.get(obj)) === 'code') return T.override(a.id, obj, p);
113
+ const before = { patch: Object.fromEntries(Object.keys(p).map(k => [k, snap(obj)[k]])), had: true, session: true };
114
+ write(obj, p);
115
+ return before;
116
+ },
117
+ undo(eng, a, v) {
118
+ if (v.record) { T.source(a.id).set(a.id, v.before); return; }
119
+ const obj = T.live(a.id); if (!obj) return;
120
+ write(obj, v.patch);
121
+ if (v.session) return;
122
+ if (!v.had) T.over.delete(a.id); else Object.assign(T.over.get(a.id)?.cur ?? {}, v.patch);
123
+ },
124
+ reasons,
125
+ });
126
+ e.ops.define('thing.remove', {
127
+ targets: '*',
128
+ desc: 'Remove a thing (undoable): a world record via world.remove, or an engine.add object (detached and kept; saved when it has an id)',
129
+ args: { id: 'string' },
130
+ can: (_, a) => { const k = kindOf(a.id); return !k || T.gone.has(a.id) ? 'noThing' : k === 'engine' ? 'engineOwned' : true; },
131
+ run(eng, a) {
132
+ if (kindOf(a.id) === 'record') {
133
+ const src = T.source(a.id);
134
+ return { record: src.remove(a.id), src };
135
+ }
136
+ T.hide(a.id, T.live(a.id), T.tier(T.byObj.get(T.live(a.id))) === 'code');
137
+ return {};
138
+ },
139
+ undo(eng, a, v) {
140
+ if (!v.record) { T.unhide(a.id); return; }
141
+ v.src.restore(v.record);
142
+ },
143
+ reasons,
144
+ });
145
+ }
146
+
147
+ /** describe().scene: counts by owner and save tier, plus the problems (never the full list: describeText({ path: 'scene' }) is the same object) */
148
+ export function describeScene(e) {
149
+ const T = e._things, n = { game: 0, code: 0, session: 0, world: 0, engine: 0 };
150
+ for (const id of [...T.byId.keys()]) {
151
+ const o = T.live(id); if (!o) continue;
152
+ const en = T.byObj.get(o), tier = T.tier(en);
153
+ if (en.owner === 'game') { n.game++; n[tier]++; } else if (tier === 'record') { if (o.parent) n.world++; } else n.engine++;
154
+ }
155
+ const ov = e.debug.overrides();
156
+ const out = { ...n, ...(ov.length && { overrides: ov, overridesNote: 'diagnostic: the screen differs from the real state until engine.debug.clear(owner)' }), unsaved: T.lost().map(en => `${en.id} (${en.at ? en.at + ', ' : ''}${en.phase === 'play' ? 'made during play' : 'no stable id'}${en.op ? ` by op ${en.op}` : ''})`),
157
+ conflicts: [...T.conflicts], orphans: T.orphans() };
158
+ if (T.atCapped) out.atCapped = true; // dev stacks stopped: later objects have at: null
159
+ return out;
160
+ }
161
+
162
+ /** engine.thing(idOrObj): throws with the closest id when nothing matches @internal */
163
+ export function thing(e, q) {
164
+ const t = findThing(e, q);
165
+ if (t) return t;
166
+ const what = typeof q === 'string' ? `'${q}'` : q?.isObject3D ? `an unregistered ${q.type}` : JSON.stringify(q);
167
+ throw codedError('thing-id', `engine.thing(${what}): nothing has this id or name${typeof q === 'string' ? hintThing(e, q) : ''}. Pass a world record id, the id given to engine.add(obj, { id }), an object name or any Object3D added with engine.add (engine.scene.add does not register)`);
168
+ }