threedog 0.8.0 → 1.0.1

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 (372) hide show
  1. package/CHANGELOG.md +223 -4
  2. package/README.md +6 -6
  3. package/core/assets/Animator.js +2 -0
  4. package/core/assets/Assets.js +44 -13
  5. package/core/assets/assetEntry.js +87 -22
  6. package/core/assets/assetHot.js +2 -1
  7. package/core/assets/assetReport.js +1 -2
  8. package/core/audio/Audio.js +24 -5
  9. package/core/base/I18n.js +6 -3
  10. package/core/base/Random.js +3 -1
  11. package/core/base/Vars.js +14 -4
  12. package/core/base/errorCodes.js +54 -16
  13. package/core/base/errorHints.js +12 -1
  14. package/core/base/errors.js +6 -4
  15. package/core/base/events.generated.js +10 -0
  16. package/core/base/follows.js +26 -0
  17. package/core/base/math.js +15 -8
  18. package/core/base/params.js +2 -2
  19. package/core/{saves → base}/saveValues.js +24 -6
  20. package/core/base/sections.js +97 -0
  21. package/core/base/spelling.js +32 -0
  22. package/core/base/validate.js +8 -29
  23. package/core/engine/Engine.js +61 -18
  24. package/core/engine/Loading.js +30 -3
  25. package/core/engine/copies.js +1 -1
  26. package/core/engine/headlessLoad.js +30 -13
  27. package/core/engine/lifecycle.js +30 -25
  28. package/core/engine/loop.js +22 -4
  29. package/core/engine/moduleSlots.js +91 -15
  30. package/core/engine/moduleTypes.js +13 -0
  31. package/core/engine/modules.js +248 -62
  32. package/core/engine/page.js +25 -8
  33. package/core/engine/plugins.js +15 -3
  34. package/core/engine/services.js +3 -0
  35. package/core/engine/startup.js +46 -36
  36. package/core/input/Input.js +39 -19
  37. package/core/input/inputKeyboard.js +39 -0
  38. package/core/input/inputPad.js +23 -2
  39. package/core/input/inputPointer.js +3 -1
  40. package/core/input/inputSeat.js +66 -0
  41. package/core/input/inputTouch.js +23 -6
  42. package/core/inspect/DebugOverrides.js +13 -2
  43. package/core/inspect/Describe.js +10 -6
  44. package/core/inspect/Inspect.js +31 -4
  45. package/core/inspect/UrlState.js +14 -10
  46. package/core/inspect/catalog.js +12 -5
  47. package/core/inspect/describeRender.js +3 -2
  48. package/core/inspect/describeText.js +6 -2
  49. package/core/inspect/metadata.generated.js +4140 -0
  50. package/core/inspect/pictureWriters.js +117 -33
  51. package/core/inspect/toolDoor.js +21 -0
  52. package/core/inspect/valueHistory.js +35 -0
  53. package/core/ops/Ops.js +32 -7
  54. package/core/ops/control.js +48 -23
  55. package/core/ops/holds.js +4 -3
  56. package/core/ops/opsAtomic.js +18 -6
  57. package/core/ops/opsCheck.js +7 -5
  58. package/core/ops/opsFail.js +5 -7
  59. package/core/ops/opsRun.js +2 -2
  60. package/core/ops/owned.js +20 -3
  61. package/core/ops/sharedPoint.js +7 -10
  62. package/core/ops/stacks.js +22 -1
  63. package/core/saves/SaveStore.js +52 -26
  64. package/core/saves/Saves.js +122 -27
  65. package/core/saves/saveApply.js +159 -61
  66. package/core/saves/saveFiles.js +30 -25
  67. package/core/saves/saveVersions.js +20 -6
  68. package/core/saves/session.js +76 -33
  69. package/core/saves/stateReplace.js +184 -0
  70. package/core/scene/Rays.js +21 -5
  71. package/core/scene/Views.js +6 -6
  72. package/core/scene/adaptive.js +13 -10
  73. package/core/scene/canvasBox.js +2 -0
  74. package/core/scene/compositeGround.js +72 -0
  75. package/core/scene/floor.js +17 -0
  76. package/core/scene/grid.js +2 -0
  77. package/core/scene/ground.contract.js +14 -0
  78. package/core/scene/ground.js +52 -17
  79. package/core/scene/pixel.js +154 -0
  80. package/core/scene/pixelRatio.js +167 -0
  81. package/core/scene/sceneDelta.js +3 -3
  82. package/core/scene/sceneMethods.js +11 -6
  83. package/core/scene/stepPoses.js +6 -1
  84. package/core/scene/thingExplain.js +1 -1
  85. package/core/scene/thingOps.js +22 -14
  86. package/core/scene/things.js +1 -1
  87. package/core/scene/tier.js +10 -0
  88. package/core/scene/view.js +126 -9
  89. package/core/stream/Batching.js +0 -1
  90. package/core/stream/Stream.js +24 -12
  91. package/core/stream/batchGroups.js +1 -0
  92. package/core/stream/scatter.js +5 -2
  93. package/core/stream/streamSources.js +2 -1
  94. package/core/threads/Commits.js +12 -7
  95. package/core/threads/Jobs.js +15 -5
  96. package/core/threads/Threads.js +5 -2
  97. package/core/time/Clock.js +3 -1
  98. package/core/time/skip.js +10 -4
  99. package/core/time/time.js +16 -10
  100. package/docs/AI.md +89 -72
  101. package/docs/API.md +18 -14
  102. package/docs/CODEMAP.md +68 -40
  103. package/docs/COMMANDS.md +22 -23
  104. package/docs/CONVENTIONS.md +120 -17
  105. package/docs/MIGRATING-0.8.md +2 -0
  106. package/docs/MIGRATING-1.0.md +101 -0
  107. package/docs/THREE.md +65 -12
  108. package/docs/api/cameraRig.md +3 -0
  109. package/docs/api/characters.md +13 -7
  110. package/docs/api/collider3d.md +9 -0
  111. package/docs/api/content.md +16 -15
  112. package/docs/api/dialogue.md +2 -1
  113. package/docs/api/engine.md +18 -16
  114. package/docs/api/events.md +14 -4
  115. package/docs/api/ground.md +2 -2
  116. package/docs/api/i18n.md +1 -1
  117. package/docs/api/input.md +2 -1
  118. package/docs/api/interactions.md +1 -1
  119. package/docs/api/inventory.md +1 -1
  120. package/docs/api/level.md +3 -2
  121. package/docs/api/nav.md +4 -2
  122. package/docs/api/particles.md +8 -5
  123. package/docs/api/pickups.md +1 -1
  124. package/docs/api/post.md +3 -4
  125. package/docs/api/quests.md +4 -2
  126. package/docs/api/rays.md +2 -0
  127. package/docs/api/rigid.md +3 -2
  128. package/docs/api/saves.md +8 -7
  129. package/docs/api/stream.md +4 -5
  130. package/docs/api/terrain.md +3 -4
  131. package/docs/api/terrainDraw.md +1 -1
  132. package/docs/api/timeline.md +2 -2
  133. package/docs/api/tools.md +3 -1
  134. package/docs/api/triggers.md +2 -0
  135. package/docs/api/vegetationDraw.md +1 -1
  136. package/docs/api/water.md +6 -2
  137. package/docs/api/weather.md +19 -4
  138. package/docs/api/weatherDraw.md +1 -1
  139. package/docs/api/world.md +1 -1
  140. package/docs/recipes/01-new-game.md +3 -3
  141. package/docs/recipes/02-npc.md +3 -4
  142. package/docs/recipes/03-items-pickups.md +11 -11
  143. package/docs/recipes/04-quests.md +2 -0
  144. package/docs/recipes/05-props-bake.md +9 -9
  145. package/docs/recipes/06-clock-events.md +6 -6
  146. package/docs/recipes/07-flow-scenes-pause.md +18 -15
  147. package/docs/recipes/08-weather-sky.md +5 -5
  148. package/docs/recipes/09-materials-lights-models.md +3 -3
  149. package/docs/recipes/10-blender-level.md +16 -4
  150. package/docs/recipes/11-vehicles.md +18 -6
  151. package/docs/recipes/12-navmesh.md +52 -8
  152. package/docs/recipes/13-animation.md +34 -8
  153. package/docs/recipes/14-custom-module.md +20 -8
  154. package/docs/recipes/15-perf.md +4 -4
  155. package/docs/recipes/16-dev-bridge.md +9 -8
  156. package/docs/recipes/18-world.md +13 -5
  157. package/docs/recipes/19-shooting-picking.md +3 -2
  158. package/docs/recipes/20-content-actions-save.md +26 -6
  159. package/docs/recipes/21-camera.md +17 -23
  160. package/docs/recipes/22-shop-gold.md +21 -12
  161. package/docs/recipes/23-ops.md +19 -15
  162. package/docs/recipes/26-ui-parts.md +3 -2
  163. package/docs/recipes/27-net.md +3 -3
  164. package/docs/recipes/28-terrain.md +3 -3
  165. package/docs/recipes/29-grid.md +1 -1
  166. package/docs/recipes/30-templates.md +10 -13
  167. package/docs/recipes/31-audio.md +2 -2
  168. package/docs/recipes/32-action-game.md +6 -5
  169. package/docs/recipes/33-stream-sources.md +4 -1
  170. package/docs/recipes/34-environment-lighting.md +7 -8
  171. package/docs/recipes/35-picture-from-reference.md +13 -9
  172. package/docs/recipes/36-ground-plants.md +3 -2
  173. package/docs/recipes/40-scene.md +11 -10
  174. package/docs/recipes/43-shader-patches-surfaces.md +7 -7
  175. package/docs/recipes/44-water-weather-hooks.md +9 -8
  176. package/docs/recipes/45-cascaded-shadows.md +3 -4
  177. package/docs/recipes/46-blender-art-route.md +3 -3
  178. package/docs/recipes/49-game-module-contract.md +2 -1
  179. package/docs/recipes/50-own-renderer.md +1 -0
  180. package/docs/recipes/51-capability-catalog.md +14 -8
  181. package/docs/recipes/52-around-the-picture.md +4 -4
  182. package/docs/recipes/55-mods-time-wrap.md +5 -4
  183. package/docs/recipes/56-webgpu-tsl.md +12 -1
  184. package/docs/recipes/57-control.md +30 -10
  185. package/docs/recipes/58-input.md +13 -0
  186. package/docs/recipes/60-judge-the-picture.md +1 -1
  187. package/docs/recipes/62-picture-code.md +106 -48
  188. package/docs/recipes/63-third-person-start.md +2 -1
  189. package/docs/recipes/64-particles.md +53 -4
  190. package/docs/recipes/65-swarm.md +2 -2
  191. package/docs/recipes/66-common-tasks.md +313 -0
  192. package/examples/action/.threedog/content-index.json +1 -1
  193. package/examples/action/GAMEMAP.md +3 -3
  194. package/examples/perf-island/.threedog/content-index.json +1 -1
  195. package/examples/perf-island/GAMEMAP.md +3 -3
  196. package/examples/perf-island/main.js +2 -2
  197. package/examples/plain-picture/GAMEMAP.md +3 -1
  198. package/examples/rc2d/GAMEMAP.md +1 -1
  199. package/examples/rc2d/rc2d.js +1 -1
  200. package/examples/styletest/.threedog/content-index.json +1 -1
  201. package/examples/styletest/GAMEMAP.md +3 -3
  202. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  203. package/examples/world/.threedog/content-index.json +1 -1
  204. package/examples/world/GAMEMAP.md +5 -4
  205. package/examples/world/main.js +3 -3
  206. package/index.d.ts +8 -5
  207. package/index.js +22 -1
  208. package/llms.txt +2 -1
  209. package/modules/ambience/Ambience.js +5 -3
  210. package/modules/calendar/index.js +7 -5
  211. package/modules/camera/FirstPersonCamera.js +3 -3
  212. package/modules/camera/FixedCamera.js +34 -20
  213. package/modules/camera/FollowCamera.js +20 -11
  214. package/modules/camera/RtsCamera.js +1 -0
  215. package/modules/camera/common.js +33 -22
  216. package/modules/camera/pixelSnap.js +62 -0
  217. package/modules/characters/Character.js +136 -43
  218. package/modules/characters/NPC.js +60 -28
  219. package/modules/characters/assetModel.js +2 -2
  220. package/modules/characters/astar.js +47 -28
  221. package/modules/characters/character.contract.js +21 -0
  222. package/modules/characters/contract.js +17 -3
  223. package/modules/characters/index.js +94 -34
  224. package/modules/characters/moveHelpers.js +80 -15
  225. package/modules/characters/mover.contract.js +14 -0
  226. package/modules/characters/movers/common.js +6 -4
  227. package/modules/characters/movers/rapier.js +12 -5
  228. package/modules/characters/movers/simple.js +25 -12
  229. package/modules/characters/movers/support.js +18 -7
  230. package/modules/characters/npcAvoid.js +15 -12
  231. package/modules/characters/npcSim.js +75 -25
  232. package/modules/characters/npcView.js +13 -6
  233. package/modules/characters/pathAsync.js +74 -24
  234. package/modules/characters/pathJob.js +38 -21
  235. package/modules/characters/player.js +59 -47
  236. package/modules/characters/seat.js +56 -0
  237. package/modules/characters/vehicle.contract.js +8 -5
  238. package/modules/characters/walkTo.js +31 -18
  239. package/modules/collision/Collision.js +44 -26
  240. package/modules/collision/contract.js +2 -2
  241. package/modules/collision/grid.js +6 -1
  242. package/modules/content/explain.js +1 -1
  243. package/modules/content/fields.js +3 -3
  244. package/modules/content/ids.js +3 -1
  245. package/modules/content/index.js +83 -27
  246. package/modules/content/loader.js +110 -130
  247. package/modules/content/markers.js +1 -1
  248. package/modules/content/models.js +48 -14
  249. package/modules/content/packs.js +2 -1
  250. package/modules/content/places.js +5 -4
  251. package/modules/content/props.js +8 -6
  252. package/modules/content/rules.js +29 -47
  253. package/modules/content/templates.js +66 -35
  254. package/modules/content/words.js +19 -6
  255. package/modules/debug/DebugPanel.js +4 -2
  256. package/modules/flow/contract.js +1 -0
  257. package/modules/flow/index.js +24 -14
  258. package/modules/gameplay/Container.js +5 -2
  259. package/modules/gameplay/Containers.js +9 -1
  260. package/modules/gameplay/Dialogue.js +82 -25
  261. package/modules/gameplay/Interactions.js +61 -32
  262. package/modules/gameplay/Inventory.js +56 -13
  263. package/modules/gameplay/Quests.js +133 -24
  264. package/modules/gameplay/boxOps.js +7 -0
  265. package/modules/gameplay/dialogueBubbles.js +14 -9
  266. package/modules/gameplay/inventoryOps.js +11 -7
  267. package/modules/gameplay/pickups.js +43 -16
  268. package/modules/gameplay/questLog.js +4 -2
  269. package/modules/gameplay/questSave.js +6 -1
  270. package/modules/gameplay/quests.contract.js +1 -1
  271. package/modules/grid/Grid.js +1 -1
  272. package/modules/grid/Layer.js +8 -4
  273. package/modules/grid/index.js +21 -15
  274. package/modules/grid/ops.js +43 -46
  275. package/modules/grid/tiles.js +1 -1
  276. package/modules/hlod/index.js +6 -3
  277. package/modules/hud/index.js +6 -4
  278. package/modules/hud/parts.js +4 -4
  279. package/modules/level/contract.js +2 -2
  280. package/modules/level/heightfield.js +17 -21
  281. package/modules/level/index.js +83 -26
  282. package/modules/level/load.js +165 -48
  283. package/modules/level/nodes.js +34 -16
  284. package/modules/lights/index.js +6 -3
  285. package/modules/lights/sources.js +3 -1
  286. package/modules/music/Music.js +4 -2
  287. package/modules/nav/contract.js +7 -5
  288. package/modules/nav/index.js +174 -44
  289. package/modules/nav/navPath.js +45 -10
  290. package/modules/net/index.js +1 -1
  291. package/modules/particles/Particles.js +85 -22
  292. package/modules/particles/effect.js +80 -28
  293. package/modules/particles/shaders.js +17 -0
  294. package/modules/photo/Photo.js +12 -10
  295. package/modules/rigid/RigidBodies.js +200 -57
  296. package/modules/rigid/Vehicles.js +15 -5
  297. package/modules/rigid/collider3d.contract.js +26 -0
  298. package/modules/rigid/ragdoll.js +55 -44
  299. package/modules/rigid/ragdollBones.js +83 -33
  300. package/modules/rigid/refresh.js +10 -0
  301. package/modules/rigid/sync.js +46 -15
  302. package/modules/settings/Settings.js +84 -37
  303. package/modules/settings/apply.js +15 -8
  304. package/modules/settings/sections.js +7 -4
  305. package/modules/settings/strings.js +2 -2
  306. package/modules/sky/skyModule.js +3 -1
  307. package/modules/swarm/Swarm.js +16 -6
  308. package/modules/terrain/ChunkManager.js +10 -16
  309. package/modules/terrain/index.js +17 -11
  310. package/modules/terrain/terrainEdit.js +13 -2
  311. package/modules/terrain/terrainGen.js +5 -3
  312. package/modules/terrain/terrainShape.js +1 -1
  313. package/modules/timeline/Timeline.js +58 -26
  314. package/modules/timeline/Tween.js +19 -13
  315. package/modules/timeline/shots.js +19 -10
  316. package/modules/triggers/index.js +87 -20
  317. package/modules/vegetation/Vegetation.js +4 -3
  318. package/modules/vegetation/draw.js +16 -0
  319. package/modules/vegetation/groundChunks.js +10 -7
  320. package/modules/vegetation/index.js +30 -7
  321. package/modules/water/Water.js +6 -2
  322. package/modules/weather/Weather.js +16 -15
  323. package/modules/weather/weatherDraw.js +7 -6
  324. package/modules/world/World.js +20 -7
  325. package/modules/world/explain.js +1 -1
  326. package/modules/world/index.js +13 -6
  327. package/modules/world/persist.js +23 -8
  328. package/modules/world/pos.js +4 -4
  329. package/modules/world/records.js +13 -7
  330. package/modules/world/sim.js +74 -23
  331. package/modules/world/simFar.js +2 -2
  332. package/modules/world/state.js +31 -6
  333. package/modules/world/thingSource.js +16 -3
  334. package/modules/world/views.js +19 -8
  335. package/package.json +7 -1
  336. package/render/PostFX.js +47 -29
  337. package/render/backend.js +5 -1
  338. package/render/fx/particles.tsl.js +8 -6
  339. package/render/fx/postWebGPU.tsl.js +3 -3
  340. package/render/layers.js +1 -1
  341. package/render/lightmap.js +23 -3
  342. package/render/occlusion.js +43 -12
  343. package/render/patches.js +2 -2
  344. package/render/postWebGL.js +4 -3
  345. package/render/probes.js +25 -0
  346. package/render/shadows.js +2 -2
  347. package/types/core.d.ts +142 -55
  348. package/types/gameplay.d.ts +92 -40
  349. package/types/generated/core/base/I18n.d.ts +2 -2
  350. package/types/generated/core/input/Input.d.ts +16 -2
  351. package/types/generated/core/input/inputSeat.d.ts +26 -0
  352. package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
  353. package/types/generated/core/ops/Ops.d.ts +2 -1
  354. package/types/generated/core/ops/control.d.ts +12 -2
  355. package/types/generated/core/saves/Saves.d.ts +26 -6
  356. package/types/generated/core/saves/session.d.ts +1 -1
  357. package/types/generated/core/scene/Views.d.ts +1 -1
  358. package/types/generated/core/stream/Stream.d.ts +6 -4
  359. package/types/generated/modules/grid/Grid.d.ts +1 -0
  360. package/types/generated/modules/particles/Particles.d.ts +4 -3
  361. package/types/generated/modules/timeline/Timeline.d.ts +5 -4
  362. package/types/generated/modules/weather/Weather.d.ts +1 -7
  363. package/types/generated/modules/world/World.d.ts +6 -4
  364. package/types/generated/render/PostFX.d.ts +6 -14
  365. package/types/nav.d.ts +36 -4
  366. package/types/physics.d.ts +55 -7
  367. package/types/pixel.d.ts +75 -0
  368. package/types/world.d.ts +14 -8
  369. package/ui/Parts.js +9 -2
  370. package/ui/theme.js +2 -2
  371. package/core/scene/engineCamera.js +0 -32
  372. package/modules/camera/projection.js +0 -21
