threedog 2.2.2 → 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 (194) hide show
  1. package/CHANGELOG.md +20 -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 +22 -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 +371 -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/gameLights.js +19 -11
  44. package/core/scene/sceneDelta.js +8 -4
  45. package/core/stream/chunkStream.js +21 -0
  46. package/core/stream/dirtyWatch.js +37 -0
  47. package/core/time/skip.js +9 -6
  48. package/core/time/time.js +72 -18
  49. package/docs/AI.md +22 -21
  50. package/docs/API.md +5 -4
  51. package/docs/CODEMAP.md +16 -10
  52. package/docs/COMMANDS.md +5 -5
  53. package/docs/CONVENTIONS.md +9 -25
  54. package/docs/api/ambience.md +1 -0
  55. package/docs/api/assets.md +10 -3
  56. package/docs/api/audio.md +5 -3
  57. package/docs/api/decals.md +16 -0
  58. package/docs/api/engine.md +1 -0
  59. package/docs/api/tools.md +3 -1
  60. package/docs/api/water.md +3 -0
  61. package/docs/recipes/09-materials-lights-models.md +15 -1
  62. package/docs/recipes/13-animation.md +51 -10
  63. package/docs/recipes/16-dev-bridge.md +1 -1
  64. package/docs/recipes/31-audio.md +15 -9
  65. package/docs/recipes/34-environment-lighting.md +11 -1
  66. package/docs/recipes/44-water-weather-hooks.md +1 -0
  67. package/examples/action/.threedog/content-index.json +1 -0
  68. package/examples/perf-island/.threedog/content-index.json +1 -0
  69. package/examples/plain-picture/.threedog/content-index.json +1 -0
  70. package/examples/rc2d/.threedog/content-index.json +1 -0
  71. package/examples/styletest/.threedog/content-index.json +1 -0
  72. package/examples/techniques/outlines-and-rim/main.js +1 -1
  73. package/examples/techniques/procedural-surface/main.js +1 -1
  74. package/examples/techniques/stylized-shading/main.js +1 -1
  75. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  76. package/examples/world/.threedog/content-index.json +1 -0
  77. package/index.d.ts +6 -2
  78. package/index.js +3 -2
  79. package/llms.txt +11 -10
  80. package/modules/ambience/Ambience.js +97 -15
  81. package/modules/camera/common.js +18 -12
  82. package/modules/characters/Character.js +30 -3
  83. package/modules/characters/NPC.js +2 -5
  84. package/modules/characters/astar.js +45 -14
  85. package/modules/characters/movers/rapier.js +53 -41
  86. package/modules/characters/movers/simple.js +37 -24
  87. package/modules/characters/npcView.js +2 -2
  88. package/modules/characters/pathAsync.js +3 -3
  89. package/modules/collision/contract.js +2 -2
  90. package/modules/content/index.js +3 -0
  91. package/modules/content/models.js +11 -4
  92. package/modules/content/templates.js +11 -11
  93. package/modules/debug/DebugPanel.js +1 -0
  94. package/modules/decals/Decals.js +393 -0
  95. package/modules/decals/index.js +1 -0
  96. package/modules/gameplay/Container.js +2 -0
  97. package/modules/gameplay/Containers.js +17 -3
  98. package/modules/gameplay/Dialogue.js +1 -1
  99. package/modules/gameplay/Interactions.js +7 -6
  100. package/modules/gameplay/Inventory.js +5 -1
  101. package/modules/gameplay/Quests.js +4 -3
  102. package/modules/gameplay/inventoryOps.js +2 -2
  103. package/modules/gameplay/pickups.js +32 -12
  104. package/modules/gameplay/questSave.js +2 -2
  105. package/modules/grid/index.js +8 -2
  106. package/modules/hud/index.js +1 -1
  107. package/modules/level/heightfield.js +1 -0
  108. package/modules/level/index.js +3 -2
  109. package/modules/level/nodes.js +2 -1
  110. package/modules/lights/index.js +27 -4
  111. package/modules/lights/slots.js +33 -16
  112. package/modules/nav/contract.js +4 -4
  113. package/modules/nav/index.js +6 -2
  114. package/modules/net/Client.js +24 -11
  115. package/modules/net/Host.js +73 -20
  116. package/modules/net/index.js +33 -21
  117. package/modules/net/sync.js +38 -8
  118. package/modules/net/transports.js +7 -3
  119. package/modules/particles/Particles.js +11 -4
  120. package/modules/particles/contract.js +6 -6
  121. package/modules/particles/effect.js +0 -1
  122. package/modules/rigid/RigidBodies.js +69 -57
  123. package/modules/rigid/Vehicles.js +8 -7
  124. package/modules/rigid/ragdoll.js +4 -6
  125. package/modules/rigid/rapierCompat.js +90 -0
  126. package/modules/rigid/sync.js +2 -5
  127. package/modules/settings/Settings.js +10 -4
  128. package/modules/sky/Sky.js +10 -2
  129. package/modules/sky/environment.js +29 -13
  130. package/modules/sky/frame.js +2 -2
  131. package/modules/sky/shader.js +5 -2
  132. package/modules/sky/skyModule.js +2 -2
  133. package/modules/swarm/Swarm.js +3 -2
  134. package/modules/swarm/grid.js +12 -7
  135. package/modules/terrain/ChunkManager.js +16 -26
  136. package/modules/triggers/index.js +5 -6
  137. package/modules/vegetation/draw.js +62 -26
  138. package/modules/vegetation/groundChunks.js +8 -22
  139. package/modules/water/Water.js +152 -24
  140. package/modules/water/surface.js +43 -20
  141. package/modules/weather/weatherDraw.js +4 -1
  142. package/modules/world/World.js +21 -2
  143. package/modules/world/index.js +5 -0
  144. package/modules/world/persist.js +1 -0
  145. package/modules/world/records.js +3 -1
  146. package/modules/world/sim.js +3 -2
  147. package/modules/world/simFar.js +4 -2
  148. package/modules/world/state.js +7 -1
  149. package/package.json +2 -2
  150. package/presets.js +30 -0
  151. package/render/PostFX.js +24 -17
  152. package/render/backend.js +72 -31
  153. package/render/cascades.js +25 -14
  154. package/render/cascades.tsl.js +32 -21
  155. package/render/fogLook.js +2 -1
  156. package/render/fx/library.tsl.js +1 -1
  157. package/render/fx/particles.tsl.js +4 -18
  158. package/render/fx/pcss.tsl.js +2 -2
  159. package/render/fx/postWebGPU.tsl.js +47 -25
  160. package/render/fx/sky.tsl.js +6 -18
  161. package/render/fx/uniforms.tsl.js +16 -0
  162. package/render/fx/water.tsl.js +24 -5
  163. package/render/fxNumbers.js +2 -0
  164. package/render/impostor.tsl.js +10 -6
  165. package/render/lights.js +6 -6
  166. package/render/occlusion.js +17 -6
  167. package/render/patches.js +40 -28
  168. package/render/postWebGL.js +6 -4
  169. package/render/reflectionProbes.js +302 -0
  170. package/render/shaderErrors.js +18 -8
  171. package/render/shadowCache.tsl.js +10 -5
  172. package/render/shadows.js +70 -49
  173. package/render/threeCompat.js +166 -0
  174. package/types/core.d.ts +33 -3
  175. package/types/gameplay.d.ts +80 -0
  176. package/types/generated/core/audio/Audio.d.ts +18 -1
  177. package/types/generated/core/ops/Ops.d.ts +2 -1
  178. package/types/generated/core/ops/control.d.ts +7 -3
  179. package/types/generated/core/saves/session.d.ts +4 -1
  180. package/types/generated/modules/ambience/Ambience.d.ts +6 -0
  181. package/types/generated/modules/debug/DebugPanel.d.ts +1 -0
  182. package/types/generated/modules/grid/index.d.ts +27 -3
  183. package/types/generated/modules/net/index.d.ts +8 -3
  184. package/types/generated/modules/sky/Sky.d.ts +1 -0
  185. package/types/generated/modules/water/Water.d.ts +15 -0
  186. package/types/generated/modules/world/index.d.ts +5 -0
  187. package/types/generated/render/patches.d.ts +5 -0
  188. package/types/physics.d.ts +66 -9
  189. package/types/tsl.d.ts +2 -0
  190. package/types/world.d.ts +2 -0
  191. package/ui/Parts.js +3 -2
  192. package/docs/MIGRATING-0.7.md +0 -39
  193. package/docs/MIGRATING-0.8.md +0 -171
  194. package/modules/rigid/refresh.js +0 -10
