threedog 2.2.0 → 2.3.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 (197) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +4 -4
  3. package/core/assets/Animator.js +66 -12
  4. package/core/assets/ik.js +144 -18
  5. package/core/assets/maskLayer.js +377 -0
  6. package/core/assets/rootMotion.js +148 -0
  7. package/core/audio/Audio.js +100 -4
  8. package/core/base/errorCodes.js +6 -369
  9. package/core/base/errorCodesModules.js +378 -0
  10. package/core/engine/Engine.js +8 -5
  11. package/core/engine/Loading.js +8 -4
  12. package/core/engine/copies.js +1 -1
  13. package/core/engine/headlessLoad.js +15 -4
  14. package/core/engine/lifecycle.js +1 -0
  15. package/core/engine/loop.js +23 -3
  16. package/core/engine/moduleSlots.js +3 -7
  17. package/core/engine/modules.js +30 -58
  18. package/core/engine/startup.js +3 -3
  19. package/core/input/Input.js +7 -3
  20. package/core/input/inputContext.js +3 -2
  21. package/core/input/inputSeat.js +1 -1
  22. package/core/inspect/DebugOverrides.js +1 -1
  23. package/core/inspect/Describe.js +7 -2
  24. package/core/inspect/describeRender.js +4 -1
  25. package/core/inspect/describeText.js +2 -2
  26. package/core/inspect/metadata.generated.js +380 -74
  27. package/core/inspect/pictureMenu.js +2 -0
  28. package/core/inspect/pictureWriters.js +4 -3
  29. package/core/ops/Ops.js +9 -3
  30. package/core/ops/actor.js +10 -0
  31. package/core/ops/control.js +17 -6
  32. package/core/ops/holds.js +1 -1
  33. package/core/ops/opsAtomic.js +6 -1
  34. package/core/ops/opsGuard.js +2 -2
  35. package/core/ops/owned.js +37 -11
  36. package/core/ops/sharedPoint.js +5 -1
  37. package/core/ops/stacks.js +30 -7
  38. package/core/saves/Saves.js +0 -2
  39. package/core/saves/saveApply.js +7 -7
  40. package/core/saves/session.js +6 -3
  41. package/core/saves/stateReplace.js +71 -41
  42. package/core/scene/Rays.js +74 -26
  43. package/core/scene/canvasBox.js +9 -0
  44. package/core/scene/gameLights.js +19 -11
  45. package/core/scene/sceneDelta.js +8 -4
  46. package/core/scene/sceneMethods.js +2 -1
  47. package/core/stream/chunkStream.js +21 -0
  48. package/core/stream/dirtyWatch.js +37 -0
  49. package/core/time/skip.js +9 -6
  50. package/core/time/time.js +72 -18
  51. package/docs/AI.md +22 -21
  52. package/docs/API.md +5 -4
  53. package/docs/CODEMAP.md +16 -10
  54. package/docs/COMMANDS.md +5 -5
  55. package/docs/CONVENTIONS.md +9 -25
  56. package/docs/api/ambience.md +1 -0
  57. package/docs/api/assets.md +10 -3
  58. package/docs/api/audio.md +5 -3
  59. package/docs/api/decals.md +16 -0
  60. package/docs/api/engine.md +1 -0
  61. package/docs/api/tools.md +3 -1
  62. package/docs/api/water.md +3 -0
  63. package/docs/recipes/09-materials-lights-models.md +15 -1
  64. package/docs/recipes/13-animation.md +51 -10
  65. package/docs/recipes/16-dev-bridge.md +4 -4
  66. package/docs/recipes/31-audio.md +15 -9
  67. package/docs/recipes/34-environment-lighting.md +11 -1
  68. package/docs/recipes/44-water-weather-hooks.md +1 -0
  69. package/examples/action/.threedog/content-index.json +1 -0
  70. package/examples/perf-island/.threedog/content-index.json +1 -0
  71. package/examples/plain-picture/.threedog/content-index.json +1 -0
  72. package/examples/rc2d/.threedog/content-index.json +1 -0
  73. package/examples/styletest/.threedog/content-index.json +1 -0
  74. package/examples/techniques/outlines-and-rim/main.js +1 -1
  75. package/examples/techniques/procedural-surface/main.js +1 -1
  76. package/examples/techniques/stylized-shading/main.js +1 -1
  77. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  78. package/examples/world/.threedog/content-index.json +1 -0
  79. package/index.d.ts +6 -2
  80. package/index.js +3 -2
  81. package/llms.txt +11 -10
  82. package/modules/ambience/Ambience.js +97 -15
  83. package/modules/camera/common.js +18 -12
  84. package/modules/characters/Character.js +30 -3
  85. package/modules/characters/NPC.js +2 -5
  86. package/modules/characters/astar.js +45 -14
  87. package/modules/characters/movers/rapier.js +53 -41
  88. package/modules/characters/movers/simple.js +37 -24
  89. package/modules/characters/npcView.js +2 -2
  90. package/modules/characters/pathAsync.js +3 -3
  91. package/modules/collision/contract.js +2 -2
  92. package/modules/content/index.js +3 -0
  93. package/modules/content/models.js +11 -4
  94. package/modules/content/templates.js +11 -11
  95. package/modules/debug/DebugPanel.js +1 -0
  96. package/modules/decals/Decals.js +393 -0
  97. package/modules/decals/index.js +1 -0
  98. package/modules/gameplay/Container.js +2 -0
  99. package/modules/gameplay/Containers.js +17 -3
  100. package/modules/gameplay/Dialogue.js +1 -1
  101. package/modules/gameplay/Interactions.js +7 -6
  102. package/modules/gameplay/Inventory.js +5 -1
  103. package/modules/gameplay/Quests.js +4 -3
  104. package/modules/gameplay/inventoryOps.js +2 -2
  105. package/modules/gameplay/pickups.js +32 -12
  106. package/modules/gameplay/questSave.js +2 -2
  107. package/modules/grid/index.js +8 -2
  108. package/modules/hud/index.js +1 -1
  109. package/modules/level/heightfield.js +1 -0
  110. package/modules/level/index.js +3 -2
  111. package/modules/level/nodes.js +2 -1
  112. package/modules/lights/index.js +27 -4
  113. package/modules/lights/slots.js +33 -16
  114. package/modules/nav/contract.js +4 -4
  115. package/modules/nav/index.js +6 -2
  116. package/modules/net/Client.js +24 -11
  117. package/modules/net/Host.js +73 -20
  118. package/modules/net/index.js +33 -21
  119. package/modules/net/sync.js +38 -8
  120. package/modules/net/transports.js +7 -3
  121. package/modules/particles/Particles.js +11 -4
  122. package/modules/particles/contract.js +6 -6
  123. package/modules/particles/effect.js +0 -1
  124. package/modules/rigid/RigidBodies.js +69 -57
  125. package/modules/rigid/Vehicles.js +8 -7
  126. package/modules/rigid/ragdoll.js +4 -6
  127. package/modules/rigid/rapierCompat.js +90 -0
  128. package/modules/rigid/sync.js +2 -5
  129. package/modules/settings/Settings.js +10 -4
  130. package/modules/sky/Sky.js +10 -2
  131. package/modules/sky/environment.js +29 -13
  132. package/modules/sky/frame.js +2 -2
  133. package/modules/sky/shader.js +5 -2
  134. package/modules/sky/skyModule.js +2 -2
  135. package/modules/swarm/Swarm.js +3 -2
  136. package/modules/swarm/grid.js +12 -7
  137. package/modules/terrain/ChunkManager.js +16 -26
  138. package/modules/triggers/index.js +5 -6
  139. package/modules/vegetation/draw.js +62 -26
  140. package/modules/vegetation/groundChunks.js +8 -22
  141. package/modules/water/Water.js +152 -24
  142. package/modules/water/surface.js +43 -20
  143. package/modules/weather/weatherDraw.js +4 -1
  144. package/modules/world/World.js +21 -2
  145. package/modules/world/index.js +5 -0
  146. package/modules/world/persist.js +1 -0
  147. package/modules/world/records.js +3 -1
  148. package/modules/world/sim.js +3 -2
  149. package/modules/world/simFar.js +4 -2
  150. package/modules/world/state.js +7 -1
  151. package/package.json +2 -2
  152. package/presets.js +30 -0
  153. package/render/PostFX.js +24 -17
  154. package/render/backend.js +72 -31
  155. package/render/cascades.js +25 -14
  156. package/render/cascades.tsl.js +32 -21
  157. package/render/fogLook.js +2 -1
  158. package/render/fx/detail.tsl.js +3 -0
  159. package/render/fx/library.tsl.js +1 -1
  160. package/render/fx/particles.tsl.js +4 -18
  161. package/render/fx/pcss.tsl.js +2 -2
  162. package/render/fx/postWebGPU.tsl.js +47 -25
  163. package/render/fx/sky.tsl.js +6 -18
  164. package/render/fx/uniforms.tsl.js +16 -0
  165. package/render/fx/water.tsl.js +24 -5
  166. package/render/fxNumbers.js +2 -0
  167. package/render/impostor.tsl.js +10 -6
  168. package/render/lights.js +6 -6
  169. package/render/occlusion.js +17 -6
  170. package/render/patches.js +40 -28
  171. package/render/postWebGL.js +6 -4
  172. package/render/reflectionProbes.js +302 -0
  173. package/render/shaderErrors.js +18 -8
  174. package/render/shadowCache.tsl.js +10 -5
  175. package/render/shadows.js +70 -49
  176. package/render/threeCompat.js +166 -0
  177. package/types/core.d.ts +33 -3
  178. package/types/gameplay.d.ts +80 -0
  179. package/types/generated/core/audio/Audio.d.ts +18 -1
  180. package/types/generated/core/ops/Ops.d.ts +2 -1
  181. package/types/generated/core/ops/control.d.ts +7 -3
  182. package/types/generated/core/saves/session.d.ts +4 -1
  183. package/types/generated/modules/ambience/Ambience.d.ts +6 -0
  184. package/types/generated/modules/debug/DebugPanel.d.ts +1 -0
  185. package/types/generated/modules/grid/index.d.ts +27 -3
  186. package/types/generated/modules/net/index.d.ts +8 -3
  187. package/types/generated/modules/sky/Sky.d.ts +1 -0
  188. package/types/generated/modules/water/Water.d.ts +15 -0
  189. package/types/generated/modules/world/index.d.ts +5 -0
  190. package/types/generated/render/patches.d.ts +5 -0
  191. package/types/physics.d.ts +66 -9
  192. package/types/tsl.d.ts +2 -0
  193. package/types/world.d.ts +2 -0
  194. package/ui/Parts.js +3 -2
  195. package/docs/MIGRATING-0.7.md +0 -39
  196. package/docs/MIGRATING-0.8.md +0 -171
  197. package/modules/rigid/refresh.js +0 -10