@@ -1,8 +1,11 @@
1
1
  // Models of placed content records: clone the shared prototype of a model name (core/assets/namedModel.js protoOf, the one path every system uses),
2
2
  // align it and its collision to the record (props and template instances).
3
+ import * as THREE from 'three';
4
+ import { codedError } from '../../core/base/errorHints.js';
3
5
  import { protoOf } from '../../core/assets/namedModel.js';
4
6
  import { wrapLod } from '../../core/assets/assetLod.js';
5
7
  import { Vector3 } from 'three';
8
+ import { clone as skeletonClone } from 'three/addons/utils/SkeletonUtils.js';
6
9
  import { list } from '../../core/base/util.js';
7
10
 
8
11
  const BASE_BAND = 0.2; // the share of the model's height above the ground that counts as its base
@@ -52,37 +55,68 @@ export function baseOf(proto) {
52
55
  * mul: a template stage's scale, multiplied onto the record's own scale (the record keeps only its authored scale). @internal
53
56
  */
54
57
  export function settle(e, rec, o, solid, mul = 1) {
55
- const { x, z } = rec.position, rot = rec.rot ?? 0, scale = (rec.scale ?? 1) * mul, ud = o.userData;
56
- ud.fit = { x, z, rot, scale };
57
- rec.position.y = e.surface(x, z, rec.floor) + (rec.offsetY ?? 0);
58
- o.position.y = rec.position.y; o.rotation.y = rot; o.scale.setScalar(scale);
58
+ const { x, z } = rec.position, rot = rotOf(rec), sv = scaleOf(rec, mul), ud = o.userData;
59
+ ud.fit = fitOf(rec, mul); ud.shape = shapeOf(rec, mul); ud.holder = holderOf(e, rec);
60
+ const tilted = isTilted(rec);
61
+ if (tilted && solid.collide && !e.collider3d) throw tiltError(rec);
62
+ // ground: false keeps the written height (a floating or hung model); a body's height is the solver's (templates.js addBody). The height comes from the ground, not from play,
63
+ // so it stays out of the save (world.rest), and a ground ray's rounding (1e-16 off a turned level) is no new height: a load would write a change for it
64
+ const y = e.surface(x, z, rec.floor) + (rec.offsetY ?? 0);
65
+ if (rec.ground !== false && !solid.body && Math.abs(rec.position.y - y) > 1e-6 && !e.world.rest(rec.id, { x, y, z })) rec.position.y = y;
66
+ o.position.y = rec.position.y; o.rotation.set(rot[0], rot[1], rot[2]); o.scale.set(sv[0], sv[1], sv[2]);
59
67
  ud.unstatic?.remove(); ud.unstatic = null;
60
68
  for (const h of ud.colliders.splice(0)) h.remove();
61
69
  // a solid prop blocks the camera with its whole mesh, not only its footprint collider: crowns and eaves stand outside the footprint, and no game code should have to say so
62
70
  const blocks = !!solid.collide && solid.collide.occluder !== false && solid.occluder !== false;
63
71
  if (solid.static !== false && e.rays) { o.updateMatrixWorld(true); ud.unstatic = e.rays.addStatic(o, { occluder: blocks }); }
64
- if (!solid.collide || !e.collision) return;
72
+ if (!solid.collide) return;
65
73
  const { collide } = solid, set = typeof collide === 'object' ? collide : null, base = set || collide === 'circle' ? baseOf(ud.proto) : null;
66
- const size = ud.proto.size.clone().multiplyScalar(scale), c = base ?? ud.proto.center, ox = c.x * scale, oz = c.z * scale;
67
- const cx = x + ox * Math.cos(rot) + oz * Math.sin(rot), cz = z - ox * Math.sin(rot) + oz * Math.cos(rot);
74
+ const size = ud.proto.size.clone().multiply(new THREE.Vector3(...sv));
75
+ if (tilted) { // a turned-over solid is not a footprint on the ground: the three-axis provider holds it (o.quaternion carries the same turn the model has)
76
+ const mid = ud.proto.center.clone().multiply(new THREE.Vector3(...sv)).applyQuaternion(o.quaternion).add(o.position);
77
+ ud.colliders.push(e.collider3d.addSolid(base
78
+ ? { position: [mid.x, mid.y, mid.z], radius: (set?.circle ?? base.width / 2) * Math.max(sv[0], sv[2]) }
79
+ : { position: [mid.x, mid.y, mid.z], size: [size.x, size.y, size.z], rotation: rot }));
80
+ return;
81
+ }
82
+ if (!e.collision) return;
83
+ const c = base ?? ud.proto.center, ox = c.x * sv[0], oz = c.z * sv[2];
84
+ const cx = x + ox * Math.cos(rot[1]) + oz * Math.sin(rot[1]), cz = z - ox * Math.sin(rot[1]) + oz * Math.cos(rot[1]);
68
85
  ud.colliders.push(base
69
- ? e.collision.addCircle({ x: cx, z: cz }, { radius: (set?.circle ?? base.width / 2) * scale, height: size.y, occluder: blocks })
70
- : e.collision.addBox({ x: cx, z: cz }, { halfWidth: size.x / 2, halfDepth: size.z / 2, rotation: rot, height: size.y, occluder: blocks }));
86
+ ? e.collision.addCircle({ x: cx, z: cz }, { radius: (set?.circle ?? base.width / 2) * Math.max(sv[0], sv[2]), height: size.y, occluder: blocks })
87
+ : e.collision.addBox({ x: cx, z: cz }, { halfWidth: size.x / 2, halfDepth: size.z / 2, rotation: rot[1], height: size.y, occluder: blocks }));
71
88
  }
