threedog 1.3.0 → 2.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 (117) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +13 -7
  3. package/bin/threedog.mjs +42 -0
  4. package/core/base/Events.js +7 -1
  5. package/core/base/errorCodes.js +1 -1
  6. package/core/base/events.generated.js +1 -0
  7. package/core/engine/Engine.js +2 -2
  8. package/core/engine/copies.js +1 -1
  9. package/core/engine/moduleTypes.js +1 -1
  10. package/core/engine/modules.js +19 -2
  11. package/core/engine/page.js +1 -0
  12. package/core/engine/services.js +2 -1
  13. package/core/engine/startup.js +4 -1
  14. package/core/inspect/InspectPerf.js +1 -1
  15. package/core/inspect/metadata.generated.js +33 -14
  16. package/core/ops/control.js +3 -3
  17. package/core/ops/holds.js +8 -3
  18. package/core/saves/saveApply.js +2 -2
  19. package/core/saves/session.js +20 -4
  20. package/core/scene/adaptive.js +2 -0
  21. package/core/scene/things.js +3 -2
  22. package/core/scene/tier.js +19 -2
  23. package/docs/AI.md +3 -3
  24. package/docs/CODEMAP.md +5 -5
  25. package/docs/COMMANDS.md +3 -2
  26. package/docs/CONVENTIONS.md +1 -0
  27. package/docs/THREE.md +1 -1
  28. package/docs/api/engine.md +5 -2
  29. package/docs/api/events.md +2 -1
  30. package/docs/api/particles.md +1 -1
  31. package/docs/api/pickups.md +1 -1
  32. package/docs/api/post.md +1 -1
  33. package/docs/api/rigid.md +1 -1
  34. package/docs/api/sky.md +1 -1
  35. package/docs/recipes/01-new-game.md +1 -1
  36. package/docs/recipes/03-items-pickups.md +1 -1
  37. package/docs/recipes/06-clock-events.md +3 -10
  38. package/docs/recipes/07-flow-scenes-pause.md +0 -1
  39. package/docs/recipes/10-blender-level.md +2 -2
  40. package/docs/recipes/{11-vehicles.md → 11-physics.md} +13 -5
  41. package/docs/recipes/12-navmesh.md +3 -3
  42. package/docs/recipes/14-custom-module.md +5 -4
  43. package/docs/recipes/20-content-actions-save.md +0 -1
  44. package/docs/recipes/21-camera.md +11 -1
  45. package/docs/recipes/27-net.md +1 -1
  46. package/docs/recipes/29-grid.md +1 -1
  47. package/docs/recipes/34-environment-lighting.md +5 -3
  48. package/docs/recipes/44-water-weather-hooks.md +1 -1
  49. package/docs/recipes/45-cascaded-shadows.md +6 -3
  50. package/docs/recipes/52-around-the-picture.md +6 -6
  51. package/docs/recipes/53-ground-up-close.md +2 -2
  52. package/docs/recipes/55-mods-time-wrap.md +3 -5
  53. package/docs/recipes/60-judge-the-picture.md +2 -2
  54. package/docs/recipes/62-picture-code.md +13 -17
  55. package/examples/action/GAMEMAP.md +4 -2
  56. package/examples/action/picture/lights.js +3 -2
  57. package/examples/perf-island/GAMEMAP.md +2 -1
  58. package/examples/perf-island/picture/lights.js +3 -2
  59. package/examples/styletest/GAMEMAP.md +2 -2
  60. package/examples/styletest/picture/env.js +1 -2
  61. package/examples/techniques/contact-shadows/README.md +1 -1
  62. package/examples/techniques/day-night-grade/picture/lights.js +3 -1
  63. package/examples/techniques/interior-light/picture/lights.js +4 -2
  64. package/examples/techniques/modular-building/picture/lights.js +3 -2
  65. package/examples/techniques/night-lights/picture/lights.js +3 -1
  66. package/examples/techniques/night-lights/picture/post.js +2 -2
  67. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -2
  68. package/examples/techniques/procedural-animation/picture/lights.js +3 -1
  69. package/examples/techniques/procedural-surface/picture/lights.js +3 -1
  70. package/examples/techniques/stylized-shading/picture/lights.js +3 -1
  71. package/examples/techniques/wet-road/picture/lights.js +3 -1
  72. package/examples/webgpu-tsl/GAMEMAP.md +4 -2
  73. package/examples/webgpu-tsl/picture/lights.js +3 -1
  74. package/examples/world/GAMEMAP.md +4 -3
  75. package/examples/world/picture/lights.js +3 -1
  76. package/examples/world/picture/post.js +2 -2
  77. package/llms.txt +33 -7
  78. package/modules/camera/common.js +22 -20
  79. package/modules/characters/Character.js +2 -2
  80. package/modules/characters/NPC.js +7 -8
  81. package/modules/characters/index.js +8 -8
  82. package/modules/characters/npcAvoid.js +2 -2
  83. package/modules/characters/player.js +10 -14
  84. package/modules/characters/playerStrings.js +1 -2
  85. package/modules/characters/seat.js +1 -1
  86. package/modules/content/index.js +2 -1
  87. package/modules/content/templates.js +3 -2
  88. package/modules/flow/index.js +5 -5
  89. package/modules/gameplay/Dialogue.js +1 -1
  90. package/modules/gameplay/Inventory.js +3 -3
  91. package/modules/gameplay/Quests.js +1 -0
  92. package/modules/gameplay/pickups.js +1 -1
  93. package/modules/gameplay/questLog.js +0 -1
  94. package/modules/grid/index.js +1 -1
  95. package/modules/hud/index.js +2 -2
  96. package/modules/level/index.js +1 -1
  97. package/modules/music/Music.js +1 -1
  98. package/modules/nav/index.js +1 -1
  99. package/modules/net/sync.js +1 -1
  100. package/modules/particles/Particles.js +13 -5
  101. package/modules/particles/effect.js +17 -3
  102. package/modules/rigid/RigidBodies.js +10 -9
  103. package/modules/rigid/sync.js +14 -0
  104. package/modules/sky/Sky.js +9 -4
  105. package/modules/sky/environment.js +4 -2
  106. package/modules/timeline/Timeline.js +1 -2
  107. package/modules/world/World.js +1 -0
  108. package/modules/world/index.js +1 -0
  109. package/modules/world/persist.js +1 -1
  110. package/package.json +6 -2
  111. package/render/PostFX.js +10 -5
  112. package/render/fx/postWebGPU.tsl.js +2 -1
  113. package/types/core.d.ts +14 -5
  114. package/types/gameplay.d.ts +1 -1
  115. package/types/generated/modules/sky/Sky.d.ts +4 -4
  116. package/types/generated/render/PostFX.d.ts +2 -2
  117. package/types/physics.d.ts +1 -1
@@ -25,7 +25,9 @@ import { warnOnce } from '../../core/base/validate.js';
25
25
 