@@ -1,11 +1,12 @@
1
1
  // Water module: draws the global water plane (sea, big lakes; snaps to a grid following the focus so it doesn't "swim") and independent water bodies (mountain lakes, ponds, each with its own level).
2
- // water({...}) takes the structural choices (sea, level, flat, size, segments). The picture is plain three.js on the module (recipes/44):
2
+ // water({...}) takes the structural choices (sea, level, flat, size, segments, ripples). The picture is plain three.js on the module (recipes/44):
3
3
  //
4
4
  // engine.use(water()); // global water only (level taken from the terrain water level)
5
5
  // engine.use(water({ sea: false })); // no global water
6
6
  // engine.use(water({ level: 4, size: 1200 }));
7
7
  // engine.water.material.color.set(0x3070a0); // the neutral material: plain three.js writes
8
8
  // engine.water.uniforms.uWave.value = 1.5; // uWave uWaveScale uWaveSpeed uFresnel, live
9
+ // engine.water.ripple([12, 0, -4], { strength: 1 }); // concentric surface wave packet (characters wading and raindrops emit automatically)
9
10
  // engine.water.material = applyEffects(new THREE.MeshPhongMaterial({ color: 0x3070a0, shininess: 90 }), { patches: engine.water.patches }); // your own material, waves kept
10
11
  // engine.water.shader({ foam: true, depthColor: { shallow: 0x55ddcc, deep: 0x082040 } }); // which GLSL exists (also wave, surface, uniforms)
11
12
  // engine.water.normalMap('water-n', { scale: 0.4, repeat: 0.05, speed: [0.01, 0.006] });
@@ -17,30 +18,40 @@ import { neutralMaterial } from '../../render/neutral.js';
17
18
  import { placeholderTexture } from '../../render/effects.js';
18
19
  import { patchMaterial, unpatchMaterial } from '../../render/patches.js';
19
20
  import { readParams, keysSchema } from '../../core/base/params.js';
20
- import { waterShader, wavesPatch, surfacePatch } from './surface.js';
21
+ import { waterShader, wavesPatch, surfacePatch, RIPPLE_DECL, WAVE_NODES } from './surface.js';
21
22
  import { codedError } from '../../core/base/errorHints.js';
22
- import { glslFloat, FRESNEL_POWER } from '../../render/fxNumbers.js';
23
+ import { glslFloat, FRESNEL_POWER, RIPPLE } from '../../render/fxNumbers.js';
23
24
  import { fogLook } from '../../render/fogLook.js';
24
25
  import { needMaterial } from '../../core/base/validate.js';
26
+ import { xzOf, yOf } from '../../core/base/math.js';
27
+ import { mulberry32 } from '../../core/base/mulberry32.js';
25
28
 
26
29
  const GREY = new THREE.Color(0xcccccc);
27
30
  /** @import { ModuleDef } from '../../types/core' */
28
- /** @import { Material, Vector3, Texture } from '../../types/common' */
31
+ /** @import { Material, Vector3, Texture, PositionLike } from '../../types/common' */
29
32
  /** @import { WaterBody, WaterOptions, WaterShaderOptions } from '../../types/world' */
30
33
  // Options accepted by water(): the structural choices only