72
- /** Is the model still as settle aligned it? update asks every frame for every built prop, because world.move sends no event: four compares, no text @internal */
73
- export const fits = (o, rec, mul = 1) => { const f = o.userData.fit, p = rec.position; return f.x === p.x && f.z === p.z && f.rot === (rec.rot ?? 0) && f.scale === (rec.scale ?? 1) * mul; };
89
+ /** Is the model still as settle aligned it, with its collider in the holder installed now (a new one starts empty; with none there is nothing to do yet)? update asks every frame for every built prop, because world.move sends no event @internal */
90
+ /** rot / scale of a record as [x, y, z]: a number is the facing about Y and a uniform scale, as it always was; an array sets each axis (the model's Euler order XYZ) */
91
+ export const rotOf = rec => Array.isArray(rec.rot) ? rec.rot : [0, rec.rot ?? 0, 0];
92
+ export const scaleOf = (rec, mul = 1) => (Array.isArray(rec.scale) ? rec.scale : [rec.scale ?? 1, rec.scale ?? 1, rec.scale ?? 1]).map(v => v * mul);
93
+ const fitOf = (rec, mul) => JSON.stringify([rec.position.x, rec.position.z, rec.ground === false ? rec.position.y : null, rotOf(rec), scaleOf(rec, mul)]);
94
+ export const fits = (e, o, rec, mul = 1) => { const h = holderOf(e, rec); return (!h || o.userData.holder === h) && o.userData.fit === fitOf(rec, mul); };
95
+ const shapeOf = (rec, mul) => JSON.stringify([rotOf(rec), scaleOf(rec, mul)]);
96
+ /** The turn and size it was built with still hold (a body moves itself, so its place says nothing) @internal */
97
+ export const fitsShape = (o, rec, mul = 1) => o.userData.shape === shapeOf(rec, mul);
98
+ /** A tilted solid needs the three-axis provider (collider3d); the same error at load (props.js) and at build, so a mistake shows once, early @internal */
99
+ export const tiltError = rec => codedError('content-misuse', `prop ${JSON.stringify(rec.id ?? rec.model)}: collide on a model turned about x or z (rot ${JSON.stringify(rec.rot)}) needs a collider3d provider: install rigid() (or your own collider3d), or set collide: false`);
100
+ export const isTilted = rec => { const r = rotOf(rec); return !!(r[0] || r[2]); };
101
+ const holderOf = (e, rec) => isTilted(rec) ? e.collider3d : e.collision;
74
102
 