26
26
  // the takeover calls the owned-camera warning quotes (core/ops/owned.js): takeCamera is the one explicit entry (its remove() gives the camera back);
27
27
  // back is the hand-back for a camera the engine yielded to a direct write (that takeover has no handle)
28
- const LEVELS = { manual: "const cam = engine.takeCamera('me') (cam.remove() gives it back)", back: "engine.autoView.manual('camera', false)" };
28
+ // set: the one additive path (screen shake, recoil, a bob): offset the drawn frame only, so the rig keeps driving and the owned check sees its own value
29
+ const LEVELS = { manual: "const cam = engine.takeCamera('me') (cam.remove() gives it back)", back: "engine.autoView.manual('camera', false)",
30
+ set: "for a shake or offset, add it inside engine.onRender and put the saved pose back in engine.onRender(fn, { when: 'after' }) (recipe 21 \"Screen shake\")" };
29
31
 
30
32
  /** True during a cutscene takeover, and updates engine.focus from the focus the owner supplied */
31
33
  function applyOverride(e) {
@@ -267,25 +269,6 @@ export function rigModule(kind, opts) {
267
269
  if (r.pitch !== undefined && r.kind === d.kind && Number.isFinite(d.pitch)) r.pitch = d.pitch;
268
270
  },
269
271
  });
270
- // a new playthrough (newGame / load) starts with the camera as installed (kind, distance, every option), placed at the player instead of flying across the map.
271
- // The same object, so a rig the game kept at boot stays the camera; its view is what the load just left on it (the part above, or a game part's load() writing the rig)
272
- ctx.track(e.events.on('session:start', () => {
273
- // a hold made by writing the camera has no handle and no one who will end it: it belonged to the playthrough that is over. A manual() hold is on purpose and stays
274
- if (owned.mode === 'yielded') owned.manual(false);
275
- // the view the load left is on the rig of the saved kind, and that may be a rig switched to at runtime (the cameraRig part above)
276
- const old = c, { yaw, pitch } = c.kind === kind ? c : home;
277
- old.onExit?.(); cache.clear();
278
- setProjection(e);
279
- setFov(e, fov0());
280
- const built = make(kind, opts);
281
- for (const k of Object.keys(home)) delete home[k];
282
- c = e.cameraRig = Object.assign(home, built, yaw !== undefined && { yaw, pitch });
283
- cache.set(kind, home);
284
- // follows the player only if the game asked (addPlayer({ cameraFollow })), through the seat the load put it in: the rig was rebuilt after that seat was taken
285
- const P = e.player, car = P?.cameraFollow ? P.vehicle : null;
286
- c.onEnter?.(false); c.follow(car ? car.object : P?.cameraFollow ? P.root : null, car?.camera); fresh = true;
287
- e.events.emit('camera:change', { kind, previous: old.kind }); // settings re-apply the player's sensitivity / fov to the rebuilt rig
288
- }));
289
272
  // a scenario put the player somewhere else (?at, ?pos): a rig that eases would open on a glide across the map; follow() puts it there at once
290
273
  ctx.track(e.events.on('state:placed', () => { if (c.target) { c.follow(c.target); fresh = true; } }));
291
274
  // The camera module places position / orientation every frame: a game that moves the camera directly takes it (the rig stops), warned once
@@ -302,6 +285,25 @@ export function rigModule(kind, opts) {
302
285
  RIG_OWNED.set(e, owned);
303
286
  return c;
304
287
  },