31
- const WATER_OPTIONS = ['sea', 'level', 'flat', 'size', 'segments'];
32
- // size / segments divide each other (cell) and the sea snap: zero or non-finite would make NaN coordinates (size is meters, so a sub-meter plane is valid: > 0)
33
- const WATER_PARAMS = keysSchema(WATER_OPTIONS, {}, { size: { type: 'number', min: Number.MIN_VALUE, optional: true }, segments: { type: 'int', min: 1, optional: true } });
34
+ const WATER_OPTIONS = ['sea', 'level', 'flat', 'size', 'segments', 'ripples'];
35
+ const WATER_PARAMS = keysSchema(WATER_OPTIONS, {}, {
36
+ size: { type: 'number', min: Number.MIN_VALUE, optional: true, desc: 'edge length of the global sea plane in meters' },
37
+ segments: { type: 'int', min: 1, optional: true, desc: 'mesh subdivisions per side of the global sea' },
38
+ ripples: { type: 'bool', optional: true, desc: 'automatic wading wakes and raindrop rings (default true)' },
39
+ });
34
40
  const SHADER_PARAMS = keysSchema(['wave', 'surface', 'depthColor', 'foam', 'uniforms']);
35
41
  const NORMAL_PARAMS = { scale: { type: 'number', min: 0, optional: true, desc: 'normal map strength' }, repeat: { type: 'number', min: 0, optional: true, desc: 'tiles per meter' },
36
42
  speed: { type: 'position', optional: true, desc: 'scroll [x, z] per second' } };
43
+ const RIPPLE_PARAMS = {
44
+ strength: { type: 'number', default: 1, min: 0, desc: 'peak ring amplitude' },
45
+ speed: { type: 'number', default: 2.6, min: 0.1, desc: 'ring expansion speed in m/s' },
46
+ duration: { type: 'number', default: 2.2, min: 0.1, desc: 'seconds until the ring fades out' },
47
+ };
37
48
 
38
49
  /** engine.water */