75
- /** Clone the shared prototype of a model for one record and align it (props and template instances) @internal */
103
+ /** Clone the shared prototype of a model for one record and align it (props and template instances). skeletonClone: a skinned part of a plain clone keeps the prototype's bones and draws where they stand @internal */
76
104
  export async function buildModel(e, api, rec, model, solid, mul = 1) {
77
105
  const proto = await protoOf(e, api, model), name = list(model)[0], lod = rec.lod ?? solid.lod;
78
106
  // settle below measures proto, never o, so collision stays the full model's; the record keeps only the word `lod`, so a save holds no level
79
- const o = lod ? await wrapLod(e.assets, name, proto.obj.clone(), { distances: Array.isArray(lod) ? lod : undefined, scale: (rec.scale ?? 1) * mul }) : proto.obj.clone();
107
+ const o = lod ? await wrapLod(e.assets, name, skeletonClone(proto.obj), { distances: Array.isArray(lod) ? lod : undefined, scale: Math.max(...scaleOf(rec, mul)) }) : skeletonClone(proto.obj);
80
108
  o.name ||= name; o.userData.name ??= name;
81
109
  o.userData.proto = proto; o.userData.colliders = [];
110
+ o.userData.refit = r => { if (!solid.body && !fits(e, o, r, mul)) settle(e, r, o, solid, mul); }; // a body places itself; a stale solid or mul is put right by the presenter's next update
111
+ // a file model only: a generator's prototype is pinned for good (Assets.cached), so nothing could free it. The built prop counts in describe().assets until it is torn down
112
+ if (!e.assets.builder(name)) o.userData.lease = await e.assets.lease(name);
82
113
  if (rec.batch === false) o.userData.batch = false; // opt out of engine.batching for this record
83
114
  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
84
115
  settle(e, rec, o, solid, mul);
85
116
  return o;
86
117
  }
118
+ /** ctx.feeds: every built solid goes into the holder installed now, so the line after use() reads it. The presenters' update asks the same every frame, for what moved @internal */
119
+ export const refit = e => { for (const rec of e.world?.query({}) ?? []) e.world.view(rec.id)?.userData.refit?.(rec); };
120
+
87
121
  /** Tear down only: geometry and material belong to the shared prototype, the next build clones it again @internal */