288
+ // a new playthrough (newGame / load) starts with the camera as installed (kind, distance, every option), placed at the player instead of flying across the map.
289
+ // The same object, so a rig the game kept at boot stays the camera; its view is what the load just left on it (the part above, or a game part's load() writing the rig)
290
+ sessionStart(e) {
291
+ // a hold made by writing the camera has no handle and no one who will end it: it belonged to the playthrough that is over. A manual() hold is on purpose and stays
292
+ if (owned.mode === 'yielded') owned.manual(false);
293
+ // the view the load left is on the rig of the saved kind, and that may be a rig switched to at runtime (the cameraRig part above)
294
+ const old = c, { yaw, pitch } = c.kind === kind ? c : home;
295
+ old.onExit?.(); cache.clear();
296
+ setProjection(e);
297
+ setFov(e, fov0());
298
+ const built = make(kind, opts);
299
+ for (const k of Object.keys(home)) delete home[k];
300
+ c = e.cameraRig = Object.assign(home, built, yaw !== undefined && { yaw, pitch });
301
+ cache.set(kind, home);
302
+ // follows the player only if the game asked (addPlayer({ cameraFollow })), through the seat the load put it in: the rig was rebuilt after that seat was taken
303
+ const P = e.player, car = P?.cameraFollow ? P.vehicle : null;
304
+ c.onEnter?.(false); c.follow(car ? car.object : P?.cameraFollow ? P.root : null, car?.camera); fresh = true;
305
+ e.events.emit('camera:change', { kind, previous: old.kind }); // settings re-apply the player's sensitivity / fov to the rebuilt rig
306
+ },
305
307
  frame(dt, e) {
306
308
  const over = !!e.cameraOverride;
307
309
  if (over !== was) { was = over; c.onOverride?.(over); }
@@ -220,7 +220,7 @@ export class Character {
220
220
  placeAt(position) {
221
221
  this.engine.control?.endTasks(this, 'placed');
222
222
  if (this.vehicle) this.exit({ force: true });
223
- else if (this.recordId && this.engine.world?.get(this.recordId)?.vehicle != null) this._writeSeat(null, null); // its record waited for a vehicle not built yet: the game put it elsewhere
223
+ else if (this.recordId && this.engine.world.get(this.recordId)?.vehicle != null) this._writeSeat(null, null); // its record waited for a vehicle not built yet: the game put it elsewhere
224
224
  return this._place(position);
225
225
  }
226
226
  /** @internal Put it there with no ending of its own: a link crossing, a step out of a vehicle */
@@ -374,7 +374,7 @@ export class Character {
374
374
  }
375
375
  /** Dispose this character completely: exit the vehicle first, release animation and mover, remove from the scene and dispose geometries and materials */
376
376
  dispose() {
377
- // a player made by addPlayer: its registry entry (st.players, keys, touch button, world:load listener) goes first, and calls this again with _release cleared
377
+ // a player made by addPlayer: its registry entry (st.players, keys, touch button, worldLoad entry) goes first, and calls this again with _release cleared
378
378
  if (this._release) { const r = this._release; this._release = null; r(); return; }
379
379
  this.disposed = true; // a model still loading by asset name is dropped on arrival
380
380
  this.engine.control?.endTasks(this, 'gone');
@@ -51,8 +51,6 @@ import { passesOf } from '../collision/grid.js';
51
51
  const STRINGS = {
52
52
  noInteract: 'NPC "{name}" has interact set, but the interactions() module is not installed: nothing can use it',
53
53
  badInteract: 'npcs.add(): interact is { op: \'npc.talk\' } or { label, op, args, radius } (op: the op name the interact key runs); got {got}',
54
- noWorld: 'NPCs need the world() module (facts live in engine.world): engine.use(world(), …, characters()); openWorld() already installs it. '
55
- + 'If you do not want NPCs, use characters({ npcs: false })',
56
54
  notNpc: 'npcs.add(): id "{id}" is already used by a "{kind}" in world; give this NPC a different id',
57
55
  sameName: 'npcs.add(): an NPC named "{name}" already exists (without id the name is the id, so the two would merge). '
58
56
  + 'Give each different NPC its own id, e.g. npcs.add({ id: "{name}_2", name: "{name}", … }); to update an existing NPC, add again with the same id',
@@ -145,10 +143,11 @@ export class NPCManager {
145
143
  /** @internal */ this._byName = new Set(); // NPCs added this run without id, using the name as id (two with one name would be one record)
146
144
  // on the event, not in remove(): world.remove(id) and thing.remove take NPCs too, and a later add of that id must not inherit the old model or trip the same-name check
147
145
  track(engine.events.on('world:remove', ({ id }) => { this._runtime.delete(id); this._handles.delete(id); this._byName.delete(id); }));
148
- // a load or new game is a new run, and it fires no world:remove: setup code adding the same names again is not a clash
149
- track(engine.events.on('world:load', () => this._byName.clear()));
150
146
  }
151
- get world() { const W = this.engine.world; if (!W) throw codedError('module-needs', STRINGS.noWorld); return W; }
147
+ /** @internal the characters module's worldLoad step: a load or new game is a new run, and it fires no world:remove, so setup code adding the
148
+ * same names again is not a clash; the avoidance index is stale too */
149
+ _worldLoad() { this._byName.clear(); this.avoid._worldLoad(); }
150
+ get world() { return this.engine.world; }
152
151
 
153
152
  /** Register the NPC model and simulation with world (called in characters init; add calls it first if npcs.add comes earlier)@internal */
154
153
  setup() {
@@ -326,7 +325,7 @@ export class NPCManager {
326
325
  }
327
326
  /** Find by id or name (id first) */
328
327
  get(idOrName) {
329
- const W = this.engine.world; if (!W) return undefined;
328
+ const W = this.engine.world;
330
329
  if (W.get(idOrName)?.kind === KIND) return this._handle(idOrName);
331
330
  for (const r of W.records.values()) if (r.kind === KIND && r.name === idOrName) return this._handle(r.id);
332
331
  return undefined;
@@ -334,11 +333,11 @@ export class NPCManager {
334
333
  /** All NPCs (kind 'npc' records in world, including far ones and those in other levels) */
335
334
  list() {
336
335
  const W = this.engine.world, out = [];
337
- if (W) for (const r of W.records.values()) if (r.kind === KIND) out.push(this._handle(r.id));
336
+ for (const r of W.records.values()) if (r.kind === KIND) out.push(this._handle(r.id));
338
337
  return out;
339
338
  }
340
339
  /** Current character model (Character) of an NPC; null if none */
341
- character(id) { const o = this.engine.world?.view(id); return (o && this._views.get(o)?.ch) || null; }
340
+ character(id) { const o = this.engine.world.view(id); return (o && this._views.get(o)?.ch) || null; }
342
341
 
343
342
  /** @internal */
344
343
  _handle(id) { let h = this._handles.get(id); if (!h) this._handles.set(id, h = new NPC(this, id)); return h; }
@@ -1,12 +1,11 @@
1
1
  // Characters module: player (keyboard/stick control, camera follow, footsteps, enter/exit vehicles) and NPCs (schedule, pathfinding, dialogue).
2
2
  // The pathfinding entry for game code is engine.characters.findPath: uses the navmesh if nav is installed and ready, else A* (astar.js is an internal fallback, not
3
3
  // exported).
4
- // NPC facts live in engine.world (kind 'npc'), the model is just a presentation when near (see the top of NPC.js): NPCs need world() installed (openWorld
5
- // already does).
4
+ // NPC facts live in engine.world (kind 'npc'), the model is just a presentation when near (see the top of NPC.js).
6
5
  // The player is also a world record (id / kind both 'player'): position, facing, motion state and current vehicle live in the record and are saved with world;
7
6
  // world splits near / far by it by default.
8
7
  // Only the mover changes the player's position (Character.move / placeAt / enter / exit), then writes back to the record; loading places the player back by the
9
- // record. So install world() before creating the player.
8
+ // record. Both are world records, so the module requires world(): use() says so at install, not addPlayer at runtime (openWorld() installs both).
10
9
  // Vehicles are used through an interface (the { object, speed, drive(), seatPosition(), exitPosition() } returned by rigid.addWheeled); rigid is not imported
11
10
  // here.
12
11
  import { Character } from './Character.js';
@@ -248,7 +247,7 @@ const NPC_CONTENT = {
248
247
  function describeCharacters(e, ctx, mgr) {
249
248
  // with a model report by the model (merged with interaction points and world's own report for the same object into one), without a model report by data
250
249
  // position
251
- for (const r of mgr && e.world ? e.world.query({ kind: 'npc', near: ctx.center, radius: ctx.radius, where: r => e.world.inZone(r) }) : []) {
250
+ for (const r of mgr ? e.world.query({ kind: 'npc', near: ctx.center, radius: ctx.radius, where: r => e.world.inZone(r) }) : []) {
252
251
  ctx.near(e.world.view(r.id) ?? r.position, { id: r.id, name: r.name, kind: 'npc', state: r.state });
253
252
  }
254
253
  if (ctx.out.player) Object.assign(ctx.out.player, { swimming: e.player.swimming, grounded: e.player.grounded, facing: Math.round(e.player.facing * 100) / 100,
@@ -265,7 +264,7 @@ export function characters(opts = {}) {
265
264
  return {
266
265
  // before rigid: the player's move this step is in the physics step that follows (as when control was an onFixed)
267
266
  content: { npcs: NPC_CONTENT },
268
- name: 'characters', skipKind: 'none', type: 'actor', provides: ['characters'], params: CHARACTERS_PARAMS, options: opts, label: 'Characters', before: ['rigid'], noSkip: 'fixed steps paths, control holders and riders, none of which a time jump moves; schedules read the calendar clock', optional: ['cameraRig', 'calendar', 'interactions', 'dialogue', 'nav', 'collision', 'rigid', 'world'],
267
+ name: 'characters', skipKind: 'none', type: 'actor', provides: ['characters'], params: CHARACTERS_PARAMS, options: opts, label: 'Characters', before: ['rigid'], noSkip: 'fixed steps paths, control holders and riders, none of which a time jump moves; schedules read the calendar clock', requires: ['world'], optional: ['cameraRig', 'calendar', 'interactions', 'dialogue', 'nav', 'collision', 'rigid'],
269
268
  install(e, ctx) {
270
269
  e.i18n.add(STRINGS); e.i18n.add({ 'zh-CN': { 'module.characters': '角色' }, en: { 'module.characters': 'characters' } });
271
270
  // move.* are defined at module install: doc examples call engine.mod('move.speed', …) in setup before creating a character, and relying on the first Character's definition would give unknown-name
@@ -282,15 +281,16 @@ export function characters(opts = {}) {
282
281
  listen(e, ctx, st);
283
282
  return charactersApi(e, st, animation);
284
283
  },
285
- // NPC simulation and animation are driven by world (simulate / present update); here we only register with world at start; without world, wait for the
286
- // first npcs.add and then report the error
287
- init(e) { if (st.mgr && e.world) st.mgr.setup(); },
284
+ // NPC simulation and animation are driven by world (simulate / present update); here we only register with world at start
285
+ init() { st.mgr?.setup(); },
288
286
  // player control runs here (stage late: after every early onFixed and the gameplay stages); then carry riders by what moved since their own step
289
287
  // (support.js): every platform mover of this step has run by now
290
288
  // control holders' steps (the player's input, game steps) run here too, in that order: one move per held character per step (core/ops/control.js)
291
289
  fixed(_dt, e) { st.paths.flush(); e.control.stepAll(); stepSeats(e); carryRiders(e, false); },
292
290
  // a timeline or frame code moved a platform: carry now, so the picture never shows a rider sinking into or floating above it
293
291
  frame(dt, e) { for (const p of st.players.values()) p.character.animate(dt); carryRiders(e, true); },
292
+ // world replaced wholesale (a load): NPC indexes first, then each player goes back to its record, in the order they were added
293
+ worldLoad() { st.mgr?._worldLoad(); for (const p of st.players.values()) p.worldLoad(); },
294
294
  describe(e, ctx) { describeCharacters(e, ctx, st.mgr); },
295
295
  // a player, a queued path and the control lookup all outlive install unless they are ended here; the player's record stays in world, as NPC records do
296
296
  dispose(e) {
@@ -53,9 +53,9 @@ export class NpcAvoid {
53
53
  shove(this._acc, own.x - o.position.x, own.z - o.position.z, Math.sqrt(d2), this._min, rec.id < o.id ? 1 : -1);
54
54
  };
55
55
  track(engine.events.on('world:remove', ({ id }) => { const s = this._start.get(id); if (s) { this._grid?.delete(s); this._filed.delete(s); this._start.delete(id); } }));
56
- // after load the simulation step count returns to the saved value, so the old index is stale
57
- track(engine.events.on('world:load', () => { this._start.clear(); this._filed.clear(); this._grid?.clear(); this._gridN = -1; }));
58
56
  }
57
+ /** @internal after a load the simulation step count returns to the saved value, so the old index is stale (NPCManager._worldLoad) */
58
+ _worldLoad() { this._start.clear(); this._filed.clear(); this._grid?.clear(); this._gridN = -1; }
59
59
 
60
60
  /**
61
61
  * Change settings: set(false) off, set(true) on, set({ radius, strength }) tune (pass only what changes; passing it means on). Read current values from on /
@@ -16,7 +16,6 @@ function checkOptions(e, st, opts) {
16
16
  const control = opts.control;
17
17
  if (control === undefined) throw codedError('player-control', DEV_STRINGS.noControl);
18
18
  if (!validControl(control)) throw codedError('player-control', fmt(DEV_STRINGS.badControl, { got: JSON.stringify(control) ?? String(control) }));
19
- if (!e.world) throw codedError('module-needs', DEV_STRINGS.noWorld);
20
19
  if (opts.input !== undefined && !e.input.seats.includes(opts.input)) throw codedError('input-seat', 'characters.addPlayer(): input is a seat from engine.input.seat({ pad, keys })');
21
20
  const id = opts.id ?? PLAYER;
22
21
  if (opts.input) for (const [other, q] of st.players) if (other !== id && q.input === opts.input) throw codedError('input-seat', `characters.addPlayer(): this seat already drives player '${other}'`);
@@ -63,18 +62,15 @@ function inputStep(e, api, p, control, input) {
63
62
  };
64
63
  }
65
64
 
66
- /** The listeners that keep the record and the player together; returns their handles */
65
+ /** What keeps the record and the player together when world is replaced wholesale: the characters module's worldLoad step calls it (index.js) */
67
66
  function watchRecord(e, W, p, id) {
68
67
  const begin = p.position.clone(), rest = p.saveMotion(); // a player made after start() is in no new-game state: this is how a new playthrough has it
69
- return [
70
- // loading: after world is replaced wholesale, place the player back by the record; if the save has no player record (saved before the player was
71
- // created), add one from the current state
72
- e.events.on('world:load', () => {
73
- const rec = W.get(id);
74
- if (rec) placeByRecord(e, p, rec, id);
75
- else { if (e.session.replacing) { if (p.vehicle) p.exit({ force: true }); p.root.position.copy(begin); p.loadMotion(rest); } W.add({ id, kind: PLAYER, position: p.position, vehicle: null }); p._store(); }
76
- }),
77
- ];
68
+ // place the player back by the record; if the save has no player record (saved before the player was created), add one from the current state
69
+ return () => {
70
+ const rec = W.get(id);
71
+ if (rec) placeByRecord(e, p, rec, id);
72
+ else { if (e.session.replacing) { if (p.vehicle) p.exit({ force: true }); p.root.position.copy(begin); p.loadMotion(rest); } W.add({ id, kind: PLAYER, position: p.position, vehicle: null }); p._store(); }
73
+ };
78
74
  }
79
75
 
80
76
  /**
@@ -102,17 +98,17 @@ export function addPlayer(e, api, st, opts) {
102
98
  if (first) e.player = p;
103
99
  if (p.cameraFollow && !p.vehicle) e.cameraRig?.follow(p.root);
104
100
  // in the map before control.take: the control lookup finds a held character by id through it
105
- const entry = { character: p, input, dispose: null };
101
+ const entry = { character: p, input, dispose: null, worldLoad: null };
106
102
  st.players.set(id, entry);
107
103
  p._release = () => entry.dispose(); // player.dispose() from the game is the same teardown as removePlayer
108
104
  if (input !== e.input) input.actor = id;
109
105
  const held = e.control.take(p, { owner: 'player-input', layer: 'base', step: inputStep(e, api, p, opts.control, input) });
110
106
  // what the keys ask of the pedal, while the keys are in charge: the seat reads it each step, so a holder above lets go of it (seat.js)
111
107
  p._pedal = () => { if (!held.active) return null; const a = input.autopilot || input.axis; return [a.y, a.x, input.down('brake') ? 1 : 0]; };
112
- const watching = watchRecord(e, W, p, id);
108
+ entry.worldLoad = watchRecord(e, W, p, id);
113
109
  // keepRecord: the module is going, not the player; its place stays in world for the next addPlayer
114
110
  entry.dispose = (keepRecord = false) => {
115
- st.players.delete(id); held.remove(); jump?.remove(); for (const h of watching) h.remove();
111
+ st.players.delete(id); held.remove(); jump?.remove();
116
112
  if (input.actor === id) input.actor = null;
117
113
  p.recordId = null; p._release = null; p.dispose(); if (!keepRecord) W.remove(id);
118
114
  if (e.player === p) e.player = st.players.values().next().value?.character ?? null; // the next player is the first now
@@ -6,8 +6,7 @@ const CONTROL_FIX = "pick how the player moves: addPlayer({ ...presets.player.th
6
6
  export const DEV_STRINGS = { noControl: 'characters.addPlayer(): no control given; ' + CONTROL_FIX,
7
7
  badControl: "characters.addPlayer(): control {got} is not a control; " + CONTROL_FIX + ". (A function returning null stands still; a game-driven move takes control, see recipe 57)",
8
8
  noFollow: "characters.addPlayer(): a camera module is installed but cameraFollow was not given, so the camera does not follow the player. " +
9
- 'Pass cameraFollow: true (presets.player.* do), or cameraFollow: false if the game aims the camera itself',
10
- noWorld: 'characters.addPlayer() needs world() installed first: the player is a record in world (position is saved, world splits near/far by it). Use engine.use(world(), …); openWorld() already installs it' };
9
+ 'Pass cameraFollow: true (presets.player.* do), or cameraFollow: false if the game aims the camera itself' };
11
10
  export const STRINGS = { 'zh-CN': { 'npc.talk': '和{name}说话', 'input.brake': '刹车' }, en: { 'npc.talk': 'Talk to {name}', 'input.brake': 'Brake' } };
12
11
 
13
12
  export const validControl = c => c === 'camera' || typeof c === 'function';
@@ -28,7 +28,7 @@ export function seatFromRecord(c, v, seat) {
28
28
  }
29
29
 
30
30
  /** The records that name this vehicle. A far NPC has no model, so only its record knows */
31
- const ridersOf = (e, v) => (v.id == null ? [] : e.world?.query({}).filter(r => r.vehicle === v.id) ?? []);
31
+ const ridersOf = (e, v) => (v.id == null ? [] : e.world.query({}).filter(r => r.vehicle === v.id));
32
32
 
33
33
  /** characters.addVehicle: join the registry, and seat the riders whose record is waiting for this id. A far NPC is seated by its next build (npcView.js). A vehicle gone for good answers those records too: nothing will come for them */
34
34
  export function addVehicle(e, v) {
@@ -25,7 +25,7 @@ import { missingText, warnOnce } from '../../core/base/validate.js';
25
25
  import { loadContent, checkRefs, BUILTIN_TESTS, BUILTIN_RUNS } from './loader.js';
26
26
  import { sectionsOf } from '../../core/base/sections.js';
27
27
  import { addProps, needWorld } from './props.js';
28
- import { templateOf, spawnTemplate, placeTemplate, defineTemplates } from './templates.js';
28
+ import { templateOf, spawnTemplate, placeTemplate, defineTemplates, templatesWorldLoad } from './templates.js';
29
29
  import { refit } from './models.js';
30
30
  import { holdProtos } from '../../core/assets/namedModel.js';
31
31
  import { packsOf } from './packs.js';
@@ -232,6 +232,7 @@ export function content() {
232
232
  st.checkOps = () => { if (e.ready) checkOps(e, st); };
233
233
  return api;
234
234
  },
235
+ worldLoad(e) { templatesWorldLoad(e, st); },
235
236
  isReady() { return api.ready; },
236
237
  // ?at=<place> / applyState({ at }): this module owns the names, core does the placing with what it gets back. An unknown name stops here: a picture of the
237
238
  // spawn point taken for "the pier" would look fine and be wrong
@@ -99,10 +99,11 @@ export function defineTemplates(e, api, st, defs) {
99
99
  if (d.stages || d.update) simulate(e, st, name);
100
100
  limitContainers(e, st, name);
101
101
  }
102
- // a save brings back runtime instances and their goods, but container limits are definition data: put them back from the template
103
- st.templateLoad ??= st.track(e.events.on('world:load', () => { for (const name of st.templates.keys()) limitContainers(e, st, name); }));
104
102
  }
105
103
 
104
+ /** The content module's worldLoad step: a save brings back runtime instances and their goods, but container limits are definition data: put them back from the template. @internal */
105
+ export function templatesWorldLoad(e, st) { for (const name of st.templates.keys()) limitContainers(e, st, name); }
106
+
106
107
  /** The definition of a template, or a dev error listing the known ones. @internal */
107
108
  export function templateOf(st, name) {
108
109
  const d = st.templates.get(name);
@@ -27,7 +27,7 @@ const FLOW_PARAMS = keysSchema(['start']);
27
27
  */
28
28
  export function flow(opts = {}) {
29
29
  readParams('flow', FLOW_PARAMS, opts);
30
- let e = null, sig = null, chain = Promise.resolve(), held = null, frozen = null, leaving = false, queued = null;
30
+ let e = null, sig = null, chain = Promise.resolve(), held = null, frozen = null, leaving = false, queued = null, before = null; // before: the state a playthrough ended in, for a failed replacement to go back to
31
31
  const states = new Map([['playing', {}], ['paused', { freeze: true, lockInput: true }]]);
32
32
  // turn freeze / input lock on or off for one state
33
33
  const hold = (def, on) => {
@@ -105,13 +105,13 @@ export function flow(opts = {}) {
105
105
  if (opts.start && opts.start !== 'playing') ctx.track(e.events.once('engine:ready', () => api.go(opts.start)));
106
106
  // a playthrough ends (engine.session): back to the start state, so its enter() runs again; a new one starts in 'playing'
107
107
  // a failed replacement keeps the old playthrough: back to the state it was in
108
- let before = null;
109
- // the state goes after every session:end listener: the start state may start things (a title track) that another listener of the same event ends (music stops there), and install order must not decide which won
110
- ctx.track(e.events.on('session:end', () => { before = api.state; queueMicrotask(() => { if (!sig.aborted) api.go(opts.start ?? 'playing'); }); }));
111
- ctx.track(e.events.on('session:start', () => api.go('playing')));
108
+ before = null;
112
109
  ctx.track(e.events.on('session:failed', ({ kind }) => { if (before && kind !== 'quick') api.go(before); })); // a quick load ended nothing here
113
110
  return api;
114
111
  },
112
+ // the state goes after the whole end step and its event: the start state may start things (a title track) that another module's sessionEnd or a game listener ends (music stops there)
113
+ sessionEnd() { before = api.state; queueMicrotask(() => { if (!sig.aborted) api.go(opts.start ?? 'playing'); }); },
114
+ sessionStart() { api.go('playing'); },
115
115
  // unloaded (unuse, replaces) in a state that stops the game: nothing else would ever end its freeze or input lock
116
116
  dispose() { frozen?.remove(); held?.remove(); frozen = held = null; },
117
117
  // ?play / applyState({ play }): leave the start state (a title) the way its Start button does; session:start then goes to 'playing'
@@ -312,7 +312,6 @@ export function dialogue(opts = {}) {
312
312
  // choice1..9 pick a choice by number: declared, never bound here (presets.bindings.dialogNumbers binds 1-9). Optional: the choice cursor
313
313
  // (basic menu keys + confirm) and clicks pick choices without them. Context 'dialog', so 1-9 stay free for hotbars outside a conversation
314
314
  for (let i = 1; i <= 9; i++) ctx.input.define('choice' + i, { context: 'dialog', label: 'dialogue.choice', optional: true });
315
- ctx.track(e.events.on('session:end', () => d._cancel())); // an open dialogue belongs to the playthrough that opened it
316
315
  ctx.ui.define('dialogue', dialogueBox);
317
316
  ctx.ui.define('dialogue.bubble', bubblePart, { multi: true });
318
317
  ctx.ops.define('dialogue.advance', {
@@ -332,6 +331,7 @@ export function dialogue(opts = {}) {
332
331
  return d;
333
332
  },
334
333
  frame(dt) { d.frame(dt); },
334
+ sessionEnd() { d._cancel(); }, // an open dialogue belongs to the playthrough that opened it
335
335
  // unloaded mid-conversation: the input context and focus entry are the conversation's, not tracked, and a say() Promise gets its end. Not on engine.dispose: waits stay pending there
336
336
  dispose(e) { if (!e.disposed) { d._bubbles.clear(); d._asks.clear(); d.end(); } },
337
337
  afterLoad() { if (!d.active?.duringLoad) d._cancel(); }, // a line open at a load belongs to the state thrown away; one a load opened stays
@@ -44,9 +44,6 @@ export class Inventory {
44
44
  if (engine.input.keysOf(action).length) track(engine.input.touchButton(action, 'inventory.action'));
45
45
  ctx.ui.define('inventory', inventoryWindow, { modal: { cancel: e => e.ui.close('inventory'), freeze: () => this.pauseGame, data: () => windowData(this) } });
46
46
  for (const ev of ['i18n:change', 'input:rebind']) track(engine.events.on(ev, () => this._refresh()));
47
- // a pack loaded after start() stays for the next playthrough with its props and definitions, and its start items with them
48
- track(engine.events.on('session:start', ({ kind }) => { if (kind === 'new') for (const d of this._lateStart) this.giveStart(d); }));
49
- track(engine.events.on('session:end', () => engine.ui.close('inventory'))); // it shows the playthrough that ended, and its freeze must not reach the next one
50
47
  // version 1 is the current shape; raise it with a migrate step when it changes. seq: the numbering of entry keys (sword#3); a save without it continues
51
48
  // after the highest key it holds
52
49
  ctx.saves.define('inventory', { atomic: true, version: 1, save: () => ({ seq: this._seq, items: this.home._save() }), load: d => {
@@ -247,6 +244,9 @@ export function inventory(opts = {}) {
247
244
  defineInventoryOps(e, ctx, inv);
248
245
  return inv;
249
246
  },
247
+ sessionEnd(e) { e.ui.close('inventory'); }, // it shows the playthrough that ended, and its freeze must not reach the next one
248
+ // a pack loaded after start() stays for the next playthrough with its props and definitions, and its start items with them
249
+ sessionStart(e, { kind }) { if (kind === 'new') for (const d of inv._lateStart) inv.giveStart(d); },
250
250
  frame(dt, e) { // the inventory key toggles the part; while open the part holds the input lock, so the close press is read raw
251
251
  const open = e.ui.isOpen('inventory');
252
252
  if (open ? e.input.pressedRaw(inv.action) : e.input.pressed(inv.action)) { if (open) e.ui.close('inventory'); else e.ui.open('inventory'); }
@@ -326,6 +326,7 @@ export function quests(opts = {}) {
326
326
  name: 'quests', skipKind: 'approx', type: 'rules', provides: ['quests'], label: 'Quests', params: QUEST_PARAMS, options: o,
327
327
  // o: the schema defaults are filled in, the class repeats none
328
328
  install(e, ctx) { q = new Quests(e, o, ctx); return q; },
329
+ sessionEnd() { q.win.toggle(false); }, // the log shows the playthrough that ended
329
330
  // Check quests in the fixed step (game time; not while frozen or flow is paused, so no rewards are granted while paused)
330
331
  fixed() { if (--q._t <= 0) { q._t = q._period; q.check(); } },
331
332
  // engine.skip: the countdown lands where stepping would have left it; conditions are checked once, on the last segment, if a check fell inside
@@ -62,7 +62,6 @@ export class Pickups {
62
62
  engine.i18n.add(STRINGS);
63
63
  // a record gone (taken without respawn, removed, not in a loaded save): its live parts are no longer needed for a rebuild
64
64
  track(engine.events.on('world:remove', ({ id, kind }) => { this._live.delete(id); dirty({ kind }); }));
65
- track(engine.events.on('world:load', () => { this._autoDirty = true; for (const id of this._live.keys()) if (!engine.world.get(id)) this._live.delete(id); }));
66
65
  present(this, track);
67
66
  }
68
67
 
@@ -364,6 +363,7 @@ export function pickups(opts = {}) {
364
363
  return pk;
365
364
  },
366
365
  fixed() { pk._auto(); },
366
+ worldLoad(e) { pk._autoDirty = true; for (const id of pk._live.keys()) if (!e.world.get(id)) pk._live.delete(id); }, // records not in the loaded world need no live parts
367
367
  describe(e, ctx) { // use the model if present (same object the interactions module reports, merged into one entry); far away only data
368
368
  const w = e.world;
369
369
  for (const r of w.query({ kind: 'pickup', near: ctx.center, radius: ctx.radius, where: r => r.until == null })) ctx.near(w.view(r.id) ?? r.position, { name: pk._name(r), kind: 'pickup', id: r.item ?? r.id });
@@ -44,7 +44,6 @@ export function questLogWindow(e, q, ctx) {
44
44
  /** @returns {QuestLogView} */
45
45
  const view = () => ({ title: e.t('quests.title'), key: e.input.label(q.action), quests: q.list(), close: () => e.ui.close(NAME) });
46
46
  ctx.ui.define(NAME, questLogPart, { modal: { cancel: eng => eng.ui.close(NAME), data: view } });
47
- track(e.events.on('session:end', () => e.ui.close(NAME))); // it shows the playthrough that ended
48
47
  const win = {
49
48
  get open() { return e.ui.isOpen(NAME); },
50
49
  toggle(on = !win.open) { if (on) e.ui.open(NAME); else e.ui.close(NAME); },
@@ -278,9 +278,9 @@ export function grids(opts = {}) {
278
278
  ctx.track(e.events.on('world:add', ({ id }) => G._reindex(id)));
279
279
  ctx.track(e.events.on('world:remove', ({ id }) => G._unindex(id)));
280
280
  ctx.track(e.events.on('world:change', ({ id, keys }) => { if (keys.includes('grid')) G._reindex(id); }));
281
- ctx.track(e.events.on('world:load', () => G._rebuild()));
282
281
  return G;
283
282
  },
283
+ worldLoad() { G._rebuild(); }, // the records were replaced wholesale (a load): index them again
284
284
  frame() { for (const t of G._tiles.values()) t.frame(); for (const p of G._previews) p.frame(); },
285
285
  explain: { grid: (e, q) => G._explain(q) },
286
286
  describe() { return G._describe(); },
@@ -211,11 +211,11 @@ export function hud(opts = {}) {
211
211
  e.i18n.add(STRINGS);
212
212
  defineHudParts(e, ctx, containers);
213
213
  for (const ev of ['quest:start', 'quest:step', 'quest:part', 'quest:done', 'quest:fail', 'state:replaced', 'op:rolledBack']) ctx.track(e.events.on(ev, syncQuests));
214
- // quest markers are derived from the quests save part: they belong to the old quests, and session:start / save:loaded rebuild them; session:failed too, the quests stayed
215
- ctx.track(e.events.on('session:end', () => { for (const m of quest.values()) m.remove(); quest.clear(); }));
216
214
  ctx.track(e.events.on('i18n:change', () => { for (const [id, it] of items) it.part?.update({ id, ...it.o }); }));
217
215
  return api;
218
216
  },
217
+ // quest markers are derived from the quests save part: they belong to the old quests, and session:start / save:loaded rebuild them; session:failed too, the quests stayed
218
+ sessionEnd() { for (const m of quest.values()) m.remove(); quest.clear(); },
219
219
  frame() {
220
220
  for (const m of api.markers) updateMarker(m);
221
221
  // input has no event for a device switch or bind(), so a hint compares its key text each frame and redraws only on a change. Not through item():
@@ -3,7 +3,7 @@
3
3
  // - collision: meshes named col_* (or userData.collider) become walls the character cannot cross; col_ meshes themselves are hidden
4
4
  // - markers: objects named spawn, spawn_*, npc_*, trigger_*, marker_* (usually Blender empties) have their positions recorded
5
5
  //
6
- // engine.use(collision(), rigid(), followCamera(), characters(), level({ url: '/models/town.glb' }), triggers());
6
+ // engine.use(world(), collision(), rigid(), followCamera(), characters(), level({ url: '/models/town.glb' }), triggers());
7
7
  // engine.events.on('level:loaded', ({ markers }) => {
8
8
  // const s = engine.level.spawn; // spawn point { x, y, z }
9
9
  // engine.characters.addPlayer({ spawn: { x: s.x, z: s.z } });
@@ -321,11 +321,11 @@ export function music(opts = {}) {
321
321
  name: 'music', skipKind: 'none', type: 'picture', params: MUSIC_PARAMS, options: opts, label: 'Music', optional: ['dialogue'], stage: 'audio',
322
322
  install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.music': '音乐' }, en: { 'module.music': 'music' } });
323
323
  m = new Music(e, opts, ctx.track);
324
- ctx.track(e.events.on('session:end', () => m.stop({ fade: 0 }))); // a playthrough ends: its music stops at once
325
324
  ctx.saves.define('music', { notAtomic: 'sound, which an atomic op leaves alone: side effects go in after', save: () => ({ override: m._override ?? null, intensity: m.intensity }), load: d => m._load(d) });
326
325
  return m;
327
326
  },
328
327
  frame(dt) { m.frame(dt); },
328
+ sessionEnd() { m.stop({ fade: 0 }); }, // a playthrough ends: its music stops at once
329
329
  dispose() { m._close(); }, // nothing would stop a looping track once the module is gone
330
330
  // the same state the tests read (music.state) plus why nothing may sound: audio still locked (ready false, the track waits in pending), rules on, ducked by dialogue
331
331
  describe() { return { ...m.state, ready: m.ready, ruled: m.ruled, ducked: !!m._duck, tracks: m.tracks.size }; },
@@ -1,5 +1,5 @@
1
1
  // Navmesh (Recast): generated after a level loads; engine.characters.findPath switches to it automatically (falls back to A* when not installed).
2
- // engine.use(level({ url }), collision(), characters(), nav({ agentRadius: 0.4 }));
2
+ // engine.use(level({ url }), world(), collision(), characters(), nav({ agentRadius: 0.4 }));
3
3
  // Once installed, engine.nav offers findPath(from, to) and the native objects navMesh / query / tileCache / crowd / helper.
4
4
  // version: +1 on every rebuild / unload. Native objects (crowd agents etc.) are destroyed on rebuild; code that cached them keeps the object and compares it (NPCs compare crowd): version counts per module, so a replaced nav can show the same number.
5
5
  //
@@ -9,7 +9,7 @@
9
9
  // at the wire (toLocal / toHost). Record fields that hold actor ids (owner...) are listed in net({ actorFields }) and swapped too.
10
10
 
11
11
  // random/level stay per machine; inventory is the home bag 'player', sent inside containers with every other bag; rigid (body velocities, for loads)
12
- // stays per machine too: each machine simulates its own physics, clients follow the host through world records (docs/recipes/11-vehicles.md, section 3)
12
+ // stays per machine too: each machine simulates its own physics, clients follow the host through world records (docs/recipes/11-physics.md, section 3)
13
13
  const SKIP = ['random', 'level', 'inventory', 'containers', 'world', 'vars', 'rigid'];
14
14
  const GENERIC = '=';
15
15
 
@@ -12,7 +12,7 @@
12
12
  // engine.particles.count('dust') // live particle count; no name = all
13
13
  //
14
14
  // Params (all optional; below are the neutral fallback values):
15
- // max 120 max particles alive at once (the default is 60 when engine.tier is 'low'; a number the game gives stands)
15
+ // max 120 max particles alive at once (the default is 60 while engine.tier is 'low' and follows a tier change; a number the game gives stands)
16
16
  // lifetime [1,2] seconds each particle lives (random range)
17
17
  // rate 10 particles per second by default for attach
18
18
  // speed [0.5,1.5] initial speed (m/s); direction [0,1,0] emit direction; spread 0.5 max angle off the direction (radians, pi = all directions)
@@ -50,6 +50,7 @@ import { isOptions, isUnder } from '../../core/base/util.js';
50
50
  import { codedError } from '../../core/base/errorHints.js';
51
51
  import { borrowRenderer } from '../../render/backend.js';
52
52
  import { ParticleLights } from './lit.js';
53
+ import { onTierChange } from '../../core/scene/tier.js';
53
54
  // one schema per public entry (unknown keys throw in dev with did-you-mean). Effect param values come in many shapes (number or [min, max], color), so most are only checked by key name
54
55
  const FX_PARAMS = keysSchema(KEYS, {}, {
55
56
  ratePerMeter: { type: 'number', optional: true, min: 0, desc: 'particles per meter the emitter moves' },
@@ -108,13 +109,20 @@ export class Particles {
108
109
  define(name, opts = {}) {
109
110
  readFx(`particles.define('${name}')`, opts);
110
111
  const old = this.effects.get(name);
111
- const o = { ...NEUTRAL, max: this.engine.tier === 'low' ? NEUTRAL.max / 2 : NEUTRAL.max, ...this._fallback, ...this._given[name], ...opts };
112
- const fx = new Effect(this, name, o);
112
+ const o = { ...NEUTRAL, max: this._tierMax(), ...this._fallback, ...this._given[name], ...opts };
113
+ // no max given anywhere: the default follows engine.tier (_tierChanged), so the buffers hold the high tier's count from the start
114
+ const follows = [this._fallback, this._given[name], opts].every(g => g?.max == null);
115
+ const fx = new Effect(this, name, o, follows ? NEUTRAL.max : undefined);
116
+ /** @internal */ fx._maxFollows = follows;
113
117
  this.effects.set(name, fx);
114
118
  // emitters attached to the old effect keep running on the new one (redefining tunes an effect, it does not stop it)
115
119
  if (old) { for (const h of this.emitters) if (h.fx === old) h.fx = fx; old.dispose(); }
116
120
  return fx;
117
121
  }
122
+ /** @internal the default max: half on a low-tier device */
123
+ _tierMax() { return this.engine.tier === 'low' ? NEUTRAL.max / 2 : NEUTRAL.max; }
124
+ /** @internal engine.tier changed (a preset, often a stored one arriving after the effects are defined): a default max follows it in place (Effect._resize); a max the game gave stays */
125
+ _tierChanged() { for (const fx of this.effects.values()) if (fx._maxFollows) fx._resize(this._tierMax()); }
118
126
  /**
119
127
  * Whether this effect has been defined
120
128
  * @param {string} name
@@ -174,7 +182,7 @@ export class Particles {
174
182
  * @param {string} [name]
175
183
  * @returns {void}
176
184
  */
177
- clear(name) { for (const fx of name ? [this.effects.get(name)].filter(Boolean) : this.effects.values()) { fx.life.fill(0); fx.aAlpha.array.fill(0); fx.alive = 0; fx._stale = fx.max; fx.points.visible = false; } }
185
+ clear(name) { for (const fx of name ? [this.effects.get(name)].filter(Boolean) : this.effects.values()) { fx.life.fill(0); fx.aAlpha.array.fill(0); fx.alive = 0; fx._stale = fx.cap; fx.points.visible = false; } }
178
186
 
179
187
  /** @internal Where the emitter is in the world (written into this._o) */
180
188
  _at(h) {
@@ -278,7 +286,7 @@ export function particles(opts = {}) {
278
286
  }
279
287
  if (opts.default) readFx('particles({ default })', opts.default);
280
288
  let p = null;
281
- return { name: 'particles', skipKind: 'none', type: 'picture', provides: ['particles'], label: 'Particles', params: PARTICLES_PARAMS, options: opts, stage: 'effects', install(e) { e.i18n.add({ 'zh-CN': { 'module.particles': '粒子' }, en: { 'module.particles': 'particles' } }); p = new Particles(e, opts); return p; }, frame(dt) { p.update(dt); },
289
+ return { name: 'particles', skipKind: 'none', type: 'picture', provides: ['particles'], label: 'Particles', params: PARTICLES_PARAMS, options: opts, stage: 'effects', install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.particles': '粒子' }, en: { 'module.particles': 'particles' } }); p = new Particles(e, opts); ctx.track(onTierChange(e, () => p._tierChanged())); return p; }, frame(dt) { p.update(dt); },
282
290
  dispose() { for (const fx of p.effects.values()) fx.dispose(); p.effects.clear(); p.emitters.clear(); p._depth?.target.depthTexture.dispose(); p._depth?.target.dispose(); p._depth?.material.dispose(); },
283
291
  counts() { return { alive: p.count(), emitters: p.emitters.size }; }, // engine.counts().particles
284
292
  // "did the dust burst fire": live particles in total and per effect that has any (idle effects left out to stay short). Kept under `alive`
@@ -48,9 +48,11 @@ function nodeSide(engine, name) {
48
48
  }
49
49
 
50
50
  export class Effect {
51
- constructor(sys, name, o) {
51
+ /** @param {any} sys @param {string} name @param {any} o @param {number} [cap] buffer slots, at least o.max: room for a default max that follows engine.tier (_resize) */
52
+ constructor(sys, name, o, cap) {
52
53
  this.sys = sys; this.name = name; this.o = o;
53
- const N = this.max = Math.max(1, Math.round(o.max));
54
+ const N = this.cap = Math.max(1, Math.round(Math.max(cap ?? 0, o.max)));
55
+ /** slots in use (spawn's ring, the update loop): o.max, at most cap */ this.max = Math.max(1, Math.round(o.max));
54
56
  this.pos = new Float32Array(N * 3); this.vel = new Float32Array(N * 3);
55
57
  this.age = new Float32Array(N); this.life = new Float32Array(N).fill(0); // life 0 = empty slot
56
58
  this.spinV = new Float32Array(N);
@@ -93,7 +95,7 @@ export class Effect {
93
95
 
94
96
  /** @internal The geometry, material and draw object for the engine's current renderer (sprite quads on WebGPU, points on WebGL) */
95
97
  _build() {
96
- const sys = this.sys, o = this.o, N = this.max, name = this.name;
98
+ const sys = this.sys, o = this.o, N = this.cap, name = this.name;
97
99
  const g = this.geometry = new THREE.BufferGeometry();
98
100
  const gpu = nodeSide(sys.engine, name); // WebGPU: the same attributes, read per instance by sprite quads
99
101
  const attr = (n, size) => { const a = new (gpu ? THREE.InstancedBufferAttribute : THREE.BufferAttribute)(new Float32Array(N * size), size); a.setUsage(THREE.DynamicDrawUsage); g.setAttribute(n, a); return a; };
@@ -220,5 +222,17 @@ export class Effect {
220
222
  }
221
223
  }
222
224
 
225
+ /**
226
+ * @internal a default max following engine.tier: only the slots in use change, inside buffers built for the larger count, so nothing the game holds
227
+ * (points, material, the uniforms its own material shares, the WebGPU nodes reading the attributes) is replaced. Particles above the new count go
228
+ */
229
+ _resize(max) {
230
+ const n = Math.min(this.cap, Math.max(1, Math.round(max)));
231
+ if (n === this.max) return;
232
+ for (let i = n; i < this.max; i++) if (this.life[i] !== 0) { this.life[i] = 0; this.aAlpha.array[i] = 0; this.alive--; }
233
+ this.max = n; this.head %= n; this._stale = this.cap; // the next upload clears the dropped slots on the GPU too
234
+ this.o.max = n; // fx.o is the effect's resolved options (public): it says the count in use, a fresh object per define (Particles.js), not the game's
235
+ }
236
+
223
237
  dispose() { this._swap.remove(); this._drop(); }
224
238
  }