threedog 0.8.0 → 1.0.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 (372) hide show
  1. package/CHANGELOG.md +219 -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
@@ -61,7 +61,10 @@ export class World {
61
61
  set anchor(a) {
62
62
  const ok = a == null || a.isObject3D || (Array.isArray(a) ? a.length === 3 && a.every(Number.isFinite) : Number.isFinite(a.x) && Number.isFinite(a.z));
63
63
  if (!ok) throw codedError('world-option', fmt(STRINGS.anchor, { got: JSON.stringify(a) }));
64
+ const boot = this._anchor, S = this.engine.session;
64
65
  this._anchor = a ?? null;
66
+ // not saved (it may be an Object3D): set during play, it ends with the playthrough and what boot left comes back. Tracked, so a failed load keeps it
67
+ if (S.captured && !this._anchorEnd) this._anchorEnd = S.track({ remove: () => { this._anchor = boot; this._anchorEnd = null; } });
65
68
  }
66
69
 
67
70
  /**
@@ -122,7 +125,9 @@ export class World {
122
125
  set(id, patch) { checkTypeRule(this.engine, 'world.write', `set world record ${id}`); return setRecord(this, id, patch); }
123
126
  /**
124
127
  * Move a record (no event; use it in simulate for things that move every step); still saved (saves diff against content).
125
- * The model of a positionFrom 'record' (default) record follows this frame; to do something else with the position in presentation, compare in update
128
+ * The model of a positionFrom 'record' (default) record follows this frame; to do something else with the position in presentation, compare in update.
129
+ * On a live character (the player, an NPC with a model) this is its placeAt: the character owns its position, so it goes there and the record says where it stands.
130
+ * A seated rider gets out to go there (placeAt ends a ride); a write equal to where it sits only follows the seat
126
131
  * @example engine.world.move(rec.id, { x: rec.position.x + 1, z: rec.position.z })
127
132
  * @param {string} id
128
133
  * @param {any} position Vector3 / object / [x, y, z] / { x, z } (y stays unchanged if omitted)
@@ -130,10 +135,18 @@ export class World {
130
135
  */
131
136
  move(id, position) {
132
137
  DEV && this.engine.ops.guard('world.move');
133
- const rec = this._need(id, 'move');
134
- putPos(`world.move("${id}")`, position, rec.position);
138
+ const rec = this._need(id, 'move'), live = this._character(rec), to = live ? { ...live.root.position } : rec.position;
139
+ putPos(`world.move("${id}")`, position, to);
140
+ if (live) { // design.md section 9: the character is the authority. A write that agrees with it is the record following (Character._store, npcSim); any other is a placement
141
+ const p = live.root.position;
142
+ if (p.x !== to.x || p.y !== to.y || p.z !== to.z) live.placeRecord(to);
143
+ rec.position.x = p.x; rec.position.y = p.y; rec.position.z = p.z;
144
+ }
145
+ this._v.placed(rec);
135
146
  this._index(rec);
136
147
  }
148
+ /** @internal The character that owns this record's pose, or null. A far record rules its own model, except a rider's: the seat would take the write back as it comes near */
149
+ _character(rec) { const ch = this.engine.control?.characterOf(rec.id); return ch && (ch.vehicle || !this._s.recordRules(rec)) ? ch : null; }
137
150
  /**
138
151
  * Remove a record (its model is torn down too) and emit the world:remove event. Does nothing if the id does not exist. Removing an initial record is saved,
139
152
  * so it stays gone after loading
@@ -172,7 +185,7 @@ export class World {
172
185
  * radius: meters, or a function (for distances that change, like terrain view distance); defaults to world.radius. Registering the same kind again: old
173
186
  * models are torn down with the old dispose and rebuilt with the new one.
174
187
  * positionFrom: 'record' (default, the model follows the record every frame) or 'view' (the model moves itself, e.g. driven by a character mover; model
175
- * position is copied back to the record at the end of each fixed step).
188
+ * position is copied back to the record at the end of each fixed step, and a write to the record moves the model and a rigid body on it).
176
189
  * @example engine.world.present('chest', { build: rec => new THREE.Mesh(boxGeo, new THREE.MeshStandardMaterial()), dispose: (rec, obj) => engine.remove(obj), show: rec
177
190
  * => !rec.looted })
178
191
  * @param {string} kind
@@ -214,8 +227,8 @@ export class World {
214
227
  * far → near step, far runs first to pay back the owed time.
215
228
  * With only far (crops), near also advances via far; with only near, far records are not simulated and owed time is not made up.
216
229
  * Both dt are accumulated real (fixed-step) seconds (not multiplied by clock.rate). For things measured in game clock (grows over days) store engine.clock.now
217
- * and compare. channel: a time channel name (or rec => name) the kind lives on; then both dt are multiplied by that channel's speed (and the record's
218
- * engine.time.local stack), so bullet time on 'enemies' slows near and far records alike (NPCs use it with their own channel).
230
+ * and compare. channel: a time channel name (or rec => name) the kind lives on; then both dt are the channel time the record lived through (its
231
+ * engine.time.local stack too), whatever the speed when far settles, so bullet time on 'enemies' slows near and far records alike (NPCs use it with their own channel).
219
232
  * radius defaults to the present radius ('view' widened by 1.25), or world.radius without present; may also be a function.
220
233
  * fullRadius + nearEvery (tiers, for crowds): records within fullRadius m (number or function) run near every step; the rest of the near zone runs near
221
234
  * once every nearEvery seconds, dt being the seconds since its last turn (deterministic: turns go by hashed id and step count, saved).
@@ -237,7 +250,7 @@ export class World {
237
250
  * @returns {{ remove(): void }}
238
251
  * @experimental
239
252
  */
240
- pauseSimulation() { const s = this._s; s.fixed = () => {}; return { remove: () => { delete s.fixed; } }; }
253
+ pauseSimulation() { const s = this._s; s.fixed = () => {}; return { remove: () => { delete s.fixed; for (const e of s.ents.values()) e.ch = e.mark = undefined; } }; } // channels kept moving: no stretch of the pause is owed
241
254
  /** Number of fixed steps simulated @experimental */ get steps() { return this._s.n; }
242
255
  }
243
256
 