39
50
  export class Water {
40
51
  /** @internal */
41
52
  constructor(engine, opts = {}, track) {
42
53
  /** @internal */ this.engine = engine;
43
- /** @internal */ this.st = { flat: true, size: 900, segments: 150, ...opts };
54
+ /** @internal */ this.st = { flat: true, size: 900, segments: 150, ripples: true, ...opts };
44
55
  const st = this.st;
45
56
  /** @internal */ this.cell = st.size / st.segments;
46
57
  /** @internal the normal map's name and how it tiles */ this._normal = { name: null, scale: 0.4, repeat: 0.05, speed: [0.01, 0.006] };
@@ -53,6 +64,19 @@ export class Water {
53
64
  this._uv = new Map();
54
65
  /** @internal the uniforms shader() keeps across rebuilds, so a game's handle to one stays live */
55
66
  this._tune = { uWave: { value: 1 }, uWaveScale: { value: 1 }, uWaveSpeed: { value: 1 }, uFresnel: { value: 0.5 } };
67
+ /** @internal 8-slot ripple ring buffer: CPU state + live Vector4 uniforms */
68
+ this._rippleUniforms = { uRippleCount: { value: 0 } };
69
+ /** @internal */ this._ripplePool = Array.from({ length: RIPPLE.slots }, (_, i) => {
70
+ const vec = new THREE.Vector4(0, 0, 0, 0);
71
+ this._rippleUniforms[`uRipple${i}`] = { value: vec };
72
+ return { vec, age: 0, duration: 0, rate: 2.6, strength: 0, active: false };
73
+ });
74
+ /** @internal */ this._rippleNext = 0;
75
+ /** @internal wading wake state keyed by actor object/record */
76
+ this._wakers = new WeakMap();
77
+ /** @internal visual-only PRNG for raindrop rings (never advances gameplay engine.random) */
78
+ this._rainRng = { state: 5371811 };
79
+ /** @internal */ this._rainAcc = 0;
56
80
  /** @internal what shader() was given so far */ this._shader = {};
57
81
  const built = this._build(this._shader);
58
82
  /**
@@ -87,12 +111,40 @@ export class Water {
87
111
  track(engine.events.on('water:remove', b => { const m = this.bodies.get(b); if (m) { this._drop(m); this.bodies.delete(b); } }));
88
112
  }
89
113
 
114
+ /** Number of currently expanding ripple rings (0..8) @type {number} */
115
+ get activeRipples() { return this._rippleUniforms.uRippleCount.value; }
116
+
117
+ /**
118
+ * Spawn an expanding concentric ripple ring at `position` (`[x, y, z]`, `{ x, z }`, `Vector3` or `Object3D`), visible on both the global sea and water bodies.
119
+ * @example engine.water.ripple(engine.player.position, { strength: 1.2, duration: 2.5 });
120
+ * @param {PositionLike} position
121
+ * @param {{ strength?: number, speed?: number, duration?: number }} [opts]
122
+ * @returns {void}
123
+ */
124
+ ripple(position, opts = {}) {
125
+ if (!position) throw codedError('water-option', 'engine.water.ripple(position, opts): position is required');
126
+ const o = readParams('engine.water.ripple', RIPPLE_PARAMS, opts);
127
+ if (o.strength <= 0) return;
128
+ const [x, z] = xzOf(position);
129
+ if (!Number.isFinite(x) || !Number.isFinite(z)) return;
130
+ let slot = this._ripplePool.find(s => !s.active);
131
+ if (!slot) {
132
+ slot = this._ripplePool[this._rippleNext];
133
+ this._rippleNext = (this._rippleNext + 1) % RIPPLE.slots;
134
+ }
135
+ slot.active = true; slot.age = 0; slot.duration = o.duration; slot.rate = o.speed; slot.strength = o.strength;
136
+ slot.vec.set(x, z, 0, o.strength);
137
+ let count = 0;
138
+ for (let i = 0; i < RIPPLE.slots; i++) if (this._ripplePool[i].active) count++;
139
+ this._rippleUniforms.uRippleCount.value = count;
140
+ }
141
+
90
142
  /** One water mesh out of the scene. The material is shared by all water, so not engine.remove (which would dispose it); the ray registration goes too @internal */
91
143
  _drop(m) { const e = this.engine; m.removeFromParent(); e.rays.forget(m); this._uv.delete(m); m.geometry.dispose(); }
92
144
  /** The module goes: its meshes and what it made leave with it; a game's material stays the game's @internal */
93
145
  dispose() {
94
146
  for (const m of [this.sea, ...this.bodies.values()]) if (m) this._drop(m);
95
- this.sea = null; this.bodies.clear(); this._own.dispose(); this.normalTexture?.dispose();
147
+ this.sea = null; this.bodies.clear(); this._own.dispose(); this.normalTexture?.dispose(); this.normalTexture = null;
96
148
  }
97
149
 
98
150
  /**
@@ -123,7 +175,7 @@ export class Water {
123
175
  readParams('engine.water.shader', SHADER_PARAMS, opts);
124
176
  const next = { ...this._shader, ...opts }, built = this._build(next); // a wrong value throws here, with nothing changed
125
177
  this._shader = next; this.patches = built.patches; this.uniforms = built.uniforms;
126
- for (const name of ['waves', 'waterSurface', 'fresnel']) unpatchMaterial(this._own, name); // patchMaterial only adds: foam taken back must leave the program
178
+ for (const name of ['waves', 'waterSurface', 'waterRipples', 'fresnel']) unpatchMaterial(this._own, name); // patchMaterial only adds: foam taken back must leave the program
127
179
  patchMaterial(this._own, this.patches);
128
180
  }
129
181
 
@@ -164,27 +216,40 @@ export class Water {
164
216
  }
165
217
  /** Scale a mesh's UVs to size * repeat (the normal map tiles in meters); a no-op without a normal map or when already at that factor @internal */
166
218
  _tile(mesh) {
167
- const u = this._uv.get(mesh); if (!this.normalTexture || !u) return;
168
- const f = u.sx * this._normal.repeat, g = u.sz * this._normal.repeat; if (f === u.f && g === u.g) return;
169
- // always from the UVs the mesh was made with: scaling the current ones by f / u.f would divide by zero after repeat 0 and lose them for good
219
+ const u = this._uv.get(mesh); if (!u) return;
220
+ const f = this.normalTexture ? u.sx * this._normal.repeat : 1, g = this.normalTexture ? u.sz * this._normal.repeat : 1;
221
+ if (f === u.f && g === u.g) return;
170
222
  const uv = mesh.geometry.attributes.uv; for (let i = 0; i < uv.count; i++) uv.setXY(i, u.base[i * 2] * f, u.base[i * 2 + 1] * g);
171
223
  uv.needsUpdate = true; u.f = f; u.g = g;
172
224
  }
173
225
  /** The patches and uniforms for what shader() was given @internal */
174
226
  _build(given) {
175
- const e = this.engine, water = this, shader = waterShader(given), surface = surfacePatch(e, shader), waves = wavesPatch(e, this._tune, shader, !!surface), { uFresnel } = this._tune;
176
- // grazing-angle reflection: the flatter the view, the closer to _reflects(); the getter follows whatever exists at draw time
227
+ const e = this.engine, water = this, shader = waterShader(given), surface = surfacePatch(e, shader), waves = wavesPatch(e, this._tune, shader, !!surface, this._rippleUniforms), { uFresnel } = this._tune;
177
228
  const uFresnelColor = { get value() { return water._reflects(); } };
229
+ const ripUniforms = { ...this._rippleUniforms, uRippleTint: uFresnelColor };
230
+ const waterRipples = { name: 'waterRipples', needs: { patches: ['waves'] }, uniforms: ripUniforms,
231
+ pars: `uniform vec3 uRippleTint;\nvarying vec2 vThreedogRippleXZ;\n${RIPPLE_DECL}`, slot: 'output', glsl: `
232
+ float threedogRipFrag = threedogWaterRipple(vThreedogRippleXZ);
233
+ outgoingLight *= 1.0 + threedogRipFrag * 0.14;
234
+ outgoingLight = mix(outgoingLight, uRippleTint * 1.12 + vec3(0.18), clamp(threedogRipFrag * ${glslFloat(RIPPLE.sheen)}, 0.0, 0.45));`,
235
+ tsl: c => {
236
+ const T = c.tsl, n = WAVE_NODES.get(c.material), U = k => c.fx.patchUniform(ripUniforms[k]);
237
+ if (!n?.xz) return c.output;
238
+ const slots = Array.from({ length: RIPPLE.slots }, (_, i) => U(`uRipple${i}`));
239
+ const rip = c.fx.waterRipple(n.xz, U('uRippleCount'), slots);
240
+ const trough = c.output.rgb.mul(T.float(1).add(rip.mul(0.14)));
241
+ const crest = T.clamp(rip.mul(RIPPLE.sheen), 0, 0.45);
242
+ return T.vec4(T.mix(trough, U('uRippleTint').mul(1.12).add(T.vec3(0.18, 0.18, 0.18)), crest), c.output.a);
243
+ } };
178
244
  const fresnel = { name: 'fresnel', uniforms: { uFresnel, uFresnelColor },
179
245
  pars: 'uniform float uFresnel; uniform vec3 uFresnelColor;', slot: 'output', glsl: `
180
246
  #if defined(LAMBERT) || defined(PHONG) || defined(STANDARD) || defined(TOON) || defined(MATCAP)
181
247
  float threedogFres = pow(1.0 - abs(dot(normalize(vViewPosition), normal)), ${glslFloat(FRESNEL_POWER)}) * uFresnel;
182
248
  outgoingLight = mix(outgoingLight, uFresnelColor, clamp(threedogFres, 0.0, 1.0));
183
- #endif`, // why the #if: a game's MeshBasicMaterial has no normal / view variables, so it gets no reflection, and patches stays one list for every material
184
- // NodeMaterial: the same blend (threedog/tsl waterFresnel) on the color before fog; the uniform nodes read these objects every render
249
+ #endif`,
185
250
  tsl: c => (c.material.isMeshBasicMaterial || c.material.isMeshBasicNodeMaterial ? c.output : c.tsl.vec4(c.fx.waterFresnel(c.output.rgb, c.tsl.normalView, c.tsl.positionViewDirection,
186
251
  c.fx.patchUniform(uFresnel), c.fx.patchUniform(uFresnelColor)), c.output.a)) };
187
- return { patches: surface ? [waves, surface, fresnel] : [waves, fresnel], uniforms: { ...waves.uniforms, ...surface?.uniforms, uFresnel } };
252
+ return { patches: surface ? [waves, surface, waterRipples, fresnel] : [waves, waterRipples, fresnel], uniforms: { ...waves.uniforms, ...surface?.uniforms, uFresnel } };
188
253
  }
189
254
  /** What grazing angles reflect: the fog color; with no fog the sky's horizon, because a fixed gray glows on dark water at night; with no sky a neutral gray @internal */
190
255
  _reflects() { const e = this.engine; return fogLook(e.scene, e.renderer)?.color ?? (e.sky ? e.uniforms.uSkyHorizon.value : GREY); }
@@ -200,7 +265,7 @@ export class Water {
200
265
  const geo = b.radius ? new THREE.CircleGeometry(b.radius, Math.max(16, seg * 2)).rotateX(-Math.PI / 2) : new THREE.PlaneGeometry(b.hw * 2, b.hd * 2, seg, seg).rotateX(-Math.PI / 2);
201
266
  const m = new THREE.Mesh(geo, this._material);
202
267
  m.position.set(b.x, b.level - 0.1, b.z);
203
- this._prep(m, b.radius ? b.radius * 2 : b.hw * 2, b.radius ? b.radius * 2 : b.hd * 2); // a rectangle tiles per meter on each axis
268
+ this._prep(m, b.radius ? b.radius * 2 : b.hw * 2, b.radius ? b.radius * 2 : b.hd * 2);
204
269
  this.engine.add(m, { owner: 'engine:water' });
205
270
  this.bodies.set(b, m);
206
271
  }
@@ -214,8 +279,71 @@ export class Water {
214
279
  this._prep(this.sea, st.size);
215
280
  this.engine.add(this.sea, { owner: 'engine:water' });
216
281
  }
282
+ /** @internal check one actor / body for water entry or wading movement */
283
+ _checkWaker(keyObj, x, y, z) {
284
+ const lv = this.engine.waterAt(x, z, y);
285
+ const inWater = Number.isFinite(lv) && y <= lv + 0.18 && y >= lv - 2.0;
286
+ let st = this._wakers.get(keyObj);
287
+ if (!inWater) { if (st) st.inWater = false; return; }
288
+ if (!st) {
289
+ st = { x, z, inWater: true };
290
+ this._wakers.set(keyObj, st);
291
+ this.ripple([x, lv, z], { strength: 0.85, duration: 2.0 });
292
+ return;
293
+ }
294
+ if (!st.inWater) {
295
+ st.inWater = true; st.x = x; st.z = z;
296
+ this.ripple([x, lv, z], { strength: 0.9, duration: 2.2 });
297
+ return;
298
+ }
299
+ const d2 = (x - st.x) * (x - st.x) + (z - st.z) * (z - st.z);
300
+ if (d2 >= 0.72) {
301
+ st.x = x; st.z = z;
302
+ this.ripple([x, lv, z], { strength: 0.55, duration: 1.8 });
303
+ }
304
+ }
305
+ /** @internal advance ripple packets and sample wading / raindrop wakes */
306
+ _stepRipples(focus, dt) {
307
+ if (dt <= 0 || this.engine.still) return;
308
+ let count = 0;
309
+ for (let i = 0; i < RIPPLE.slots; i++) {
310
+ const s = this._ripplePool[i];
311
+ if (!s.active) continue;
312
+ s.age += dt;
313
+ if (s.age >= s.duration) { s.active = false; s.vec.set(0, 0, 0, 0); continue; }
314
+ const k = 1 - s.age / s.duration;
315
+ s.vec.z = s.age * s.rate;
316
+ s.vec.w = s.strength * k * k;
317
+ count++;
318
+ }
319
+ this._rippleUniforms.uRippleCount.value = count;
320
+ if (!this.st.ripples || this.engine.frozen) return;
321
+ if (!this.sea && !this.bodies.size) return;
322
+ const p = this.engine.player;
323
+ if (p?.position) this._checkWaker(p, p.position.x, p.position.y, p.position.z);
324
+ const near = this.engine.world?.near?.(focus, 40);
325
+ if (near) for (let i = 0; i < near.length; i++) {
326
+ const r = near[i];
327
+ if (r.id === 'player' || r.kind !== 'npc') continue;
328
+ const rx = r.x, rz = r.z, ry = yOf(r) ?? this.engine.surface(rx, rz);
329
+ if (Number.isFinite(rx) && Number.isFinite(rz) && Number.isFinite(ry)) this._checkWaker(r, rx, ry, rz);
330
+ }
331
+ const rain = this.engine.uniforms.uRain.value;
332
+ if (rain > 0.15) {
333
+ this._rainAcc += dt * rain * 6;
334
+ while (this._rainAcc >= 1) {
335
+ this._rainAcc -= 1;
336
+ const rx = focus.x + (mulberry32(this._rainRng) - 0.5) * 28;
337
+ const rz = focus.z + (mulberry32(this._rainRng) - 0.5) * 28;
338
+ const lv = this.engine.waterAt(rx, rz);
339
+ if (Number.isFinite(lv) && lv >= this.engine.surface(rx, rz) - 0.05) {
340
+ this.ripple([rx, lv, rz], { strength: 0.22 * rain, speed: 1.8, duration: 1.1 });
341
+ }
342
+ }
343
+ }
344
+ }
217
345
  /**
218
- * Per-frame update: global water snaps to the focus grid, normal map scrolls (called by the module itself each frame)
346
+ * Per-frame update: global water snaps to the focus grid, normal map scrolls, ripples expand (called by the module itself each frame)
219
347
  * @param {Vector3} focus
220
348
  * @param {number} dt
221
349
  * @returns {void}
@@ -228,7 +356,8 @@ export class Water {
228
356
  this.sea.position.x = Math.round(focus.x / c) * c;
229
357
  this.sea.position.z = Math.round(focus.z / c) * c;
230
358
  }
231
- if (this.normalTexture) { const s = this._normal.speed; this.normalTexture.offset.x += s[0] * dt; this.normalTexture.offset.y += s[1] * dt; }
359
+ if (this.normalTexture && !this.engine.still) { const s = this._normal.speed; this.normalTexture.offset.x += s[0] * dt; this.normalTexture.offset.y += s[1] * dt; }
360
+ this._stepRipples(focus, dt);
232
361
  }
233
362
  }
234
363
 
@@ -240,12 +369,11 @@ export class Water {
240
369
  export function water(opts = {}) {
241
370
  readParams('water', WATER_PARAMS, opts);
242
371
  let w = null;
243
- return { name: 'water', skipKind: 'none', type: 'picture', label: 'Water', params: WATER_PARAMS, options: opts, stage: 'environment', optional: ['sky'], install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.water': '水面' }, en: { 'module.water': 'water' } }); w = new Water(e, opts, ctx.track); return w; }, frame(dt, e) { w.update(e.focus, dt); }, dispose() { w.dispose(); },
244
- // "is there water where I think": the global sea (its level and plane size; null = none, e.g. no water level) and each separate body
372
+ return { name: 'water', skipKind: 'none', type: 'picture', label: 'Water', params: WATER_PARAMS, options: opts, stage: 'environment', optional: ['sky', 'world'], install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.water': '水面' }, en: { 'module.water': 'water' } }); w = new Water(e, opts, ctx.track); return w; }, frame(dt, e) { w.update(e.focus, dt); }, dispose() { w.dispose(); },
245
373
  describe() {
246
374
  const r = v => Math.round(v * 10) / 10, s = w.sea;
247
375
  const bodies = [...w.bodies.keys()].map(b => ({ x: r(b.x), z: r(b.z), level: r(b.level), ...(b.radius ? { radius: r(b.radius) } : { size: [r(b.hw * 2), r(b.hd * 2)] }) }));
248
- return { sea: s ? { level: r(s.position.y + 0.2), size: w.st.size } : null, bodies };
376
+ return { sea: s ? { level: r(s.position.y + 0.2), size: w.st.size } : null, bodies, ripples: w.activeRipples };
249
377
  } };
250
378
  }
251
379
 
@@ -1,4 +1,4 @@
1
- // The water's shader code (recipes/44): the wave function, depth color, crest foam and a replaceable surface function, all set through
1
+ // The water's shader code (recipes/44): the wave function, interactive ripples, depth color, crest foam and a replaceable surface function, all set through
2
2
  // engine.water.shader({ wave, surface, depthColor, foam, uniforms }). With no depthColor / foam / surface function the surface patch is not
3
3
  // added at all, so plain water pays nothing.
4
4
  //
@@ -13,7 +13,7 @@ import { readParams, keysSchema } from '../../core/base/params.js';
13
13
  import { declareUniforms } from '../../render/uniformDecl.js';
14
14
  import { hashText } from '../../render/effects.js';
15
15
  import { codedError } from '../../core/base/errorHints.js';
16
- import { glslFloat as gf, WAVE as W, WAVE_MAX, DEPTH, FOAM } from '../../render/fxNumbers.js';
16
+ import { glslFloat as gf, WAVE as W, WAVE_MAX, DEPTH, FOAM, RIPPLE } from '../../render/fxNumbers.js';
17
17
 
18
18
  const DEPTH_KEYS = ['shallow', 'deep', 'by', 'curve'];
19
19
  const FOAM_KEYS = ['color', 'start', 'end', 'opacity'];
@@ -24,6 +24,17 @@ const WAVE = `float threedogWaterWave(vec3 p, float t) {
24
24
  return sin(p.x * ${gf(W.x[0])} + t * ${gf(W.x[1])}) * ${gf(W.x[2])} + cos(p.z * ${gf(W.z[0])} + t * ${gf(W.z[1])}) * ${gf(W.z[2])}
25
25
  + sin((p.x + p.z) * ${gf(W.xz[0])} + t * ${gf(W.xz[1])}) * ${gf(W.xz[2])}; }`;
26
26
 
27
+ const RIPPLE_DECL = `uniform float uRippleCount;
28
+ ${Array.from({ length: RIPPLE.slots }, (_, i) => `uniform vec4 uRipple${i};`).join(' ')}
29
+ float threedogWaterRipple(vec2 xz) {
30
+ if (uRippleCount < 0.5) return 0.0;
31
+ float sum = 0.0, d, env;
32
+ ${Array.from({ length: RIPPLE.slots }, (_, i) => `if (uRipple${i}.w > 0.001) { d = length(xz - uRipple${i}.xy) - uRipple${i}.z; env = clamp(1.0 - abs(d) * ${gf(1 / RIPPLE.width)}, 0.0, 1.0); sum += sin(d * ${gf(RIPPLE.freq)}) * env * env * uRipple${i}.w; }`).join('\n ')}
33
+ return sum;
34
+ }`;
35
+
36
+ export { RIPPLE_DECL };
37
+
27
38
  /**
28
39
  * Check and normalize what engine.water.shader takes (throws on wrong values with the fix)
29
40
  * @internal
@@ -44,36 +55,48 @@ export function waterShader(o) {
44
55
  return { wave: wave ?? WAVE, surface, waveMax: waveMax ?? WAVE_MAX, depth: d || null, foam: f || null, custom: declareUniforms('engine.water.shader uniforms', o.uniforms) };
45
56
  }
46
57
 
58
+ function emptyRipples() {
59
+ const out = { uRippleCount: { value: 0 } };
60
+ for (let i = 0; i < RIPPLE.slots; i++) out[`uRipple${i}`] = { value: new THREE.Vector4(0, 0, 0, 0) };
61
+ return out;
62
+ }
63
+
47
64
  /**
48
- * The 'waves' patch: moves the vertices by threedogWaterWave; with a surface it also hands the height and world position to the fragment.
65
+ * The 'waves' patch: moves the vertices by threedogWaterWave + interactive ripples; hands world xz (and with a surface, wave height + worldPos) to fragment.
49
66
  * tune: the { uWave, uWaveScale, uWaveSpeed } objects, the same ones across shader() rebuilds so a game's handle to them stays live
50
67
  * @internal
51
68
  */
52
- export function wavesPatch(e, tune, shader, surface) {
53
- const vary = surface ? 'varying float vThreedogWave; varying vec3 vThreedogWaterPos;' : '';
69
+ export function wavesPatch(e, tune, shader, surface, rippleUniforms = null) {
70
+ const rips = rippleUniforms ?? emptyRipples();
71
+ const vary = 'varying vec2 vThreedogRippleXZ;' + (surface ? ' varying float vThreedogWave; varying vec3 vThreedogWaterPos;' : '');
54
72
  return wavesTsl({ name: 'waves', cacheKey: hashText(shader.wave + shader.custom.decl + vary),
55
- uniforms: { uTime: e.uniforms.uTime, uWave: tune.uWave, uWaveScale: tune.uWaveScale, uWaveSpeed: tune.uWaveSpeed, ...shader.custom.uniforms },
56
- slot: 'position', pars: `uniform float uTime; uniform float uWave; uniform float uWaveScale; uniform float uWaveSpeed;\n${shader.custom.decl}\n${vary}\n${shader.wave}`, glsl: `
57
- vec3 wp = (modelMatrix * vec4(position, 1.0)).xyz * uWaveScale; float tw = uTime * uWaveSpeed;
73
+ uniforms: { uTime: e.uniforms.uTime, uWave: tune.uWave, uWaveScale: tune.uWaveScale, uWaveSpeed: tune.uWaveSpeed, ...rips, ...shader.custom.uniforms },
74
+ slot: 'position', pars: `uniform float uTime; uniform float uWave; uniform float uWaveScale; uniform float uWaveSpeed;\n${RIPPLE_DECL}\n${shader.custom.decl}\n${vary}\n${shader.wave}`, glsl: `
75
+ vec3 wp0 = (modelMatrix * vec4(position, 1.0)).xyz;
76
+ vec3 wp = wp0 * uWaveScale; float tw = uTime * uWaveSpeed;
58
77
  float threedogWave = threedogWaterWave(wp, tw);
59
- transformed.y += threedogWave * uWave;` + (surface ? `
60
- vThreedogWave = threedogWave; vThreedogWaterPos = (modelMatrix * vec4(transformed, 1.0)).xyz;` : '') }, shader, surface);
78
+ float threedogRip = threedogWaterRipple(wp0.xz);
79
+ transformed.y += threedogWave * uWave + threedogRip * ${gf(RIPPLE.lift)};
80
+ vThreedogRippleXZ = wp0.xz;` + (surface ? `
81
+ vThreedogWave = threedogWave + threedogRip * 0.2; vThreedogWaterPos = (modelMatrix * vec4(transformed, 1.0)).xyz;` : '') }, shader, surface);
61
82
  }
62
83
 
63
- // NodeMaterial side of the two patches. material -> { wave, pos }: the TSL twins of the varyings vThreedogWave / vThreedogWaterPos, which the
64
- // waves code makes and the waterSurface code reads (that is why waterSurface needs waves, on both sides). Kept per material because each
65
- // NodeMaterial builds its own nodes; WeakMap so a dropped material takes its entry with it.
66
- const WAVE_NODES = new WeakMap();
84
+ // NodeMaterial side of the patches. material -> { xz, wave?, pos? }: the TSL twins of the varyings vThreedogRippleXZ / vThreedogWave / vThreedogWaterPos.
85
+ // Kept per material because each NodeMaterial builds its own nodes; WeakMap so a dropped material takes its entry with it.
86
+ export const WAVE_NODES = new WeakMap();
67
87
  /** Add the tsl field to the waves patch: the built-in wave only (your own wave GLSL has no TSL twin: no tsl, so a NodeMaterial names the patch) */
68
88
  function wavesTsl(p, shader, surface) {
69
89
  if (shader.wave !== WAVE) return p;
70
90
  p.tsl = c => {
71
91
  const T = c.tsl, U = k => c.fx.patchUniform(p.uniforms[k]);
72
- // same inputs as the GLSL: world position of the undisplaced vertex * waveScale, time * waveSpeed
73
- const h = c.fx.waterWave(T.modelWorldMatrix.mul(T.vec4(T.positionGeometry, 1)).xyz.mul(U('uWaveScale')), U('uTime').mul(U('uWaveSpeed')));
74
- const out = c.position.add(T.vec3(0, h.mul(U('uWave')), 0));
75
- // varying(): computed per vertex and interpolated, as the GLSL varyings are (not recomputed per pixel)
76
- if (surface) WAVE_NODES.set(c.material, { wave: T.varying(h), pos: T.varying(T.modelWorldMatrix.mul(T.vec4(out, 1)).xyz) });
92
+ const wp0 = T.modelWorldMatrix.mul(T.vec4(T.positionGeometry, 1)).xyz;
93
+ const h = c.fx.waterWave(wp0.mul(U('uWaveScale')), U('uTime').mul(U('uWaveSpeed')));
94
+ const slots = Array.from({ length: RIPPLE.slots }, (_, i) => U(`uRipple${i}`));
95
+ const rip = c.fx.waterRipple(wp0.xz, U('uRippleCount'), slots);
96
+ const out = c.position.add(T.vec3(0, h.mul(U('uWave')).add(rip.mul(RIPPLE.lift)), 0));
97
+ const entry = { xz: T.varying(wp0.xz), wave: null, pos: null };
98
+ if (surface) { entry.wave = T.varying(h.add(rip.mul(0.2))); entry.pos = T.varying(T.modelWorldMatrix.mul(T.vec4(out, 1)).xyz); }
99
+ WAVE_NODES.set(c.material, entry);
77
100
  return out;
78
101
  };
79
102
  return p;
@@ -83,7 +106,7 @@ function surfaceTsl(p, shader) {
83
106
  if (shader.surface) return p;
84
107
  p.tsl = c => {
85
108
  const n = WAVE_NODES.get(c.material);
86
- if (!n) throw codedError('shader-patch', "waterSurface reads the wave height the 'waves' patch hands over; add waves before it (needs: waves)");
109
+ if (!n?.wave) throw codedError('shader-patch', "waterSurface reads the wave height the 'waves' patch hands over; add waves before it (needs: waves)");
87
110
  const T = c.tsl, U = k => c.fx.patchUniform(p.uniforms[k]), d = shader.depth;
88
111
  const fn = c.fx.waterSurface({ waveMax: shader.waveMax,
89
112
  depth: d && { shallow: U('uWaterShallow'), deep: U('uWaterDeep'), curve: U('uWaterCurve'), by: d.by },
@@ -35,12 +35,15 @@ export class WeatherDraw {
35
35
  /** Particle systems drawn now: field -> { field, object, material, uniforms, spec } (rain / snow when the table has them, plus fields engine.weather.defineField adds) @type {Map<string, any>} */
36
36
  this.systems = new Map();
37
37
  // zero cost when unused: a table where nothing ever rains or snows builds no particle meshes
38
+ if (!isOptions(rain)) throw codedError('weather-option', `weather({ rain }): expected an options object, got ${JSON.stringify(rain)}`);
39
+ if (!isOptions(snow)) throw codedError('weather-option', `weather({ snow }): expected an options object, got ${JSON.stringify(snow)}`);
38
40
  const { cover, ...snowGiven } = snow;
39
41
  /** @internal what weather({ rain, snow }) gave: defineField(field, null) goes back to it */ this._given = { rain, snow: snowGiven };
40
42
  for (const k of Object.keys(BASE)) if (this._used(k)) this._build(k, this._given[k], BASE[k]);
41
43
  // snow cover: foliage / ground season tint moves toward the snow colors as current.snow rises (ground.cover)
42
44
  if (cover !== undefined) {
43
- if (isOptions(cover)) readParams('weather({ snow: { cover } })', keysSchema(['foliage', 'ground', 'strength']), cover);
45
+ if (!isOptions(cover)) throw codedError('weather-option', "weather({ snow: { cover } }) needs a color for foliage and / or ground, e.g. cover: { foliage: 0xf2f4f6, ground: 0xeef0f2, strength: 0.8 }");
46
+ readParams('weather({ snow: { cover } })', keysSchema(['foliage', 'ground', 'strength']), cover);
44
47
  if (cover.foliage == null && cover.ground == null) throw codedError('weather-option', "weather({ snow: { cover } }) needs a color for foliage and / or ground, e.g. cover: { foliage: 0xf2f4f6, ground: 0xeef0f2, strength: 0.8 }");
45
48
  /** @internal */ this._cover = { strength: cover.strength ?? 0.8 };
46
49
  /** @internal */ this._coverMod = { foliage: cover.foliage ?? null, ground: cover.ground ?? null, amount: 0 };
@@ -14,6 +14,7 @@ import { Sim } from './sim.js';
14
14
  import { initState, mixInternals } from './state.js';
15
15
  import { putPos, centerOf } from './pos.js';
16
16
  import { codedError } from '../../core/base/errorHints.js';
17
+ import { addDirtyWatcher } from '../../core/stream/dirtyWatch.js';
17
18
 
18
19
  const STRINGS = {
19
20
  anchor: 'world.anchor must be null, an Object3D, a Vector3 / { x, z } or [x, y, z]; got {got}',
@@ -48,6 +49,7 @@ export class World {
48
49
  this.buildPerFrame = buildPerFrame;
49
50
  /** @internal */ this._v = new Views(this);
50
51
  /** @internal */ this._s = new Sim(this);
52
+ /** @internal */ this._watchers = null;
51
53
  }
52
54
 
53
55
  /**
@@ -135,7 +137,7 @@ export class World {
135
137
  * @returns {void}
136
138
  */
137
139
  move(id, position) {
138
- DEV && this.engine.ops.guard('world.move');
140
+ DEV && this.engine.ops.guardClientAllowed('world.move');
139
141
  const rec = this._need(id, 'move'), live = this._character(rec), to = live ? { ...live.root.position } : rec.position;
140
142
  putPos(`world.move("${id}")`, position, to);
141
143
  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
@@ -252,8 +254,25 @@ export class World {
252
254
  * @returns {{ remove(): void }}
253
255
  * @experimental
254
256
  */
255
- 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
257
+ pauseSimulation() {
258
+ const s = this._s;
259
+ let active = true;
260
+ s._pauses = (s._pauses ?? 0) + 1;
261
+ if (s._pauses === 1) s.fixed = () => {};
262
+ return { remove: () => {
263
+ if (!active) return;
264
+ active = false;
265
+ if (--s._pauses > 0) return;
266
+ delete s.fixed;
267
+ for (const e of s.ents.values()) e.ch = e.mark = undefined;
268
+ } };
269
+ } // channels kept moving: no stretch of the pause is owed
256
270
  /** Number of fixed steps simulated @experimental */ get steps() { return this._s.n; }
271
+ /**
272
+ * @internal Subscribe to record mutations for incremental sync (zero overhead when unwatched)
273
+ * @returns {{ dirty: Set<string>, all: boolean, remove(): void }}
274
+ */
275
+ trackDirty() { return addDirtyWatcher(this); }
257
276
  }
258
277
 
259
278
  /**
@@ -33,6 +33,11 @@ const WORLD_PARAMS = keysSchema(['cellSize', 'radius', 'farEvery', 'farMaxPerTic
33
33
  * World data module: installed as engine.world. Put things here that must be saved, survive level changes and keep changing while far away; models are only built while nearby
34
34
  * @example engine.use(world())
35
35
  * @param {{ cellSize?: number, radius?: number, farEvery?: number, farMaxPerTick?: number, buildPerFrame?: number }} [opts]
36
+ * cellSize: spatial hash cell size in meters (default 32);
37
+ * radius: distance in meters around the stream source for presenting models and running near simulation (default 60);
38
+ * farEvery: seconds between far-record simulation ticks (default 1);
39
+ * farMaxPerTick: maximum far records updated per simulation tick (default 128);
40
+ * buildPerFrame: maximum new view models built per frame (default 4).
36
41
  * @returns {import('../../types/core').ModuleDef<World>}
37
42
  */
38
43
  export function world(opts = {}) {
@@ -209,6 +209,7 @@ export function loadWorld(w, d) {
209
209
  for (const [id, base] of w._base) if (!w._removed.has(id)) w._insert(w._fromBase(id, base));
210
210
  for (const [id, r] of Object.entries(d?.records || {})) w._insert({ id, ...r });
211
211
  if (built) w._v.keepSame(built);
212
+ w._touchAll();
212
213
  w._recordsLoaded({ count: w.records.size }); // ctx.things.recordsLoaded: the modules' worldLoad step, then 'world:load' (core/saves/session.js step 2)
213
214
  }
214
215
 
@@ -53,7 +53,7 @@ function repose(w, have, base, rec) {
53
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 && sameRot(have.rot, base.rot)) { if (rec.rot === undefined) delete have.rot; else have.rot = structuredClone(rec.rot); }
56
+ if (have && sameRot(have.rot, base.rot)) { if (rec.rot === undefined) delete have.rot; else have.rot = structuredClone(rec.rot); w._touch(have.id); }
57
57
  Object.assign(base.position, rec.position);
58
58
  if (rec.rot === undefined) delete base.rot; else base.rot = structuredClone(rec.rot);
59
59
  }
@@ -87,6 +87,7 @@ export function setRecord(w, id, patch) {
87
87
  if (live) { live.takePose(rest); delete rest.rot; }
88
88
  Object.assign(rec, rest);
89
89
  if (position) w.move(id, position);
90
+ w._touch(id);
90
91
  if (w._v.presenters.get(rec.kind)?.show) w._v.dirty = true;
91
92
  w.engine.events.emit('world:change', { id, kind: rec.kind, keys: Object.keys(patch) });
92
93
  return rec;
@@ -101,6 +102,7 @@ export function removeRecord(w, id) {
101
102
  w._s.removed(id);
102
103
  w._unsaved.delete(id);
103
104
  if (w._base.has(id)) w._removed.add(id); else w._origin.delete(id);
105
+ w._touch(id);
104
106
  w.engine.events.emit('world:remove', { id, kind: rec.kind });
105
107
  }
106
108
 
@@ -206,13 +206,14 @@ export class Sim {
206
206
  if (s.far) s.far(rec, lived - d);
207
207
  }
208
208
  s.near(rec, d, this.w.view(rec.id));
209
+ this.w._touch(rec.id);
209
210
  }
210
211
  farOne(e, s, now) {
211
212
  const dt = now - e.last;
212
213
  if (dt <= 0) { e.last = now; return 0; } // added during this step
213
214
  const d = this.settle(e, s, dt);
214
215
  e.last = now;
215
- if (s.pure) this.flights.add(e, s, dt, d); else s.far(e.rec, d);
216
+ if (s.pure) this.flights.add(e, s, dt, d); else { s.far(e.rec, d); this.w._touch(e.rec.id); }
216
217
  return 1;
217
218
  }
218
219
  /** engine.skip: move simulation time without stepping; on the last segment (done) every record with far catches up what it owes in one far(rec, dt), in id order.
@@ -229,7 +230,7 @@ export class Sim {
229
230
  if (owed <= 0) { e.last = now; continue; }
230
231
  const d = this.settle(e, s, owed);
231
232
  e.last = now;
232
- if (s.pure) this.flights.now(e, s, d); else s.far(e.rec, d);
233
+ if (s.pure) this.flights.now(e, s, d); else { s.far(e.rec, d); this.w._touch(e.rec.id); }
233
234
  }
234
235
  }
235
236
  rebucket(K, P) {
@@ -74,10 +74,12 @@ export class FarFlights {
74
74
  e.flight = null;
75
75
  if (e.dead) return;
76
76
  const rec = e.rec, snap = f.snaps[i][0];
77
+ let touched = false;
77
78
  for (const k in res) {
78
79
  if (k === 'id' || k === 'kind' || same(res[k], snap[k])) continue;
79
- if (k === 'position') this.sim.w.move(rec.id, res.position); else rec[k] = res[k];
80
+ if (k === 'position') this.sim.w.move(rec.id, res.position); else { rec[k] = res[k]; touched = true; }
80
81
  }
81
- for (const k in snap) if (!(k in res)) delete rec[k];
82
+ for (const k in snap) if (!(k in res)) { delete rec[k]; touched = true; }
83
+ if (touched) this.sim.w._touch(rec.id);
82
84
  }
83
85
  }
@@ -7,6 +7,7 @@ import { saveWorld, loadWorld, renamePending, isPlain } from './persist.js';
7
7
  import { Cells } from '../../core/stream/cells.js';
8
8
  import { centerOf } from './pos.js';
9
9
  import { codedError } from '../../core/base/errorHints.js';
10
+ import { touchDirty, touchDirtyAll } from '../../core/stream/dirtyWatch.js';
10
11
 
11
12
  export function initState(w, cellSize) {
12
13
  /** @internal */ w._anchor = null;
@@ -84,6 +85,7 @@ class Internals {
84
85
  for (const k of Object.keys(r)) if (k !== 'position' && !(k in fields)) delete r[k];
85
86
  Object.assign(r, fields); Object.assign(r.position, position); this._index(r);
86
87
  }
88
+ this._touchAll();
87
89
  };
88
90
  }
89
91
  /** @internal Whether id is an authored (content) record, removed or not: thing.remove's undo puts such a record back without a world.add */
@@ -137,7 +139,11 @@ class Internals {
137
139
  return rec;
138
140
  }
139
141
  /** Position changed: update the cell; if it crosses the build / teardown distance, make the presentation layer refresh next frame @internal */
140
- _index(rec) { this._cells.put(rec); this._v.track(rec); }
142
+ _index(rec) { this._cells.put(rec); this._v.track(rec); this._touch(rec.id); }
143
+ /** Mark one record id as dirty for active watchers (zero cost when unwatched) @internal */
144
+ _touch(id) { touchDirty(this, id); }
145
+ /** Mark all records for full reconciliation on active watchers @internal */
146
+ _touchAll() { touchDirtyAll(this); }
141
147
  }
142
148
 
143
149
  /** Copy the internal methods onto World.prototype (getters stay getters) */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "threedog",
3
- "version": "2.2.0",
4
- "description": "Web 3D game engine on three.js, built to be driven by an AI. Start: npm install threedog three && npm install -D @threedog/tools && npx threedog init (writes the game and its CLAUDE.md). No built-in art",
3
+ "version": "2.3.0",
4
+ "description": "Web 3D game engine on three.js, built to be driven by an AI. Start: npm install threedog three && npm install -D @threedog/tools && npx threedog init (writes the game, AGENTS.md and CLAUDE.md). No built-in art",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",