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,234 @@
1
+ # Changing the art / writing a style pack
2
+
3
+ **The engine ships no art.** No default style, character model, terrain look or terrain generator: with no style pack and no model everything is a
4
+ plain neutral placeholder (a gray capsule for characters, a gray box for props and pickups, flat gray ground at y = 0, one white hemisphere light plus
5
+ one neutral directional light without shadows or tone mapping), and the console says once in dev what is missing and how to fix it.
6
+
7
+ A style pack is a plain object passed in as `createEngine({ style })`. It holds **looks only**: colors, the default character / pickup shapes,
8
+ materials and shaders, sky and lighting, post effects, UI look. Not part of it: model / texture / sound files and procedural models content names (an
9
+ **asset pack**, `engine.assets.manifest`, recipe 05 "Asset packs"), sounds (section 5), gameplay data and timing (a **content pack**, recipe 20;
10
+ `sky({ hoursPerDay })`). Which key is read by whom is in the "style pack keys" table of `../CODEMAP.md`; the field list is in `../api/style.md`. Every
11
+ entry can be omitted; omitted entries are the neutral placeholders above (the city example passes no style pack at all). Write it as a plain object literal, no `@type` or `as const`: fields with a fixed set of words (`shading`, `mode`, `type` …) accept any string in the types, and a wrong word is reported by `threedog style check` with the fix.
12
+
13
+ ## 0. Installing the lowpoly style pack
14
+ The low-poly look is an optional package, `@threedog/style-lowpoly` (source in the monorepo: `packages/styles/lowpoly/`):
15
+ ```sh
16
+ npm install @threedog/style-lowpoly
17
+ ```
18
+ ```js
19
+ import { createEngine, presets, openWorld } from 'threedog';
20
+ import lowpoly from '@threedog/style-lowpoly';
21
+ import { terrainPreset, terrainStrings } from '@threedog/terrain-noise'; // the world shape is not a look: its own package
22
+ const engine = createEngine({ canvas, style: lowpoly, strings: terrainStrings }); // terrainStrings: names of the preset's ground types
23
+ engine.use(openWorld({ camera: 'follow', seed: 7, terrain: terrainPreset() })); // noise terrain (hills, rivers, biomes) that lowpoly colors, see recipes/28
24
+ ```
25
+ Besides the style object it exports `assets` (an asset pack of procedural trees, rocks, grass, flowers: `engine.assets.manifest(assets)`; the same
26
+ generators as a plain map are `models`). Its `bloom` / `ao` / `outline` come from `@threedog/post-effects` (style packs never import each other; R34 checks). The terrain generator `terrainPreset` / `riverAt` / `BIOMES` /
27
+ `terrainStrings` is a separate package, `@threedog/terrain-noise`: the shape of the world is gameplay, so a style pack keeps only the colors of its
28
+ ground types (`terrain.colors`, `biomeColors`).
29
+
30
+ ## 0b. Composing a style from parts
31
+ `style` may be a list of parts, deep-merged left to right into `engine.style`, so one pack's materials, another pack's sky and the game's own colors
32
+ mix without copying whole packs:
33
+ ```js
34
+ import lowpoly from '@threedog/style-lowpoly';
35
+ const dusk = { sky: { sunSize: 600, keyframes: myDuskKeyframes } }; // only these two sky fields change
36
+ const engine = createEngine({ canvas, style: [lowpoly, dusk, { ui: { accent: '#7fd3ff' }, post: null }] });
37
+ ```
38
+ Rules (`core/styleParts.js`): plain `{ }` objects merge key by key at every depth; everything else replaces whole (arrays such as `sky.keyframes` and
39
+ `post`, functions, three.js objects); a key set to `null` removes it; `undefined` is ignored; nested lists flatten, so a pack can itself be a list of
40
+ parts; parts are never mutated. One object (not a list) is used as it is.
41
+
42
+ **Post effects by name.** `post` is a list, so `{ post: [myGrain] }` replaces everything before it. To add to or trim the list use the two helpers
43
+ (exported by `threedog`); they are parts too:
44
+ ```js
45
+ import { createEngine, postAdd, postRemove } from 'threedog';
46
+ import lowpoly from '@threedog/style-lowpoly';
47
+ import { bloom } from '@threedog/post-effects';
48
+ createEngine({ canvas, style: [lowpoly, postAdd(myGrain, bloom({ strength: 0.6 })), postRemove('ao')] });
49
+ ```
50
+ `postAdd(...effects)` appends; an effect whose `name` is already in the list (`'bloom'`, `'ao'`, `'outline'`) replaces that one in place.
51
+ `postRemove(...names)` drops effects by name. `{ post: null }` still clears the list; `{ post: [...] }` still replaces it whole.
52
+
53
+ **Retinting the procedural models.** `style.palette` holds the colors the trees, rocks, grass and flowers are built from (lowpoly: `bark`, `pine`,
54
+ `pineLight`, `leaf`, `rock`, `grassBase`, `grassTip`, `bloom`...; the keys are in `lowpoly.palette`). One part changes them all:
55
+ `style: [lowpoly, { palette: { pine: 0xa07a2e, leaf: 0xd98a3a } }]` (autumn); keys left out keep the pack's colors. A generator of your own written
56
+ with `function` (not an arrow) reads `this.palette`; the palette is part of the model cache key, so a changed palette rebuilds. `.glb` files and
57
+ models baked earlier keep their colors.
58
+
59
+ ## 0c. What a style may not hold
60
+ Swapping the style must never change the map or the rules, only how they look. So these are **not** style fields, and a dev run throws an error
61
+ naming where each goes:
62
+ - water level, whether there is a sea, the water mesh size: `style.water.level / sea / size` -> `engine.use(water({ level, sea, size }))`
63
+ - terrain shape and size (seed, chunk size, resolution, water level, height functions): `style.terrain.config.*` -> `terrain({ ... })`. The one
64
+ look in `terrain.config` is `shading: 'flat' | 'smooth'`
65
+ Quality settings are not world state and may stay in a style (shadow `mapSize` and `low` overrides, water `segments`); players can override them in
66
+ settings. Packs under `packages/styles/**` are also checked by `threedog check` (R34).
67
+
68
+ ## 1. Creating a new style pack
69
+ Copy `packages/styles/lowpoly/` to your game (or a new package `@threedog/style-toon`), edit the values in `index.js`, then switch to it in the game:
70
+ ```js
71
+ import toon from './style/index.js';
72
+ const engine = createEngine({ canvas, style: toon });
73
+ ```
74
+ **A material role is a free label inside the style, not a fixed list.** `makeMaterial('anything', { color })` is always legal: a role the style does not
75
+ name falls back to `materials.default`, and a new role (`'lantern'`, `'roof'`) becomes real the moment the style adds `materials.lantern`. The engine
76
+ warns only when a name looks like a typo of a known role (`'buidling'`).
77
+
78
+ Keys you will change most often:
79
+ | Key | What it controls |
80
+ |---|---|
81
+ | `materials` | The material per role. Three forms: a spec `{ default: { type: 'toon', steps: 3 }, water: { type: 'phong', shininess: 90 } }` (lambert / phong / standard / physical / toon / basic; a wrong type throws), any three.js material instance `water: new THREE.MeshMatcapMaterial({ matcap })` (cloned per use), or a function `prop: (params, role) => new THREE.ShaderMaterial({...})`. Style packs may create materials directly; games still go through `makeMaterial` |
82
+ | `antialias` | `false` for sharp pixel edges; omitted = on for desktop, off for phones (players can switch it in settings) |
83
+ | `post` | List of post effects, see 2c (lowpoly: `[outline(), ao(), bloom()]`; `outline({ enabled: true })` for a cartoon look) |
84
+ | `sky` `weather` `water` `terrain` `seasons` `clouds` | Sky keyframes (sun color and intensity over the day, fog color, shadows), rain and snow, water, terrain colors (`terrain.colors` palette, `terrain.biomeColors` ground type -> palette names, `terrain.steep` slope colors; a type with no color is gray; `terrain.config.shading: 'flat'` for facets (the only `terrain.config` key; engine default smooth); `terrain.material` swaps the whole ground material, chunks have `uv` = world xz / chunk size; `water.material: (engine, { uniforms, waves, normalMap }) => Material` swaps the whole water surface, e.g. `applyEffects(new THREE.MeshToonMaterial({ color }), { clouds: false, patches: [waves] })` keeps the built-in waves), seasonal tints |
85
+ | `character` | Default character colors `colors`; `create(engine, colors)` builds the procedural character (lowpoly: its `shapes.js`; without it a gray capsule); `model` a registered model every character uses |
86
+ | `pickup` `particles` | Items on the ground (`pickup.model(item, { color, size })` returns an Object3D or geometry; without it a plain gray box), particle presets (dust smoke leaves splash sparks...) |
87
+ | `triggers` `grid` | Tool colors, not art: trigger zone wireframe (`debugColor`), grid placement preview (`ok` / `bad`). The engine has neutral defaults (gray; light = can place, dark = cannot); a pack may recolor them |
88
+ | `ui` | UI colors, `font` (a CSS font-family list), `fonts` (font asset names to load at start, the files in an asset pack: recipes/05 §3b), extra `css`, `templates` that replace a whole UI piece |
89
+
90
+ Lights: every engine has `engine.lights = { sun, hemi }`, plain three.js lights. Without a style pack they are a neutral placeholder (white
91
+ hemisphere + neutral directional light, no shadows); the look (sun color and intensity curves, sky colors, fog, shadow softness, exposure, tone
92
+ mapping) comes from the style pack's `sky`, `exposure` and `toneMapping`, and the sky module drives the same two lights. For your own lighting hide or
93
+ retune them and add three.js lights.
94
+
95
+ **Lights and stalls.** three.js builds one shader program per material for each light setup. `engine.start()` compiles everything visible behind the
96
+ loading screen (`engine.startup.compileMs`), but adding or removing a light later, or toggling `visible` on one, changes the setup and compiles again:
97
+ a frame can freeze for hundreds of milliseconds. Keep the number of lights fixed: create them up front and fade with `intensity` (0 = off, no
98
+ recompile). In dev the console warns (code `light-recompile`) when programs were compiled in a frame where the lights changed.
99
+
100
+ For many torches, street lamps, campfires, muzzle flashes or neon signs use the light pool: a fixed number of real lights, created once at install,
101
+ moves to the sources that matter most (near the camera, bright, high `priority`) and fades with intensity, so the light setup never changes. Install
102
+ it before `engine.start()` so the startup compile covers its lights:
103
+ ```js
104
+ import { lightPool } from 'threedog';
105
+ engine.use(lightPool({ point: 8 })); // 8 PointLights; lightPool({ spot: 2, shadows: 1 }) adds spots / lets one point light cast
106
+ for (const t of torches) engine.lightPool.add(t, { // an Object3D is followed; a position stays put
107
+ color: 0xffa040, intensity: 4, distance: 8,
108
+ flicker: (time, i) => 0.85 + 0.15 * Math.sin(time * 13 + i),
109
+ glow: t.getObjectByName('halo'), // stand-in while it has no real light: its material's opacity / emissiveIntensity fades to 0 as the light fades in
110
+ });
111
+ const flash = engine.lightPool.add(gun.muzzle, { intensity: 0, priority: 5, distance: 6 });
112
+ flash.set({ intensity: 8 }); /* next frame */ flash.set({ intensity: 0 }); // muzzle flash: no light is created
113
+ ```
114
+ `engine.lightPool.usage()` (and `describe().lightPool`) lists which source each real light holds; `focus` measures from the player instead of the
115
+ camera. Options and handle: `../api/lightPool.md`.
116
+
117
+ ## 2. Using your own models instead of procedural ones
118
+ Models are assets, not style keys: content names them, an asset pack maps the names to files or generators. Register a later manifest with the same
119
+ name to swap one:
120
+ ```js
121
+ engine.assets.manifest(lowpolyAssets); // import { assets as lowpolyAssets } from '@threedog/style-lowpoly': pine, rock, flower... built in code
122
+ engine.assets.manifest({ name: 'mine', models: { pine: () => myPineGeometry(), well: '/models/well.glb' } }); // replaces pine, adds well
123
+ ```
124
+ Vegetation takes a geometry (`geometry: await engine.assets.geometry('pine')`, the first mesh in the model) or a whole model with one material per
125
+ mesh, e.g. bark trunk + alpha-cut leaf cards:
126
+ `engine.vegetation.add('oak', { model: await engine.assets.model('oak'), wind: 0.02 })` (still one draw call per part; felling hides every part). For
127
+ the import workflow see `10-blender-level.md`.
128
+ `mergeColored(parts, { flat: false })` keeps smooth normals; UVs survive when every part has them.
129
+ A generator in `models` may also return an Object3D with its own materials; those are used as they are.
130
+
131
+ ## 2b. Wind, cloud shadows and season tint on your own materials
132
+ The engine's shader effects are named patches that work on any material that has the usual three.js chunks (WebGL only):
133
+ ```js
134
+ import { applyEffects } from 'threedog';
135
+ const leaves = applyEffects(new THREE.MeshToonMaterial({ color: 0x5a8a3a }), { wind: 0.03, season: 'foliage' }); // clouds default on
136
+ engine.vegetation.add('bush', { geometry, material: leaves }); // vegetation adds them itself; effects: false keeps the material untouched
137
+ ```
138
+ The shadow sways with the wind automatically. Your own effect (pixel snapping, dissolve...) is a patch too, and stacks with the built-in ones and with
139
+ the material's own `onBeforeCompile`:
140
+ `applyEffects(mat, { patches:
141
+ [{ name: 'snap', cacheKey: 64, uniforms, glsl: { vertex: { pars: '...', project_vertex: '...code after #include <project_vertex>' } } }] })`.
142
+ A missing `#include` anchor throws. A hand-written `ShaderMaterial` can `#include <threedog_wind_vertex>`, `<threedog_clouds_pars_fragment>` etc. (see
143
+ `render/effects.js`) with `engine.uniforms` as its uniforms.
144
+ `material.clone()` does not carry patches (three's `Material.copy` skips `onBeforeCompile`): a pack's Material instance in `materials` is fine
145
+ (`makeMaterial` keeps its patches); when you clone one yourself, apply the effects to the clone again.
146
+
147
+ Patches on one material must agree. Each patch declares what it relies on, and a bad combination throws when it is added (or logs once at compile):
148
+ | Field | Meaning | Checked |
149
+ |---|---|---|
150
+ | `needs.data` | Program inputs the code reads: `'instancing'`, `'instancingColor'`, `'vertexColors'`, `'skinning'`, `'batching'` | when the program compiles (console.error once per material) |
151
+ | `needs.patches` | Patches it builds on, e.g. `['world']` for the `vThreedogWorld` varying (world position; `applyEffects` adds `world` itself when a patch needs it) | when added |
152
+ | `conflicts` | Patch names it cannot share a material with | when added, both ways |
153
+ | `uniforms` | A uniform name belongs to one patch; share `engine.uniforms` (`uTime`, `uWind`, `uCloud`...) instead of making your own `uTime` | when added |
154
+ | `shadow` | Render steps: without it the color pass only; `true` also runs its vertex code in the depth (sun / spot shadows) and distance (point-light shadows) passes | - |
155
+ | `cacheKey` | Changes whenever the GLSL text changes (defines, branches), never for uniform values; the program key joins every patch's `name=cacheKey` in order | same name + cacheKey with different code throws |
156
+ ```js
157
+ applyEffects(mat, { wind: 0.03, season: 'foliage', patches: [{ name: 'ripple', needs: { patches: ['world'] }, conflicts: ['wind'],
158
+ glsl: { fragment: { color_fragment: 'diffuseColor.rgb *= 0.9 + 0.1 * sin(vThreedogWorld.x);' } } }] }); // throws: 'wind' and 'ripple' cannot be combined
159
+ ```
160
+
161
+ ## 2c. Post effects (slots)
162
+ Post-processing is an ordered list of named effects. Each runs in a slot, then by `order` (low first):
163
+ `scene` (replaces the scene render, one at a time, e.g. pixelation) -> `hdr` (linear color: outline, AO, bloom) -> tone mapping -> `ldr` (sRGB: LUT,
164
+ palette, grain, vignette) -> `final` (FXAA / SMAA).
165
+ An effect is `{ name, slot, order, params, create(ctx) => pass, update?(pass, params) }`; under WebGL the pass is any three.js postprocessing Pass. It
166
+ is built the first time it is on.
167
+ ```js
168
+ import { bloom, outline } from '@threedog/post-effects'; // never from another style pack: packs do not depend on each other
169
+ import { LUTPass } from 'three/addons/postprocessing/LUTPass.js';
170
+ const toon = { name: 'toon', post: [outline({ enabled: true, thickness: 1.5 }), bloom({ strength: 0.2 }),
171
+ { name: 'lut', slot: 'ldr', params: { lut: myLut }, create: ({ params }) => new LUTPass({ lut: params.lut }) }] };
172
+ // at runtime (settings, photo mode, a game's own effect):
173
+ engine.look.post.set({ 'bloom.strength': 0.6 });
174
+ engine.look.post.set({ 'outline.enabled': false }); // MSAA: engine.post.setAntialias(false)
175
+ engine.look.post.patch('vignette', { glsl: 'color.rgb *= 0.9;', slot: 'ldr', order: 10 }); // patch('vignette', null) removes it
176
+ ```
177
+ An effect that reads scene depth (`needsDepth: true`, e.g. `outline`) must run before any pass that swaps buffers (a `ShaderPass`, a scene-slot
178
+ `RenderPixelatedPass`, the tone-mapping output): only the buffer the scene render wrote holds scene depth. A chain that breaks this throws when the
179
+ effect is added or enabled, naming both effects; give the depth reader a lower `order`. `dof` copies the scene depth into its own output
180
+ (`pass.keepsDepth = true`, no extra pass), so `dof` and `outline` can both be on as long as `dof` has the lower `order` (default: dof 5, outline 10;
181
+ lines stay sharp over the blur). `threedog style check` reports the other order as an error.
182
+ `createEngine({ post: { bloom: false } })` overrides an effect's startup on/off; `costly: true` effects start off on low-tier devices. MSAA
183
+ (`antialias`) works with every effect on.
184
+ The settings menu shows `bloom` / `ao` toggles only when the style pack registers effects with those names.
185
+
186
+ ### Optional post effects package and `fuse`
187
+ The engine ships no effects; `@threedog/post-effects` (install it like `@threedog/terrain-noise`, import only what you use) has `bloom`, `ao`,
188
+ `outline`, `dof` (all `hdr`; outline and dof read depth) and `lut` (contrast / saturation / warm-cool / optional 3D LUT), `grain`, `vignette`,
189
+ `chromatic` (`ldr`). A style pack lists the ones it wants in its own `post`. `lut`, `grain`, `vignette`, `chromatic`, `dof`, `ao` and `outline` are off
190
+ until `enabled: true`.
191
+ ```js
192
+ import { vignette, grain, lut } from '@threedog/post-effects';
193
+ createEngine({ canvas, style: [lowpoly, postAdd(lut({ saturation: 1.1, temperature: 0.15 }), vignette(), grain({ amount: 0.04 }))] });
194
+ engine.look.post.set({ 'vignette.enabled': true }); // photo mode, settings...
195
+ engine.look.post.set({ 'grain.amount': 0.1 }); // updates in place
196
+ ```
197
+ `fuse` is how a light color effect avoids a fullscreen pass of its own: instead of `create()` it carries a GLSL snippet
198
+ `fuse: { uniforms: { uMyAmount: 'float' }, values: p => ({ uMyAmount: p.amount }), glsl: 'color.rgb *= 1.0 - uMyAmount * length(vUv - 0.5);' }`.
199
+ Effects with a `fuse` that are on and next to each other in one slot (never `scene`) are compiled into ONE shader and drawn in one pass, in
200
+ `order`; turning one off, `set()` or `remove()` recompiles or just updates the uniforms. The snippet edits `vec4 color` and may use `vUv`,
201
+ `tDiffuse`, `uTime`, `uResolution`, `fxHash(vec2)`; uniform names are shared by the whole group, so prefix them with the effect name. A snippet that
202
+ samples `tDiffuse` at other positions (blur, color fringe) sets `reads: true` and then starts a new group. Four ldr effects: 1 pass instead of 4.
203
+ Effects without `fuse` (bloom, outline, `dof`...) stay one pass each.
204
+
205
+ ### Outline modes
206
+ `outline({ mode: 'depth' | 'normal' | 'both' })`: `depth` (default, silhouettes), `normal` (creases; the scene is drawn once more with normals, so
207
+ it is `costly` and off on low-tier devices), `both`. `fadeWithDistance: false` keeps lines at any distance; `wobble: 1.5` jitters the lines by up to 1.5
208
+ pixels at 8 steps a second (hand-drawn). To exempt objects: `outline({ offLayer: OUTLINE_OFF_LAYER })` and `mesh.layers.enable(OUTLINE_OFF_LAYER)`
209
+ (three.js layers; layer 0 stays on, so the object still renders normally; costs one extra render of just the exempt objects, nothing when
210
+ `offLayer` is `null`). Normal mode draws the scene with a plain override material, so wind-animated foliage lines up with its static shape.
211
+
212
+ Textures by asset name, grain / paper / strokes (`detail`), shadow tint, rim light, toon ramps and the GLSL exits are all spec keys: recipe 37.
213
+
214
+ ## 3. When the engine gets a new "look parameter"
215
+ Hard rule 1: a module only writes a neutral gray fallback and reads `engine.style.xxx ?? fallback`, **and the real value is added to the lowpoly pack
216
+ (its `index.js`) at the same time** (with a one-line comment saying what it means),
217
+ and the new field gets a doc comment in `types/style.d.ts` (`docs/api/` is generated from there). Materials always go through
218
+ `makeMaterial('role', { color })`, leaving the surface feel to `style.materials[role]`. Whose style: `engine.makeMaterial('role', { color })` uses that
219
+ engine's pack; the free `makeMaterial()` uses the first engine created (fine for one engine, a dev warning when two packs run). Engine code and style packs always
220
+ go through the engine (`create(engine, colors)`, `pickup.model(item, { color, size }, engine)`, `water.material(engine, ...)`), so two engines never share materials.
221
+ Look parameters only: a field that changes the world (a level, a size, a seed) goes to the module's options, not the style (section 0c).
222
+
223
+ ## 4. Verify
224
+ - `npm run check`: the hard-rule check reports "material created directly" (in engine modules, games and examples; style packs are allowed) and
225
+ "non-gray fallback color"; the type check catches misspelled keys in the style pack.
226
+ - `npm run map`: the "style pack keys" table in CODEMAP is updated.
227
+ - Take screenshots only when the look changed, and compare two times of day: `npm run shot -- / --time 12:00`, `npm run shot -- / --time 18:30`
228
+ (images go to .threedog/shots/).
229
+ - It must still run without a style pack: `npm test -- 小城`.
230
+
231
+ ## 5. Sounds and music (the game's, not the style pack's)
232
+ Sounds are game config, passed to `createEngine({ audio: { sounds, ambience, music, footsteps, levels } })` and read back as `engine.audio.config`; a
233
+ style pack carries none. The engine plays nothing the game did not name. Buses, sounds by name, the ambience rule table, music rules, footsteps and
234
+ ducking: `recipes/31-audio.md`.
@@ -0,0 +1,67 @@
1
+ # Importing Blender models and levels
2
+
3
+ ## 1. Place things in Blender by naming convention (the level module recognizes names)
4
+ | Purpose | How to name it |
5
+ |---|---|
6
+ | Walkable ground | Object name contains `ground` `floor` `road` `terrain` `stair(s)` `ramp`, or custom property `walkable = true` (if there are none, every mesh counts as walkable); ground type = custom property `groundType`, otherwise the material name |
7
+ | Walls / obstacles | `col_xxx`: a hidden collision box that only blocks the player (hidden automatically after loading); or custom property `collider = true` (a visible object that also blocks) |
8
+ | Spawn point | Empty object `spawn` (or `spawn_2`...) |
9
+ | NPC position | Empty object `npc_店主` |
10
+ | Trigger zone | Empty object `trigger_门口`; the custom properties `shape` (cylinder/sphere/box), `radius`, `height` become trigger zone parameters |
11
+ | Other markers | Empty object `marker_宝箱`; all custom properties go into `userData` unchanged |
12
+ | Things a save must know (a door that opens, a rock that can be removed) | Custom property `template = 'door'` (an instance of a content template; its other custom properties fill the template's state) or `id = true` (the node itself is the model). The node becomes a world record with id `<level file name>/<node name>` (`town/door_front`), saved as a diff (needs `world()` installed, and `content()` for `template`); untagged meshes stay static scenery (recipe 30 §2) |
13
+
14
+ Export glTF/GLB (tick "Custom Properties") into `art/models/` (create it if missing).
15
+
16
+ ## 2. Compression
17
+ `npm run assets` compresses to `public/models/<same name>.glb` (Meshopt geometry + WebP textures; `-- --ktx2` uses KTX2 textures). Object names and
18
+ hierarchy are kept; faces are not reduced. Only changed files are processed; `-- --force` redoes everything.
19
+
20
+ ## 3. Putting it in the game (main.js)
21
+ ```js
22
+ import { createEngine, presets, level, collision, followCamera, characters, interactions, dialogue, triggers, content, hlod } from 'threedog';
23
+ engine.use(level({ url: '/models/town.glb' }), collision(), followCamera(), characters(), interactions({ ...presets.interactions.nearest }), dialogue(), triggers(), content(), hlod());
24
+ engine.events.once('level:loaded', () => { // once: level:loaded fires again on every level change
25
+ engine.characters.createPlayer({ ...presets.player.thirdPerson, spawn: engine.level.spawn });
26
+ engine.content.load(data); // a place in content can be a marker name directly: { place: 'npc_店主' }
27
+ });
28
+ engine.start();
29
+ ```
30
+ - Trigger zone data: write `{ 门口: { fromLevel: true, onEnter: { toast: '欢迎' } } }` in `<game>/content/triggers.js` (tag = the name after `trigger_`).
31
+ - Content validation (`npm run check`) reads the level `.glb` files in `art/models/` and `public/models/` (needs `@gltf-transform/cli` installed):
32
+ marker names used in content (`{ place: 'npc_店主' }`) need no description in `content/places.js`; a `fromLevel` trigger zone must have a
33
+ `trigger_<tag>` node, and a node's `template` must exist in `content/templates.js`. Without a readable `.glb` the old rule holds (validation
34
+ skips `fromLevel`, GAMEMAP notes "cannot be read statically"); `level.js` is only for code-built levels.
35
+ - `npm run assets -- check` prints what the level will find in each model (spawns, colliders, triggers, template nodes, duplicate ids) plus
36
+ material / color-space suspicions; `-- --json` gives the same as data.
37
+ - `level:loaded` fires on every level change; for something done only once (creating the player) use `engine.events.once`. When the level changes, the
38
+ old level's trigger zones and the like are deleted automatically (`level.track`); NPCs, pickups and props placed by marker only lose their model
39
+ while their data stays (with a zone), and are rebuilt when you return to this level; things that were picked up / deleted stay gone.
40
+ - Get a marker in code: `engine.level.marker('marker_宝箱')?.position`, `engine.level.markersWith('npc_')`.
41
+ - Many buildings: install `hlod()`, which merges distant ones into a few meshes. For a navmesh see `12-navmesh.md`.
42
+ - A single model (not a level): `engine.assets.manifest({ models: { house: '/models/house.glb' } })`,
43
+ `const h = await engine.assets.model('house', { static: true })` (static: registers it for rays).
44
+ - For models with skeletal animation see `13-animation.md`.
45
+
46
+ ## 4. Grass and trees on a level
47
+ Without `terrain()`, `vegetation()` grows on its own chunks over whatever provides the ground: the level, a code-built ground (`engine.setGround`), or
48
+ the flat default. Rules read `engine.surface / slope / groundType`, so pick the level's surfaces by ground type (a mesh's `groundType` custom
49
+ property, else its material name) with `rule.biomes`, and limit the scatter with `area`:
50
+ ```js
51
+ engine.use(level({ url: '/models/town.glb' }), vegetation({ area: { min: [-80, -80], max: [80, 80] }, viewChunks: 3 }), collision());
52
+ engine.vegetation.add('grass', { geometry: grassGeo, nearOnly: true, rule: { perChunk: 500, biomes: { lawn: 1 } } });
53
+ engine.vegetation.add('tree', { model: oak, rule: { perChunk: 6, biomes: { lawn: 0.6, park: 1 }, maxSlope: 0.4, collider: 0.4 } });
54
+ ```
55
+ Chunks stream around `engine.stream` sources and stay one InstancedMesh per species per chunk (LOD, shadows and felling work as on terrain:
56
+ `instanceAt` / `removeInstance`, saved). Collision and path planning see the trees through `engine.ground.forEachCollider`; a new level or `setGround`
57
+ re-places them; after changing a ground function behind the same provider call `engine.vegetation.rebuild()`. Heights are unlimited unless the rule
58
+ sets `minHeight / maxHeight`. Content `vegetation` works the same way. With `terrain()` installed, `vegetation()` takes no options (density and view
59
+ distance are terrain options). Rapier (`rigid()`) bodies collide with them too (cylinders from `engine.ground.forEachCollider`, gone when felled).
60
+
61
+ ## 5. Verify
62
+ - `npm run assets` prints each file's size before and after compression; a browser 404 appears in `.threedog/errors.log` (asset load failure).
63
+ - `describe()`: `ready` is true and `loading` is empty; the player's coordinates are at the spawn point; `nearby` contains trigger zones
64
+ (`kind: 'trigger'`) and NPCs.
65
+ Text version: `npm run shot -- /your-page.html --describe-only`.
66
+ - Collision: `engine.collision.walkable({ x, z })` is false inside a col_ box; ground: `engine.surface(x, z)` equals the step / floor height.
67
+ - Related tests: `npm test -- 关卡`, `npm test -- "compressed assets"`, `npm test -- HLOD`, `npm test -- "vegetation ground"`.
@@ -0,0 +1,55 @@
1
+ # Vehicles and boarding
2
+
3
+ Required modules: `collision()` + `rigid()` (Rapier physics; the vehicle controller lives there) + `characters()`. With
4
+ `interactions({ ...presets.interactions.nearest })` installed, a "board/exit" prompt (E key) appears automatically near a vehicle.
5
+ Convention: **the front of the car faces the model's +Z**, and a wheel's `position` is relative to the body origin (meters). Rapier has to be
6
+ downloaded and initialized, so build the car after `engine:ready`.
7
+
8
+ ## 1. Build a car (main.js)
9
+ ```js
10
+ import { presets, THREE, makeMaterial } from 'threedog';
11
+
12
+ function makeCar() {
13
+ const car = new THREE.Group();
14
+ const body = new THREE.Mesh(new THREE.BoxGeometry(1.8, 0.6, 3.6), makeMaterial('vehicle', { color: 0xc04a3a }));
15
+ body.position.y = 0.3; body.castShadow = true; car.add(body);
16
+ const wheels = [[-0.85, 1.2, true, false], [0.85, 1.2, true, false], [-0.85, -1.2, false, true], [0.85, -1.2, false, true]].map(([x, z, steer, drive]) => {
17
+ const w = new THREE.Mesh(new THREE.CylinderGeometry(0.35, 0.35, 0.25, 10).rotateZ(Math.PI / 2), makeMaterial('vehicle', { color: 0x333333 }));
18
+ w.position.set(x, 0, z); car.add(w); // wheels are children of the body: they follow suspension, steering and rolling
19
+ return { position: [x, 0, z], radius: 0.35, steer, drive, object: w };
20
+ });
21
+ return { car, wheels };
22
+ }
23
+
24
+ engine.events.on('engine:ready', () => {
25
+ const { car, wheels } = makeCar();
26
+ car.position.set(10, engine.surface(10, 0) + 1.5, 0); // place it slightly above the ground and let it drop
27
+ const v = engine.rigid.addVehicle(car, { wheels, mass: 600, engineForce: 1200, camera: { distance: 14, height: 2 } });
28
+ window.car = v; // handy for tests and the console
29
+ });
30
+ ```
31
+ `addVehicle` options: `id` stable id (default `vehicle1`, `vehicle2`... in creation order; give one when that order varies), `wheels` (at least 3),
32
+ `mass` in kg, `engineForce` throttle force, `brakeForce`, `maxSteer` in radians, `suspension: { rest, stiffness, damping }`,
33
+ `seat` seat position, `camera` camera distance/height while driving, `size` body collision box (by default the model's bounding box, wheels excluded),
34
+ `friction` grip, `exitOffset` how far from the side of the body the player lands when exiting (meters, default 0.8).
35
+ Rigid bodies and vehicles do not change a model's shadow settings: set `mesh.castShadow = true` yourself if you want a shadow.
36
+
37
+ ## 2. Boarding and driving
38
+ - Player: press E near the car to board (when interactions is installed); while driving, WASD = throttle/steering; the brake key (action `brake`, only
39
+ when the game gives one: `characters({ ...presets.keys.brake })` is B / gamepad LT, or `characters({ brakeKeys: ['KeyX'] })`; keep it off Space so
40
+ it doesn't compete with jumping) brakes, and without one the engine warns once; press E again to exit.
41
+ - Saving: the player save records which vehicle the player is in (its `id`); loading an on-foot save while driving exits the vehicle first, and
42
+ loading a driving save puts the player back in the car.
43
+ - Code: `engine.player.enter(v)`, `engine.player.exit()`; `engine.player.vehicle` is the vehicle being driven (null when on foot); `v.driver` is who is driving.
44
+ - NPCs/scripts driving: `v.drive(throttle -1..1, steer -1..1 (right is positive), brake 0-1)`; the last values set are used on every fixed step.
45
+ - Events: `vehicle:enter`, `vehicle:exit` (`{ character, vehicle }`). Removal: `v.remove()` (anyone inside exits first; the model stays,
46
+ `engine.remove(car)` deletes it).
47
+ - Native objects: `v.body` (Rapier rigid body), `v.controller` (vehicle controller), `v.speed` (m/s, negative when reversing).
48
+
49
+ ## 3. Verify
50
+ - In a test (no real key presses): `engine.player.enter(car); engine.input.autopilot = { x: 0, y: 1 }; engine.step(3)`,
51
+ then `describe().player.vehicle.speed` is above 0 and the car has moved; after `engine.player.exit()`, `engine.player.vehicle` is null and the
52
+ player stands outside the door.
53
+ - Vehicle speed is only in the object form `engine.describe().player.vehicle` (the player line of describeText does not show it);
54
+ `describe().player.mover` and `grounded` are there too.
55
+ - Related test: `npm test -- 载具` (test page in the engine repository: `packages/engine/tests/vehicle/`, with a complete car and steps).
@@ -0,0 +1,79 @@
1
+ # Navigation mesh (nav)
2
+
3
+ There is a single pathfinding entry point: `engine.characters.findPath(from, to)`; NPC schedules use it too.
4
+ - Without `nav()` (or before it is built): the collision module's grid A* (good enough for open terrain with a few obstacles).
5
+ - With `nav()`: after a level loads, a Recast navmesh is built; paths are more accurate and go around walls more cleverly. **Only level ground (the
6
+ level module) is supported for now**; procedural terrain keeps using A*.
7
+
8
+ ## 1. Install (main.js)
9
+ ```js
10
+ import { level, collision, followCamera, characters, nav } from 'threedog';
11
+ engine.use(level({ url: '/models/town.glb' }), collision(), followCamera(), characters(),
12
+ nav({ agentRadius: 0.4, agentHeight: 1.8, maxClimb: 0.45, maxSlope: 45, debug: false })); // debug: true draws the navmesh
13
+ ```
14
+ - Mesh source: the walkable meshes in the level (naming convention in `10-blender-level.md`). Walls = the level's `col_` boxes + every
15
+ `addBox / addCircle` in the collision module;
16
+ they sync automatically as dynamic obstacles: add an obstacle in game and the affected tiles rebuild themselves, no manual refresh.
17
+ - Recast (about 1 MB) is downloaded only in start(); until it is ready findPath falls back to A*.
18
+
19
+ ## 2. Use
20
+ ```js
21
+ const path = engine.characters.findPath(engine.player.position, { x: 4, z: 5 }); // [{ x, z }...] or null (unreachable)
22
+ const wall = engine.collision.addBox([16, 0, 0], { halfWidth: 4.5, halfDepth: 1 }); // temporarily block a gap (center, half width, half depth); the navmesh updates with it
23
+ wall.remove(); // remove the obstacle
24
+ engine.npcs.add({ name: '信使', position: [4, 0, -5], schedule: [{ at: 0, position: [4, 0, 5] }] }); // the NPC finds its own way there
25
+ engine.nav.dispose(); // unload the navmesh; afterwards A* is used again
26
+ ```
27
+ Native Recast objects: `engine.nav.navMesh / query / tileCache / crowd` (crowd needs `nav({ crowd: true })`).
28
+
29
+ ## 3. Verify
30
+ - `describe().nav`: `{ ready: true, version, obstacles: number of obstacles }`; in `describeText()` it is the "nav: {...}" line.
31
+ - In a test: after `engine.pause()` call `findPath` and look at the waypoints (going around a wall they pass through the gap); after `addBox`,
32
+ `engine.step(0.1)` and query again: the path should switch sides.
33
+ - Did the NPC arrive: after `engine.step(30)`, check `engine.npcs.get('信使').position`.
34
+ - To see the mesh: `nav({ debug: true })` + `npm run shot -- /your-page.html`. Related test: `npm test -- 导航网格` (test page in the engine repository:
35
+ `packages/engine/tests/nav/`).
36
+
37
+ ## 4. Many paths at once: findPathAsync
38
+ `findPath` answers now, on the main thread. For crowds (dozens of NPCs repathing, AI squads) use `findPathAsync`: the same search (navmesh if ready, else A*)
39
+ runs in `engine.threads` workers and `done(path, status)` runs at the start of a fixed step about 4 steps (67 ms) later, through `engine.commits`.
40
+ ```js
41
+ const req = engine.characters.findPathAsync(guard.position, target, (path, status) => { // status 'ok' | 'noPath' | 'notReady', as findPath({ detailed: true })
42
+ guard.path = path;
43
+ }, { radius: 0.5 });
44
+ req.remove(); // the target changed before the answer came: done is never called
45
+ engine.characters.pathsPerStep = 64; // requests sent per fixed step (default 32); the rest wait in order
46
+ ```
47
+ - Built-in NPCs already use it; keep `findPath` for the few calls that need a path this step (player click-to-move).
48
+ - threads on / off / slow / crashed give identical paths on the identical step: the worker mirrors the navmesh (exported bytes) and the collision colliders;
49
+ if either changes while a batch is in flight, that batch is recomputed on the main thread on the new state.
50
+ - With A*, ground shape (water, slope) is sampled on a 1 m raster cached 5 s (colliders and terrain trees are tested exactly), and the search stays inside
51
+ the start-goal box plus a margin, so an async path can differ slightly from `findPath`'s.
52
+ - A save taken while a request is in flight does not keep it: the NPC asks again after loading. Tests: `npm test -- "paths:"`.
53
+
54
+ ## 5. One source for "can walk there"
55
+ `createEngine({ movement: { radius, height, maxSlope, stepHeight } })` sets it once; read it as `engine.movement`. Collision, the Rapier capsule, the
56
+ navmesh, A* and level steps all read it, so a module never writes its own 0.4 or 0.45. A character's position belongs to its mover: other systems
57
+ request movement (`placeAt`, `move`, vehicle `enter`) and never set `player.position`.
58
+
59
+ ## Fences and rivers (collision)
60
+
61
+ Walls and water that are not meshes: `engine.collision.addSegment(a, b, { thickness })` is a thin wall along a line; `addBlocked(fn)` marks ground impassable where `fn(x, z)` is true. Both return `{ remove() }` and are free when unused.
62
+
63
+ ```js
64
+ // A river along x 5..9 with a bridge at z -1..1: the bridge is just a hole in the blocked function
65
+ engine.collision.addBlocked((x, z) => x > 5 && x < 9 && !(z > -1 && z < 1), { bounds: { minX: 5, maxX: 9, minZ: -50, maxZ: 50 } });
66
+ // A fence with a gate: two segments, the gap between them is the gate
67
+ engine.collision.addSegment([-18, 0, -12], [-18, 0, -4]);
68
+ engine.collision.addSegment([-18, 0, 0], [-18, 0, 12], { thickness: 0.4 });
69
+ ```
70
+
71
+ Walkers stop at the edge and slide along it; `collision.walkable()` and A* pathing, sync and async, see both. `fn` must be pure and deterministic (no clock, no random). Async paths cannot send a function to the worker, so `fn` is sampled into the 1 m ground raster instead (re-sampled when you add or remove a field): give `bounds`, or every requested tile is sampled in full. Navmesh mode (`nav()` installed) does not see `addBlocked`; use `addSegment` or bake the river into the mesh there.
72
+
73
+ ## Line of sight and straight-line checks: collision.lineClear
74
+ `engine.collision.lineClear(a, b, { radius })` answers "is anything solid between a and b?" for a 3D segment: boxes, circles and terrain trees, with heights (a 1 m wall does not block a sight line 3 m above it; a collider's `y` / `height` count). It is a boolean; `addBlocked` water is ignored. Give eye heights in `a` / `b`; `radius` fattens the line (pass the character radius for "can I walk straight there").
75
+ ```js
76
+ const sees = engine.collision.lineClear([guard.x, 1.6, guard.z], [player.x, 1.6, player.z]); // true = clear view
77
+ const straight = engine.collision.lineClear(me.position, goal, { radius: engine.movement.radius });
78
+ ```
79
+ The A* fallback smooths paths with the same idea: it samples each shortcut at most one character radius apart (so a thin fence cannot be skipped), starts from the character's real position, and its cell size follows `radius` (1-2 m) unless you pass `step`.
@@ -0,0 +1,149 @@
1
+ # Animation state machine (skeletal animation)
2
+
3
+ There is a single entry point: `engine.assets.animate(model, config)` -> Animator (advanced every frame by the engine; never call mixer.update yourself).
4
+ For characters (player, NPCs), passing `model` builds the Animator automatically and switches clips by character state (idle walk run swim jump fall drive).
5
+
6
+ ## 1. The model
7
+ Export a glTF with animations from Blender, put it in `art/models/` -> `npm run assets` -> `public/models/hero.glb`. Register it and fetch a copy (the
8
+ skeleton is cloned correctly; clips are in `userData.animations`):
9
+ ```js
10
+ engine.assets.manifest({ models: { hero: '/models/hero.glb', dog: '/models/dog.glb' } });
11
+ const hero = await engine.assets.model('hero');
12
+ ```
13
+
14
+ ## 2. Mapping: game action names -> whatever the asset calls its clips
15
+ States are the mapping. The left side is what your game says (`idle`, `attack`, `hurt`), the right side is the clip name in the file, so a new model
16
+ only changes the right side:
17
+ ```js
18
+ states: { idle: { clip: 'Idle_Sword' }, attack: { clip: 'Sword_Slash', loop: false }, hurt: { clip: 'HitRecieve', loop: false }, death: { clip: 'Death', loop: false } }
19
+ ```
20
+ **Keep the mapping as data, on the model's manifest entry** (it describes the file, so it travels with it in an asset pack). `assets.animate(model)`
21
+ and characters start from it; config passed in code adds states and wins per state. Swapping the model then only edits its manifest entry:
22
+ ```js
23
+ engine.assets.manifest({ name: 'heroes', models: { hero: { url: '/models/hero.glb', animation: {
24
+ fade: 0.2,
25
+ states: { idle: { clip: 'Idle_Sword' }, walk: { clip: 'Walk' }, attack: { clip: 'Sword_Slash', loop: false, timing: 0.62 }, hurt: { clip: 'HitRecieve', loop: false } },
26
+ } } } });
27
+ engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'hero' }); // no clips / animation in code
28
+ engine.assets.mapping(engine.player.anim.root); // after whenReady: the entry's mapping, or null
29
+ ```
30
+ A character's default names (`Idle`, `Walk`...) never shadow a mapped state, and the entry's `fade` beats the style pack's.
31
+
32
+ - A clip name also matches the part after the last `|`: Blender / FBX2glTF exports `CharacterArmature|Idle`, you write `Idle`.
33
+ - Dev checks: a state whose clip is not in the model warns at `assets.animate()` with the available clip names and where to fix it
34
+ (`state "attack" maps to a missing clip ... Fix the clip name in manifest "heroes" models.hero.animation.states.attack`); unknown keys
35
+ (`loops: false`) warn ``did you mean `loop`?``; `go('atack')` / `sync('atack')` warn ``did you mean `attack`?`` and return null.
36
+ - **Check the actions the game plays**, once after building (a test, the console): `anim.check(['idle', 'walk', 'attack', 'hurt'])` returns `[]`, or
37
+ one line per problem with its fix
38
+ (`action "hurt" has no state. Add it to manifest "heroes" models.hero.animation.states.hurt: { clip: '<name>' } (clips in the model: ...)`). A model
39
+ with no clips says so.
40
+ - Several states may share one clip (they share one AnimationAction, so switching between them does not cross-fade).
41
+ - Bone names: GLTFLoader drops dots, so `Wrist.R` becomes `WristR` in `model.getObjectByName`.
42
+
43
+ ## 3. A character with a skinned model (most common)
44
+ ```js
45
+ engine.characters.createPlayer({ ...presets.player.thirdPerson, model: hero,
46
+ clips: { idle: 'Idle', walk: 'Walk', run: 'Run', jump: 'Jump' }, // character state -> clip name in the glTF; states you leave out use the capitalised name if the model has that clip
47
+ });
48
+ engine.player.playAction('Wave'); // one-shot clip (skipped if the clip doesn't exist); returns to the previous state when done
49
+ engine.player.anim.state; // current state name
50
+ ```
51
+ For smooth walk/run blending, use `animation` instead of `clips` and write a `move` blend tree (when the model has no walk/run states, move is used
52
+ automatically; the `speed` parameter is in m/s):
53
+ ```js
54
+ engine.characters.createPlayer({ ...presets.player.thirdPerson, model: hero, animation: { states: {
55
+ idle: { clip: 'Idle' },
56
+ move: { blend: [{ clip: 'Walk', at: 1.5 }, { clip: 'Run', at: 6 }], param: 'speed', sync: true }, // sync: align footsteps
57
+ jump: { clip: 'Jump', loop: false },
58
+ } } });
59
+ ```
60
+ The default transition time comes from the style pack's `style.character.animation.fade`.
61
+
62
+ **By asset name.** `model` also takes the name of a registered model asset, and a style pack can set `style.character.model: 'hero'` as the default
63
+ for every character (a per-character `model` wins). The character is built at once with the placeholder body (the style's `create()` or the gray
64
+ capsule); when the asset loads, a skeleton-correct copy replaces it under the same root, so position, facing, state, collision and the world view
65
+ stay. Then `ready` turns true, `whenReady` settles and `character:model` is emitted. A name missing from a registered manifest throws with the
66
+ registered names; a failed load keeps the placeholder and warns once; a character disposed before loading ends never gets the model.
67
+ ```js
68
+ engine.assets.manifest({ models: { hero: '/models/hero.glb' } });
69
+ const p = engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'hero' }); // placeholder now, the hero once loaded
70
+ await p.whenReady; // p.anim is set from here (unless the load failed)
71
+ ```
72
+
73
+ ## 4. Non-character objects (a dog, a windmill, a door)
74
+ ```js
75
+ const dog = await engine.assets.model('dog'); engine.add(dog);
76
+ const anim = engine.assets.animate(dog, {
77
+ fade: 0.25,
78
+ states: {
79
+ idle: { clip: 'Idle' },
80
+ move: { blend: [{ clip: 'Walk', at: 1 }, { clip: 'Run', at: 5 }], param: 'speed' },
81
+ bark: { clip: 'Bark', loop: false, then: 'idle', lock: true }, // one-shot; lock: go() doesn't interrupt it while it plays
82
+ },
83
+ transitions: { '*>idle': 0.4 }, // transition seconds for specific switches
84
+ });
85
+ anim.go('idle');
86
+ anim.set('speed', 3); anim.go('move'); // just set the speed every frame
87
+ anim.action('bark');
88
+ engine.events.on('anim:end', ({ root, state }) => { if (root === dog) console.log(state, 'finished'); });
89
+ anim.dispose(); // no longer needed: stop per-frame updates (call this when deleting the model)
90
+ ```
91
+ **Gameplay timing never reads the animation**: the mixer advances per frame and `anim:end` is emitted per frame, so dropped frames, fast-forward
92
+ (step's frameEvery) and a model being torn down when it is far away all make it drift from game time. When an attack lands, cooldowns, recovery and
93
+ "finish the swing before moving" are timed in fixed steps:
94
+ ```js
95
+ engine.input.define('attack', ['KeyF', 'Mouse0'], 'Attack'); // no module binds it for you
96
+ let t = -1; // seconds since the swing started (-1 = not swinging); put it in a world record if it must be saved
97
+ engine.onFixed(dt => {
98
+ if (t < 0) { if (!engine.input.pressed('attack')) return; t = 0; }
99
+ const before = t; t += dt;
100
+ if (before < 0.3 && t >= 0.3) hitEnemiesInFront(); // hit check at 0.3 s
101
+ if (t >= 0.6) t = -1; // can swing again after 0.6 s
102
+ engine.player.anim.sync(t < 0 ? null : 'attack', t); // the animation follows t (the attack state of section 5)
103
+ });
104
+ ```
105
+ ## 5. Gameplay controls progress: `sync(state, t)`
106
+ Who owns the clock: **gameplay**. An action timeline counts `t` in fixed-step seconds (recipe 06) and decides hit windows, i-frames and when the
107
+ action ends; the animation only shows `t`.
108
+ `anim.sync(state, t)` poses `state` at gameplay time `t`: the clip does not advance or end by itself (no `anim:end`), and `go()` / `action()` leave it
109
+ alone, so a character's per-frame locomotion cannot override it. `sync(null)` hands control back; the next `go()` switches as usual. Entering a synced
110
+ state cross-fades like `go()` (the `transitions` table applies).
111
+ `timing` on the state maps gameplay seconds to clip seconds:
112
+ ```js
113
+ const anim = engine.player.anim; // or engine.assets.animate(model, {...})
114
+ Object.assign(anim.states, {
115
+ // gameplay: windup 0-0.16, hit 0.16-0.28, recovery 0.28-0.62. The clip raises the sword until 0.24 s and brings it down by 0.5 s:
116
+ attack: { clip: 'Sword_Slash', loop: false, timing: [[0, 0], [0.16, 0.24], [0.28, 0.5], [0.62, 1]] }, // piecewise linear
117
+ roll: { clip: 'Roll', loop: false, timing: 0.62 }, // a number: stretch the whole clip over 0.62 gameplay seconds
118
+ hurt: { clip: 'HitRecieve', loop: false, timing: 0.45 },
119
+ death: { clip: 'Death', loop: false }, // no timing: clip seconds = t (clamped at the last frame)
120
+ });
121
+ engine.onFixed(() => { // one call site: whatever gameplay is doing decides the pose
122
+ if (f.dead) anim.sync('death', f.deadT);
123
+ else if (f.stun > 0) anim.sync('hurt', f.stunMax - f.stun);
124
+ else if (f.act) anim.sync(f.act.id, f.act.t);
125
+ else anim.sync(null); // free: locomotion (idle / walk / run) takes over
126
+ });
127
+ ```
128
+ - Calibrate `timing` once by looking: sync the raw clip (no timing) at a few `t` and watch the weapon hand (`describe()` or a bone's world position);
129
+ put the down-swing inside the hit phase.
130
+ - Pause, fast-forward, hit-stop (t stays still), loading mid-action and replays all line up, because the pose is a pure function of `t`.
131
+ - Looping states wrap `t`, one-shots clamp it to the clip.
132
+
133
+ Use `anim:end` only for presentation (change an expression, play the next clip). Native objects: `anim.mixer` (AnimationMixer), `anim.actions` (clip
134
+ name -> AnimationAction). Things without a skeleton that only move/rotate as a whole use `engine.timeline.tween`, not an Animator.
135
+
136
+ Bones after the pose: `const h = player.onPose((c, dt) => { sword.position.copy(hand.getWorldPosition(v)); })` runs every frame right after the character's pose is
137
+ applied (clips or procedural rig); `h.remove()` stops it. Presentation only.
138
+
139
+ ## 6. Verify
140
+ - `anim.describe()` -> `{ state, clip, time, progress, driven, t, weights }` (clip seconds, 0-1 progress, whether sync drives it, the last gameplay t,
141
+ each fading state's share); the player's is in `describe().player.anim`.
142
+ - In a test: `engine.pause(); anim.go('move'); engine.step(0.4)`, then look at `anim.state` and `anim.actions.get('Walk').getEffectiveWeight()` (all
143
+ clip weights sum to 1).
144
+ - Characters: `describe().player.state` (idle/walk/run...) matches `engine.player.anim.state`.
145
+ - `anim.check([...actions])` is `[]`.
146
+ - Related tests: `npm test -- "Animation state machine"` (in the engine repository: two-bone figure built in code by `makeRig()`, in
147
+ `packages/engine/tests/vehicle/`), `npm test -- 骨骼动画链路` (a real CC0 glTF character, `packages/engine/tests/anim/`: manifest mapping, cross-fade, sync, alignment of the
148
+ slash with the hit phase, dev warnings) and `npm test -- 骨骼动画最小链路` (a skinned GLB generated in code by `tests/anim/rig.js` through GLTFExporter,
149
+ loaded like a file: manifest mapping, `check`, sync holding the pose against frame time).