@@ -1,4 +1,4 @@
1
- // World's contribution to thing.explain() (core/scene/thingExplain.js): the record's fields as `state`, and the record's own collision / picking rules.
1
+ // World's contribution to engine.explain({ thing }) (core/scene/thingExplain.js): the record's fields as `state`, and the record's own collision / picking rules.
2
2
  // Template rules come from the content module's explainer (content/explain.js), which runs after this and overrides these.
3
3
 
4
4
  /** @internal Fill state and rules for a thing that has a world record */
@@ -39,15 +39,20 @@ export function world(opts = {}) {
39
39
  readParams('world', WORLD_PARAMS, opts);
40
40
  let w = null;
41
41
  return {
42
- name: 'world', type: 'world', provides: ['world'], label: 'World data', params: WORLD_PARAMS, options: opts, stage: 'ground',
42
+ name: 'world', skipKind: 'approx', type: 'world', provides: ['world'], label: 'World data', params: WORLD_PARAMS, options: opts, stage: 'ground',
43
43
  install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.world': '世界数据' }, en: { 'module.world': 'world data' } });
44
44
  w = new World(e, opts);
45
+ const followed = e.stream.player.pos;
45
46
  e.stream.player.at(() => w.center); // the default stream source sits where gameplay is simulated (world.anchor, else the player)
46
- e.stream.addReadyCheck('world', s => s.detail !== 'full' || w.ready);
47
- e.saves.register('world', { atomic: true, version: 5, migrate: WORLD_MIGRATE, save: () => w.toJSON(), load: d => w.fromJSON(d), checkNewGame: codePlaced });
48
- e._things.addSource(recordSource(w)); // engine.thing / thing.set / the shared id space reach the records through this
49
- e.explainWith(worldExplain);
50
- e.budget.metric('worldRecords', () => w.records.size);
47
+ ctx.track({ remove: () => e.stream.player.at(followed) }); // no closure over this world stays behind
48
+ ctx.stream.addReadyCheck('world', s => s.detail !== 'full' || w.ready);
49
+ // after the modules, not in world's own step: physics writes the models at stage late, and a record must end the step on the solver's result, a save included
50
+ ctx.track(e.onFixed(() => w._v.pull(), { phase: 'late' }));
51
+ ctx.track(e.time.onMove(() => w._s.moved()));
52
+ ctx.saves.register('world', { atomic: true, version: 5, migrate: WORLD_MIGRATE, save: () => w.toJSON(), load: d => w.fromJSON(d), checkNewGame: codePlaced });
53
+ ctx.things.addSource(recordSource(w)); // engine.thing / thing.set / the shared id space reach the records through this
54
+ ctx.things.explainWith(worldExplain);
55
+ ctx.budget.metric('worldRecords', () => w.records.size);
51
56
  if (DEV) { // orphans are known once content loaded (engine:ready), after a load, and per level for `<level>/<node>` ids
52
57
  const warn = () => {
53
58
  targets();
@@ -89,3 +94,5 @@ export function world(opts = {}) {
89
94
  dispose() { w.dispose(); },
90
95
  };
91
96
  }
97
+
98
+ export const handRolled = 'none: far records by hand are ordinary objects in ordinary lists';
@@ -9,7 +9,8 @@
9
9
  // Changes are found by comparing JSON against the original content, not by events: fields changed directly inside simulate are saved too.
10
10
  // Save format (part 'world', version 5): every record is keyed by its stable id, and only what play changed is stored:
11
11
  // { seq, step, time, records: { id: whole runtime record without id }, changed: { id: { set?: changed fields, del?: [removed fields] } },
12
- // removed: [ids of removed initial records], owed: { id: simulation seconds owed, only for kinds simulated with far } }
12
+ // removed: [ids of removed initial records], owed: { id: simulation seconds owed, only for kinds simulated with far },
13
+ // marks: { id: the channel reading its debt counts from, signed, only for kinds on a time channel; a save without them still loads (sim.js) } }
13
14
  // Version 1 kept records as an array: migrate step 1 (WORLD_MIGRATE) turns it into the id-keyed object.
14
15
  // Version 2 numbered runtime records `<kind>-<n>`; version 3 uses `<kind>#<n>`, so a runtime id can never equal an authored one (authored ids may not
15
16
  // contain `#`, content/ids.js). Step 2 renames them (legacyRuntimeIds says which), and the containers part follows with the same map (a template
@@ -24,8 +25,8 @@
24
25
  import { legacyRuntimeIds, renameIdKeys, renameIdValues } from '../../core/saves/saveIds.js';
25
26
  import { codedError } from '../../core/base/errorHints.js';
26
27
  import { fmt } from '../../core/base/validate.js';
27
- import { isPlainObject } from '../../core/base/util.js';
28
- import { refuseSave, saveNumberOk, SAVE_MAX } from '../../core/saves/saveValues.js';
28
+ import { isPlainObject, list } from '../../core/base/util.js';
29
+ import { refuseSave, checkSaveFile, saveNumberOk, SAVE_MAX, SAVE_MAX_SECONDS } from '../../core/base/saveValues.js';
29
30
 
30
31
  const PLAIN_STRINGS = {
31
32
  msg: "saved world data must be plain values (number, string, boolean, array, plain object): {path} is {what}. A model: world.present('crate', { build: rec => mesh }), then world.view(id) gets it; logic: world.simulate(); not saved: world.add(rec, { save: false })",
@@ -134,10 +135,10 @@ export function saveWorld(w) {
134
135
  // with the game half-loaded. Refusing throws: saves.apply rolls the whole load back and reports this message (save-bad-record).
135
136
  const SHAPE_STRINGS = {
136
137
  obj: 'must be a plain object', kind: 'must have kind (a string)', pos: `must be { x, y, z } with finite numbers within ±${SAVE_MAX}`,
137
- arr: 'must be an array of record ids', motion: 'must be a plain object (the character motion state) or null', nav: 'must be a plain object (the NPC path state)', path: 'must be null or a list of { x, z } with finite numbers', num: 'must be a finite number within ±{max}', count: 'must be a finite number >= 0',
138
+ arr: 'must be an array of record ids', motion: 'must be a plain object (the character motion state) or null', nav: 'must be a plain object (the NPC path state)', path: 'must be null or a list of { x, z } with finite numbers', link: 'must be null or a link leg with an id and both ends', num: 'must be a finite number within ±{max}', count: 'must be a finite number >= 0', base: 'must be a finite number',
138
139
  };
139
140
  /** Throw save-bad-record for the first malformed core field of a world save (fields of the game's own are not checked); kindOf(id) is the kind of an authored record @internal */
140
- function checkWorldSave(d, kindOf) {
141
+ function checkWorldSave(d, kindOf, assets) {
141
142
  const bad = (path, why, got) => refuseSave('world', path, why, got);
142
143
  const pos = (path, p) => { if (!isPlainObject(p) || !['x', 'y', 'z'].every(k => saveNumberOk(p[k]))) bad(path, SHAPE_STRINGS.pos, p); };
143
144
  const num = (path, v) => { if (v !== undefined && !(Number.isFinite(v) && v >= 0)) bad(path, SHAPE_STRINGS.count, v); };
@@ -145,20 +146,32 @@ function checkWorldSave(d, kindOf) {
145
146
  // and its numbers feed the mover: a wrong one comes back a step later as a NaN position. The player holds them on the record itself
146
147
  const speeds = (path, o) => { for (const k of ['vx', 'vy', 'vz', 'facing', 'amount']) if (o[k] != null && !saveNumberOk(o[k])) bad(`${path}.${k}`, SHAPE_STRINGS.num, o[k]); };
147
148
  const motion = (path, m) => { if (m == null) return; if (!isPlainObject(m)) bad(path, SHAPE_STRINGS.motion, m); speeds(path, m); };
149
+ // a link leg on a path point ({ id, from, to }) or the crossing under way ({ link, from, to, seconds, time }): the mover reads them on every step of a crossing
150
+ const leg = (path, l, id) => { if (!isPlainObject(l) || !['string', 'number'].includes(typeof l[id])) bad(path, SHAPE_STRINGS.link, l); pos(`${path}.from`, l.from); pos(`${path}.to`, l.to); };
148
151
  // rec.nav of an NPC is written in place the same way, and every NPC has one. Another kind's `nav` is the game's own field
149
152
  const nav = (path, v) => {
150
153
  if (!isPlainObject(v)) bad(path, SHAPE_STRINGS.nav, v);
151
154
  if (v.path != null && !(Array.isArray(v.path) && v.path.every(p => isPlainObject(p) && saveNumberOk(p.x) && saveNumberOk(p.z)))) bad(`${path}.path`, SHAPE_STRINGS.path, v.path);
155
+ v.path?.forEach((p, i) => { if (p.link != null) leg(`${path}.path.${i}.link`, p.link, 'id'); });
156
+ if (v.link == null) return;
157
+ leg(`${path}.link`, v.link, 'link');
158
+ for (const k of ['seconds', 'time']) if (!(saveNumberOk(v.link[k]) && v.link[k] >= 0)) bad(`${path}.link.${k}`, SHAPE_STRINGS.count, v.link[k]);
152
159
  };
160
+ // a prop, pickup or NPC builds what its model field says, when it comes near: by then the load is long over, so a URL there stops here
161
+ const model = (path, m) => { const name = list(m)[0]; if (typeof name === 'string') checkSaveFile(assets, 'world', path, name); };
153
162
  if (!isPlainObject(d)) bad('the world part', SHAPE_STRINGS.obj, d);
154
163
  num('seq', d.seq); num('step', d.step); num('time', d.time);
155
- for (const f of ['records', 'changed', 'owed']) if (d[f] !== undefined && !isPlainObject(d[f])) bad(f, SHAPE_STRINGS.obj, d[f]);
164
+ if (d.time > SAVE_MAX_SECONDS) bad('time', SHAPE_STRINGS.count, d.time); // a step no longer moves it: world time stops for good
165
+ // far records take turns in buckets[step % period]: only a whole number lands in one. seq numbers new ids: past safe whole numbers it stops counting and ids repeat
166
+ for (const k of ['step', 'seq']) if (d[k] !== undefined && !Number.isSafeInteger(d[k])) bad(k, SHAPE_STRINGS.count, d[k]);
167
+ for (const f of ['records', 'changed', 'owed', 'marks']) if (d[f] !== undefined && !isPlainObject(d[f])) bad(f, SHAPE_STRINGS.obj, d[f]);
156
168
  if (d.removed !== undefined && !(Array.isArray(d.removed) && d.removed.every(id => typeof id === 'string'))) bad('removed', SHAPE_STRINGS.arr, d.removed);
157
169
  for (const [id, r] of Object.entries(d.records ?? {})) {
158
170
  if (!isPlainObject(r)) bad(`records.${id}`, SHAPE_STRINGS.obj, r);
159
171
  if (typeof r.kind !== 'string') bad(`records.${id}`, SHAPE_STRINGS.kind, r.kind);
160
172
  pos(`records.${id}.position`, r.position); // world.add gives every record one, and the cell index reads it
161
173
  motion(`records.${id}.motion`, r.motion);
174
+ model(`records.${id}.model`, r.model);
162
175
  if (r.kind === 'npc') nav(`records.${id}.nav`, r.nav);
163
176
  if (r.kind === 'player') speeds(`records.${id}`, r);
164
177
  }
@@ -166,7 +179,7 @@ function checkWorldSave(d, kindOf) {
166
179
  if (!isPlainObject(c) || (c.set !== undefined && !isPlainObject(c.set)) || (c.del !== undefined && !Array.isArray(c.del))) bad(`changed.${id}`, SHAPE_STRINGS.obj, c);
167
180
  if (c.set && 'position' in c.set) pos(`changed.${id}.set.position`, c.set.position);
168
181
  if (c.del?.includes('position')) pos(`changed.${id}.del`, undefined);
169
- if (c.set) motion(`changed.${id}.set.motion`, c.set.motion);
182
+ if (c.set) { motion(`changed.${id}.set.motion`, c.set.motion); model(`changed.${id}.set.model`, c.set.model); }
170
183
  if (c.set && 'kind' in c.set && typeof c.set.kind !== 'string') bad(`changed.${id}.set`, SHAPE_STRINGS.kind, c.set.kind);
171
184
  // shortcut: an NPC whose content loads after the save is not known here, so its changed nav goes unchecked; move the check to where a pending change is applied if a fuzz run reaches it
172
185
  if ((c.set?.kind ?? kindOf(id)) === 'npc') {
@@ -175,11 +188,13 @@ function checkWorldSave(d, kindOf) {
175
188
  }
176
189
  }
177
190
  for (const [id, v] of Object.entries(d.owed ?? {})) num(`owed.${id}`, v);
191
+ // a mark is a base, not a count: a record faster than its channel (time.local above 1) moves it below zero, and it can pass any fixed range the same way
192
+ for (const [id, v] of Object.entries(d.marks ?? {})) if (!Number.isFinite(v)) bad(`marks.${id}`, SHAPE_STRINGS.base, v);
178
193
  }
179
194
 
180
195
  /** Load: replace runtime records wholesale; loaded initial records go back to the original then get the save's changes; unloaded content waits for its add. Independent of the order of content.load @internal */
181
196
  export function loadWorld(w, d) {
182
- checkWorldSave(d, id => w._base.get(id)?.kind); // before anything is cleared: a refused save leaves the world as it was (the rollback then has nothing to undo here)
197
+ checkWorldSave(d, id => w._base.get(id)?.kind, w.engine.assets); // before anything is cleared: a refused save leaves the world as it was (the rollback then has nothing to undo here)
183
198
  w._v.clear();
184
199
  w.records.clear(); w._cells.clear(); w._unsaved.clear();
185
200
  for (const id of [...w._origin.keys()]) if (!w._base.has(id)) w._origin.delete(id); // runtime records come from the save now (no op to name)
@@ -1,6 +1,6 @@
1
1
  // Position read / write for world: shared by add / move / query. A wrong position (a Vector3 used as an array, [x, z] with only two numbers) silently becomes NaN and null in the save,
2
- // so dev builds throw on the spot and say how to fix it.
3
- import { DEV, goodPos, fmt } from '../../core/base/validate.js';
2
+ // so every build throws on the spot and says how to fix it: a NaN worked out during play reaches a release build too.
3
+ import { goodPos, fmt } from '../../core/base/validate.js';
4
4
  import { badPosition } from '../../core/base/math.js';
5
5
 
6
6
  const STRINGS = {
@@ -11,10 +11,10 @@ const STRINGS = {
11
11
  /** Write position v (Vector3 / object / [x, y, z] / { x, z }) into p; y stays unchanged if omitted @internal */
12
12
  export function putPos(fn, v, p) {
13
13
  const arr = Array.isArray(v), o = v.isObject3D ? v.position : v;
14
- if (DEV && arr && v.length !== 3) throw badPosition(fmt(STRINGS.arr, { fn }), v);
14
+ if (arr && v.length !== 3) throw badPosition(fmt(STRINGS.arr, { fn }), v);
15
15
  const x = arr ? v[0] : o.x, y = arr ? v[1] : o.y ?? p.y, z = arr ? v[2] : o.z;
16
16
  // check before writing: a bad position leaves no half-written NaN in the data
17
- if (DEV && !goodPos([x, y, z])) throw badPosition(fmt(STRINGS.nan, { fn, got: JSON.stringify(v) }), v);
17
+ if (!goodPos([x, y, z])) throw badPosition(fmt(STRINGS.nan, { fn, got: JSON.stringify(v) }), v);
18
18
  p.x = x; p.y = y; p.z = z;
19
19
  }
20
20
  /** Query center: objects use position, arrays are [x, y, z], others (Vector3 / { x, z }) are used as is, no allocation @internal */
@@ -50,20 +50,22 @@ export function addRecord(w, def, opts) {
50
50
  * shortcut: a physics body keeps its own place (positionFrom 'view') until the page reloads; teach restBody to teleport if an editor moves such a place live.
51
51
  */
52
52
  function repose(w, have, base, rec) {
53
- const pose = r => `${r.position.x},${r.position.z},${r.rot}`;
53
+ const pose = r => `${r.position.x},${r.position.z},${r.rot}`, sameRot = (a, b) => JSON.stringify(a) === JSON.stringify(b); // rot may be [x, y, z], and the baseline holds its own copy
54
54
  if (pose(base) === pose(rec)) return;
55
55
  if (have?.position.x === base.position.x && have.position.z === base.position.z) { Object.assign(have.position, rec.position); w._index(have); }
56
- if (have && have.rot === base.rot) { if (rec.rot === undefined) delete have.rot; else have.rot = rec.rot; }
56
+ if (have && sameRot(have.rot, base.rot)) { if (rec.rot === undefined) delete have.rot; else have.rot = structuredClone(rec.rot); }
57
57
  Object.assign(base.position, rec.position);
58
- if (rec.rot === undefined) delete base.rot; else base.rot = rec.rot;
58
+ if (rec.rot === undefined) delete base.rot; else base.rot = structuredClone(rec.rot);
59
59
  }
60
60
 
61
61
  export function restRecord(w, id, position, tolerance) {
62
- const rec = w.records.get(id), base = w._base.get(id); if (!rec) return;
62
+ const rec = w.records.get(id), base = w._base.get(id); if (!rec) return false;
63
63
  const a = rec.position, b = base?.position;
64
64
  const same = !!b && Math.abs(a.x - b.x) <= tolerance && Math.abs(a.y - b.y) <= tolerance && Math.abs(a.z - b.z) <= tolerance;
65
+ if (!same) return false;
65
66
  putPos(`world.rest("${id}")`, position, rec.position); w._index(rec);
66
- if (same) base.position = { ...rec.position };
67
+ base.position = { ...rec.position };
68
+ return true;
67
69
  }
68
70
 
69
71
  export function orphanIds(w) {
@@ -77,8 +79,12 @@ export function orphanIds(w) {
77
79
  export function setRecord(w, id, patch) {
78
80
  DEV && w.engine.ops.guard('world.set');
79
81
  const rec = w._need(id, 'set');
80
- if (DEV) { if ('id' in patch || 'kind' in patch) throw codedError('world-add', fmt(STRINGS.setKey, { id })); if (mustBePlain(w, w.records.get(id).kind, !w._unsaved.has(id))) checkPlain({ ...patch, position: undefined }, id); }
81
- const { position, ...rest } = patch;
82
+ if ('id' in patch || 'kind' in patch) throw codedError('world-add', fmt(STRINGS.setKey, { id }));
83
+ if (DEV && mustBePlain(w, w.records.get(id).kind, !w._unsaved.has(id))) checkPlain({ ...patch, position: undefined }, id);
84
+ const { position, ...rest } = patch, live = w.engine.control?.characterOf(id);
85
+ // a character owns its rot and scale like its position: told before any field lands, so a refusal writes nothing. Its facing is in its motion: a rot kept here would go stale.
86
+ // Any standing model counts, far too: there is no later build to hand the write to
87
+ if (live) { live.takePose(rest); delete rest.rot; }
82
88
  Object.assign(rec, rest);
83
89
  if (position) w.move(id, position);
84
90
  if (w._v.presenters.get(rec.kind)?.show) w._v.dirty = true;
@@ -2,13 +2,18 @@
2
2
  // (simulate / anchor); this is the implementation.
3
3
  // Time: the dt of both near and far is "accumulated fixed-step seconds" (real seconds, the same ruler as a plain onFixed dt; not multiplied by clock.rate).
4
4
  // simulate(kind, { channel }) puts the kind on a time channel (engine.time): every dt handed to near / far (the owed payback and engine.skip's catch-up too)
5
- // is multiplied by that channel's speed now, times the record's own engine.time.local stack, so bullet time on 'enemies' slows near and far alike.
6
- // channel may be a function of the record (NPCs: each record names its own). The bookkeeping below stays in real seconds; only the handed dt is scaled.
5
+ // is the channel time the record lived through, so bullet time on 'enemies' slows near and far alike.
6
+ // channel may be a function of the record (NPCs: each record names its own; it is read at each settlement, so a change of channel counts from the next one).
7
+ // Why a mark and not "owed seconds x the speed now": a settlement comes late, and the speed at that moment says nothing about the stretch it pays. engine.time
8
+ // already counts each channel, so a record keeps only the channel reading of its last settlement (e.mark); what it owes is the reading now minus the mark. The
9
+ // record's own engine.time.local rate moves its mark as each step passes (accrue). The turn bookkeeping below stays in real seconds.
7
10
  // For one record going near, far, near again, the dts add up to the elapsed time:
8
11
  // far dt = seconds accumulated since the last simulation; on the far → near step, far first pays back the owed time, then near runs.
9
12
  // A kind with only far (crops) does not split near / far and always advances at far's pace; a kind with only near is not simulated while far and its owed time
10
13
  // is not made up.
11
- // Owed time is saved: it is paid back after loading, so simulate code never tracks time itself.
14
+ // Owed time is saved: it is paid back after loading, so simulate code never tracks time itself. A save holds real seconds (owed) and, for a channel kind, the
15
+ // mark: channel readings come back from the same save, so the debt comes back to the bit. A save without marks has only the real seconds: that stretch is
16
+ // read at the speed the record first meets, the one case with no record of the past.
12
17
  // Determinism: near / far is split by the gameplay anchor (world.anchor), far work is capped by count with the rest queued first for the next step, and buckets
13
18
  // follow the step count (saved) —
14
19
  // so the result depends only on data and step count, not on machine speed, frame rate or whether models are built.
@@ -38,14 +43,15 @@ export class Sim {
38
43
  constructor(w) {
39
44
  this.w = w;
40
45
  this.sims = new Map(); // kind → { near, far, farEvery, radius }
41
- this.ents = new Map(); // id → { rec, h, last, near, queued, dead }: last = time of the last simulation, near = step number of the last near simulation
46
+ this.ents = new Map(); // id → { rec, h, last, near, queued, dead, ch, mark }: last = time of the last simulation, near = step number of the last near simulation, ch / mark = the channel debt (top of the file)
42
47
  this.kinds = new Map(); // kind → { set: Set<ent>, P, buckets }: P is the far period (steps), buckets[step % P] is this step's turn
43
- this.owed = new Map(); // from a save, content not added yet: id → time of the last simulation (used when added)
48
+ this.owed = new Map(); // from a save, content not added yet: id → { last, mark } of the last simulation (used when added)
44
49
  this.backlog = []; // far simulations left undone by the previous step's cap (FIFO, done first next step)
45
50
  this.time = 0; // accumulated simulation seconds (saved)
46
51
  this.n = 0; // simulation step count (saved: buckets follow it, so after loading the same batch is up as in a live run)
47
52
  this.at = { x: 0, z: 0 }; // this step's simulation center (taken from world.anchor at the start of each step)
48
53
  this.dt = 0;
54
+ this.ahead = 0; // seconds this.time moved that the channels have not: they move at the end of a step or skip segment, after our hook (see moved)
49
55
  this.list = []; // records inside a near radius this step (reused, not allocated each step)
50
56
  this.order = []; // last step's near list sorted by id: reused when the membership did not change (most steps), so no sort per step
51
57
  this.flights = new FarFlights(this); // far with worker: true (simFar.js)
@@ -64,19 +70,52 @@ export class Sim {
64
70
  }
65
71
  if (s.worker && s.far) this.flights.register(kind, s);
66
72
  this.sims.set(kind, s);
73
+ for (const e of this.kinds.get(kind)?.set ?? []) this.open(e, s);
67
74
  return { remove: () => { if (this.sims.get(kind) === s) this.sims.delete(kind); } };
68
75
  }
69
- /** dt as the kind's near / far gets it: on its time channel when simulate set one (real seconds otherwise) */
70
- scaled(s, rec, dt) {
71
- const ch = s.channel;
72
- return ch == null ? dt : dt * this.w.engine.time.scale(typeof ch === 'function' ? ch(rec) : ch, rec.id);
76
+ /** The channel a record of this kind is on now */
77
+ channelOf(s, rec) { return typeof s.channel === 'function' ? s.channel(rec) : s.channel; }
78
+ /** dt at the speed of this moment: one step about to pass (real seconds on a kind without a channel) */
79
+ scaled(s, rec, dt) { return s.channel == null ? dt : dt * this.w.engine.time.scale(this.channelOf(s, rec), rec.id); }
80
+ /** A channel's seconds as of this.time (see ahead) */
81
+ reading(ch) { const T = this.w.engine.time; return T.now(ch) + this.ahead * T.scale(ch); }
82
+ /** Start a record's debt. What it already owes with no mark (a save without marks, a kind that got its simulate late) is read at the speed now.
83
+ * A channel not defined yet opens at the first settlement, which then names the missing channel */
84
+ open(e, s) {
85
+ if (s.channel == null) return;
86
+ const ch = this.channelOf(s, e.rec);
87
+ if (!this.w.engine.time.channels().includes(ch)) return;
88
+ if (e.ch !== undefined && e.ch !== ch) e.mark = undefined;
89
+ e.mark ??= this.reading(ch) - this.scaled(s, e.rec, this.time - e.last);
90
+ e.ch = ch;
73
91
  }
92
+ /** Close the stretch since the last settlement: the dt far / near gets for it. real = its seconds, the answer for a kind without a channel. Call before e.last moves */
93
+ settle(e, s, real) {
94
+ if (s.channel == null) return real;
95
+ if (e.ch === undefined) { this.open(e, s); if (e.ch === undefined) return this.scaled(s, e.rec, real); }
96
+ const now = this.reading(e.ch), d = Math.max(0, now - e.mark), ch = this.channelOf(s, e.rec);
97
+ e.mark = ch === e.ch ? now : this.reading(ch);
98
+ e.ch = ch;
99
+ return d;
100
+ }
101
+ /** Records with a rate of their own: this stretch's difference from the channel goes on the mark as it passes, since no reading holds it */
102
+ accrue(dt) {
103
+ const T = this.w.engine.time, local = this.w.engine.stacks.get('time.local');
104
+ for (const id of local.ids()) {
105
+ const e = this.ents.get(id), L = local.value(id);
106
+ if (e?.ch !== undefined && L !== 1) e.mark -= dt * T.scale(e.ch) * (L - 1);
107
+ }
108
+ }
109
+ /** The channels caught up with this.time (engine.time.onMove) */
110
+ moved() { this.ahead = 0; }
74
111
  /** A new record starts counting time from the moment it is added (owed time from a save carries on) */
75
112
  added(rec) {
76
- const id = rec.id, o = this.owed.get(id);
113
+ const id = rec.id, o = this.owed.get(id), s = this.sims.get(rec.kind);
77
114
  if (o !== undefined) this.owed.delete(id);
78
- const e = { rec, h: hashOf(id), last: o ?? this.time, near: -1, queued: false, dead: false, flight: null };
115
+ const e = { rec, h: hashOf(id), last: o?.last ?? this.time, near: -1, queued: false, dead: false, flight: null, ch: undefined, mark: o?.mark };
79
116
  this.ents.set(id, e);
117
+ // a save without marks opens at its first settlement: the channels of that save may not be back yet
118
+ if (s && (!o || o.mark !== undefined)) this.open(e, s);
80
119
  let K = this.kinds.get(rec.kind); if (!K) this.kinds.set(rec.kind, K = { set: new Set(), P: 0, buckets: null });
81
120
  K.set.add(e); if (K.P) K.buckets[e.h % K.P].add(e);
82
121
  }
@@ -87,6 +126,8 @@ export class Sim {
87
126
  }
88
127
  /** This record was simulated near in the latest step (the presentation layer uses it to keep positionFrom 'view' models) */
89
128
  isNear(id) { return this.ents.get(id)?.near === this.n; }
129
+ /** A kind simulated near that is not near now (far, or a net client that lets the host simulate): its record rules and a model that still stands follows it */
130
+ recordRules(rec) { return !!this.sims.get(rec.kind)?.near && !this.isNear(rec.id); }
90
131
 
91
132
  /** Near radius: the written one, else the presentation radius. Models that move themselves (positionFrom 'view') widen to the teardown distance (1.25×) —
92
133
  * why: the model may still exist within that distance, and one with a model must run near, otherwise far changes to the data get copied back over by world from the model position */
@@ -99,6 +140,7 @@ export class Sim {
99
140
 
100
141
  fixed(dt, anchor) {
101
142
  const W = this.w, now = this.time += dt, n = ++this.n;
143
+ this.ahead = dt; this.accrue(dt);
102
144
  this.at.x = anchor.x; this.at.z = anchor.z; this.dt = dt;
103
145
  if (!this.sims.size) return;
104
146
  let maxR2 = -1;
@@ -155,16 +197,21 @@ export class Sim {
155
197
  // near takes one step, or for a tiered kind everything since its last turn up to one tier period (the outer part waits P steps between turns; a record
156
198
  // moving inward catches up its gap the same way); what is older came from far: far pays that stretch back first
157
199
  const step = s.P > 1 ? Math.max(dt, Math.min(now - e.last, s.P * dt)) : dt;
158
- const owed = now - step - e.last;
200
+ const owed = now - step - e.last, lived = this.settle(e, s, now - e.last);
159
201
  e.last = now;
160
- if (owed > 1e-9 && s.far) s.far(rec, this.scaled(s, rec, owed));
161
- s.near(rec, this.scaled(s, rec, step), this.w.view(rec.id));
202
+ // the plain step reads the speed directly, so a record just loaded (no mark, near owes nothing) gets the bits of a run that kept going
203
+ let d = s.P > 1 ? lived : this.scaled(s, rec, step);
204
+ if (owed > 1e-9) { // what far pays and what near gets add up to what the record lived through; only the newest stretch is near's
205
+ d = Math.min(lived, this.scaled(s, rec, step));
206
+ if (s.far) s.far(rec, lived - d);
207
+ }
208
+ s.near(rec, d, this.w.view(rec.id));
162
209
  }
163
210
  farOne(e, s, now) {
164
211
  const dt = now - e.last;
212
+ if (dt <= 0) { e.last = now; return 0; } // added during this step
213
+ const d = this.settle(e, s, dt);
165
214
  e.last = now;
166
- if (dt <= 0) return 0; // added during this step
167
- const d = this.scaled(s, e.rec, dt);
168
215
  if (s.pure) this.flights.add(e, s, dt, d); else s.far(e.rec, d);
169
216
  return 1;
170
217
  }
@@ -172,15 +219,16 @@ export class Sim {
172
219
  * Same rule as a far turn: kinds with only near are not made up. Worker kinds run here synchronously (the skip result must exist when skip returns) */
173
220
  skip(dt, done) {
174
221
  const now = this.time += dt;
222
+ this.ahead = dt; this.accrue(dt);
175
223
  if (!done) return;
176
224
  for (const e of [...this.ents.values()].sort(byId)) {
177
225
  const s = !e.dead && this.sims.get(e.rec.kind);
178
226
  if (!s?.far) continue;
179
227
  if (e.flight) this.flights.land(e);
180
228
  const owed = now - e.last;
229
+ if (owed <= 0) { e.last = now; continue; }
230
+ const d = this.settle(e, s, owed);
181
231
  e.last = now;
182
- if (owed <= 0) continue;
183
- const d = this.scaled(s, e.rec, owed);
184
232
  if (s.pure) this.flights.now(e, s, d); else s.far(e.rec, d);
185
233
  }
186
234
  }
@@ -192,7 +240,7 @@ export class Sim {
192
240
  /** Save: step count, accumulated seconds, and how many seconds each far-simulated record still owes (near ones simulate every step, owe nothing, are not written).
193
241
  * Step count and seconds are saved too: after loading buckets take turns in the same batch and dt has the same float error, so one save advances the same way every time */
194
242
  toJSON() {
195
- const owed = {}, W = this.w, t = this.time;
243
+ const owed = {}, marks = {}, W = this.w, t = this.time;
196
244
  // in flight (worker far not landed): the record does not have that stretch yet, so it is still owed
197
245
  // only kinds simulated with far owe time: a prop, pickup or near-only kind never makes it up, so it writes nothing (saves stay small);
198
246
  // a tiered near record waiting for its turn does owe its gap (near pays it on the turn), so a loaded save hands it the same dt as a live run
@@ -200,16 +248,19 @@ export class Sim {
200
248
  const s = this.sims.get(e.rec.kind);
201
249
  if (!s?.far && !(s?.P > 1 && e.near === this.n)) continue;
202
250
  const last = e.flight ? e.flight.from : e.last;
203
- if (t - last > 1e-6 && !W._unsaved.has(id)) owed[id] = t - last;
251
+ if (t - last <= 1e-6 || W._unsaved.has(id)) continue;
252
+ owed[id] = t - last;
253
+ if (e.ch !== undefined) marks[id] = e.flight ? e.mark - e.flight.d : e.mark;
204
254
  }
205
- for (const [id, last] of this.owed) owed[id] = t - last; // those whose content is not added back yet are written too (used on the next add)
206
- return { step: this.n, time: t, owed };
255
+ // those whose content is not added back yet are written too (used on the next add)
256
+ for (const [id, o] of this.owed) { owed[id] = t - o.last; if (o.mark !== undefined) marks[id] = o.mark; }
257
+ return { step: this.n, time: t, owed, ...(Object.keys(marks).length && { marks }) };
207
258
  }
208
259
  /** Load: work back the last simulation time from "seconds owed"; records are re-added later by loadWorld */
209
260
  fromJSON(d) {
210
261
  for (const e of this.ents.values()) e.dead = true; // results still in flight belong to the old records: dropped
211
262
  this.ents.clear(); this.kinds.clear(); this.backlog.length = 0; this.order.length = 0;
212
263
  this.n = d?.step ?? 0; this.time = d?.time ?? 0;
213
- this.owed = new Map(Object.entries(d?.owed || {}).map(([id, s]) => [id, this.time - s]));
264
+ this.owed = new Map(Object.entries(d?.owed || {}).map(([id, s]) => [id, { last: this.time - s, mark: d?.marks?.[id] }]));
214
265
  }
215
266
  }
@@ -37,7 +37,7 @@ export class FarFlights {
37
37
  s.key = kind + '#' + ++this.defs;
38
38
  if (T.size) T.pureLane().broadcast({ def: s.key, src: s.pure.src, label }, 'def:' + s.key);
39
39
  }
40
- /** dt: real seconds this turn covers (bookkeeping); d: the dt far gets (dt on the kind's time channel, sim.scaled) */
40
+ /** dt: real seconds this turn covers (bookkeeping); d: the dt far gets (sim.settle) */
41
41
  add(e, s, dt, d = dt) {
42
42
  let b = this.open.get(s); if (!b) this.open.set(s, b = []);
43
43
  b.push([e, dt, d]);
@@ -51,7 +51,7 @@ export class FarFlights {
51
51
  const engine = this.sim.w.engine, T = engine.threads;
52
52
  // copies taken now: what far sees is the record as of this step, whatever happens to it during the flight
53
53
  const f = { s, items, snaps: items.map(([e, , d]) => [structuredClone(e.rec), d]), results: null };
54
- for (const [e, dt] of items) e.flight = { f, from: e.last - dt };
54
+ for (const [e, dt, d] of items) e.flight = { f, from: e.last - dt, d };
55
55
  const t = engine.commits.request({ lag: FAR_LAG, apply: r => this.apply(f, r), fallback: () => f.snaps.map((_, i) => this.compute(f, i)) });
56
56
  // a failed worker run is ignored: the fallback runs the same code here at the due step and throws the same (clear) error
57
57
  if (T.size) T.pureLane().run({ call: s.key, items: f.snaps }).then(r => { f.results = r.map(x => x.args[0]); t.resolve(f.results); }, () => {});
@@ -1,7 +1,8 @@
1
1
  // Internal half of World (World.js copies these onto World.prototype; a mixin, not a base class, so the generated World.d.ts needs no import of this file): state tables, the hooks the engine calls, and the helpers other world files use.
2
2
  // Split by responsibility: World.js keeps the public API and its documentation; nothing here is public.
3
3
  import { DEV, fmt } from '../../core/base/validate.js';
4
- import { STRINGS as RECORD_STRINGS, restRecord, orphanIds } from './records.js';
4
+ import { STRINGS as RECORD_STRINGS, restRecord, orphanIds, removeRecord } from './records.js';
5
+ import { keepTable } from '../../core/base/sections.js';
5
6
  import { saveWorld, loadWorld, renamePending, isPlain } from './persist.js';
6
7
  import { Cells } from '../../core/stream/cells.js';
7
8
  import { centerOf } from './pos.js';
@@ -9,6 +10,7 @@ import { codedError } from '../../core/base/errorHints.js';
9
10
 
10
11
  export function initState(w, cellSize) {
11
12
  /** @internal */ w._anchor = null;
13
+ /** @internal the session handle that ends an anchor set during play */ w._anchorEnd = null;
12
14
  /** @internal id of the record whose model build() is running right now (sync part only), else null */ w._building = null;
13
15
  /** @internal */ w._zone = null;
14
16
  /** @internal */ w._cells = new Cells(cellSize);
@@ -29,10 +31,14 @@ class Internals {
29
31
  get buildingId() { return this._building; }
30
32
  /**
31
33
  * @internal An authored record's resting place, known only once its model is built (a physics body lifted to sit on the ground): when the record is
32
- * still where its content put it (within tolerance meters), the content position moves there too, so the record stays out of the save. A record that was
33
- * moved is left alone.
34
+ * still where its content put it (within tolerance meters), record and content position move there together, so the record stays out of the save. A record
35
+ * that was moved, or that no content wrote, is left alone: the answer says which.
36
+ * @returns {boolean}
37
+ * @internal
34
38
  */
35
- rest(id, position, tolerance = 0) { restRecord(this, id, position, tolerance); }
39
+ rest(id, position, tolerance = 0) { return restRecord(this, id, position, tolerance); }
40
+ /** @internal What stands for the model of id being built now: an async build compares it after waiting, because a load or rebuild may have started another build meanwhile */
41
+ building(id) { return this._v.map.get(id); }
36
42
  /**
37
43
  * @internal The dev editor changed the design itself: the entry's old content is gone, not removed in play, so no baseline and no "removed" mark stay behind for
38
44
  * the save to pin. The record is already gone (thing.remove); the content loader puts the new one in as an authored record again.
@@ -55,11 +61,31 @@ class Internals {
55
61
  * each with the reason (still authored, or the new id has saved data of its own), for the dev warning.
56
62
  * @param {Record<string, string | null>} map
57
63
  * @returns {string[]}
64
+ * @internal
58
65
  */
59
66
  renameIds(map) {
60
67
  for (const [a, b] of Object.entries(map)) this._renames.set(a, b);
61
68
  return renamePending(this);
62
69
  }
70
+ /**
71
+ * @internal A failed content load puts the world back (core/base/sections.js undo): the function that does it. Records it added go, poses and fields it changed return, and
72
+ * the tables a save diffs against (a deep copy: repose writes inside the baseline) are as they were.
73
+ * @returns {() => void}
74
+ * @internal
75
+ */
76
+ undoPoint() {
77
+ const live = [...this.records.values()].map(r => [r, { ...r, position: { ...r.position } }]), had = new Set(this.records.keys());
78
+ const base = structuredClone(this._base), pending = structuredClone(this._pending), tables = [this._removed, this._renames, this._levels, this._origin, this._unsaved].map(keepTable);
79
+ return () => {
80
+ for (const id of [...this.records.keys()]) if (!had.has(id)) removeRecord(this, id);
81
+ for (const [t, was] of [[this._base, base], [this._pending, pending]]) { t.clear(); for (const [k, v] of was) t.set(k, v); }
82
+ for (const fn of tables) fn();
83
+ for (const [r, { position, ...fields }] of live) {
84
+ for (const k of Object.keys(r)) if (k !== 'position' && !(k in fields)) delete r[k];
85
+ Object.assign(r, fields); Object.assign(r.position, position); this._index(r);
86
+ }
87
+ };
88
+ }
63
89
  /** @internal Whether id is an authored (content) record, removed or not: thing.remove's undo puts such a record back without a world.add */
64
90
  authored(id) { return this._base.has(id); }
65
91
  /**
@@ -76,11 +102,10 @@ class Internals {
76
102
  get center() { return this.anchor ?? this.engine.actorPosition() ?? this.engine.focus; }
77
103
 
78
104
  // ---------- called by the engine ----------
79
- /** Fixed step: read this step's simulation center → simulate → copy model-driven positions back to the data @internal */
105
+ /** Fixed step: read this step's simulation center → simulate. Model-driven positions come back to the data after every module has run (index.js) @internal */
80
106
  fixed(dt) {
81
107
  const a = this.center;
82
108
  this._s.fixed(dt, centerOf(a));
83
- this._v.pull();
84
109
  }
85
110
  /** Every frame: build / tear down models by stream sources, sync positions, call update @internal */
86
111
  frame(dt) { this._v.frame(dt); }
@@ -1,4 +1,4 @@
1
- // What the world module tells core about its records: engine._things.addSource(...) at install. Core knows only this shape (has / get / set / remove /
1
+ // What the world module tells core about its records: engine._things.addSource(...) at install. Core knows only this shape (has / get / set / refuses / refusesUndo / remove /
2
2
  // explain, plus idOf / view / ids / restore for the model link and undo), never the World class, so engine.thing, thing.set and the shared id space
3
3
  // work the same whether or not this module is installed.
4
4
  import { fmt } from '../../core/base/validate.js';
@@ -32,10 +32,23 @@ export function recordSource(w) {
32
32
  idOf: obj => w.idOf(obj),
33
33
  view: id => w.view(id),
34
34
  explain: id => describeRecord(w, id),
35
+ /** Why its owner cannot apply this change, or null: thing.set answers with it in can, because a throw inside an op freezes gameplay */
36
+ refuses: (id, patch) => w.engine.control?.characterOf(id)?.poseProblem(patch) ?? null,
37
+ /** The same for an undo: a placement that ended a ride goes back to that seat, which may be gone or taken by now */
38
+ refusesUndo(id, before) {
39
+ if (!before.ride) return null;
40
+ const ch = w.engine.control?.characterOf(id);
41
+ return ch ? ch.seatProblem(before.ride) : `'${id}' has no model now, so nothing can sit in that seat`;
42
+ },
35
43
  /** Change a record (position / rot / scale); returns the values it replaced (set(id, thatValue) is the undo) */
36
44
  set(id, patch) {
37
- // rot / scale are the template instance fields (templates.js); a record without them reads as rot 0, scale 1
38
- const rec = w.get(id), before = { position: { ...rec.position }, ...(patch.rot != null && { rot: rec.rot ?? 0 }), ...(patch.scale != null && { scale: rec.scale ?? 1 }) };
45
+ // rot / scale are the template instance fields (templates.js); a record without them reads as rot 0, scale 1, and a live character's turn is its facing.
46
+ // Only what the patch writes: the undo of a turn must not place a rider who rode on since
47
+ const rec = w.get(id), live = w.engine.control?.characterOf(id);
48
+ if (patch.ride) { const { position, ...rest } = patch; w.set(id, rest); live.backInSeat(patch.ride); w.move(id, live.root.position); return null; } // the undo of a placement that ended a ride
49
+ const before = { ...(patch.position && { position: { ...rec.position } }), ...(patch.rot != null && { rot: live ? live.facing : rec.rot ?? 0 }), ...(patch.scale != null && { scale: rec.scale ?? 1 }) };
50
+ // not enumerable: the op's value stays plain, and a vehicle is no record field. The undo reads it back from this object
51
+ if (patch.position && live?.vehicle) Object.defineProperty(before, 'ride', { value: { vehicle: live.vehicle, seat: live.seat } });
39
52
  w.set(id, patch);
40
53
  return before;
41
54
  },