@@ -20,18 +20,48 @@ export class NetHost {
20
20
  this.n = 0; // diff counter: a client that sees a gap asks for a snapshot
21
21
  this.base = new Map(); // shared baseline (sync.js)
22
22
  this.keys = null;
23
+ this.trackers = null; // incremental dirty-set watchers for world / containers (attached while peers > 0)
23
24
  this.steps = 0; this.lastSent = 0;
24
25
  this.stats = { in: 0, out: 0, rejected: 0, diffs: 0, snapshots: 0 };
25
- this.subs = [t.on('join', id => this.join(id)), t.on('leave', id => this.leave(id)), t.on('message', (m, from) => this.receive(m, from))];
26
+ const markAll = () => this._markAll();
27
+ this.subs = [
28
+ t.on('join', id => this.join(id)), t.on('leave', id => this.leave(id)), t.on('message', (m, from) => this.receive(m, from)),
29
+ e.events.on('state:replaced', markAll), e.events.on('op:rolledBack', markAll),
30
+ ];
26
31
  }
27
32
  send(msg, peer) { this.stats.out++; this.t.send(msg, peer.id); }
33
+ _startTrackers() {
34
+ if (this.trackers) return;
35
+ this.trackers = { world: this.e.world?.trackDirty?.() ?? null, containers: this.e.inventory?.trackDirty?.() ?? null };
36
+ }
37
+ _stopTrackers() {
38
+ if (!this.trackers) return;
39
+ this.trackers.world?.remove(); this.trackers.containers?.remove();
40
+ this.trackers = null;
41
+ }
42
+ _markAll() {
43
+ if (!this.trackers) return;
44
+ if (this.trackers.world) { this.trackers.world.all = true; this.trackers.world.dirty.clear(); }
45
+ if (this.trackers.containers) { this.trackers.containers.all = true; this.trackers.containers.dirty.clear(); }
46
+ }
47
+ flushDiff(exclude = null) {
48
+ this.keys ??= partKeys(this.e, this.o.sync);
49
+ const parts = diffParts(this.e, this.keys, this.base, this.trackers);
50
+ if (!parts) return false;
51
+ this.n++; this.stats.diffs++; this.lastSent = this.steps;
52
+ for (const p of this.peers.values()) if (p !== exclude) this.send({ t: 'd', n: this.n, tick: this.e.time.tick, parts }, p);
53
+ return true;
54
+ }
28
55
 