88
- export function unbuildModel(e, o) { o.userData.unstatic?.remove(); for (const h of o.userData.colliders) h.remove(); e.detach(o); }
122
+ export function unbuildModel(e, o) { o.userData.lease?.remove(); o.userData.unstatic?.remove(); for (const h of o.userData.colliders) h.remove(); o.removeFromParent(); }
@@ -47,7 +47,8 @@ export function packsOf(data) {
47
47
  packs.forEach((p, i) => {
48
48
  if (!isPlainObject(p)) throw codedError('content-pack', fmt(STRINGS.notPack, { at: i + 1, got: Array.isArray(p) ? 'an array' : typeof p }));
49
49
  for (const [key, v] of Object.entries(p)) {
50
- if (key === 'rules') { claim('rules.conditions', v?.conditions, i); claim('rules.kinds', v?.kinds, i); }
50
+ if (key === 'level' && (typeof v === 'string' || v?.isObject3D)) claim('level', { level: 1 }, i); // a load has one transaction: the second level would drop the first with all that stands on it
51
+ else if (key === 'rules') { claim('rules.conditions', v?.conditions, i); claim('rules.kinds', v?.kinds, i); }
51
52
  // audio: named tables are ids (a sound in two packs is an error), rule lists concatenate
52
53
  else if (key === 'audio') { claim('audio.sounds', v?.sounds, i); claim('audio.footsteps', v?.footsteps, i); claim('audio.music.tracks', v?.music?.tracks, i); }
53
54
  else if (key !== 'name' && !NOT_KEYED.has(key) && isPlainObject(v)) claim(key, v, i);
@@ -2,14 +2,15 @@
2
2
  // api is engine.content: where and offset read a place through api.place, so a wrapped place is the one they use.
3
3
  import { placeY } from '../../core/scene/ground.js';
4
4
  import { codedError } from '../../core/base/errorHints.js';
5
+ import { placeProblem } from './rules.js';
5
6
 
6
- /** content.load: add the packs' places, then the places option on top. A text entry in a place file waits for the option */
7
- export function addPlaces(places, packs, given) {
7
+ /** content.load: the packs' places, then the places option on top, checked. A text entry in a place file waits for the option */
8
+ export function placesOf(packs, given) {
8
9
  const pl = {};
9
10
  for (const p of packs) for (const [name, at] of Object.entries(p.places ?? {})) if (at && typeof at === 'object') pl[name] = at;
10
11
  Object.assign(pl, given);
11
- for (const [name, p] of Object.entries(pl)) if (p?.rot !== undefined && !Number.isFinite(p.rot)) throw codedError('content-place', `Place "${name}": rot must be a number of radians about Y, got ${JSON.stringify(p.rot)}`);
12
- Object.assign(places, pl);
12
+ for (const [name, p] of Object.entries(pl)) { const bad = placeProblem(p); if (bad) throw codedError('content-place', `Place "${name}": ${bad}`); }
13
+ return pl;
13
14
  }
14
15
 
15
16
  /** content.place */
@@ -1,6 +1,6 @@
1
1
  // Props (each item of content/props.js): data is a plain record in engine.world with kind 'prop'; model and collision are "presentation that exists only when
2
2
  // near".
3
- // record: { id, kind: 'prop', position: {x,y,z}, model, rot?, scale?, collide?, occluder?, offsetY?, static?, batch?, source?, zone? } (plain values only)
3
+ // record: { id, kind: 'prop', position: {x,y,z}, model, rot?, scale?, ground?, collide?, occluder?, offsetY?, static?, batch?, source?, zone? } (plain values only)
4
4
  // rot = the entry's rot plus its place's. source names the arrangement an entry was copied from: a tag for world.query, nothing at runtime reads it.
5
5
  // Initial world data (initial: true on add): the save records only moves / removals, independent of content.load running before or after loading a save;
6
6
  // positions using level markers carry a zone (data is kept across level changes).
@@ -17,6 +17,7 @@ import { buildModel, settle, fits, unbuildModel } from './models.js';
17
17
  import { placeTemplate } from './templates.js';
18
18
  import { srcOf } from './ids.js';
19
19
  import { placeY } from '../../core/scene/ground.js';
20
+ import { isTilted, tiltError } from './models.js';
20
21
  import { PLACEMENT_FIELDS, collideProblem } from './rules.js';
21
22
  import { list } from '../../core/base/util.js';
22
23
  import { DEV, fmt, closest } from '../../core/base/validate.js';
@@ -38,14 +39,15 @@ export function addProps(e, api, props, st, zoneOf, ids) {
38
39
  if (p.grid) return placeGridItem(e, p, i, zoneOf(p), ids, at); // a pre-placed grid item (grid module)
39
40
  const collide = collideProblem(p.collide);
40
41
  if (collide) throw codedError('content-misuse', `props[${i}] (model ${JSON.stringify(p.model)}): collide ${collide}`);
41
- const id = propId(p, i), { x, y, z } = api.where(p), zone = zoneOf(p), floor = api._floorOf(p);
42
+ if (p.collide && isTilted(p) && !e.collider3d) throw tiltError({ ...p, id: p.id });
43
+ const id = propId(p, i), free = p.ground === false, { x, y, z } = api.where(free ? { ...p, y: undefined, floor: undefined } : p), zone = zoneOf(p), floor = api._floorOf(p);
42
44
  if (p.id != null) ids.claim(p.id, `props[${i}] (model ${JSON.stringify(p.model)})`);
43
45
  // compute y from the ground now (same as when the model is built): unmoved props equal the content and stay out of the save
44
- const def = { id, kind: 'prop', position: { x, y: y ?? placeY(e, `props[${i}] (model ${JSON.stringify(p.model)})`, x, z), z }, model: p.model };
45
- for (const k of ['scale', 'collide', 'occluder', 'static', 'batch', 'lod', 'source']) if (p[k] !== undefined) def[k] = p[k];
46
+ const def = { id, kind: 'prop', position: { x, y: free ? p.y ?? 0 : y ?? (placeY(e, `props[${i}] (model ${JSON.stringify(p.model)})`, x, z)), z }, model: p.model };
47
+ for (const k of ['scale', 'ground', 'collide', 'occluder', 'static', 'batch', 'lod', 'source']) if (p[k] !== undefined) def[k] = p[k];
46
48
  const rot = api._facingOf(p);
47
49
  if (rot !== undefined) def.rot = rot;
48
- if (p.y) def.offsetY = p.y;
50
+ if (p.y && !free) def.offsetY = p.y;
49
51
  if (floor !== undefined) def.floor = floor; // kept so a moved prop lands on the same storey
50
52
  if (zone != null) def.zone = zone;
51
53
  const rec = world.add(def, { initial: true });
@@ -95,7 +97,7 @@ function presentProps(e, api, world, st) {
95
97
  radius: () => Math.max(world.radius, e.stream.activeRadius),
96
98
  build: rec => buildModel(e, api, rec, rec.model, rec), // a failed model generation is reported by world (does not block loading), retried when near again
97
99
  // moved / rot or scale changed (world.move sends no event, so compare here): world already put the model at the new position; collision and rays follow
98
- update(rec, o) { if (!fits(o, rec)) settle(e, rec, o, rec); },
100
+ update(rec, o) { if (!fits(e, o, rec)) settle(e, rec, o, rec); },
99
101
  dispose: (rec, o) => unbuildModel(e, o),
100
102
  }));
101
103
  }
@@ -28,6 +28,7 @@
28
28
  // check: (data, ctx) => { for (const [id, r] of Object.entries(data)) if (!ctx.data.items?.[r.makes]) ctx.err(`recipe ${id} makes unknown item ${r.makes}`); } } } };
29
29
 
30
30
  import { list, isObject } from '../../core/base/util.js';
31
+ import { sectionDocs, sectionEffects } from '../../core/inspect/metadata.generated.js';
31
32
 
32
33
  const counts = o => Object.entries(o || {}).map(([k, n]) => `${k}×${n}`).join('、');
33
34
  const opText = v => Array.isArray(v) ? `${v[0]}${v[1] ? ' ' + Object.entries(v[1]).map(([k, x]) => `${k}=${x}`).join(' ') : ''}` : String(v);
@@ -47,7 +48,6 @@ const RULE_STRINGS = {
47
48
  give: { ref: 'itemCounts', desc: 'give items', describe: v => `give ${counts(v)}` },
48
49
  take: { ref: 'itemCounts', desc: 'take items', describe: v => `take ${counts(v)}` },
49
50
  bump: { ref: 'counter', desc: 'counter +1', describe: v => `counter ${v}+1` },
50
- startQuest: { ref: 'quest', desc: 'start a quest', describe: v => `start quest ${v}` },
51
51
  toast: { ref: 'text', desc: 'show a toast', describe: v => `toast "${v}"` },
52
52
  particles: { ref: 'particles', desc: 'play particles', describe: v => `particles ${v.name}×${v.count ?? ''}` },
53
53
  marker: { ref: 'position', desc: 'add an objective marker (hud module)', describe: v => `marker ${posText(v)}${v.label ? `"${v.label}"` : ''}` },
@@ -55,27 +55,6 @@ const RULE_STRINGS = {
55
55
  clearMarker: { ref: 'position', raw: true, desc: 'remove an objective marker', describe: v => `remove marker ${posText(v)}` },
56
56
  op: { ref: 'op', desc: "run a game op (engine.ops.run); the game's own actions are ops", describe: v => `op ${opText(v)}` },
57
57
  },
58
- // content file name -> description (only these files are recognized in content/)
59
- files: {
60
- items: 'items (id -> name, icon, description); also export startItems for starting items',
61
- pickups: 'pickups on the ground (list)',
62
- containers: 'chests / shelves (container id -> { capacity, items: starting goods }; starting goods are placed only the first time, then saved)',
63
- npcs: 'NPCs (id -> name, schedule, interact)',
64
- dialogues: 'dialogues (id -> speaker, nodes)',
65
- quests: 'quests (id -> title, steps, reward; a step can have a target position)',
66
- actions: 'own key actions of the game (action name -> default key, label)',
67
- places: 'place names (name -> { x, z, y?, rot? }; rot turns everything placed there about Y; coordinates may be computed at runtime in main.js)',
68
- triggers: 'trigger zones (tag -> position / from level, enter/exit effects)',
69
- level: 'level markers (spawn point, NPCs, trigger zones) of a code-built level: for the tools (content checks, GAMEMAP); load() accepts the file and does not read it',
70
- vegetation: 'vegetation (name -> model, growth rule)',
71
- props: 'props (list: model, position, facing, collision; or { template, x, z } = an instance of a template; or { id, grid, item, cell } = a grid item), streamed in on demand',
72
- templates: 'reusable objects (name -> model, collide, interact, container, sound, animate, state defaults, physics body); shared read-only definitions',
73
- audio: 'sounds by asset name, ambience and music rules as data, footsteps (sounds, ambience, music: { tracks, rules }, footsteps)',
74
- views: 'named fixed camera views (name -> { position: [x, y, z], target?: [x, y, z], fov? }); engine.views.show(name), ?view=name, npm run shot -- -w game --view name',
75
- grids: 'placement grids (name -> { cell, origin, size, zone?, flat? }); layout rules, not saved',
76
- renames: "renamed or deleted authored ids (old id -> new id, or null = deleted on purpose): the player's saved changes follow the new id",
77
- rules: 'condition words and data kinds added by the game ({ conditions, kinds }); actions are ops, not effect words',
78
- },
79
58
  // Placement fields: the keys one entry of a content file may have, in the core/base/params.js spec format. Declared once here, read by the loader
80
59
  // (unknown keys), content-check (unknown keys with did-you-mean, wrong type, out of range, not in values) and engine.content.fields() (an editor
81
60
  // panel's rows), so the three cannot drift apart. props has three entry shapes: a plain model ('props'), a template instance ('props.template',
@@ -83,49 +62,50 @@ const RULE_STRINGS = {
83
62
  // (x, z are optional when place is given), so they are marked optional here.
84
63
  fields: (() => {
85
64
  const at = {
86
- place: { type: 'string', optional: true, desc: "place name (places.js / level marker); x and z are then offsets from it and turn with the place's rot" },
65
+ place: { label: 'Place', rare: true, type: 'string', optional: true, desc: "place name (places.js / level marker); x and z are then offsets from it and turn with the place's rot" },
87
66
  x: { type: 'number', optional: true, desc: 'meters along x (offset from place when place is given)' },
88
67
  z: { type: 'number', optional: true, desc: 'meters along z (offset from place when place is given)' },
89
- floor: { type: 'number', optional: true, desc: 'reference height of the storey it stands on (multi-layer ground)' },
90
- y: { type: 'number', optional: true, desc: 'meters above the ground it stands on' },
68
+ floor: { label: 'Storey height', rare: true, type: 'number', optional: true, desc: 'reference height of the storey it stands on (multi-layer ground)' },
69
+ y: { label: 'Height', type: 'number', optional: true, desc: 'meters above the ground it stands on (the height itself when ground is false)' },
91
70
  };
92
71
  const pose = {
93
- rot: { type: 'number', optional: true, desc: 'facing around the vertical axis, radians' },
94
- scale: { type: 'number', optional: true, min: 0, desc: 'uniform scale (1 = model size)' },
72
+ rot: { label: 'Facing', type: 'number|position', optional: true, desc: 'facing around the vertical axis, radians; or [x, y, z] radians to tilt it (a tilted collide needs a collider3d provider)' },
73
+ scale: { label: 'Size', type: 'number|position', optional: true, desc: 'uniform scale (1 = model size), or [x, y, z] per axis' },
95
74
  };
96
75
  // a plain tag, so world.query({ where: r => r.source === 'stall' }) finds every copy of one arrangement; nothing else reads it
97
- const copied = { source: { type: 'string', optional: true, desc: 'name of the arrangement this entry was copied from; queryable, no other effect' } };
76
+ const copied = { source: { label: 'Copied from', rare: true, type: 'string', optional: true, desc: 'name of the arrangement this entry was copied from; queryable, no other effect' } };
98
77
  return {
99
78
  props: {
100
79
  id: { type: 'string', optional: true, desc: 'stable id (needed when entries are later inserted in the middle)' },
101
80
  model: { type: 'any', desc: "model name, or [name, ...args] for a generated model" }, ...at, ...pose, ...copied,
102
- collide: { type: 'any', optional: true, desc: "collision: 'box', 'circle', { circle: radius, occluder?: false }, or false = none" },
103
- occluder: { type: 'bool', optional: true, desc: 'false = a solid prop the follow camera may pass through (walkers are still stopped)' },
104
- static: { type: 'bool', optional: true, desc: 'never moves (may be merged into one draw call)' },
105
- batch: { type: 'bool', optional: true, desc: 'false = never batch this copy' },
106
- lod: { type: 'any', optional: true, desc: 'true = lower-detail levels far away (threedog assets optimize --lod), or rising distances in meters like [40, 120]; such a copy is never batched' },
81
+ ground: { type: 'bool', optional: true, desc: 'false = do not snap to the ground: y is the height in the world' },
82
+ collide: { label: 'Collision', rare: true, type: 'any', optional: true, desc: "collision: 'box', 'circle', { circle: radius, occluder?: false }, or false = none" },
83
+ occluder: { label: 'Blocks camera', rare: true, type: 'bool', optional: true, desc: 'false = a solid prop the follow camera may pass through (walkers are still stopped)' },
84
+ static: { label: 'Never moves', rare: true, type: 'bool', optional: true, desc: 'never moves (may be merged into one draw call)' },
85
+ batch: { label: 'Merge copies', rare: true, type: 'bool', optional: true, desc: 'false = never batch this copy' },
86
+ lod: { label: 'Far detail', rare: true, type: 'any', optional: true, desc: 'true = lower-detail levels far away (threedog assets optimize --lod), or rising distances in meters like [40, 120]; such a copy is never batched' },
107
87
  },
108
88
  'props.template': {
109
89
  template: { type: 'string', desc: 'template name (content/templates.js)' },
110
90
  id: { type: 'string', optional: true, desc: 'stable id; instances with state should have one' }, ...at, ...pose, ...copied,
111
- items: { type: 'object', optional: true, desc: "starting goods of the instance's container { itemId: count }" },
91
+ items: { label: 'Starts with', rare: true, type: 'object', optional: true, desc: "starting goods of the instance's container { itemId: count }" },
112
92
  },
113
93
  'props.grid': {
114
94
  id: { type: 'string', desc: 'stable id (the player can move or pick it up)' },
115
95
  grid: { type: 'string', desc: 'grid name (content/grids.js)' },
116
96
  item: { type: 'string', desc: 'grid item name' },
117
97
  cell: { type: 'position', desc: 'grid cell [col, row]' },
118
- rotation: { type: 'int', optional: true, values: [0, 1, 2, 3], desc: 'quarter turns' },
119
- fields: { type: 'object', optional: true, desc: 'record fields of this copy' },
98
+ rotation: { label: 'Quarter turns', type: 'int', optional: true, values: [0, 1, 2, 3], desc: 'quarter turns' },
99
+ fields: { label: 'Own fields', rare: true, type: 'object', optional: true, desc: 'record fields of this copy' },
120
100
  },
121
101
  pickups: {
122
102
  id: { type: 'string', optional: true, desc: 'stable id' },
123
103
  item: { type: 'string', desc: 'item id (items.js)' }, ...at,
124
104
  count: { type: 'int', optional: true, min: 1, desc: 'how many one pickup gives' },
125
- data: { type: 'any', optional: true, desc: 'extra data handed to the game' },
126
- radius: { type: 'number', optional: true, min: 0, desc: 'pickup reach in meters' },
127
- auto: { type: 'bool', optional: true, desc: 'taken by walking into it, no key' },
128
- respawn: { type: 'number', optional: true, min: 0, desc: 'seconds until it comes back (0 = never)' },
105
+ data: { label: 'Extra data', rare: true, type: 'any', optional: true, desc: 'extra data handed to the game' },
106
+ radius: { label: 'Reach', rare: true, type: 'number', optional: true, min: 0, desc: 'pickup reach in meters' },
107
+ auto: { label: 'Walk to take', rare: true, type: 'bool', optional: true, desc: 'taken by walking into it, no key' },
108
+ respawn: { label: 'Comes back after', rare: true, type: 'number', optional: true, min: 0, desc: 'seconds until it comes back (0 = never)' },
129
109
  },
130
110
  views: {
131
111
  position: { type: 'position', optional: true, desc: 'camera position [x, y, z]' },
@@ -148,10 +128,10 @@ const S = RULE_STRINGS;
148
128
  export const CONDITIONS = RULE_STRINGS.conditions;
149
129
  /** Built-in effect words of the engine */
150
130
  export const EFFECTS = RULE_STRINGS.effects;
131
+ /** Every effect word of the engine: the built-in ones and those a section's owner declares, which metadata.mjs reads out for the tools that run without an engine */
132
+ export const ALL_EFFECTS = { ...EFFECTS, ...Object.fromEntries(Object.entries(sectionEffects).map(([k, d]) => [k, { ...d, describe: v => d.describe.replace('{v}', v) }])) };
151
133
  /** ref → ref -> how to write the value */
152
134
  export const REFS = RULE_STRINGS.refs;
153
- /** content file name -> description */
154
- export const CONTENT_FILES = RULE_STRINGS.files;
155
135
  /** content entry shape -> { key: field spec } (core/base/params.js format): 'props', 'props.template', 'props.grid', 'pickups', 'views'. Read via fields.js */
156
136
  export const PLACEMENT_FIELDS = RULE_STRINGS.fields;
157
137
  /** Why a prop's or template's `collide` is wrong, or null. One rule for the load and content-check: a mistyped object must not quietly become a box */
@@ -161,23 +141,25 @@ export function collideProblem(v) {
161
141
  if (form && Number.isFinite(v.circle) && v.circle > 0 && (v.occluder === undefined || typeof v.occluder === 'boolean')) return null;
162
142
  return `must be one of false, "box", "circle" or { circle: radius in meters above 0, occluder?: false }, got ${JSON.stringify(v)}`;
163
143
  }
144
+ /** Why a place cannot load, or null: a turned place moves everything standing on it, so a bad rot stops at the load and in content-check alike */
145
+ export const placeProblem = p => p?.rot !== undefined && !Number.isFinite(p.rot) ? `rot must be a number of radians about Y, got ${JSON.stringify(p.rot)}` : null;
164
146
  /** Clock time notation 'HH:MM' (24-hour) */
165
147
  export const CLOCK_RE = /^([01]\d|2[0-3]):[0-5]\d$/;
166
148
 
167
149
  /** Merge the engine vocabulary and the game vocabulary (default export of the game's content/rules.js) -> { conditions, effects }. Games add conditions only */
168
150
  export function mergeRules(game = {}) {
169
- return { conditions: { ...CONDITIONS, ...game.conditions }, effects: EFFECTS };
151
+ return { conditions: { ...CONDITIONS, ...game.conditions }, effects: ALL_EFFECTS };
170
152
  }
171
- /** Every content name a game may use: the engine's files plus the game's kinds (rules.js kinds) -> description; the one list loader, content-check and GAMEMAP share */
153
+ /** Every content name a game may use: the engine's sections plus the game's kinds (rules.js kinds) -> description; the one list loader, content-check and GAMEMAP share */
172
154
  export function contentFiles(game = {}) {
173
- const out = { ...CONTENT_FILES, startItems: 'starting items (exported from items.js)' };
155
+ const out = { ...sectionDocs };
174
156
  for (const [name, k] of Object.entries(game?.kinds || {})) out[name] ??= k?.desc || 'game data kind';
175
157
  return out;
176
158
  }
177
159
  /** Problems with a game's kinds table (name clashes with an engine file, a load that is no function): a list of messages */
178
160
  export function kindProblems(game = {}) {
179
161
  return Object.entries(game?.kinds || {}).flatMap(([name, k]) => [
180
- ...(CONTENT_FILES[name] || name === 'startItems' ? [`kind "${name}" is an engine content file name: pick another name (engine files: ${Object.keys(CONTENT_FILES).join(', ')})`] : []),
162
+ ...(sectionDocs[name] ? [`kind "${name}" is an engine content file name: pick another name (engine files: ${Object.keys(sectionDocs).join(', ')})`] : []),
181
163
  ...(k?.load !== undefined && typeof k.load !== 'function' ? [`kind "${name}": load must be a function (e, data) => …, or left out when the game imports the file itself`] : []),
182
164
  ]);
183
165
  }
@@ -197,7 +179,7 @@ export function describeCond(c, vocab = CONDITIONS) {
197
179
  return list(c).map(x => say(vocab, x).join(S.and)).join(S.and);
198
180
  }
199
181
  /** Describe an effect as one human-readable sentence (for the map); vocab defaults to the engine vocabulary */
200
- export function describeEffect(a, vocab = EFFECTS) {
182
+ export function describeEffect(a, vocab = ALL_EFFECTS) {
201
183
  if (!a) return '';
202
184
  if (typeof a === 'function') return S.fn;
203
185
  return list(a).map(x => say(vocab, x).join(S.then)).join(S.then);
@@ -21,12 +21,13 @@
21
21
  // A placement may override only rot / scale / y / items and the state fields; a different look or behaviour is a different template.
22
22
  // Recipe: docs/recipes/30-templates.md.
23
23
  // body: { shape: 'box' | 'ball' | 'hull', mass?, friction?, restitution?, damping?, angularDamping? } makes each copy a rigid body (needs rigid()):
24
- // it can be pushed, the model moves itself and its position is copied back to the record, so a pushed crate's place is saved like any other change.
24
+ // it can be pushed, the model moves itself and its position is copied back to the record, so a pushed crate's place is saved like any other change,
25
+ // and its whole state (turn, speed, asleep) with it in the save part 'rigid'. A copy nothing moved stays out of the save.
25
26
  // Ids: an instance with state (state / container / interact / body) should have a written id (ids.js); without one dev warns.
26
27
  import { checkOptions, freezeDef, missingText, fmt, DEV } from '../../core/base/validate.js';
27
28
  import { xzOf } from '../../core/base/math.js';
28
29
  import { placeY } from '../../core/scene/ground.js';
29
- import { buildModel, settle, fits, unbuildModel } from './models.js';
30
+ import { buildModel, settle, fits, fitsShape, unbuildModel, scaleOf } from './models.js';
30
31
  import { srcOf, stateful, templateId } from './ids.js';
31
32
  import { PLACEMENT_FIELDS, collideProblem } from './rules.js';
32
33
  import { fieldsShape } from './fields.js';
@@ -145,8 +146,8 @@ function instanceFields(name, d, p, keys, shape) {
145
146
  const state = Object.keys(d.state ?? {});
146
147
  for (const key of Object.keys(p)) if (DEF_KEYS.includes(key) && !state.includes(key)) throw codedError('content-template', fmt(STRINGS.defKey, { name, key }));
147
148
  checkOptions(`template '${name}' instance`, p, [...keys, ...state]);
148
- // dev: a state value outside the template's fields (range, values, type) fails here, for engine.content.spawn as well as for content
149
- if (DEV) for (const k of state) { const why = p[k] !== undefined && whyBad(shape[k], p[k]); if (why) throw codedError('content-template', `template '${name}' instance: ${k} ${why}`); }
149
+ // a state value outside the template's fields (range, values, type) fails here, for engine.content.spawn as well as for content
150
+ for (const k of state) { const why = p[k] !== undefined && whyBad(shape[k], p[k]); if (why) throw codedError('content-template', `template '${name}' instance: ${k} ${why}`); }
150
151
  if (p.items && !d.container) throw codedError('content-template', fmt(STRINGS.noBox, { name }));
151
152
  const own = structuredClone(d.state ?? {});
152
153
  for (const k of state) if (p[k] !== undefined) own[k] = structuredClone(p[k]);
@@ -169,20 +170,21 @@ function limitContainers(e, st, name) {
169
170
 
170
171
  /** How a template's instances look: shared prototype model, collision, interaction; built near, torn down far (once per template name). */
171
172
  function present(e, api, st, name) {
172
- if (st.templateViews.has(name)) return;
173
- if (e.world.presents(name)) throw codedError('content-template', fmt(STRINGS.taken, { name }));
174
- st.templateViews.add(name);
175
173
  const def = () => st.templates.get(name); // a later load may replace the definition: always read the current one
176
- const body = !!def().body; // a physics body moves the model itself: the record follows the model (positionFrom 'view'), so a pushed position is saved
177
- st.track(e.world.present(name, { // tracked: without content there is no definition to build from, and a new content() must be able to present the kind
174
+ const body = !!def().body, was = st.templateViews.get(name); // a physics body moves the model itself: the record follows the model (positionFrom 'view'), so a pushed position is saved
175
+ if (was?.body === body) return;
176
+ was?.remove(); // a reload that adds or takes out `body`: who places the model changes, and world reads that once per presenter. Every copy rebuilds, from the record
177
+ if (e.world.presents(name)) throw codedError('content-template', fmt(STRINGS.taken, { name }));
178
+ st.templateViews.set(name, st.track(e.world.present(name, { // tracked: without content there is no definition to build from, and a new content() must be able to present the kind
178
179
  radius: () => Math.max(e.world.radius, e.stream.activeRadius), // same build distance as props
179
180
  positionFrom: body ? 'view' : 'record',
180
181
  async build(rec) {
181
- const d = def(), model = modelOf(d, rec), id = rec.id;
182
+ const d = def(), model = modelOf(d, rec), id = rec.id, mine = e.world.building(id);
182
183
  const o = await buildModel(e, api, rec, model, d.body ? { ...d, static: false, collide: false } : d, stageScale(d, rec));
183
184
  o.userData.model = JSON.stringify(model); // the built model, as text (describe / tests read it); serialized once per build, never per frame
184
185
  o.userData.modelFrom = modelSource(d, rec); // update compares this cheap key every frame: a stage with another model rebuilds the copy
185
- if (d.body) addBody(e, rec, o, d.body);
186
+ if (d.body && e.world.building(id) === mine) addBody(e, rec, o, d); // a build a load or rebuild replaced meanwhile is dropped: its body would take the id, and the saved state, from the real one
187
+ o.userData.useFrom = e.interactions;
186
188
  if (d.interact && e.interactions) o.userData.use = e.interactions.add(o, {
187
189
  id, radius: d.interact.radius ?? 2.5, height: d.interact.height, action: d.interact.action,
188
190
  label: () => label(e, def().interact?.label, e.world.get(id)) ?? name,
@@ -195,40 +197,70 @@ function present(e, api, st, name) {
195
197
  const d = def();
196
198
  // a stage that names another model: tear this copy down, world builds the new one next frame (the record, and so the save, is untouched)
197
199
  if (d.stages && !sameModel(o.userData, d, rec)) { e.world.rebuild(rec.id); return; }
200
+ if (d.interact && o.userData.useFrom !== e.interactions) { e.world.rebuild(rec.id); return; } // its use lives in the interactions module it was built with: another one starts empty
198
201
  const mul = stageScale(d, rec);
199
- if (!d.body && !fits(o, rec, mul)) settle(e, rec, o, d, mul); // a body places itself; a stage scale re-aligns collision too
200
- else if (d.body) restBody(e, rec, o);
202
+ if (d.body) { // a body places itself. Its turn and size were built into the solver: a new one needs a new body, built where the record stands
203
+ if (!fitsShape(o, rec, mul) || !sameBody(e, o.userData, d)) { e.world.rebuild(rec.id); return; }
204
+ restBody(e, rec, o);
205
+ } else if (!fits(e, o, rec, mul)) settle(e, rec, o, d, mul); // a stage scale re-aligns collision too
201
206
  d.animate?.(rec, o, dt);
202
207
  },
203
208
  dispose(rec, o) { o.userData.use?.remove(); o.userData.body?.remove(); unbuildModel(e, o); },
204
- }));
209
+ })));
210
+ st.templateViews.get(name).body = body;
205
211
  }
206
212
 
213
+ const SETTLE = 0.05; // meters: a body that only settled (contact with uneven ground) moves less than this; a push moves it more
207
214
  /**
208
- * A rigid body for one built copy, never batched (it moves). It rests on the ground at the record's place: the collider is centred on the model's origin,
209
- * so the copy is lifted by half its height, and that resting place counts as the authored one (world.rest), so an untouched crate stays out of the save.
210
- * The body starts asleep: it stays exactly there until something hits it; then its moves are copied to the record (positionFrom 'view') and saved.
215
+ * A rigid body for one built copy, never batched (it moves). The body owns the pose and the record follows it (positionFrom 'view'), so one thing decides a copy's place:
216
+ * - A copy still where content put it stands on the ground: the collider is centred on the model's origin, so it is lifted by half its height, and that place counts
217
+ * as the authored one (world.rest). It starts asleep and atRest, which keeps it out of the save: content rebuilds it.
218
+ * - A copy with state in the save (the 'rigid' part, keyed by record id): that state is the pose, speed and sleep, and the record takes it, since no step runs before the next read.
219
+ * - A copy moved with no state (rebuilt by a new holder, a save without it, or a record moved after that state: rigid drops it): it starts awake at the record, so one left in the air comes down.
211
220
  */
212
- function addBody(e, rec, o, b) {
213
- const { shape, ...opts } = b, s = o.userData.proto.size, scale = rec.scale ?? 1;
214
- o.userData.batch = false;
215
- const ground = e.surface(rec.position.x, rec.position.z, rec.floor), y = Math.max(rec.position.y, ground + s.y * scale / 2);
216
- e.world.rest(rec.id, { x: rec.position.x, y, z: rec.position.z });
217
- o.position.y = rec.position.y;
221
+ function addBody(e, rec, o, d) {
222
+ const { shape, ...opts } = d.body, s = o.userData.proto.size, ud = o.userData, p = rec.position;
223
+ ud.batch = false; ud.bodyFrom = d.body; ud.holder = bodyHolder(e);
224
+ const half = s.y * scaleOf(rec)[1] / 2, floor = e.surface(p.x, p.z, rec.floor) + half;
225
+ // a state from the save decides this copy's place, even when the record reads as unmoved (put back by an undo): resting it would rewrite the baseline to a place it is not at
226
+ const unmoved = !e.rigid?.stateFor?.(rec.id) && e.world.rest(rec.id, { x: p.x, y: rec.ground === false ? Math.max(p.y, floor) : floor, z: p.z });
227
+ o.position.y = p.y;
218
228
  o.updateMatrixWorld(true);
229
+ if (!ud.holder) return; // the copy stands as a plain model; sameBody builds its body when a holder is ready
219
230
  const add = shape === 'ball' ? 'addBall' : shape === 'hull' && o.isMesh ? 'addHull' : 'addBox'; // a hull needs one mesh; a group gets a box
220
- o.userData.body = e.rigid[add](o, opts);
221
- o.userData.body?.body.sleep();
231
+ const b = ud.body = ud.holder[add](o, { ...opts, id: rec.id });
232
+ if (!b) return;
233
+ // a place written with no height (thing.set [x, 0, z]) means on the ground: a body put inside it goes through a thin floor and falls for good
234
+ b.place = at => { const y = e.surface(at.x, at.z, rec.floor) + half; return at.y < y - SETTLE ? { x: at.x, y, z: at.z } : at; };
235
+ if (b.atRest === false) { const t = b.body.translation(); p.x = t.x; p.y = t.y; p.z = t.z; return; }
236
+ b.atRest = true;
237
+ if (unmoved) b.body.sleep();
238
+ else { const at = b.place(p); if (at !== p) { p.y = at.y; ud.holder.setPosition(b, at); } }
222
239
  }
223
- const SETTLE = 0.05; // meters: a body that only settled (contact with uneven ground) moves less than this; a push moves it more
224
- /** While an authored body only settles where content put it, that settled pose is its authored rest (it stays out of the save); once pushed, the record keeps the change */
240
+ /** Who can hold a body now: a rigid still loading its solver is not one yet, so a copy built meanwhile waits instead of throwing */
241
+ const bodyHolder = e => e.rigid?.ready ? e.rigid : null;
242
+ /**
243
+ * Does the copy carry what the template asks for now, in the holder installed now? A body is a handle into one solver: another holder has none of it, and a hot reload
244
+ * that changes `body` cannot reach a built one. Same definition is a yes without serializing; a reloaded equal one is adopted, as sameModel does.
245
+ */
246
+ function sameBody(e, ud, d) {
247
+ if (ud.holder !== bodyHolder(e)) return false;
248
+ if (ud.bodyFrom === d.body) return true;
249
+ if (JSON.stringify(ud.bodyFrom) !== JSON.stringify(d.body)) return false;
250
+ ud.bodyFrom = d.body;
251
+ return true;
252
+ }
253
+ /**
254
+ * While a body only settles where content put it, the settled pose is its authored rest and it stays out of the save. Settling ends when it first sleeps:
255
+ * from then on anything that wakes it is play, however small the move, and the body's state goes in the save, so nothing a player did is lost to a tolerance.
256
+ */
225
257
  function restBody(e, rec, o) {
226
- const ud = o.userData, b = ud.body?.body;
227
- if (ud.pushed || !b) return;
258
+ const ud = o.userData, entry = ud.body;
259
+ if (!entry?.atRest) return;
228
260
  ud.restAt ??= { ...rec.position };
229
- const p = rec.position, r = ud.restAt;
230
- if (Math.abs(p.x - r.x) > SETTLE || Math.abs(p.y - r.y) > SETTLE || Math.abs(p.z - r.z) > SETTLE) { ud.pushed = true; return; }
231
- if (b.isSleeping()) e.world.rest(rec.id, p, SETTLE);
261
+ const p = rec.position, r = ud.restAt, asleep = entry.body.isSleeping();
262
+ if ((ud.settled && !asleep) || Math.abs(p.x - r.x) > SETTLE || Math.abs(p.y - r.y) > SETTLE || Math.abs(p.z - r.z) > SETTLE) { entry.atRest = false; return; }
263
+ if (asleep) { e.world.rest(rec.id, p, SETTLE); ud.settled = true; }
232
264
  }
233
265
 
234
266
  /**
@@ -258,7 +290,6 @@ const stageScale = (d, rec) => d.stages?.[rec.stage ?? 0]?.scale ?? 1;
258
290
  */
259
291
  function simulate(e, st, name) {
260
292
  if (st.templateSims.has(name)) return;
261
- st.templateSims.add(name);
262
293
  const grow = rec => {
263
294
  const d = st.templates.get(name);
264
295
  if (!d?.stages) return;
@@ -267,10 +298,10 @@ function simulate(e, st, name) {
267
298
  e.world.set(rec.id, next); // through world.set: world:change fires and the save keeps it, like any other gameplay change
268
299
  e.events.emit('template:stage', { id: rec.id, template: name, stage: next.stage, name: d.stages[next.stage].name });
269
300
  };
270
- st.track(e.world.simulate(name, {
301
+ st.templateSims.set(name, st.track(e.world.simulate(name, {
271
302
  near: (rec, dt) => { grow(rec); st.templates.get(name)?.update?.(rec, dt, e); },
272
303
  far: rec => grow(rec),
273
- }));
304
+ })));
274
305
  }
275
306
 
276
307
  const label = (e, l, rec) => typeof l === 'function' ? l(rec, e) : l && e.i18n.has(l) ? e.t(l) : l;
@@ -1,7 +1,9 @@
1
1
  // Running condition and effect words: content.test and content.run. The vocabulary is rules.js, the built-in meanings are in loader.js.
2
- import { warnMissing } from '../../core/base/validate.js';
2
+ import { warnMissing, warnOnce } from '../../core/base/validate.js';
3
+ import { coded } from '../../core/base/errorHints.js';
3
4
  import { parseClock } from '../../core/time/dayTime.js';
4
5
  import { list } from '../../core/base/util.js';
6
+ import { failure, isRunFailure } from '../../core/ops/opsFail.js';
5
7
 
6
8
  /** Convert content notation to runtime values by ref (clock time -> fraction, place -> { x, z }) */
7
9
  const norm = (e, api, ref, v) => ref === 'clock' ? parseClock(v, e.calendar?.hoursPerDay ?? 24) : ref === 'position' ? api.where(typeof v === 'string' ? { place: v } : v) : v;
@@ -18,17 +20,28 @@ export function testWords(e, api, conds, c, actor) {
18
20
  }));
19
21
  }
20
22
 
21
- /** content.run */
23
+ /**
24
+ * content.run. The answer goes up, in the shape ops use: { ok: true }, or a failure whose facts.failed lists each word that failed [{ word, code, facts }], so an op or a
25
+ * reward that returns it fails with it. The caller decides what that means; the event is for what has no caller above it (a dialogue do, a trigger)
26
+ */
22
27
  export function runWords(e, api, effects, a, actor) {
23
- if (!a) return;
28
+ if (!a) return { ok: true };
24
29
  const ctx = { actor };
25
30
  if (typeof a === 'function') return a(e, ctx);
26
31
  // One failing effect must not drop the ones after it (a reward with give + spawn would be half given): run them all, then rethrow the first error
27
- let first = null, failed = 0;
32
+ let first = null, threw = 0;
33
+ const failed = [];
28
34
  for (const x of list(a)) for (const [k, v] of Object.entries(x)) {
29
35
  const d = effects.get(k);
30
36
  if (!d) { warnMissing('effect', k, [...effects.keys()]); continue; }
31
- try { d.run(e, d.raw ? v : norm(e, api, d.ref, v), v, ctx); } catch (err) { first ??= err; failed++; }
37
+ try { const r = d.run(e, d.raw ? v : norm(e, api, d.ref, v), v, ctx); if (isRunFailure(r)) failed.push({ word: k, code: r.code, facts: r.facts }); } catch (err) { first ??= err; threw++; }
32
38
  }
33
- if (first) { if (failed > 1) first.message += ` (${failed} effects failed; the others ran)`; throw first; }
39
+ const answer = failed.length ? failure({ code: failed[0].code, facts: { failed } }) : { ok: true };
40
+ if (failed.length) {
41
+ warnOnce(coded('content-misuse', `content: effect { ${failed[0].word} } failed with '${answer.code}'. Listen to content:failed, or read what content.run returns`));
42
+ e.events.emit('content:failed', { code: answer.code, failed, actor: actor ?? null });
43
+ }
44
+ // a word that threw is a bug and goes on as a throw; the answers of the words beside it ride along, so a reward's debt survives it
45
+ if (first) { if (threw > 1) first.message += ` (${threw} effects failed; the others ran)`; first.answer = answer; throw first; }
46
+ return answer;
34
47
  }
@@ -79,7 +79,7 @@ export class DebugPanel {
79
79
  ws.innerHTML = Object.keys(e.weather.types).map(k => `<option value="${esc(k)}">${esc(e.weather.label(k))}</option>`).join('') + `<option value="auto">${esc(e.weather.label('auto'))}</option>`;
80
80
  ws.value = e.weather.name;
81
81
  }
82
- ws.onchange = () => { if (ws.value === 'auto') e.weather.setAuto(true); else { e.weather.setAuto(false); e.weather.set(ws.value, { seconds: 8 }); } };
82
+ ws.onchange = () => { if (ws.value === 'auto') e.weather.auto = true; else { e.weather.auto = false; e.weather.set(ws.value, { seconds: 8 }); } };
83
83
  engine.i18n.add({ 'zh-CN': { 'debug.toggle': '调试面板' }, en: { 'debug.toggle': 'Debug panel' } }); // the settings menu's rebind page shows this name
84
84
  }
85
85
 
@@ -126,7 +126,7 @@ export function debug(opts = {}) {
126
126
  readParams('debugPanel', DEBUG_PANEL_PARAMS, opts);
127
127
  let d = null; const prof = { n: 0, t: 0, cpu: 0 };
128
128
  return {
129
- name: 'debugPanel', type: 'ui', params: DEBUG_PANEL_PARAMS, options: opts, label: 'Debug panel', optional: ['calendar', 'weather', 'terrain'],
129
+ name: 'debugPanel', skipKind: 'none', type: 'ui', params: DEBUG_PANEL_PARAMS, options: opts, label: 'Debug panel', optional: ['calendar', 'weather', 'terrain'],
130
130
  install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.debugPanel': '调试面板' }, en: { 'module.debugPanel': 'debug panel' } });
131
131
  d = new DebugPanel(e, opts); e.debug.panel = d;
132
132
  // the toggle action has no key of its own (presets.bindings.debug binds F3); optional: the panel works by code (panel.el.hidden) too
@@ -146,3 +146,5 @@ export function debug(opts = {}) {
146
146
  },
147
147
  };
148
148
  }
149
+
150
+ export const handRolled = 'none: a dev overlay is ordinary DOM with no shape of its own';