threedog 0.0.0-stage → 0.1.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 (459) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +39 -2
  4. package/core/Animator.js +267 -0
  5. package/core/Assets.js +240 -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/Describe.js +134 -0
  13. package/core/Engine.js +221 -0
  14. package/core/Events.js +95 -0
  15. package/core/I18n.js +94 -0
  16. package/core/Input.js +245 -0
  17. package/core/Inspect.js +97 -0
  18. package/core/InspectScene.js +187 -0
  19. package/core/Jobs.js +146 -0
  20. package/core/Loading.js +149 -0
  21. package/core/Ops.js +272 -0
  22. package/core/Random.js +52 -0
  23. package/core/Rays.js +160 -0
  24. package/core/SaveStore.js +85 -0
  25. package/core/Saves.js +253 -0
  26. package/core/Stream.js +279 -0
  27. package/core/Threads.js +158 -0
  28. package/core/UrlState.js +93 -0
  29. package/core/Vars.js +34 -0
  30. package/core/actor.js +23 -0
  31. package/core/assetEntry.js +89 -0
  32. package/core/assetLoad.js +190 -0
  33. package/core/assetManifest.js +35 -0
  34. package/core/audioRules.js +121 -0
  35. package/core/audioVoice.js +225 -0
  36. package/core/batchGroups.js +116 -0
  37. package/core/canvasBox.js +63 -0
  38. package/core/dayTime.js +15 -0
  39. package/core/describeText.js +136 -0
  40. package/core/easing.js +34 -0
  41. package/core/errorCodes.js +172 -0
  42. package/core/errorHints.js +203 -0
  43. package/core/errors.js +40 -0
  44. package/core/events.generated.js +84 -0
  45. package/core/ground.js +102 -0
  46. package/core/inputContext.js +69 -0
  47. package/core/inputDefaults.js +22 -0
  48. package/core/inputPad.js +35 -0
  49. package/core/inputPointer.js +48 -0
  50. package/core/inputTouch.js +48 -0
  51. package/core/lifecycle.js +68 -0
  52. package/core/lightWatch.js +36 -0
  53. package/core/loop.js +199 -0
  54. package/core/math.js +33 -0
  55. package/core/modules.js +182 -0
  56. package/core/movement.js +19 -0
  57. package/core/mulberry32.js +14 -0
  58. package/core/opsCheck.js +86 -0
  59. package/core/opsGuard.js +26 -0
  60. package/core/opsHistory.js +27 -0
  61. package/core/page.js +78 -0
  62. package/core/pureWorker.js +5 -0
  63. package/core/saveApply.js +128 -0
  64. package/core/saveFiles.js +139 -0
  65. package/core/saveIds.js +53 -0
  66. package/core/saveVersions.js +97 -0
  67. package/core/scatter.js +92 -0
  68. package/core/sceneMethods.js +125 -0
  69. package/core/screenToGround.js +39 -0
  70. package/core/session.js +171 -0
  71. package/core/shadowTypes.js +15 -0
  72. package/core/skip.js +104 -0
  73. package/core/startup.js +133 -0
  74. package/core/streamCells.js +24 -0
  75. package/core/streamSources.js +73 -0
  76. package/core/styleParts.js +96 -0
  77. package/core/targeting.js +64 -0
  78. package/core/thingOps.js +157 -0
  79. package/core/things.js +198 -0
  80. package/core/threadPure.js +120 -0
  81. package/core/threadServe.js +25 -0
  82. package/core/tier.js +11 -0
  83. package/core/validate.js +188 -0
  84. package/docs/AI.md +149 -0
  85. package/docs/API.md +84 -0
  86. package/docs/CODEMAP.md +335 -0
  87. package/docs/COMMANDS.md +96 -0
  88. package/docs/CONVENTIONS.md +134 -0
  89. package/docs/PERF.md +217 -0
  90. package/docs/THREE.md +86 -0
  91. package/docs/api/ambience.md +15 -0
  92. package/docs/api/assets.md +60 -0
  93. package/docs/api/audio.md +53 -0
  94. package/docs/api/budget.md +40 -0
  95. package/docs/api/cameraRig.md +120 -0
  96. package/docs/api/characters.md +142 -0
  97. package/docs/api/clock.md +7 -0
  98. package/docs/api/collision.md +35 -0
  99. package/docs/api/content.md +63 -0
  100. package/docs/api/debug.md +10 -0
  101. package/docs/api/dialogue.md +39 -0
  102. package/docs/api/engine.md +190 -0
  103. package/docs/api/entities.md +61 -0
  104. package/docs/api/events.md +91 -0
  105. package/docs/api/flow.md +27 -0
  106. package/docs/api/grids.md +11 -0
  107. package/docs/api/ground.md +16 -0
  108. package/docs/api/hlod.md +34 -0
  109. package/docs/api/hud.md +31 -0
  110. package/docs/api/i18n.md +10 -0
  111. package/docs/api/input.md +24 -0
  112. package/docs/api/interactions.md +31 -0
  113. package/docs/api/inventory.md +66 -0
  114. package/docs/api/jobs.md +10 -0
  115. package/docs/api/level.md +41 -0
  116. package/docs/api/lightPool.md +56 -0
  117. package/docs/api/music.md +34 -0
  118. package/docs/api/nav.md +26 -0
  119. package/docs/api/net.md +14 -0
  120. package/docs/api/openWorld.md +24 -0
  121. package/docs/api/particles.md +41 -0
  122. package/docs/api/photo.md +15 -0
  123. package/docs/api/post.md +9 -0
  124. package/docs/api/quests.md +36 -0
  125. package/docs/api/rays.md +26 -0
  126. package/docs/api/rigid.md +84 -0
  127. package/docs/api/saves.md +31 -0
  128. package/docs/api/settings.md +36 -0
  129. package/docs/api/sky.md +58 -0
  130. package/docs/api/stream.md +31 -0
  131. package/docs/api/style.md +134 -0
  132. package/docs/api/terrain.md +34 -0
  133. package/docs/api/timeline.md +39 -0
  134. package/docs/api/tools.md +55 -0
  135. package/docs/api/triggers.md +56 -0
  136. package/docs/api/vars.md +9 -0
  137. package/docs/api/vegetation.md +52 -0
  138. package/docs/api/water.md +48 -0
  139. package/docs/api/weather.md +29 -0
  140. package/docs/api/world.md +30 -0
  141. package/docs/recipes/01-new-game.md +148 -0
  142. package/docs/recipes/02-npc.md +151 -0
  143. package/docs/recipes/03-items-pickups.md +158 -0
  144. package/docs/recipes/04-quests.md +83 -0
  145. package/docs/recipes/05-props-bake.md +159 -0
  146. package/docs/recipes/06-clock-events.md +104 -0
  147. package/docs/recipes/07-flow-scenes-pause.md +128 -0
  148. package/docs/recipes/08-weather-sky.md +74 -0
  149. package/docs/recipes/09-style-pack.md +234 -0
  150. package/docs/recipes/10-blender-level.md +67 -0
  151. package/docs/recipes/11-vehicles.md +55 -0
  152. package/docs/recipes/12-navmesh.md +57 -0
  153. package/docs/recipes/13-animation.md +146 -0
  154. package/docs/recipes/14-custom-module.md +91 -0
  155. package/docs/recipes/15-perf.md +78 -0
  156. package/docs/recipes/16-dev-bridge.md +146 -0
  157. package/docs/recipes/18-world.md +185 -0
  158. package/docs/recipes/19-shooting-picking.md +76 -0
  159. package/docs/recipes/20-content-actions-save.md +176 -0
  160. package/docs/recipes/21-camera.md +104 -0
  161. package/docs/recipes/22-shop-gold.md +107 -0
  162. package/docs/recipes/23-ops.md +139 -0
  163. package/docs/recipes/26-ui-parts.md +138 -0
  164. package/docs/recipes/27-net.md +96 -0
  165. package/docs/recipes/28-terrain.md +80 -0
  166. package/docs/recipes/29-grid.md +87 -0
  167. package/docs/recipes/30-templates.md +131 -0
  168. package/docs/recipes/31-audio.md +126 -0
  169. package/docs/recipes/32-action-game.md +33 -0
  170. package/docs/recipes/33-stream-sources.md +37 -0
  171. package/docs/recipes/34-environment-lighting.md +35 -0
  172. package/docs/recipes/35-style-from-reference.md +89 -0
  173. package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
  174. package/docs/recipes/37-terrain-look-hooks.md +97 -0
  175. package/docs/recipes/38-environment-look-hooks.md +81 -0
  176. package/docs/recipes/40-scene.md +79 -0
  177. package/docs/recipes/41-thing-registry.md +64 -0
  178. package/docs/recipes/42-terrain-shape.md +64 -0
  179. package/docs/recipes/43-shader-patches-surface-looks.md +118 -0
  180. package/docs/recipes/44-water-weather-look-hooks.md +133 -0
  181. package/docs/recipes/45-cascaded-shadows.md +51 -0
  182. package/docs/recipes/46-blender-art-route.md +92 -0
  183. package/docs/recipes/47-island-snow-backdrop.md +44 -0
  184. package/examples/action/DESIGN.md +3 -0
  185. package/examples/action/GAMEMAP.md +127 -0
  186. package/examples/action/content/actions.js +8 -0
  187. package/examples/action/content/audio.js +9 -0
  188. package/examples/action/content/index.js +9 -0
  189. package/examples/action/content/items.js +4 -0
  190. package/examples/action/content/places.js +4 -0
  191. package/examples/action/content/props.js +11 -0
  192. package/examples/action/content/templates.js +10 -0
  193. package/examples/action/look.js +5 -0
  194. package/examples/action/main.js +137 -0
  195. package/examples/action/models.js +25 -0
  196. package/examples/sheepisland/GAMEMAP.md +108 -0
  197. package/examples/sheepisland/content/index.js +6 -0
  198. package/examples/sheepisland/content/props.js +19 -0
  199. package/examples/sheepisland/content/templates.js +5 -0
  200. package/examples/sheepisland/content/vegetation.js +8 -0
  201. package/examples/sheepisland/main.js +71 -0
  202. package/examples/sheepisland/params.js +25 -0
  203. package/examples/sheepisland/style/index.js +79 -0
  204. package/examples/sheepisland/style/models.js +59 -0
  205. package/examples/sheepisland/views.js +9 -0
  206. package/examples/styletest/GAMEMAP.md +135 -0
  207. package/examples/styletest/content/index.js +9 -0
  208. package/examples/styletest/content/items.js +8 -0
  209. package/examples/styletest/content/npcs.js +8 -0
  210. package/examples/styletest/content/places.js +5 -0
  211. package/examples/styletest/content/props.js +16 -0
  212. package/examples/styletest/content/templates.js +9 -0
  213. package/examples/styletest/content/vegetation.js +31 -0
  214. package/examples/styletest/look.js +11 -0
  215. package/examples/styletest/main.js +95 -0
  216. package/examples/styletest/models.js +87 -0
  217. package/examples/styletest/overrides.js +33 -0
  218. package/examples/styletest/panel.js +135 -0
  219. package/examples/styletest/params.js +32 -0
  220. package/examples/styletest/views.js +31 -0
  221. package/examples/world/DESIGN.md +5 -0
  222. package/examples/world/GAMEMAP.md +171 -0
  223. package/examples/world/content/actions.js +8 -0
  224. package/examples/world/content/audio.js +25 -0
  225. package/examples/world/content/bodies.js +12 -0
  226. package/examples/world/content/containers.js +4 -0
  227. package/examples/world/content/dialogues.js +33 -0
  228. package/examples/world/content/index.js +17 -0
  229. package/examples/world/content/items.js +10 -0
  230. package/examples/world/content/npcs.js +14 -0
  231. package/examples/world/content/pickups.js +11 -0
  232. package/examples/world/content/places.js +6 -0
  233. package/examples/world/content/props.js +12 -0
  234. package/examples/world/content/quests.js +15 -0
  235. package/examples/world/content/rules.js +23 -0
  236. package/examples/world/content/templates.js +5 -0
  237. package/examples/world/content/vegetation.js +32 -0
  238. package/examples/world/main.js +168 -0
  239. package/examples/world/models.js +28 -0
  240. package/index.d.ts +279 -0
  241. package/index.js +120 -0
  242. package/llms.txt +56 -0
  243. package/modules/ambience/Ambience.js +183 -0
  244. package/modules/camera/FirstPersonCamera.js +133 -0
  245. package/modules/camera/FixedCamera.js +155 -0
  246. package/modules/camera/FollowCamera.js +85 -0
  247. package/modules/camera/RtsCamera.js +134 -0
  248. package/modules/camera/common.js +152 -0
  249. package/modules/camera/index.js +11 -0
  250. package/modules/characters/Character.js +223 -0
  251. package/modules/characters/NPC.js +242 -0
  252. package/modules/characters/assetModel.js +42 -0
  253. package/modules/characters/astar.js +59 -0
  254. package/modules/characters/behaviors.js +72 -0
  255. package/modules/characters/footsteps.js +13 -0
  256. package/modules/characters/index.js +212 -0
  257. package/modules/characters/moveHelpers.js +29 -0
  258. package/modules/characters/movers/common.js +62 -0
  259. package/modules/characters/movers/rapier.js +74 -0
  260. package/modules/characters/movers/simple.js +38 -0
  261. package/modules/characters/npcAvoid.js +129 -0
  262. package/modules/characters/npcSim.js +144 -0
  263. package/modules/characters/npcView.js +42 -0
  264. package/modules/characters/pathAsync.js +107 -0
  265. package/modules/characters/pathJob.js +61 -0
  266. package/modules/characters/pathWorker.js +7 -0
  267. package/modules/characters/playerStrings.js +12 -0
  268. package/modules/characters/proceduralRig.js +54 -0
  269. package/modules/collision/Collision.js +176 -0
  270. package/modules/collision/grid.js +63 -0
  271. package/modules/content/ids.js +95 -0
  272. package/modules/content/index.js +152 -0
  273. package/modules/content/loader.js +187 -0
  274. package/modules/content/models.js +69 -0
  275. package/modules/content/packs.js +69 -0
  276. package/modules/content/props.js +89 -0
  277. package/modules/content/rules.js +133 -0
  278. package/modules/content/templates.js +189 -0
  279. package/modules/debug/DebugPanel.js +168 -0
  280. package/modules/entities/Entities.js +239 -0
  281. package/modules/entities/build.js +25 -0
  282. package/modules/entities/index.js +4 -0
  283. package/modules/flow/index.js +98 -0
  284. package/modules/gameplay/Container.js +227 -0
  285. package/modules/gameplay/Containers.js +89 -0
  286. package/modules/gameplay/Dialogue.js +216 -0
  287. package/modules/gameplay/Interactions.js +243 -0
  288. package/modules/gameplay/Inventory.js +214 -0
  289. package/modules/gameplay/Quests.js +195 -0
  290. package/modules/gameplay/boxOps.js +60 -0
  291. package/modules/gameplay/dialogueBox.js +48 -0
  292. package/modules/gameplay/interactionPrompt.js +28 -0
  293. package/modules/gameplay/inventoryOps.js +137 -0
  294. package/modules/gameplay/pickups.js +113 -0
  295. package/modules/gameplay/questLog.js +54 -0
  296. package/modules/gameplay/questSave.js +71 -0
  297. package/modules/grid/Grid.js +184 -0
  298. package/modules/grid/Layer.js +142 -0
  299. package/modules/grid/index.js +236 -0
  300. package/modules/grid/ops.js +73 -0
  301. package/modules/grid/preview.js +85 -0
  302. package/modules/grid/tiles.js +75 -0
  303. package/modules/hlod/index.js +164 -0
  304. package/modules/hud/index.js +164 -0
  305. package/modules/hud/parts.js +80 -0
  306. package/modules/level/geometry.js +46 -0
  307. package/modules/level/heightfield.js +160 -0
  308. package/modules/level/index.js +231 -0
  309. package/modules/level/nodes.js +84 -0
  310. package/modules/lights/index.js +224 -0
  311. package/modules/music/Music.js +290 -0
  312. package/modules/music/index.js +2 -0
  313. package/modules/music/rules.js +28 -0
  314. package/modules/nav/index.js +154 -0
  315. package/modules/nav/navPath.js +17 -0
  316. package/modules/net/Client.js +136 -0
  317. package/modules/net/Host.js +117 -0
  318. package/modules/net/Net.js +49 -0
  319. package/modules/net/index.js +75 -0
  320. package/modules/net/sync.js +114 -0
  321. package/modules/net/transports.js +118 -0
  322. package/modules/particles/Particles.js +179 -0
  323. package/modules/particles/effect.js +112 -0
  324. package/modules/particles/shaders.js +28 -0
  325. package/modules/photo/Photo.js +143 -0
  326. package/modules/rigid/RigidBodies.js +262 -0
  327. package/modules/rigid/Vehicles.js +97 -0
  328. package/modules/rigid/sync.js +158 -0
  329. package/modules/settings/Settings.js +294 -0
  330. package/modules/settings/apply.js +20 -0
  331. package/modules/settings/index.js +3 -0
  332. package/modules/settings/sections.js +156 -0
  333. package/modules/settings/strings.js +53 -0
  334. package/modules/settings/view.js +65 -0
  335. package/modules/sky/Sky.js +257 -0
  336. package/modules/sky/calendar.js +80 -0
  337. package/modules/sky/cascades.js +125 -0
  338. package/modules/sky/clouds.js +79 -0
  339. package/modules/sky/domeLayers.js +33 -0
  340. package/modules/sky/environment.js +115 -0
  341. package/modules/sky/fog.js +136 -0
  342. package/modules/sky/frame.js +76 -0
  343. package/modules/sky/layers.js +69 -0
  344. package/modules/sky/look.js +50 -0
  345. package/modules/sky/schedule.js +80 -0
  346. package/modules/sky/shader.js +96 -0
  347. package/modules/sky/shadow.js +80 -0
  348. package/modules/sky/skyModule.js +59 -0
  349. package/modules/terrain/ChunkManager.js +291 -0
  350. package/modules/terrain/chunkJob.js +19 -0
  351. package/modules/terrain/chunkQueries.js +42 -0
  352. package/modules/terrain/chunkWorker.js +5 -0
  353. package/modules/terrain/index.js +110 -0
  354. package/modules/terrain/mountTerrain.js +32 -0
  355. package/modules/terrain/terrainColorMap.js +41 -0
  356. package/modules/terrain/terrainDefaults.js +39 -0
  357. package/modules/terrain/terrainEdit.js +139 -0
  358. package/modules/terrain/terrainGen.js +155 -0
  359. package/modules/terrain/terrainIsland.js +131 -0
  360. package/modules/terrain/terrainMesh.js +92 -0
  361. package/modules/terrain/terrainShape.js +108 -0
  362. package/modules/terrain/terrainShapeMain.js +41 -0
  363. package/modules/terrain/terrainTexture.js +44 -0
  364. package/modules/timeline/Timeline.js +249 -0
  365. package/modules/timeline/Tween.js +118 -0
  366. package/modules/timeline/letterbox.js +24 -0
  367. package/modules/timeline/shots.js +88 -0
  368. package/modules/triggers/index.js +261 -0
  369. package/modules/vegetation/Vegetation.js +255 -0
  370. package/modules/vegetation/groundChunks.js +177 -0
  371. package/modules/vegetation/index.js +40 -0
  372. package/modules/vegetation/modelGeometry.js +21 -0
  373. package/modules/water/Water.js +144 -0
  374. package/modules/water/surface.js +88 -0
  375. package/modules/weather/Weather.js +251 -0
  376. package/modules/weather/particles.js +92 -0
  377. package/modules/weather/shaders.js +49 -0
  378. package/modules/world/World.js +231 -0
  379. package/modules/world/cells.js +42 -0
  380. package/modules/world/index.js +64 -0
  381. package/modules/world/persist.js +107 -0
  382. package/modules/world/pos.js +20 -0
  383. package/modules/world/records.js +89 -0
  384. package/modules/world/sim.js +175 -0
  385. package/modules/world/simFar.js +82 -0
  386. package/modules/world/state.js +115 -0
  387. package/modules/world/views.js +182 -0
  388. package/package.json +66 -4
  389. package/presets.js +96 -0
  390. package/render/PostFX.js +243 -0
  391. package/render/detail.js +105 -0
  392. package/render/effects.js +142 -0
  393. package/render/engineUniforms.js +23 -0
  394. package/render/fuse.js +72 -0
  395. package/render/lighting.js +100 -0
  396. package/render/lights.js +16 -0
  397. package/render/materials.js +203 -0
  398. package/render/patches.js +252 -0
  399. package/render/surface.js +67 -0
  400. package/render/uniformDecl.js +29 -0
  401. package/types/common.d.ts +34 -0
  402. package/types/core.d.ts +1773 -0
  403. package/types/gameplay.d.ts +1812 -0
  404. package/types/generated/core/Audio.d.ts +200 -0
  405. package/types/generated/core/Batching.d.ts +47 -0
  406. package/types/generated/core/Budget.d.ts +90 -0
  407. package/types/generated/core/Commits.d.ts +31 -0
  408. package/types/generated/core/Events.d.ts +46 -0
  409. package/types/generated/core/I18n.d.ts +30 -0
  410. package/types/generated/core/Input.d.ts +118 -0
  411. package/types/generated/core/Jobs.d.ts +41 -0
  412. package/types/generated/core/Ops.d.ts +162 -0
  413. package/types/generated/core/Random.d.ts +49 -0
  414. package/types/generated/core/Rays.d.ts +49 -0
  415. package/types/generated/core/Saves.d.ts +161 -0
  416. package/types/generated/core/Stream.d.ts +93 -0
  417. package/types/generated/core/Threads.d.ts +82 -0
  418. package/types/generated/core/audioVoice.d.ts +47 -0
  419. package/types/generated/core/page.d.ts +18 -0
  420. package/types/generated/core/session.d.ts +48 -0
  421. package/types/generated/modules/ambience/Ambience.d.ts +48 -0
  422. package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
  423. package/types/generated/modules/flow/index.d.ts +10 -0
  424. package/types/generated/modules/grid/Grid.d.ts +151 -0
  425. package/types/generated/modules/grid/Layer.d.ts +64 -0
  426. package/types/generated/modules/grid/index.d.ts +86 -0
  427. package/types/generated/modules/hlod/index.d.ts +11 -0
  428. package/types/generated/modules/hud/index.d.ts +10 -0
  429. package/types/generated/modules/lights/index.d.ts +13 -0
  430. package/types/generated/modules/music/Music.d.ts +111 -0
  431. package/types/generated/modules/net/Net.d.ts +34 -0
  432. package/types/generated/modules/net/index.d.ts +53 -0
  433. package/types/generated/modules/net/transports.d.ts +58 -0
  434. package/types/generated/modules/particles/Particles.d.ts +69 -0
  435. package/types/generated/modules/sky/Sky.d.ts +152 -0
  436. package/types/generated/modules/sky/skyModule.d.ts +10 -0
  437. package/types/generated/modules/timeline/Timeline.d.ts +51 -0
  438. package/types/generated/modules/water/Water.d.ts +29 -0
  439. package/types/generated/modules/weather/Weather.d.ts +72 -0
  440. package/types/generated/modules/world/World.d.ts +242 -0
  441. package/types/generated/modules/world/index.d.ts +15 -0
  442. package/types/generated/render/PostFX.d.ts +128 -0
  443. package/types/generated/render/materials.d.ts +90 -0
  444. package/types/generated/render/patches.d.ts +41 -0
  445. package/types/generated/ui/Focus.d.ts +11 -0
  446. package/types/generated/ui/LoadingScreen.d.ts +2 -0
  447. package/types/generated/ui/UI.d.ts +57 -0
  448. package/types/nav.d.ts +52 -0
  449. package/types/physics.d.ts +584 -0
  450. package/types/style.d.ts +628 -0
  451. package/types/worker.d.ts +11 -0
  452. package/types/world.d.ts +772 -0
  453. package/ui/Focus.js +51 -0
  454. package/ui/LoadingScreen.js +42 -0
  455. package/ui/Parts.js +195 -0
  456. package/ui/UI.js +167 -0
  457. package/ui/defaults.js +85 -0
  458. package/ui/theme.js +124 -0
  459. package/ui/touchPart.js +49 -0