29
56
  join(id) {
30
- const e = this.e, o = this.o;
31
- const peer = { id, actor: o.actorFor(id), tokens: o.burst, results: [], posTick: e.time.tick };
57
+ const e = this.e, o = this.o, first = this.peers.size === 0;
58
+ if (first) this._startTrackers();
59
+ const peer = { id, actor: o.actorFor(id), tokens: o.burst, results: [], posTick: e.time.tick, needResync: false, lastResyncTick: null };
32
60
  this.peers.set(id, peer);
33
61
  e.ops.allow(() => o.join(e, peer)); // setting up the peer's avatar / bag is host bookkeeping, not a gameplay action
34
62
  e.events.emit('net:join', { peer: id, actor: peer.actor });
63
+ if (first) { this.base.clear(); this._markAll(); }
64
+ else this.flushDiff(peer); // broadcast pending changes (and the new peer's avatar/bag) to existing peers before the snapshot refreshes base
35
65
  this.snapshot(peer);
36
66
  }
37
67
  leave(id) {
@@ -40,9 +70,11 @@ export class NetHost {
40
70
  this.peers.delete(id);
41
71
  e.ops.allow(() => this.o.leave(e, peer));
42
72
  e.events.emit('net:leave', { peer: id, actor: peer.actor });
73
+ if (!this.peers.size) { this.base.clear(); this._stopTrackers(); }
43
74
  }
44
75
  snapshot(peer) {
45
76
  this.keys ??= partKeys(this.e, this.o.sync);
77
+ if (!this.base.size) diffParts(this.e, this.keys, this.base, this.trackers);
46
78
  this.stats.snapshots++;
47
79
  this.send({ t: 's', n: this.n, tick: this.e.time.tick, you: peer.actor, every: this.o.syncEvery, parts: snapshotParts(this.e, this.keys) }, peer);
48
80
  }
@@ -51,17 +83,20 @@ export class NetHost {
51
83
  const peer = this.peers.get(from);
52
84
  if (!peer || !m || typeof m !== 'object') return;
53
85
  this.stats.in++;
54
- // ops and positions change gameplay state, so they wait for the next fixed step (game logic only in fixed steps): run here, inside a network
55
- // callback, they landed between steps at a time set by the network, not by the tick (review 0.4 B). A resync only sends, so it answers now
86
+ // ops and positions wait for the next fixed step (game logic only in fixed steps); resync is coalesced and rate-limited in fixed()
56
87
  if (m.t === 'op' || m.t === 'p') this.inbox.push([m, from]);
57
- else if (m.t === 'resync') this.snapshot(peer);
88
+ else if (m.t === 'resync') peer.needResync = true;
58
89
  }
59
- /** @internal start of the fixed step: apply what arrived since the last one, in arrival order (a peer that left meanwhile is skipped) */
90
+ /** @internal start of the fixed step: apply what arrived since the last one, in arrival order (only the last position per peer; a peer that left meanwhile is skipped) */
60
91
  drain() {
61
92
  const box = this.inbox; this.inbox = [];
62
- for (const [m, from] of box) {
93
+ const lastPos = new Map();
94
+ for (let i = 0; i < box.length; i++) if (box[i][0].t === 'p') lastPos.set(box[i][1], i);
95
+ for (let i = 0; i < box.length; i++) {
96
+ const [m, from] = box[i];
63
97
  const peer = this.peers.get(from); if (!peer) continue;
64
- if (m.t === 'op') this.request(peer, m); else this.position(peer, m);
98
+ if (m.t === 'op') this.request(peer, m);
99
+ else if (lastPos.get(from) === i) this.position(peer, m);
65
100
  }
66
101
  }
67
102
 
@@ -97,31 +132,49 @@ export class NetHost {
97
132
  position(peer, m) {
98
133
  const e = this.e, rec = e.world?.get(peer.actor), p = m.p;
99
134
  if (!rec || !Array.isArray(p) || p.length !== 3 || !p.every(isNum)) return;
100
- const dt = Math.min(0.25, Math.max(STEP, (e.time.tick - peer.posTick) * STEP)); // idle time earns no long jump
135
+ const ticks = e.time.tick - peer.posTick;
136
+ if (ticks <= 0) return;
137
+ const dt = Math.min(0.25, ticks * STEP); // idle time earns no long jump
101
138
  peer.posTick = e.time.tick;
102
139
  const c = rec.position, dx = p[0] - c.x, dy = p[1] - c.y, dz = p[2] - c.z, d = Math.hypot(dx, dy, dz), max = this.o.maxSpeed * dt + 0.5;
103
140
  const k = d > max ? max / d : 1;
104
141
  e.ops.allow(() => {
105
142
  e.world.move(peer.actor, { x: c.x + dx * k, y: c.y + dy * k, z: c.z + dz * k });
106
- const f = m.f && typeof m.f === 'object' ? m.f : {};
107
- for (const key of this.o.avatarFields) if (key in f && plainScalar(f[key])) rec[key] = f[key];
143
+ const f = m.f && typeof m.f === 'object' ? m.f : null;
144
+ if (!f) return;
145
+ let patch = null;
146
+ for (const key of this.o.avatarFields) {
147
+ if (Object.hasOwn(f, key) && plainScalar(f[key]) && rec[key] !== f[key]) (patch ||= {})[key] = f[key];
148
+ }
149
+ if (patch) e.world.set(peer.actor, patch);
108
150
  });
109
151
  }
110
152
 
111
153
  fixed(dt) {
112
154
  const o = this.o;
113
155
  this.drain();
114
- for (const p of this.peers.values()) p.tokens = Math.min(o.burst, p.tokens + o.rate * dt);
156
+ if (!this.peers.size) return;
157
+ const cool = Math.max(30, o.syncEvery * 5);
158
+ for (const p of this.peers.values()) {
159
+ p.tokens = Math.min(o.burst, p.tokens + o.rate * dt);
160
+ if (p.needResync && (p.lastResyncTick == null || this.e.time.tick - p.lastResyncTick >= cool)) {
161
+ p.needResync = false;
162
+ p.lastResyncTick = this.e.time.tick;
163
+ this.snapshot(p);
164
+ }
165
+ }
115
166
  if (++this.steps % o.syncEvery) return;
116
- this.keys ??= partKeys(this.e, o.sync);
117
- const parts = diffParts(this.e, this.keys, this.base);
118
- if (parts) { this.n++; this.stats.diffs++; this.lastSent = this.steps; for (const p of this.peers.values()) this.send({ t: 'd', n: this.n, tick: this.e.time.tick, parts }, p); }
119
- else if (this.steps - this.lastSent >= o.keepAlive) { this.lastSent = this.steps; for (const p of this.peers.values()) this.send({ t: 'k', n: this.n }, p); } // lets a client notice a lost last diff
167
+ const sent = this.flushDiff();
168
+ if (!sent && this.steps - this.lastSent >= o.keepAlive) { this.lastSent = this.steps; for (const p of this.peers.values()) this.send({ t: 'k', n: this.n }, p); } // lets a client notice a lost last diff
120
169
  for (const p of this.peers.values()) { for (const r of p.results) this.send(r, p); p.results.length = 0; }
121
170
  }
122
- // close the transport as the client does: otherwise a webSocket host stays in the relay room after engine.dispose() (heartbeat still
123
- // running) and the other players never see the host leave
124
- dispose() { for (const s of this.subs) s.remove(); this.t.close?.(); }
171
+ // leave connected peers so their guest-* records are removed, then drop listeners and close the transport so other players see the host leave
172
+ dispose() {
173
+ for (const id of [...this.peers.keys()]) this.leave(id);
174
+ this._stopTrackers();
175
+ for (const s of this.subs) s.remove();
176
+ this.t.close?.();
177
+ }
125
178
  }
126
179
 
127
180
  /** op return values travel as plain data; anything else (a three.js object, a function) is dropped */
@@ -29,9 +29,14 @@ const NET_PARAMS = keysSchema(OPTS);
29
29
  * @param {{ role: 'host' | 'client', transport: any, sync?: 'auto' | string[], syncEvery?: number, keepAlive?: number, rate?: number, burst?: number, maxSpeed?: number, posEvery?: number,
30
30
  * actorFor?: (peerId: number) => string, actorFields?: string[], avatarFields?: string[], interpolate?: string[], avatar?: boolean,
31
31
  * onJoin?: (e: any, peer: { id: number, actor: string }) => void, onLeave?: (e: any, peer: { id: number, actor: string }) => void }} opts
32
- * sync: save parts to sync ('auto' = world, containers, vars and every other save part except random / level / rigid); syncEvery: steps between diffs (3 = 20/s);
33
- * rate / burst: op requests per second per peer and the burst allowance; actorFields: record fields holding actor ids (swapped like ids, default ['owner']);
34
- * avatarFields: own-avatar fields the client sends with its position; interpolate: record kinds that glide on clients (default ['player']).
32
+ * role: host (owns the game) or client (mirrors the host); transport: message transport such as webSocket(url) or fakeNetwork().connect();
33
+ * sync: save parts to sync (auto syncs world, containers, vars and other save parts except random, level and rigid); syncEvery: fixed steps between state diffs (default 3);
34
+ * keepAlive: fixed steps between idle heartbeat messages (default 60); rate / burst: per-peer op requests per second and burst allowance (default 20);
35
+ * maxSpeed: maximum avatar movement speed in m/s accepted from a client (default 15); posEvery: fixed steps between client position updates (default 3);
36
+ * actorFor: maps a numeric peer id to its actor id (default guest-<id>); actorFields: record fields holding actor ids to remap per peer (default owner);
37
+ * avatarFields: own-avatar record fields sent with client position updates; interpolate: record kinds smoothed on clients between diffs (default player);
38
+ * avatar: automatically create a player world record and bag per joining peer (default true);
39
+ * onJoin: host callback fired after a peer joins; onLeave: host callback fired before a peer leaves.
35
40
  * @returns {import('../../types/core').ModuleDef<Net>}
36
41
  * @example
37
42
  * // host
@@ -48,33 +53,40 @@ export function net(opts = {}) {
48
53
  readParams('net', NET_PARAMS, opts);
49
54
  if (opts.role !== 'host' && opts.role !== 'client') throw codedError('net-option', fmt(STRINGS.role, { got: String(JSON.stringify(opts.role)) }));
50
55
  if (!opts.transport) throw codedError('net-option', STRINGS.transport);
51
- const left = new Map(); // actor -> last position, so a peer that reconnects comes back where it left
52
56
  const o = {
53
57
  sync: 'auto', syncEvery: 3, keepAlive: 60, rate: 20, burst: 20, maxSpeed: 15, posEvery: 3,
54
58
  actorFor: id => 'guest-' + id, actorFields: ['owner'], avatarFields: ['facing', 'amount', 'grounded', 'swimming'], interpolate: ['player'], avatar: true,
55
59
  ...opts,
56
60
  };
57
- o.join = (e, peer) => {
58
- if (o.avatar && e.world && !e.world.get(peer.actor)) {
59
- const at = left.get(peer.actor) ?? e.world.get('player')?.position ?? { x: 0, y: 0, z: 0 };
60
- e.world.add({ id: peer.actor, kind: 'player', position: { ...at } }, { save: false });
61
- }
62
- // the peer drives its avatar: net holds its control slot for good (core/ops/control.js), so a host-side walkTo or cutscene on it is a
63
- // control-net error, not a fight with the peer's next position (the record leaving the world drops the hold)
64
- if (o.avatar && e.world?.get(peer.actor)) o.control.take(peer.actor, { owner: 'net', layer: 'net' });
65
- if (o.avatar && e.inventory) e.inventory.container(peer.actor);
66
- o.onJoin?.(e, { id: peer.id, actor: peer.actor });
67
- };
68
- o.leave = (e, peer) => {
69
- o.onLeave?.(e, { id: peer.id, actor: peer.actor });
70
- const rec = e.world?.get(peer.actor);
71
- if (o.avatar && rec) { left.set(peer.actor, { ...rec.position }); e.world.remove(peer.actor); } // the bag stays: a reconnect gets it back
72
- };
61
+ for (const k of ['syncEvery', 'keepAlive', 'rate', 'burst', 'maxSpeed', 'posEvery']) {
62
+ if (typeof o[k] !== 'number' || !Number.isFinite(o[k]) || o[k] <= 0) throw codedError('net-option', `net({ ${k} }): must be a positive number, got ${JSON.stringify(o[k])}`);
63
+ }
73
64
  let n = null;
74
65
  return {
75
66
  name: 'net', skipKind: 'none', type: 'net', params: NET_PARAMS, options: opts, label: 'Multiplayer', stage: 'late', optional: ['world', 'inventory'],
76
67
  // ctx.control: the holds on remote characters are the module's, so removing net hands them back
77
- install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.net': '联机' }, en: { 'module.net': 'multiplayer' } }); o.control = ctx.control; return (n = new Net(e, o)); },
68
+ install(e, ctx) {
69
+ e.i18n.add({ 'zh-CN': { 'module.net': '联机' }, en: { 'module.net': 'multiplayer' } });
70
+ const left = new Map(); // per-install: actor -> last position, so a peer that reconnects comes back where it left
71
+ const cfg = {
72
+ ...o, control: ctx.control,
73
+ join(eng, peer) {
74
+ if (o.avatar && eng.world && !eng.world.get(peer.actor)) {
75
+ const at = left.get(peer.actor) ?? eng.world.get('player')?.position ?? { x: 0, y: 0, z: 0 };
76
+ eng.world.add({ id: peer.actor, kind: 'player', position: { ...at } }, { save: false });
77
+ }
78
+ if (o.avatar && eng.world?.get(peer.actor)) cfg.control.take(peer.actor, { owner: 'net', layer: 'net' });
79
+ if (o.avatar && eng.inventory) eng.inventory.container(peer.actor);
80
+ o.onJoin?.(eng, { id: peer.id, actor: peer.actor });
81
+ },
82
+ leave(eng, peer) {
83
+ o.onLeave?.(eng, { id: peer.id, actor: peer.actor });
84
+ const rec = eng.world?.get(peer.actor);
85
+ if (o.avatar && rec) { left.set(peer.actor, { ...rec.position }); eng.world.remove(peer.actor); } // the bag stays: a reconnect gets it back
86
+ },
87
+ };
88
+ return (n = new Net(e, cfg));
89
+ },
78
90
  fixed(dt) { n._fixed(dt); },
79
91
  frame(dt) { n._frame(dt); },
80
92
  describe() { return { role: n.role, actor: n.actor, connected: n.connected, peers: n.peers.length, pending: n.pending.size }; },
@@ -34,16 +34,45 @@ function readPart(e, key) {
34
34
  }
35
35
 
36
36
  /** @internal host: entries of `parts` changed since `base` (Map key -> Map id -> json); updates base. Returns null when nothing changed */
37
- export function diffParts(e, keys, base) {
37
+ export function diffParts(e, keys, base, trackers = null) {
38
38
  let out = null;
39
39
  for (const key of keys) {
40
- const now = readPart(e, key), b = base.get(key) ?? base.set(key, new Map()).get(key);
40
+ const b = base.get(key) ?? base.set(key, new Map()).get(key);
41
+ const tr = trackers && (key === 'world' ? trackers.world : key === 'containers' ? trackers.containers : null);
42
+ if (tr && !tr.all) {
43
+ if (tr.dirty.size === 0) continue; // 0 allocation when nothing changed in this part
44
+ let set = null, del = null;
45
+ const recs = key === 'world' ? e.world.records : null;
46
+ for (const id of tr.dirty) {
47
+ const val = recs ? recs.get(id) : tr.read(id);
48
+ if (val === undefined) {
49
+ if (b.delete(id)) (del ||= []).push(id);
50
+ } else {
51
+ const j = JSON.stringify(val);
52
+ if (b.get(id) !== j) { b.set(id, j); (set ||= {})[id] = val; }
53
+ }
54
+ }
55
+ tr.dirty.clear();
56
+ if (set || del) (out ||= {})[key] = { set: set ?? undefined, del: del ?? undefined };
57
+ continue;
58
+ }
59
+ if (tr) { tr.all = false; tr.dirty.clear(); }
41
60
  let set = null, del = null;
42
- for (const id in now) {
43
- const j = JSON.stringify(now[id]);
44
- if (b.get(id) !== j) { b.set(id, j); (set ||= {})[id] = now[id]; }
61
+ if (key === 'world') {
62
+ const recs = e.world.records;
63
+ for (const [id, rec] of recs) {
64
+ const j = JSON.stringify(rec);
65
+ if (b.get(id) !== j) { b.set(id, j); (set ||= {})[id] = rec; }
66
+ }
67
+ for (const id of b.keys()) if (!recs.has(id)) { b.delete(id); (del ||= []).push(id); }
68
+ } else {
69
+ const now = readPart(e, key);
70
+ for (const id in now) {
71
+ const j = JSON.stringify(now[id]);
72
+ if (b.get(id) !== j) { b.set(id, j); (set ||= {})[id] = now[id]; }
73
+ }
74
+ for (const id of b.keys()) if (!(id in now)) { b.delete(id); (del ||= []).push(id); }
45
75
  }
46
- for (const id of b.keys()) if (!(id in now)) { b.delete(id); (del ||= []).push(id); }
47
76
  if (set || del) (out ||= {})[key] = { set: set ?? undefined, del: del ?? undefined };
48
77
  }
49
78
  return out;
@@ -68,7 +97,8 @@ export function idMap(me) {
68
97
  * Position changes of interpolated kinds go to `glide(id, to)` instead of moving now; the own avatar keeps its local position (the client drives its own movement).
69
98
  */
70
99
  export function applyPart(e, key, part, full, opts) {
71
- const set = full ? part : part.set ?? {}, del = full ? null : part.del ?? [], { toLocal } = opts;
100
+ if (!part || typeof part !== 'object') return;
101
+ const set = full ? part : (part.set && typeof part.set === 'object' ? part.set : {}), del = full ? null : (Array.isArray(part.del) ? part.del : []), { toLocal } = opts;
72
102
  if (key === 'world') return applyWorld(e, set, del, full, opts);
73
103
  if (key === 'containers') {
74
104
  const data = {};
@@ -109,7 +139,7 @@ function applyWorld(e, set, del, full, { toLocal, actorFields, avatarFields, smo
109
139
  if (changed) W.set(id, patch);
110
140
  if (own) continue; // own avatar: position stays local (this client drives its own movement)
111
141
  const p = have.position;
112
- if (p.x === position.x && p.y === position.y && p.z === position.z) continue;
142
+ if (!p || !position || (p.x === position.x && p.y === position.y && p.z === position.z)) continue;
113
143
  if (!full && smooth(have)) glide(id, position); else W.move(id, position);
114
144
  }
115
145
  }
@@ -88,8 +88,10 @@ export function fakeNetwork(opts = {}) {
88
88
  const copy = msg == null ? null : structuredClone(msg);
89
89
  const at = Math.max(clock() + W.latency + rand() * W.jitter, link.at);
90
90
  link.at = at;
91
- queue.push({ at, fn: () => { if (c && link === c.link && !c.cut) c.seen = clock(); fn(copy); } }); // seen: what the client received
92
- queue.sort((a, b) => a.at - b.at);
91
+ const item = { at, fn: () => { if (c && link === c.link && !c.cut) c.seen = clock(); fn(copy); } }; // seen: what the client received
92
+ let i = queue.length;
93
+ while (i > 0 && queue[i - 1].at > at) i--;
94
+ queue.splice(i, 0, item);
93
95
  if (!manual && !timer) timer = setTimeout(tick, Math.max(0, at - clock())); // wall-clock
94
96
  }
95
97
  // one heartbeat check: dead after MISSED intervals with nothing received, else ping once per interval
@@ -149,7 +151,9 @@ export function webSocket(url, { host = false, key, heartbeat = 2000, reconnect
149
151
  seen = performance.now(); // wall-clock
150
152
  s.onmessage = m => {
151
153
  seen = performance.now(); // wall-clock
152
- const d = JSON.parse(m.data);
154
+ let d;
155
+ try { d = JSON.parse(m.data); } catch { return; }
156
+ if (!d || typeof d !== 'object') return;
153
157
  if (d.pong) return;
154
158
  if (d.hello) { t.id = d.hello.id; t.key = d.hello.key ?? null; tries = 0; if (!host) ev.emit('open'); }
155
159
  else if (d.join != null) ev.emit('join', d.join);
@@ -69,6 +69,12 @@ const EMIT_PARAMS = { count: { type: 'number', default: 10, min: 0, desc: 'parti
69
69
  const ATTACH_PARAMS = { rate: { type: 'number', optional: true, min: 0, desc: 'particles per second (default: the effect rate)' },
70
70
  ratePerMeter: { type: 'number', optional: true, min: 0, desc: 'particles per meter moved (default: the effect ratePerMeter)' }, offset: 'any?', overrides: 'any?' };
71
71
  const _vs = new THREE.Vector2(); // canvas CSS size (particle point scale follows the canvas height, not the window)
72
+ /** Whether a material (or any material in a multi-material array) should be hidden from the opaque soft-particle depth prepass */
73
+ function skipsDepth(m) {
74
+ if (!Array.isArray(m)) return !m.depthWrite || m.transmission > 0;
75
+ for (let i = 0; i < m.length; i++) if (!m[i].depthWrite || m[i].transmission > 0) return true;
76
+ return false;
77
+ }
72
78
  /** @import { ModuleDef } from '../../types/core' */
73
79
  /** @import { Object3D, PositionLike } from '../../types/common' */
74
80
  /** @import { ParticleEffect, ParticleEmitter, ParticleOptions, ParticlesOptions } from '../../types/gameplay' */
@@ -211,12 +217,13 @@ export class Particles {
211
217
  */
212
218
  _sceneDepth(r, scene, camera) {
213
219
  const d = this._depth ??= { target: new THREE.WebGLRenderTarget(1, 1, { depthTexture: new THREE.DepthTexture(1, 1) }), frame: -1, camera: null,
214
- material: new THREE.MeshDepthMaterial({ colorWrite: false, side: THREE.DoubleSide }) };
220
+ material: new THREE.MeshDepthMaterial({ colorWrite: false, side: THREE.DoubleSide }), off: [] };
215
221
  if (d.frame === r.info.render.frame && d.camera === camera) return d.target.depthTexture;
216
- const size = r.getDrawingBufferSize(_vs), off = [];
222
+ const size = r.getDrawingBufferSize(_vs), off = d.off;
223
+ off.length = 0;
217
224
  d.target.setSize(size.x, size.y);
218
225
  // by layer, not visible: an opaque child of a transparent parent still counts
219
- scene.traverseVisible(o => { if (o.material && (o.isPoints || [o.material].flat().some(m => !m.depthWrite || m.transmission > 0))) { off.push(o, o.layers.mask); o.layers.disableAll(); } });
226
+ scene.traverseVisible(o => { if (o.material && (o.isPoints || skipsDepth(o.material))) { off.push(o, o.layers.mask); o.layers.disableAll(); } });
220
227
  // a throwing render must not leave the scene on the depth material with layers off (M11): the renderer and scene come back through the
221
228
  // engine's one borrow (render/backend.js), the layers of the objects switched off here are this pass's own to give back
222
229
  try {
@@ -225,7 +232,7 @@ export class Particles {
225
232
  r.state.buffers.depth.setMask(true); // the transparent pass left it off, and the clear needs it
226
233
  r.setRenderTarget(d.target); r.render(scene, camera);
227
234
  }, { scene });
228
- } finally { for (let i = 0; i < off.length; i += 2) off[i].layers.mask = off[i + 1]; }
235
+ } finally { for (let i = 0; i < off.length; i += 2) off[i].layers.mask = off[i + 1]; off.length = 0; }
229
236
  d.frame = r.info.render.frame; d.camera = camera;
230
237
  return d.target.depthTexture;
231
238
  }
@@ -3,15 +3,15 @@
3
3
  // particles are presentation, so a replacement only has to answer these calls.
4
4
  export default {
5
5
  name: 'particles',
6
- api: ['define', 'emit', 'attach', 'count'],
7
- ops: [],
8
- events: [],
9
- saves: {},
10
6
  describe: true,
7
+ api: ['define', 'emit', 'attach', 'count'],
11
8
  options: {},
9
+ saves: {},
12
10
  probe: {
13
- setup: [['define', 'spark', { max: 8 }], ['emit', 'spark', { x: 0, y: 0, z: 0 }, { count: 3 }]],
14
- emits: [],
15
11
  state: null,
12
+ emits: [],
13
+ setup: [['define', 'spark', { max: 8 }], ['emit', 'spark', { x: 0, y: 0, z: 0 }, { count: 3 }]],
16
14
  },
15
+ ops: [],
16
+ events: [],
17
17
  };
@@ -121,7 +121,6 @@ export class Effect {
121
121
  const u = this._own.uniforms;
122
122
  u.uDepth.value = sys._sceneDepth(r, scene, camera);
123
123
  r.getCurrentViewport(u.uDepthView.value); u.uClip.value.set(camera.near, camera.far);
124
- this._own.uniformsNeedUpdate = true;
125
124
  };
126
125
  this.points.frustumCulled = false; this.points.visible = false; this.points.renderOrder = 10;
127
126
  this.points.matrixAutoUpdate = false;