@@ -0,0 +1,63 @@
1
+ // Grid index of colliders: register each by bounding circle in the cells it covers; queries look at a few nearby cells instead of scanning all colliders.
2
+ // Results are ordered circles first, then boxes, each in insertion order, exactly the callback order of a linear scan (resolve edits the position in turn, so a different order changes the result).
3
+ const CELL = 8, MAX_CELLS = 64, KEY = 1048576; // colliders too large (covering > 64 cells) skip the grid and are scanned linearly, so registration cost does not blow up
4
+ const byOrder = (a, b) => a._b - b._b || a._o - b._o;
5
+
6
+ /** Cell span [x0, x1, z0, z1] that an item (x, z, r) covers */
7
+ const cellRange = it => [Math.floor((it.x - it.r) / CELL), Math.floor((it.x + it.r) / CELL), Math.floor((it.z - it.r) / CELL), Math.floor((it.z + it.r) / CELL)];
8
+
9
+ /** Add it to out once per query (stamp st) when its circle overlaps the query circle; module-level so query() builds no closure */
10
+ function take(out, it, x, z, range, st) {
11
+ if (it._q === st) return;
12
+ it._q = st;
13
+ const dx = it.x - x, dz = it.z - z, rr = range + it.r;
14
+ if (dx * dx + dz * dz < rr * rr) out.push(it);
15
+ }
16
+
17
+ export class CollisionGrid {
18
+ constructor() { this.cells = new Map(); this.big = []; this.seq = 0; this.stamp = 0; this.out = []; }
19
+ /** Register; item needs x, z, r. isBox puts it after circles in the callback order */
20
+ add(item, isBox) {
21
+ item._o = this.seq++; item._b = isBox ? 1 : 0;
22
+ const [x0, x1, z0, z1] = cellRange(item);
23
+ if ((x1 - x0 + 1) * (z1 - z0 + 1) > MAX_CELLS) { this.big.push(item); return; }
24
+ for (let i = x0; i <= x1; i++) for (let j = z0; j <= z1; j++) {
25
+ const k = i * KEY + j; let c = this.cells.get(k); if (!c) this.cells.set(k, c = []); c.push(item);
26
+ }
27
+ }
28
+ remove(item) {
29
+ const bi = this.big.indexOf(item); if (bi >= 0) { this.big.splice(bi, 1); return; }
30
+ const [x0, x1, z0, z1] = cellRange(item);
31
+ for (let i = x0; i <= x1; i++) for (let j = z0; j <= z1; j++) {
32
+ const k = i * KEY + j, c = this.cells.get(k); if (!c) continue;
33
+ c.splice(c.indexOf(item), 1); if (!c.length) this.cells.delete(k);
34
+ }
35
+ }
36
+ /** Colliders intersecting the circle at (x, z) with radius range (exactly filtered, sorted). The returned array is reused by the next query, do not keep it */
37
+ query(x, z, range) {
38
+ const out = this.out; out.length = 0;
39
+ const st = ++this.stamp;
40
+ const big = this.big;
41
+ for (let i = 0; i < big.length; i++) take(out, big[i], x, z, range, st);
42
+ const x0 = Math.floor((x - range) / CELL), x1 = Math.floor((x + range) / CELL), z0 = Math.floor((z - range) / CELL), z1 = Math.floor((z + range) / CELL);
43
+ for (let i = x0; i <= x1; i++) for (let j = z0; j <= z1; j++) {
44
+ const c = this.cells.get(i * KEY + j);
45
+ if (c) for (let k = 0; k < c.length; k++) take(out, c[k], x, z, range, st);
46
+ }
47
+ if (out.length > 1) out.sort(byOrder);
48
+ return out;
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Does a collider in the grid block a character of `radius` standing at (x, z)? The obstacle half of Collision.walkableAt,
54
+ * shared with the pathfinding worker (it rebuilds a grid from the same colliders), so both answer identically. Worker-safe: no imports.
55
+ */
56
+ export function gridBlocks(grid, x, z, radius) {
57
+ for (const it of grid.query(x, z, radius + 1)) {
58
+ if (!it._b) { if (Math.hypot(x - it.x, z - it.z) < radius + it.r) return true; continue; }
59
+ const dx = x - it.x, dz = z - it.z, lx = dx * it.c - dz * it.s, lz = dx * it.s + dz * it.c;
60
+ if (Math.abs(lx) < it.hw + radius && Math.abs(lz) < it.hd + radius) return true;
61
+ }
62
+ return false;
63
+ }
@@ -0,0 +1,95 @@
1
+ // Stable ids of authored entries (one place for the rules; recipes/30-templates.md "Ids"):
2
+ // written id as written (`chest-home`); may not contain `#` or `/` (runtime and level-node ids use them, so they never collide)
3
+ // keyed content (npcs, containers) the key
4
+ // stateless prop without id `prop:<model>:<index>`, a template prop without id `<template>:<index>` (pure decoration only)
5
+ // level-model node `<level>/<node>` (level module)
6
+ // An entry with state (pickups, grid items, templates with state / container / interact / body) needs a written id: an index id shifts when an entry
7
+ // is inserted above it, and the save then puts its changes on the wrong entry. Dev warns once per load, naming the entries and the id to write.
8
+ // Two entries with the same id in one load are an error with the fix. Source lines ("defined in content/props.js:14") come from the dev-only
9
+ // line tables of packages/tools/vite/vite-threedog-content-src.js (srcOf); a release build has none.
10
+ import { DEV, warnOnce, fmt } from '../../core/validate.js';
11
+
12
+ const STRINGS = {
13
+ badId: 'content: id "{id}" ({what}) may not contain "#" or "/": "#" is for records made during play and "/" for level-model nodes. Write it with - _ . or :, e.g. "{fix}"',
14
+ dup: 'content: id "{id}" is used twice: by {a} and by {b}. Ids name an entry in saves, so each must be unique: rename one, e.g. "{id}-2"',
15
+ noId: 'content: {n} entr(y/ies) with state have no id, so saves match them by array index and an inserted entry shifts them: {list}. '
16
+ + 'Write the id they have now (e.g. id: \'{first}\') to keep old saves working, or a readable one',
17
+ };
18
+ const RENAME_STRINGS = {
19
+ shape: "content renames: write { oldId: 'newId' } (or oldId: null for an entry deleted on purpose), got {got} for '{id}'",
20
+ badTarget: "content renames: '{a}' -> '{b}': the new id may not contain \"#\" (that is for records made during play)",
21
+ stuck: 'content renames: saved data under {list} was not moved. A rename moves saved state only when the old id is gone from content and the new id has none of its own',
22
+ };
23
+
24
+ /** The dev line table the vite plugin attached to a content value (null in release or for data built in code) */
25
+ const tableOf = v => (DEV && v && typeof v === 'object' && globalThis.__threedogSrc?.get(v)) || null;
26
+
27
+ /**
28
+ * Where content entry `key` (array index or object key) of `container` was written: 'content/props.js:14', or null.
29
+ * @param {any} container the array / object a content file exports (props, pickups, npcs, templates...)
30
+ * @param {string | number} key
31
+ * @returns {string | null}
32
+ * @internal
33
+ */
34
+ export function srcOf(container, key) {
35
+ const t = tableOf(container);
36
+ return t ? `${t.file}:${t.at[key] ?? t.line}` : null;
37
+ }
38
+
39
+ /** Per content.load: catches duplicate ids across props, pickups, NPCs, containers and grid items, and collects stateful entries without an id @internal */
40
+ export class IdCheck {
41
+ constructor() { this.seen = new Map(); this.missing = []; }
42
+ /** An authored id: format check, and an error if this load already used it @param {string} id @param {string} what e.g. "props[3] (template chest)" */
43
+ claim(id, what) {
44
+ if (typeof id === 'string' && /[#/]/.test(id)) throw new Error(fmt(STRINGS.badId, { id, what, fix: id.replace(/[#/]/g, '-') }));
45
+ const a = this.seen.get(id);
46
+ if (a) throw new Error(fmt(STRINGS.dup, { id, a, b: what }));
47
+ this.seen.set(id, what);
48
+ }
49
+ /** A stateful entry relies on its index id */
50
+ unnamed(id, what) { this.missing.push(`${what} -> '${id}'`); }
51
+ /** One dev warning per load listing the stateful entries without an id */
52
+ done() {
53
+ if (!DEV || !this.missing.length) return;
54
+ const m = this.missing;
55
+ warnOnce(fmt(STRINGS.noId, { n: String(m.length), list: m.slice(0, 6).join(', ') + (m.length > 6 ? ', …' : ''), first: m[0].split("-> '")[1].slice(0, -1) }));
56
+ }
57
+ }
58
+
59
+ /**
60
+ * content/renames.js ({ oldId: 'newId' | null }): before any placement is added, saved changes, removals, owed time and container goods under an old
61
+ * authored id move to the new id (null drops them quietly). World and inventory remember the map, so a save loaded after content is renamed too.
62
+ * Why in content and not a save version: renaming is an authoring change; the save format stays the same and an unrenamed save still loads. @internal
63
+ * @param {any} e
64
+ * @param {Record<string, string | null>} map
65
+ */
66
+ export function applyRenames(e, map) {
67
+ for (const [a, b] of Object.entries(map || {})) {
68
+ if (b !== null && typeof b !== 'string') throw new Error(fmt(RENAME_STRINGS.shape, { id: a, got: JSON.stringify(b) }));
69
+ if (typeof b === 'string' && b.includes('#')) throw new Error(fmt(RENAME_STRINGS.badTarget, { a, b }));
70
+ }
71
+ const stuck = e.world?.renameIds(map) ?? [];
72
+ e.inventory?.renameIds(map);
73
+ if (DEV && stuck.length) warnOnce(fmt(RENAME_STRINGS.stuck, { list: stuck.join(', ') }));
74
+ }
75
+
76
+ /** Index id of a pickup without a written id (the loader's id, and what `threedog content ids` writes) @param {any} p @param {number} i @internal */
77
+ export const pickupId = (p, i) => p.id ?? `pickup:${p.item}:${i}`;
78
+ /** Index id of a template instance without a written id @param {any} p @param {number} i @internal */
79
+ export const templateId = (p, i) => p.id ?? `${p.template}:${i}`;
80
+ /** Instances of this template keep state a save must find again by id @param {any} d @internal */
81
+ export const stateful = d => !!(d?.state || d?.container || d?.interact || d?.body);
82
+
83
+ /**
84
+ * Stateful entries that rely on their index id, with the id they have now: what dev warns about at load and `threedog content ids` writes into the
85
+ * content files (node side, no engine). One list, so the warning and the writer always agree. Grid items are not here: they cannot load without an id.
86
+ * @param {{ pickups?: any[], props?: any[], templates?: Record<string, any> }} c
87
+ * @returns {{ file: 'pickups' | 'props', index: number, id: string }[]}
88
+ * @internal
89
+ */
90
+ export function missingIds(c) {
91
+ const out = [];
92
+ (Array.isArray(c.pickups) ? c.pickups : []).forEach((p, i) => { if (p && p.id == null) out.push({ file: 'pickups', index: i, id: pickupId(p, i) }); });
93
+ (Array.isArray(c.props) ? c.props : []).forEach((p, i) => { if (p?.template && p.id == null && stateful(c.templates?.[p.template])) out.push({ file: 'props', index: i, id: templateId(p, i) }); });
94
+ return out;
95
+ }
@@ -0,0 +1,152 @@
1
+ // Content loader: hands the plain data in the game's content/*.js to the engine (items, pickups, vegetation, NPCs, dialogues, quests, key actions, trigger
2
+ // zones, props).
3
+ // engine.use(content());
4
+ // engine.assets.manifest(lowpolyAssets); // models content names (an asset pack; content never holds paths or code)
5
+ // engine.content.load(data, { places: { home: { x, z } } }); // or several packs at once: load([base, dlc, level]) (packs.js)
6
+ // Condition/effect vocabulary is in rules.js. Games add condition words (content/rules.js, or content.condition(name, { test }) in code);
7
+ // a game's own actions are ops, called from content with { op: ['noun.verb', args] } and tested with { can: [...] }.
8
+ // Op names used in content are checked when the game becomes ready (did you mean...).
9
+ // Templates (content/templates.js): reusable objects placed from props.js ({ template, x, z }) or engine.spawn; see templates.js.
10
+ // Props (content/props.js) and pickups (pickups.js) are stored in engine.world (requires world(); openWorld() includes it; see props.js for the stable id
11
+ // rule),
12
+ // models and collision are built only near the focus; move / remove with engine.world.move / remove, saved with the save. Procedural models of vegetation and
13
+ // props go through engine.assets.cached (name = model name):
14
+ // baked files from npm run bake are read from file, otherwise cached automatically in dev. Models arrive asynchronously: the loading screen of start() waits
15
+ // for them (isReady) before the game counts as ready.
16
+ // Repeated load: a quest's startOn and a trigger's enter/exit effects do not attach listeners twice (the later load overrides the same name).
17
+ // Pickups, props and NPCs are initial world data: the save records only changes and removals, so content.load before or after loading a save gives the same
18
+ // result.
19
+ // Positions that use level markers belong to the current level: the data carries a zone, and a level change only tears down models (pickups taken and removals
20
+ // are remembered); trigger zones are removed on level change.
21
+ import { warnMissing, missingText } from '../../core/validate.js';
22
+ import { reportError } from '../../core/errors.js';
23
+ import { parseClock } from '../../core/dayTime.js';
24
+ import { CONDITIONS, EFFECTS, list } from './rules.js';
25
+ import { loadContent, BUILTIN_TESTS, BUILTIN_RUNS } from './loader.js';
26
+ import { templateOf, spawnTemplate, placeTemplate } from './templates.js';
27
+ import { packsOf } from './packs.js';
28
+ import { placeY } from '../../core/ground.js';
29
+ import { IdCheck } from './ids.js';
30
+
31
+ export function content() {
32
+ let e = null, places = {};
33
+ // load state (shared across repeated load calls): see loader.js
34
+ const pending = new Set();
35
+ const st = {
36
+ triggers: {}, subs: null, startOn: new Map(), ops: new Set(), kinds: {},
37
+ templates: new Map(), templateViews: new Set(), // template name -> frozen definition; names whose presenter is registered
38
+ templateSrc: new Map(), // dev: template name -> 'content/templates.js:12'
39
+ levelPlace: name => !!name && !(name in places) && !!e.level?.marker(name),
40
+ wait: p => { pending.add(p); p.catch(err => reportError(e, err, 'content model', { soft: true })).finally(() => pending.delete(p)); },
41
+ };
42
+ const conds = new Map(Object.entries(CONDITIONS).map(([k, d]) => [k, { ...d, test: BUILTIN_TESTS[k] }]));
43
+ const effects = new Map(Object.entries(EFFECTS).map(([k, d]) => [k, { ...d, run: BUILTIN_RUNS[k] }]));
44
+ // convert content notation to runtime values by ref (clock time -> fraction, place -> { x, z })
45
+ const norm = (ref, v) => ref === 'clock' ? parseClock(v, e.sky?.hoursPerDay ?? 24) : ref === 'position' ? api.where(typeof v === 'string' ? { place: v } : v) : v;
46
+
47
+ const api = {
48
+ /** All vegetation models are ready and the models of nearby world data such as props are built (world.ready) */
49
+ get ready() { return pending.size === 0 && (!e.world || e.world.ready); },
50
+ /** marker markers added by the marker effect: id -> hud marker */
51
+ markers: new Map(),
52
+ /**
53
+ * Load content data: one pack (the object of content/index.js) or a list of packs loaded together in order, where an id defined by two packs is an error
54
+ * (packs.js).
55
+ * Models are asset names (engine.assets.manifest / an asset pack), never paths. places: place name -> position
56
+ * @example engine.content.load([baseContent, forestDlc], { places: { home: { x: 0, z: 0 } } })
57
+ * @param {any} data
58
+ * @param {{ places?: Record<string, any> }} [opts]
59
+ */
60
+ load(data, { places: pl = {} } = {}) {
61
+ Object.assign(places, pl);
62
+ const packs = packsOf(data), ids = new IdCheck(); // one IdCheck for the whole call: an id used in two packs' props / pickups is an error too
63
+ e.ops.allow(() => { for (const p of packs) loadContent(e, api, p, st, ids); }); // loading data is setup, not a gameplay action (ops guard)
64
+ ids.done();
65
+ st.checkOps?.();
66
+ return api;
67
+ },
68
+ /** Register a condition word: condition('timeAfter', { ref: 'clock', desc, test: (e, value) => ... }) */
69
+ condition(name, def) { conds.set(name, def); return api; },
70
+ /** Whether a condition holds (object = all listed items hold, array = every item holds, function = called directly) */
71
+ test(c) {
72
+ if (!c) return true;
73
+ if (typeof c === 'function') return !!c(e);
74
+ return list(c).every(x => Object.entries(x).every(([k, v]) => {
75
+ const d = conds.get(k);
76
+ if (!d) { warnMissing('condition', k, [...conds.keys()]); return false; }
77
+ return !!d.test(e, norm(d.ref, v), v);
78
+ }));
79
+ },
80
+ /** Run an effect (object, array or function) */
81
+ run(a) {
82
+ if (!a) return;
83
+ if (typeof a === 'function') return a(e);
84
+ for (const x of list(a)) for (const [k, v] of Object.entries(x)) {
85
+ const d = effects.get(k);
86
+ if (!d) { warnMissing('effect', k, [...effects.keys()]); continue; }
87
+ d.run(e, norm(d.ref, v), v);
88
+ }
89
+ },
90
+ /**
91
+ * The shared definition of a content template (content/templates.js), frozen: instance state lives on the world record, never here.
92
+ * @example engine.content.template('chest').container.capacity // 6, the same for every chest
93
+ * @param {string} name
94
+ * @returns {Readonly<Record<string, any>>}
95
+ */
96
+ template(name) { return templateOf(st, name); },
97
+ /**
98
+ * @internal A level-model node with the custom property template: an authored instance with id `<level>/<node>` (level module).
99
+ * entry is a props-style entry ({ template, id, x, z, floor, rot, scale, state fields }); origin = { level, node }
100
+ */
101
+ placeNode(entry, zone, origin) { placeTemplate(e, api, st, entry, 0, zone, null, origin); },
102
+ /** @internal dev: where a template is defined ('content/templates.js:12'), null if unknown */
103
+ templateSource(name) { return st.templateSrc.get(name) ?? null; },
104
+ /** Place name -> position { x, z } plus y when the place has a height (level markers, places given with y); null if not found */
105
+ place(name) {
106
+ const p = places[name] ?? e.level?.marker(name)?.position;
107
+ return p ? { x: p.x, z: p.z, ...(p.y !== undefined && { y: p.y }) } : null;
108
+ },
109
+ /**
110
+ * Position notation in content { place?, x?, z?, floor?, y? } -> world coordinates { x, z }, plus y when the notation pins a height.
111
+ * floor: reference height for multi-layer ground (second storey, bridge deck, lower dungeon level): it stands on the highest layer not above floor;
112
+ * a level-marker place lends its own height as floor. y: meters above that ground (shelves, floating pickups).
113
+ * Without floor / y / a marker height the result is { x, z } and the thing sits on the top layer.
114
+ * @example engine.content.where({ place: 'tower', x: 1, floor: 6 }) // the tower's second floor, not its roof
115
+ */
116
+ where(p) {
117
+ const base = p.place ? api.place(p.place) : null;
118
+ if (p.place && !base) throw new Error(`Place "${p.place}" not found: give its coordinates in the places of content.load, or add this marker to the level`);
119
+ const x = (base?.x ?? 0) + (p.x ?? 0), z = (base?.z ?? 0) + (p.z ?? 0), floor = p.floor ?? base?.y;
120
+ if (floor === undefined && p.y === undefined) return { x, z };
121
+ return { x, y: placeY(e, `content.where(${JSON.stringify(p.place ?? { x: p.x, z: p.z })})`, x, z, floor) + (p.y ?? 0), z };
122
+ },
123
+ /** @internal The floor a position notation stands on (its own floor, else its marker's height); undefined = top layer */
124
+ _floorOf(p) { return p.floor ?? (p.place ? api.place(p.place)?.y : undefined); },
125
+ };
126
+ return {
127
+ name: 'content', label: 'Content',
128
+ optional: ['level', 'sky', 'inventory', 'quests', 'particles', 'hud', 'vegetation', 'dialogue', 'triggers', 'collision', 'world', 'interactions', 'grids', 'rigid'],
129
+ install(engine) {
130
+ e = engine;
131
+ /**
132
+ * Place a new instance of a content template at runtime (a gameplay change: call it inside an op or a fixed step); saved whole.
133
+ * Returns the world record (kind = template name). at is a ground position ({ x, z }, [x, y, z] or an object);
134
+ * fields may set id, rot, scale, y (height above ground), items (container start goods) and the template's state fields.
135
+ * Installed by content(), so it exists once the content module is used.
136
+ * @example engine.ops.define('chest.build', { run: (e, { x, z }) => e.spawn('chest', { x, z }, { items: { stick: 3 } }).id });
137
+ */
138
+ e.spawn = (name, at, fields) => spawnTemplate(e, st, name, at, fields);
139
+ // content may name ops that main.js defines after load: check once everything is set up, and again for loads after that
140
+ const check = () => {
141
+ for (const name of st.ops) if (!e.ops.defs.has(name)) throw new Error(`content: ${missingText('op', name, [...e.ops.defs.keys()])} (used in { op } / { can })`);
142
+ };
143
+ e.events.on('engine:ready', check);
144
+ st.checkOps = () => { if (e.ready) check(); };
145
+ return api;
146
+ },
147
+ isReady() { return api.ready; },
148
+ describe() {
149
+ return { props: e.world ? e.world.query({ kind: 'prop' }).length : 0, templates: [...st.templates.keys()], markers: api.markers.size };
150
+ },
151
+ };
152
+ }
@@ -0,0 +1,187 @@
1
+ // Content loading: hands the plain data of content/*.js to the modules (items, pickups, vegetation, NPCs, dialogues, quests, key actions, trigger zones,
2
+ // props).
3
+ // Position notation: { place: 'home', x: 1, z: 5 } = offset from place home; places come from the places argument of load or level markers; without place it is
4
+ // a world coordinate.
5
+ // Optional floor (reference height on multi-layer ground) and y (meters above that ground): see content.where.
6
+ import { toast } from '../../ui/UI.js';
7
+ import { parseClock } from '../../core/dayTime.js';
8
+ import { cachedModel } from './models.js';
9
+ import { addProps, needWorld } from './props.js';
10
+ import { defineTemplates } from './templates.js';
11
+ import { srcOf, applyRenames, pickupId } from './ids.js';
12
+ import { DEV, checkOptions } from '../../core/validate.js';
13
+ import { NO_GAME_EFFECTS, contentFiles, kindProblems, unknownContent, list } from './rules.js';
14
+
15
+ const each = (o, fn) => Object.entries(o || {}).forEach(([k, v]) => fn(k, v));
16
+ const all = (o, fn) => Object.entries(o || {}).every(([k, n]) => fn(k, n));
17
+
18
+ /** The inventory for the item words (has / lacks / give / take); without the module, a clear error instead of a TypeError deep inside */
19
+ const inv = (e, word) => e.inventory ?? (() => { throw new Error(`content word { ${word} } needs the inventory module: add inventory() to engine.use(...), `
20
+ + 'or track the thing with a flag / counter ({ setFlag } / { bump }) or a game condition word instead'); })();
21
+
22
+ /** Execution part of the engine's built-in words (descriptions are in rules.js) */
23
+ export const BUILTIN_TESTS = {
24
+ can: (e, v) => e.ops.can(v[0], v[1] ?? {}).ok,
25
+ flag: (e, v) => !!e.vars.flag(v),
26
+ notFlag: (e, v) => !e.vars.flag(v),
27
+ has: (e, v) => all(v, (id, n) => inv(e, 'has').has(id, n)),
28
+ lacks: (e, v) => all(v, (id, n) => !inv(e, 'lacks').has(id, n)),
29
+ counter: (e, v) => all(v, (k, n) => e.vars.counter(k) >= n),
30
+ };
31
+ export const BUILTIN_RUNS = {
32
+ op: (e, v) => { e.ops.run(v[0], v[1] ?? {}); }, setFlag: (e, v) => e.vars.setFlag(v),
33
+ give: (e, v) => each(v, (id, n) => inv(e, 'give').add(id, n)),
34
+ take: (e, v) => each(v, (id, n) => inv(e, 'take').remove(id, n)),
35
+ bump: (e, v) => e.vars.bump(v),
36
+ startQuest: (e, v) => e.quests.start(v),
37
+ toast: (e, v) => toast(e, v),
38
+ particles: (e, v) => e.particles.emit(v.name, v.at, { count: v.count }),
39
+ marker: (e, v, raw) => { // running the same marker again: remove the old one first (otherwise the old marker stays on screen)
40
+ const id = markerId(raw);
41
+ e.content.markers.get(id)?.remove();
42
+ e.content.markers.set(id, e.hud?.marker(v, { label: raw.label }));
43
+ },
44
+ clearMarker: (e, v, raw) => { const id = markerId(raw); e.content.markers.get(id)?.remove(); e.content.markers.delete(id); },
45
+ };
46
+ const markerId = raw => raw.id ?? (typeof raw === 'string' ? raw : raw.place ?? `${raw.x},${raw.z}`);
47
+
48
+ /**
49
+ * Load one content pack. c is the merged object of content/index.js (or one pack of a list); api is engine.content; ids is the IdCheck shared by every pack of
50
+ * this load call (ids.js); st is the content module's load state (shared across repeated load calls):
51
+ * { triggers: merged trigger table, subs: listener handles, startOn: quest id -> listener handle, pending: set of model Promises being generated,
52
+ * levelPlace(name) }
53
+ * Order: vocabulary -> key actions -> vegetation -> items -> containers -> pickups -> NPCs -> dialogues -> quests -> trigger zones -> templates -> props.
54
+ * Pickups, props and NPCs are initial world data: the save records only changes and removals, independent of load order (rules at the top of world/World.js).
55
+ * Positions that use level markers (not in places) belong to the current level: pickup, prop and NPC data carry a zone (= current level name,
56
+ * engine.world.zone),
57
+ * a level change only tears down models and they are rebuilt on return, with taken / moved / removed state intact; trigger zones are not data and are removed
58
+ * on level change (level.track).
59
+ */
60
+ export function loadContent(e, api, c, st, ids) {
61
+ const { where } = api;
62
+ const origin = (id, list, key) => { if (DEV) e.world?.setOrigin(id, { definedAt: srcOf(list, key) }); };
63
+ const onLevel = (...ps) => ps.some(p => p && typeof p === 'object' ? st.levelPlace(p.place) : st.levelPlace(p));
64
+ const bind = (h, ...ps) => { if (h && onLevel(...ps)) e.level?.track(h); return h; };
65
+ const zoneOf = (...ps) => onLevel(...ps) ? e.world?.zone ?? null : null;
66
+
67
+ each(c.rules?.conditions, (name, d) => api.condition(name, d));
68
+ if (c.rules?.effects) throw new Error(NO_GAME_EFFECTS);
69
+ // game kinds stay registered across loads, so a later content.load({ recipes }) without rules still finds them
70
+ const bad = kindProblems(c.rules);
71
+ if (bad.length) throw new Error('content/rules.js: ' + bad.join('; '));
72
+ Object.assign(st.kinds, c.rules?.kinds);
73
+ const known = contentFiles({ kinds: st.kinds });
74
+ for (const k of Object.keys(c)) if (k !== 'name' && !known[k]) throw new Error('content.load: ' + unknownContent(k, { kinds: st.kinds }));
75
+ collectOps(c, st.ops);
76
+
77
+ if (c.renames) applyRenames(e, c.renames); // first: saved state under an old id must reach the new id before anything is placed under it
78
+
79
+ each(c.actions, (name, a) => e.input.define(name, a.keys, a.label));
80
+
81
+ // audio: sounds / footsteps by name into engine.audio.config, rules to ambience() / music() (core/audioRules.js). A pack loaded again
82
+ // replaces its own rules (hot reload): a named pack by its name, an unnamed one by the data object itself, so loading the same object
83
+ // twice never stacks its rules (a fresh key per load did); two different unnamed objects both keep theirs
84
+ if (c.audio) e.audio.contentPack(c.name ? 'pack:' + c.name : c, c.name ? `pack "${c.name}"` : 'pack (no name)', c.audio);
85
+
86
+ // vegetation: generator models go through assets.cached (baked file -> dev cache -> compute), file models give their first mesh's geometry; register all
87
+ // kinds at the same moment once all models are ready
88
+ // (each registration rebuilds terrain chunks; registering one by one would rebuild several times at start). content's isReady waits for them
89
+ const veg = [];
90
+ each(c.vegetation, (name, { model: m, lod, ...rest }) => {
91
+ const geo = x => cachedModel(e, x) ?? e.assets.geometry(list(x)[0]);
92
+ veg.push(Promise.all([geo(m), lod && geo(lod)]).then(([geometry, lodGeometry]) => [name, { ...rest, geometry, ...(lodGeometry && { lodGeometry }) }])
93
+ .catch(err => { console.error(`[content] vegetation ${name}: model generation failed`, err); return null; })); // one failure does not affect the others
94
+ });
95
+ if (veg.length) st.wait(Promise.all(veg).then(list => { for (const v of list) if (v) e.vegetation.add(v[0], v[1]); }));
96
+
97
+ each(c.items, (id, d) => e.inventory.define(id, d));
98
+ each(c.startItems, (id, n) => e.inventory.add(id, n, { silent: true }));
99
+ // containers: starting goods are placed only the first time (if the save already has the container, the save wins; no refill after it was emptied and
100
+ // reloaded)
101
+ each(c.containers, (id, d) => { ids.claim(id, `containers.${id}`); e.inventory.container(id, { capacity: d.capacity, items: d.items }); });
102
+ // pickups: data goes into world (kind 'pickup'). id: the written id if given, else `pickup:<item>:<index in the pickups array>` (stable for the same content;
103
+ // when inserting in the middle, give existing entries an id)
104
+ if (c.pickups?.length) needWorld(e);
105
+ c.pickups?.forEach((p, i) => {
106
+ const id = pickupId(p, i);
107
+ if (p.id != null) ids.claim(id, `pickups[${i}] (${p.item})`); else ids.unnamed(id, `pickups[${i}] (${p.item})`); // taken / respawning is state
108
+ e.inventory.spawnPickup(p.item, where(p), { id, count: p.count, data: p.data, radius: p.radius, auto: p.auto, respawnSeconds: p.respawn, initial: true, zone: zoneOf(p) });
109
+ origin(id, c.pickups, i);
110
+ });
111
+
112
+ const hpd = e.sky?.hoursPerDay ?? 24;
113
+ each(c.npcs, (id, n) => { // the key in content is the NPC's stable id (used by saves and quest targets)
114
+ const plan = n.schedule ?? [];
115
+ ids.claim(id, `npcs.${id}`);
116
+ // every documented npcs.add option can be written in content (arriveDistance, talkRadius, speed...); the same option table checks the spelling.
117
+ // The content form owns start / schedule (clock strings, places) and the id (the key), so those are translated below and not passed as written
118
+ checkOptions(`content npcs.${id}`, n, [...e.npcs.optionKeys.filter(k => !['id', 'position', 'zone', 'initial'].includes(k)), 'start']);
119
+ const { start: _s, schedule: _p, ...rest } = n;
120
+ e.npcs.add({ ...rest, id, schedule: plan.map(s => ({ at: parseClock(s.at, hpd), position: where(s) })), position: where(n.start || plan[0]), zone: zoneOf(n.start, ...plan), initial: true });
121
+ origin(id, c.npcs, id);
122
+ });
123
+
124
+ // dialogue: a line can be several variants [{ if: condition, text }, ..., { text }]; the first whose condition holds is used
125
+ each(c.dialogues, (id, d) => {
126
+ const nodes = {};
127
+ each(d.nodes, (nid, n) => {
128
+ nodes[nid] = {
129
+ ...n, speaker: n.speaker ?? d.speaker,
130
+ text: Array.isArray(n.text) ? () => n.text.find(v => api.test(v.if)).text : n.text,
131
+ do: n.do && (() => api.run(n.do)),
132
+ choices: n.choices?.map(ch => ({ ...ch, if: ch.if && (() => api.test(ch.if)), do: ch.do && (() => api.run(ch.do)) })),
133
+ };
134
+ });
135
+ e.dialogue.define(id, nodes);
136
+ });
137
+
138
+ // quests: a step target can be a place, { place, x, z }, { x, z }, { npc: 'id' } (follows the NPC) or { nearest: itemId } (the nearest pickup)
139
+ // { npc } reads the position by id each frame: follow the model if there is one, else (far away, other level) use the data position
140
+ const target = t => t == null ? undefined : t.npc ? () => e.npcs?.get(t.npc)?.position : t.nearest ? t : where(typeof t === 'string' ? { place: t } : t);
141
+ // a step may be parallel goals { text?, all: [{ text, done, target, optional }] }; fail / onFail are a condition and an effect like done / reward
142
+ const goal = s => ({ ...(s.id != null && { id: s.id }), text: s.text, done: () => api.test(s.done), target: target(s.target), ...(s.optional && { optional: true }) }); // id: stable for saves
143
+ each(c.quests, (id, q) => {
144
+ e.quests.define(id, {
145
+ title: q.title, desc: q.desc,
146
+ steps: q.steps.map(s => s.all ? { ...(s.id != null && { id: s.id }), text: s.text, all: s.all.map(goal) } : goal(s)),
147
+ reward: q.reward && (() => api.run(q.reward)),
148
+ ...(q.fail && { fail: () => api.test(q.fail) }), ...(q.onFail && { onFail: () => api.run(q.onFail) }),
149
+ });
150
+ st.startOn.get(id)?.remove(); // loading the same quest again: replace the old listener instead of attaching twice
151
+ if (q.startOn) st.startOn.set(id, e.events.on(q.startOn, () => e.quests.start(id)));
152
+ });
153
+
154
+ // trigger zones: fromLevel = the level's trigger_<tag> marker; otherwise placed by position. Enter/exit effects look up the merged table, and the listener is
155
+ // attached only once
156
+ if (c.triggers) {
157
+ Object.assign(st.triggers, c.triggers);
158
+ if (Object.values(c.triggers).some(t => t.fromLevel)) e.triggers.fromMarkers();
159
+ each(c.triggers, (tag, t) => {
160
+ if (!t.fromLevel) bind(e.triggers.add({ ...t, tag, position: where(t.position), onEnter: null, onExit: null }), t.position);
161
+ });
162
+ st.subs ??= [
163
+ e.events.on('trigger:enter', ({ tag }) => api.run(st.triggers[tag]?.onEnter)),
164
+ e.events.on('trigger:exit', ({ tag }) => api.run(st.triggers[tag]?.onExit)),
165
+ ];
166
+ }
167
+
168
+ // grids (layout rules, not saved) before props: a props entry with grid places an item on one; a repeated load keeps the grid that exists
169
+ each(c.grids, (name, g) => {
170
+ if (!e.grids) throw new Error(`content grids: install grids() to use grid "${name}"`);
171
+ if (!e.grids.get(name)) e.grids.add(name, g);
172
+ });
173
+ // templates before props: a props entry with template places an instance of it
174
+ if (c.templates) { needWorld(e); defineTemplates(e, api, st, c.templates); }
175
+ // props: data goes into world (kind 'prop'); models and collision are built nearby and torn down when far by present in props.js
176
+ if (c.props?.length) addProps(e, api, c.props, st, zoneOf, ids);
177
+
178
+ // game kinds last: their data may name the items, NPCs and places loaded above
179
+ each(st.kinds, (name, k) => { if (c[name] !== undefined) k.load(e, c[name], api); });
180
+ }
181
+
182
+ /** Op names that content data refers to ({ op: [...] } / { can: [...] } anywhere), checked against engine.ops once the game is ready */
183
+ function collectOps(v, out, depth = 0) {
184
+ if (!v || typeof v !== 'object' || depth > 12) return;
185
+ if (!Array.isArray(v)) for (const k of ['op', 'can']) if (Array.isArray(v[k]) && typeof v[k][0] === 'string') out.add(v[k][0]);
186
+ for (const x of Array.isArray(v) ? v : Object.values(v)) collectOps(x, out, depth + 1);
187
+ }
@@ -0,0 +1,69 @@
1
+ // Models in content: procedural model cache (vegetation, props, templates) and the shared-prototype model of a placed record (props and template instances).
2
+ import * as THREE from 'three';
3
+ import { makeMaterial } from '../../render/materials.js';
4
+ import { list } from './rules.js';
5
+
6
+ /**
7
+ * A model named in content (name or [name, params...]) whose asset entry is a generator (an asset pack's procedural model) goes through assets.cached:
8
+ * name = model name, params count into the cache key. Returns a Promise (geometry or Object3D); null for a file model or an unknown name (assets.model takes those)
9
+ */
10
+ export function cachedModel(e, m) {
11
+ const [name, ...args] = list(m), fn = e.assets.builder(name);
12
+ if (!fn) return null;
13
+ // pass the generator function to cached as is (dev cache hashes its source); wrap only when there are several params
14
+ return args.length > 1 ? e.assets.cached(name, function (p) { return fn.apply(this, p); }, args) : e.assets.cached(name, fn, args[0]);
15
+ }
16
+
17
+ // One prototype per model name: a generator entry -> assets.cached (baked file / dev cache); a file entry -> assets.model. Content names models only (no paths).
18
+ const protos = new WeakMap(); // engine.content → Map(model key → Promise<{ obj, size, center }>)
19
+ function protoOf(e, api, model) {
20
+ if (!protos.has(api)) protos.set(api, new Map());
21
+ const cache = protos.get(api), key = JSON.stringify(model);
22
+ if (!cache.has(key)) {
23
+ const gen = cachedModel(e, model);
24
+ cache.set(key, (gen ? gen.then(r => {
25
+ const p = r.isObject3D ? r : new THREE.Mesh(r, makeMaterial('prop', { vertexColors: !!r.attributes.color }, e));
26
+ p.traverse(o => { if (o.isMesh) o.castShadow = o.receiveShadow = true; });
27
+ return p;
28
+ }) : e.assets.model(list(model)[0])).then(obj => {
29
+ const box = new THREE.Box3().setFromObject(obj); // collision and the "build within what distance" check both use the prototype's bounding box, computed once
30
+ return { obj, size: box.getSize(new THREE.Vector3()), center: box.getCenter(new THREE.Vector3()) };
31
+ }));
32
+ }
33
+ return cache.get(key);
34
+ }
35
+
36
+ /**
37
+ * Align a built model and its collision to the record (once when built, again after the record moved or rot / scale changed).
38
+ * look = { collide, static } comes from the prop record, or from the template definition for template instances. @internal
39
+ */
40
+ export function settle(e, rec, o, look) {
41
+ const { x, z } = rec.position, rot = rec.rot ?? 0, scale = rec.scale ?? 1, ud = o.userData;
42
+ ud.fit = fitKey(rec);
43
+ rec.position.y = e.surface(x, z, rec.floor) + (rec.offsetY ?? 0);
44
+ o.position.y = rec.position.y; o.rotation.y = rot; o.scale.setScalar(scale);
45
+ ud.unstatic?.remove(); ud.unstatic = null;
46
+ for (const h of ud.colliders.splice(0)) h.remove();
47
+ if (look.static !== false && e.rays) { o.updateMatrixWorld(true); ud.unstatic = e.rays.addStatic(o); }
48
+ if (!look.collide || !e.collision) return;
49
+ const size = ud.proto.size.clone().multiplyScalar(scale), c = ud.proto.center.clone().multiplyScalar(scale);
50
+ const cx = x + c.x * Math.cos(rot) + c.z * Math.sin(rot), cz = z - c.x * Math.sin(rot) + c.z * Math.cos(rot);
51
+ ud.colliders.push(look.collide === 'circle'
52
+ ? e.collision.addCircle({ x: cx, z: cz }, { radius: Math.max(size.x, size.z) / 2, height: size.y })
53
+ : e.collision.addBox({ x: cx, z: cz }, { halfWidth: size.x / 2, halfDepth: size.z / 2, rotation: rot, height: size.y }));
54
+ }
55
+ /** What settle last aligned to; update compares it because world.move sends no event @internal */
56
+ export const fitKey = rec => `${rec.position.x},${rec.position.z},${rec.rot ?? 0},${rec.scale ?? 1}`;
57
+
58
+ /** Clone the shared prototype of a model for one record and align it (props and template instances) @internal */
59
+ export async function buildModel(e, api, rec, model, look) {
60
+ const proto = await protoOf(e, api, model), o = proto.obj.clone(), name = list(model)[0];
61
+ o.name ||= name; o.userData.name ??= name;
62
+ o.userData.proto = proto; o.userData.colliders = [];
63
+ if (rec.batch === false) o.userData.batch = false; // opt out of engine.batching for this record
64
+ o.position.set(rec.position.x, 0, rec.position.z); // world puts the model on the record after build; height and collision are aligned here
65
+ settle(e, rec, o, look);
66
+ return o;
67
+ }
68
+ /** Tear down only: geometry and material belong to the shared prototype, the next build clones it again @internal */
69
+ export function unbuildModel(e, o) { o.userData.unstatic?.remove(); for (const h of o.userData.colliders) h.remove(); e.detach(o); }
@@ -0,0 +1,69 @@
1
+ // Content packs: engine.content.load([basePack, dlcPack, levelPack]) loads several data packs as one load.
2
+ // Why one load and not several load() calls: a repeated load deliberately overrides the same name (hot reload, a later chapter replacing a quest),
3
+ // so two packs that both define items.apple would silently fight. Inside one load the packs must not overlap: the same id in two packs is an error
4
+ // naming both. Rules:
5
+ // - packs load in list order, so a pack may use what an earlier pack defines (a level pack placing a template from a base pack)
6
+ // - keyed tables (items, npcs, dialogues, quests, templates, vegetation, triggers, game kinds..., and rules.conditions / rules.kinds): one id, one pack
7
+ // - audio: sounds, footsteps and music.tracks are keyed tables; ambience and music.rules lists concatenate
8
+ // - startItems add up (two packs that both give 'gold' give the sum), so it is not an id table
9
+ // - lists (props, pickups) concatenate; their ids are checked across all packs by the same IdCheck as a single load (ids.js)
10
+ // - a pack may carry name: 'forest-dlc' for error messages; no other extra key (unknown keys are errors)
11
+ // Content references assets by name only: a model written as a file path or a function is reported here in dev (the static check is
12
+ // npm run check -> content-check, packages/tools/content-check/world.mjs).
13
+ import { DEV, warnOnce, fmt } from '../../core/validate.js';
14
+
15
+ const STRINGS = {
16
+ dup: 'content.load: {key}.{id} is defined by both {a} and {b}. Packs loaded together may not share an id: rename one, or drop it from one pack',
17
+ notPack: 'content.load: pack {at} must be a plain object of content tables ({ items, props, ... }), got {got}',
18
+ path: 'content: {what} names the model "{m}" as a file path. Content refers to assets by name only: register the file in an asset pack '
19
+ + "(engine.assets.manifest({ models: { {short}: '{m}' } })) and write model: '{short}'",
20
+ code: 'content: {what} gives a function as its model. Content is data: register the generator in an asset pack (engine.assets.manifest({ models: { name: fn } })) and write its name',
21
+ };
22
+ const plain = v => v !== null && typeof v === 'object' && !Array.isArray(v);
23
+ // plain-object tables that are not "one id, one pack": their entries combine (startItems counts add, each pack's load gives its own)
24
+ const NOT_KEYED = new Set(['startItems']);
25
+ const PATH = /[/\\]|\.(glb|gltf|fbx|obj|png|jpe?g|webp|ktx2|mp3|ogg|wav)$/i;
26
+
27
+ /** Label of a pack in messages: its name, else its position @param {any} p @param {number} i */
28
+ const packLabel = (p, i) => (p?.name ? `pack "${p.name}"` : `pack #${i + 1}`);
29
+
30
+ /**
31
+ * Normalize content.load's argument to a list of packs and throw on an id defined by two packs (rules at the top of this file) @internal
32
+ * @param {any} data one pack or a list of packs
33
+ * @returns {any[]}
34
+ */
35
+ export function packsOf(data) {
36
+ const packs = Array.isArray(data) ? data.flat(Infinity) : [data];
37
+ if (packs.length < 2) { if (DEV && packs[0]) modelRefs(packs[0]); return packs; }
38
+ const owner = new Map(); // 'items.apple' -> pack index
39
+ const claim = (key, table, i) => {
40
+ for (const id of Object.keys(table || {})) {
41
+ const k = key + '.' + id, was = owner.get(k);
42
+ if (was !== undefined) throw new Error(fmt(STRINGS.dup, { key, id, a: packLabel(packs[was], was), b: packLabel(packs[i], i) }));
43
+ owner.set(k, i);
44
+ }
45
+ };
46
+ packs.forEach((p, i) => {
47
+ if (!plain(p)) throw new Error(fmt(STRINGS.notPack, { at: i + 1, got: Array.isArray(p) ? 'an array' : typeof p }));
48
+ for (const [key, v] of Object.entries(p)) {
49
+ if (key === 'rules') { claim('rules.conditions', v?.conditions, i); claim('rules.kinds', v?.kinds, i); }
50
+ // audio: named tables are ids (a sound in two packs is an error), rule lists concatenate
51
+ else if (key === 'audio') { claim('audio.sounds', v?.sounds, i); claim('audio.footsteps', v?.footsteps, i); claim('audio.music.tracks', v?.music?.tracks, i); }
52
+ else if (key !== 'name' && !NOT_KEYED.has(key) && plain(v)) claim(key, v, i);
53
+ }
54
+ if (DEV) modelRefs(p);
55
+ });
56
+ return packs;
57
+ }
58
+
59
+ /** Dev: model fields that hold a file path (warn) or a function (throw) instead of an asset name */
60
+ function modelRefs(p) {
61
+ const check = (what, m) => {
62
+ const name = Array.isArray(m) ? m[0] : m;
63
+ if (typeof name === 'function') throw new Error(fmt(STRINGS.code, { what }));
64
+ if (typeof name === 'string' && PATH.test(name)) warnOnce(fmt(STRINGS.path, { what, m: name, short: name.split(/[/\\]/).pop().replace(/\.\w+$/, '') }));
65
+ };
66
+ for (const [n, v] of Object.entries(p.vegetation || {})) { check(`vegetation.${n}`, v?.model); if (v?.lod) check(`vegetation.${n}.lod`, v.lod); }
67
+ for (const [n, t] of Object.entries(p.templates || {})) check(`templates.${n}`, t?.model);
68
+ (Array.isArray(p.props) ? p.props : []).forEach((x, i) => { if (x?.model !== undefined) check(`props[${i}]`, x.model); });
69
+ }