BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

workerWorld.js 75.6 KiB Download Raw
1import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS, NAV_STUCK_MS } from "../../../shared/protocol/constants.js";
2import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
3import {
4 chunkKey,
5 chunkToRegion,
6 parseChunkKey,
7 regionKey,
8 tileKey,
9 tileToChunk,
10 tileToLocal,
11 tileToRegion,
12 tileIndex
13} from "../world/coordinates.js";
14import { cloneChunkData, createEmptyChunkData, isChunkTilePassable, isChunkTileClearForRangedAttacks } from "../world/chunkData.js";
15import { closedNeighborEdges } from "../world/chunkFlags.js";
16import { EcsWorld } from "../ecs/world.js";
17import { Component } from "../ecs/components.js";
18import { deserializeEntity, publicEntityView, serializeEntity } from "../ecs/serialize.js";
19import { chunkBoundsAround, findPath } from "../navigation/astar.js";
20import { WorkerMessage } from "./protocol.js";
21import { collectSpawnRequests } from "./spawners.js";
22import { mobDefinition } from "../../../shared/definitions/mobs.js";
23import {
24 bagView,
25 applyBagView,
26 addGroundItem,
27 expireGroundItems,
28 groundItemsInChunk,
29 groundItemsInRegion,
30 handleItemCommand,
31 removeGroundItem,
32 publicGroundItem,
33 setGroundItemsForRegion,
34 stripCarriedCoinsForDeath
35} from "../items/bags.js";
36import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights, clearSpellAutoRepeat } from "../spells/service.js";
37import { stepSummons } from "../spells/summons.js";
38import { stepJadeiteFairies } from "../spells/jadeiteFairy.js";
39import {
40 handleJewelryTeleportCommand,
41 stepJewelryTeleports,
42 cancelJewelryTeleport
43} from "../equipment/jewelryTeleport.js";
44import { publicSpellsView } from "../../../shared/spells/state.js";
45import { maybeOpenDoorOnApproach, stepDoors, entityCanOpenDoors } from "../doors/service.js";
46import {
47 handleGatherCommand,
48 stepGather,
49 cancelGather,
50 clearOreRespawnsForChunk,
51 clearTreeRespawnsForChunk,
52 clearPlantRespawnsForChunk
53} from "../gathering/service.js";
54import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
55import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";
56import { handleFishingCommand, stepFishing } from "../fishing/service.js";
57import { handleShearingCommand, stepShearing, originIsBusyPinned } from "../shearing/service.js";
58import { handleAlchemyCommand } from "../alchemy/service.js";
59import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
60import {
61 applyRemoteMeleeSwing,
62 applyRemoteRangedShot,
63 attackProfileOf,
64 clearEngage,
65 engageTarget,
66 ensureMobCombat,
67 isUntargetable,
68 queueMeleeApproach,
69 queueStandInRangeApproach,
70 resolveCombatTarget,
71 silenceDeadPlayer,
72 stepAggression,
73 stepCombat,
74 stepPassiveHealthRegen,
75 chebyshev,
76 tryArmStaffSpellAttack
77} from "../combat/service.js";
78import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
79import { SkillId } from "../../../shared/definitions/skills.js";
80import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
81import { passiveStaminaRegenMultiplier, dropAmuletInsteadOfCoins } from "../../../shared/equipment/jewelryEffects.js";
82import { JewelryItemId } from "../../../shared/definitions/jewelryItems.js";
83import { EQUIPMENT_SLOT } from "../../../shared/definitions/items.js";
84import { syncCharacterChunkPresence } from "../navigation/chunkPresence.js";
85import {
86 STAMINA_REGEN_PER_SECOND,
87 STAMINA_XP_PER_POINT_SPENT,
88 staminaCostPerRunStep,
89 publicStaminaView
90} from "../../../shared/stamina/rules.js";
91import {
92 stepCostForGround,
93 PATH_GROUND_STEP_COST,
94 SOFT_OCCUPIED_DWELL_MS
95} from "../../../shared/navigation/pathGround.js";
96import { GroundType, normalizeGround } from "../../../shared/definitions/tiles.js";
97import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
98import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
99import { stepStatusEffects } from "../statusEffects/service.js";
100import { hasStatusEffect, StatusEffectType } from "../../../shared/statusEffects/rules.js";
101
102export class WorkerWorld
103{
104 constructor (workerId)
105 {
106 this.workerId = workerId;
107 this.ecs = new EcsWorld();
108 this.chunks = new Map();
109 this.ownedRegions = new Set();
110 this.occupancy = new Map();
111 this.ghosts = new Map();
112 this.ghostOccupancy = new Map();
113 this.characterEntities = new Map();
114 this.frozen = new Set();
115 this.groundItems = new Map();
116 this.groundByTile = new Map();
117 this.oreRespawns = new Map();
118 this.treeRespawns = new Map();
119 this.campfireExpires = new Map();
120 this.fireSessions = new Map();
121 this.fishingSpotRespawns = new Map();
122 this.fishSessions = new Map();
123 this.pendingSpellImpacts = [];
124 this.jadeiteFairyTimers = new Map();
125 this.jewelryTeleportSessions = new Map();
126 this.settings = { ...DEFAULT_WORLD_SETTINGS };
127 this.activeRevisionId = 1;
128 }
129
130 handle (message)
131 {
132 switch (message.type)
133 {
134 case WorkerMessage.configure:
135 return this.#configure(message);
136 case WorkerMessage.assignRegion:
137 return this.#assignRegion(message);
138 case WorkerMessage.dropRegion:
139 return this.#dropRegion(message);
140 case WorkerMessage.replaceRegionChunks:
141 return this.#replaceRegionChunks(message);
142 case WorkerMessage.setReplicas:
143 return this.#setReplicas(message);
144 case WorkerMessage.setSimulatingChunks:
145 return this.#setSimulatingChunks(message);
146 case WorkerMessage.setGhosts:
147 return this.#setGhosts(message);
148 case WorkerMessage.spawn:
149 return this.#spawn(message);
150 case WorkerMessage.despawn:
151 return this.#despawn(message.entityId);
152 case WorkerMessage.despawnCharacter:
153 return this.#despawnCharacter(message.characterId);
154 case WorkerMessage.reattachSession:
155 return this.#reattachSession(message.characterId, message.sessionId);
156 case WorkerMessage.command:
157 return this.#command(message);
158 case WorkerMessage.stepMovement:
159 return this.#stepMovement(message.now);
160 case WorkerMessage.stepSystems:
161 return this.#stepSystems(message.now, message.dt ?? (1 / 20));
162 case WorkerMessage.stepSpawners:
163 return { spawnRequests: collectSpawnRequests(this, Date.now()) };
164 case WorkerMessage.setGroundItems:
165 setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion);
166 return { ok: true };
167 case WorkerMessage.inspectBag:
168 return this.#inspectBag(message.entityId);
169 case WorkerMessage.inspectSkills:
170 return this.#inspectSkills(message.entityId);
171 case WorkerMessage.inspectSpells:
172 return this.#inspectSpells(message.entityId);
173 case WorkerMessage.inspectStamina:
174 return this.#inspectStamina(message.entityId);
175 case WorkerMessage.applyBag:
176 return this.#applyBag(message.entityId, message.bag);
177 case WorkerMessage.applyAppearance:
178 return this.#applyAppearance(message.entityId, message.appearance);
179 case WorkerMessage.engageTarget:
180 return this.#engageTargetMessage(message);
181 case WorkerMessage.listTownGuardsNear:
182 return this.#listTownGuardsNear(message);
183 case WorkerMessage.updateFlight:
184 return this.#updateFlight(message.entityId, message.flight, message.now);
185 case WorkerMessage.chunkIsSimulating:
186 return this.chunkIsSimulating(message.tileX, message.tileY, message.dimensionId);
187 case WorkerMessage.applyTransfer:
188 return this.#applyTransfer(message);
189 case WorkerMessage.commitTransfer:
190 return this.#commitTransfer(message.entityId);
191 case WorkerMessage.abortTransfer:
192 return this.#abortTransfer(message.entityId);
193 case WorkerMessage.snapshotChunk:
194 return this.#chunkSnapshot(message.chunkX, message.chunkY, !!message.staticOnly, message.dimensionId);
195 case WorkerMessage.listLoaders:
196 return this.#listLoaders();
197 case WorkerMessage.listPublicEntities:
198 return this.#listPublicEntities();
199 case WorkerMessage.entitiesInRegion:
200 return this.#entitiesInRegion(message.regionX, message.regionY, message.dimensionId);
201 case WorkerMessage.inspect:
202 return publicEntityView(this.ecs, message.entityId);
203 case WorkerMessage.remoteCombatEngage:
204 return this.#remoteCombatEngage(message);
205 case WorkerMessage.applyRemoteMelee:
206 return this.#applyRemoteMelee(message);
207 case WorkerMessage.applyRemoteRanged:
208 return this.#applyRemoteRanged(message);
209 case WorkerMessage.applyCombatHitXp:
210 return this.#applyCombatHitXp(message);
211 case WorkerMessage.spawnCorpseDrops:
212 return this.#spawnCorpseDrops(message);
213 case WorkerMessage.applyRespawn:
214 return this.#applyRespawn(message);
215 case WorkerMessage.relocateEntity:
216 return this.#relocateEntity(message);
217 case WorkerMessage.clearCombat:
218 {
219 clearEngage(this.ecs, message.entityId);
220 const handle = this.ecs.handleOf(message.entityId);
221 if (handle != null)
222 {
223 silenceDeadPlayer(this.ecs, handle);
224 cancelGather(this.ecs, handle);
225 clearFollow(this.ecs, message.entityId);
226 }
227 for (const entity of this.ecs.query(Component.combat))
228 {
229 if (entity.combat.targetEntityId === message.targetEntityId)
230 { entity.combat.targetEntityId = null; }
231 }
232 return { ok: true };
233 }
234 case WorkerMessage.setItemLastSales:
235 {
236 this.itemLastSales = new Map();
237 for (const [key, sale] of Object.entries(message.sales ?? {}))
238 { this.itemLastSales.set(Number(key), sale); }
239 return { ok: true };
240 }
241 case WorkerMessage.stationExchangeClerk:
242 return this.#stationExchangeClerk(message);
243 case WorkerMessage.releaseExchangeClerk:
244 return this.#releaseExchangeClerk(message);
245 case WorkerMessage.pinDialogue:
246 return this.#pinDialogue(message.entityId, message.characterId);
247 case WorkerMessage.unpinDialogue:
248 return this.#unpinDialogue(message.entityId, message.characterId);
249 default:
250 throw new Error(`Unknown worker message ${message.type}`);
251 }
252 }
253
254 ownsRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
255 {
256 return this.ownedRegions.has(regionKey(regionX, regionY, dimensionId));
257 }
258
259 requireOwnedEntity (sessionId, characterId)
260 {
261 return this.#requireOwnedEntity(sessionId, characterId);
262 }
263
264 chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID)
265 {
266 return this.#chunkData(chunkX, chunkY, dimensionId);
267 }
268
269 #configure (message)
270 {
271 if (message.settings)
272 { this.settings = { ...this.settings, ...message.settings }; }
273 if (message.activeRevisionId != null)
274 { this.activeRevisionId = message.activeRevisionId; }
275 return { ok: true };
276 }
277
278 #assignRegion (message)
279 {
280 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
281 this.ownedRegions.add(regionKey(message.regionX, message.regionY, dim));
282 for (const chunk of message.chunks ?? [])
283 {
284 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
285 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
286 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
287 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
288 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY, chunkDim), {
289 data: cloneChunkData(chunk.data),
290 simulating: false,
291 replica: false,
292 dimensionId: chunkDim
293 });
294 }
295 return { ok: true };
296 }
297
298 #replaceRegionChunks (message)
299 {
300 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
301 for (const chunk of message.chunks ?? [])
302 {
303 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
304 const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim);
305 const existing = this.chunks.get(key);
306 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
307 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
308 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
309 this.chunks.set(key, {
310 data: cloneChunkData(chunk.data),
311 simulating: existing?.simulating ?? false,
312 replica: existing?.replica ?? false,
313 dimensionId: chunkDim
314 });
315 }
316 return { ok: true };
317 }
318
319 #dropRegion (message)
320 {
321 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
322 const dropped = [];
323 for (const record of this.#entitiesInRegion(message.regionX, message.regionY, dim))
324 {
325 const components = record.payload?.components;
326 if (components?.creature && !components?.character && components?.health)
327 { components.health.current = components.health.max; }
328 dropped.push(record);
329 this.#destroyEntity(record.entityId);
330 }
331 const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion);
332 for (const item of groundItems)
333 { removeGroundItem(this, item.groundItemId); }
334 for (const [key, chunk] of [...this.chunks.entries()])
335 {
336 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
337 if (chunk.replica)
338 { continue; }
339 if (dimensionId !== dim)
340 { continue; }
341 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
342 {
343 clearOreRespawnsForChunk(this, chunkX, chunkY);
344 clearTreeRespawnsForChunk(this, chunkX, chunkY);
345 clearPlantRespawnsForChunk(this, chunkX, chunkY);
346 this.chunks.delete(key);
347 }
348 }
349 this.ownedRegions.delete(regionKey(message.regionX, message.regionY, dim));
350 return { dropped, groundItems };
351 }
352
353 #setReplicas (message)
354 {
355 const keep = new Set();
356 for (const chunk of message.chunks ?? [])
357 {
358 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? OVERWORLD_ID);
359 const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim);
360 keep.add(key);
361 const existing = this.chunks.get(key);
362 if (existing && !existing.replica)
363 { continue; }
364 this.chunks.set(key, {
365 data: cloneChunkData(chunk.data),
366 simulating: false,
367 replica: true,
368 dimensionId: chunkDim
369 });
370 }
371 for (const [key, chunk] of [...this.chunks.entries()])
372 {
373 if (chunk.replica && !keep.has(key))
374 { this.chunks.delete(key); }
375 }
376 return { ok: true };
377 }
378
379 #setSimulatingChunks (message)
380 {
381 const simulating = new Set(message.chunkKeys ?? []);
382 for (const [key, chunk] of this.chunks)
383 {
384 if (chunk.replica)
385 {
386 chunk.simulating = false;
387 continue;
388 }
389 chunk.simulating = simulating.has(key);
390 }
391 return { ok: true };
392 }
393
394 #setGhosts (message)
395 {
396 this.ghosts.clear();
397 this.ghostOccupancy.clear();
398 for (const ghost of message.ghosts ?? [])
399 {
400 this.ghosts.set(ghost.entityId, ghost);
401 const dim = normalizeDimensionId(ghost.dimensionId ?? OVERWORLD_ID);
402 const key = tileKey(ghost.tileX, ghost.tileY, dim);
403 let set = this.ghostOccupancy.get(key);
404 if (!set)
405 {
406 set = new Set();
407 this.ghostOccupancy.set(key, set);
408 }
409 set.add(ghost.entityId);
410 }
411 return { ok: true };
412 }
413
414 #spawn (message)
415 {
416 const entityId = deserializeEntity(this.ecs, message);
417 const handle = this.ecs.handleOf(entityId);
418 const position = this.ecs.get(handle, Component.position);
419 if (!position)
420 {
421 this.ecs.destroy(handle);
422 throw new Error("Spawned entity is missing position.");
423 }
424 const flying = this.#isFlying(handle);
425 if (!flying)
426 {
427 if (this.#hasOtherOccupant(entityId, position.tileX, position.tileY))
428 {
429 this.ecs.destroy(handle);
430 const error = new Error("That tile is occupied.");
431 error.userFacing = true;
432 throw error;
433 }
434 this.#occupy(entityId, position.tileX, position.tileY);
435 }
436 const creature = this.ecs.get(handle, Component.creature);
437 const def = creature ? mobDefinition(creature.mobTypeId) : null;
438 if (def?.freeFlight)
439 { ensureFlightComponent(this.ecs, handle, position, def); }
440 const character = this.ecs.get(handle, Component.character);
441 if (character?.characterId)
442 {
443 this.characterEntities.set(character.characterId, entityId);
444 syncCharacterChunkPresence(this.ecs, handle, Date.now());
445 }
446 return publicEntityView(this.ecs, entityId);
447 }
448
449 #despawn (entityId)
450 {
451 return this.#destroyEntity(entityId);
452 }
453
454 #despawnCharacter (characterId)
455 {
456 releaseShopBrowsersForCharacter(this, characterId);
457 const entityId = this.characterEntities.get(characterId);
458 if (!entityId)
459 { return null; }
460 return this.#destroyEntity(entityId);
461 }
462
463 #reattachSession (characterId, sessionId)
464 {
465 const entityId = this.characterEntities.get(characterId | 0);
466 if (!entityId)
467 { return { ok: false }; }
468 const handle = this.ecs.handleOf(entityId);
469 if (handle == null)
470 { return { ok: false }; }
471 this.ecs.add(handle, Component.networkIdentity, { sessionId });
472 return { ok: true, entityId };
473 }
474
475 #destroyEntity (entityId)
476 {
477 const handle = this.ecs.handleOf(entityId);
478 if (handle == null)
479 { return null; }
480 const view = publicEntityView(this.ecs, entityId);
481 const position = this.ecs.get(handle, Component.position);
482 const character = this.ecs.get(handle, Component.character);
483 if (position && !this.#isFlying(handle))
484 { this.#vacate(entityId, position.tileX, position.tileY); }
485 if (character?.characterId)
486 { this.characterEntities.delete(character.characterId); }
487 this.frozen.delete(entityId);
488 this.ecs.destroy(handle);
489 return view;
490 }
491
492 #command (message)
493 {
494 const { sessionId, command } = message;
495 switch (command.type)
496 {
497 case "move-to":
498 return this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
499 case "set-gait":
500 return this.#setGait(sessionId, command.characterId, command.gait);
501 case "attack":
502 return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
503 case "cancel-attack":
504 return this.#cancelAttack(sessionId, command.characterId);
505 case "interact":
506 return this.#interact(sessionId, command.characterId, command.targetEntityId, command.purpose);
507 case "follow":
508 return this.#follow(sessionId, command.characterId, command.targetEntityId);
509 case "cancel-follow":
510 return this.#cancelFollow(sessionId, command.characterId);
511 case "jewelry-teleport":
512 {
513 const jewelry = handleJewelryTeleportCommand(this, sessionId, command, message.now ?? Date.now());
514 if (jewelry)
515 { return jewelry; }
516 return { events: [] };
517 }
518 case "set-spell-favorite":
519 case "reorder-spell-favorites":
520 case "set-spell-autocast":
521 case "arm-spell":
522 case "cancel-arm-spell":
523 case "cast-spell-tile":
524 case "cast-spell-entity":
525 case "read-spellbook":
526 return handleSpellCommand(this, sessionId, command, message.now ?? Date.now()) ?? { events: [] };
527 default:
528 {
529 const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
530 if (gather)
531 { return gather; }
532 const fire = handleFirestartingCommand(this, sessionId, command, message.now ?? Date.now());
533 if (fire)
534 { return fire; }
535 const fishing = handleFishingCommand(this, sessionId, command, message.now ?? Date.now());
536 if (fishing)
537 { return fishing; }
538 const shearing = handleShearingCommand(this, sessionId, command, message.now ?? Date.now());
539 if (shearing)
540 { return shearing; }
541 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
542 if (craft)
543 { return craft; }
544 const shop = handleShopCommand(this, sessionId, command, message.now ?? Date.now());
545 if (shop)
546 { return shop; }
547 const alchemy = handleAlchemyCommand(this, sessionId, command);
548 if (alchemy)
549 { return alchemy; }
550 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
551 return result ?? { events: [] };
552 }
553 }
554 }
555
556 #spawnCorpseDrops (message)
557 {
558 const events = [];
559 const drops = [...(message.drops ?? [])];
560 let privateBag = null;
561 if (message.dropCarriedCoins)
562 {
563 const entityId = this.characterEntities.get(message.characterId);
564 const handle = entityId != null ? this.ecs.handleOf(entityId) : null;
565 const equipment = handle != null ? this.ecs.get(handle, Component.equipment) : null;
566 if (dropAmuletInsteadOfCoins(equipment))
567 {
568 const amulet = equipment?.slots?.[EQUIPMENT_SLOT.amulet]
569 ?? equipment?.slots?.amulet
570 ?? null;
571 if (amulet && (amulet.itemId | 0) === JewelryItemId.rubyAmulet)
572 {
573 equipment.slots[EQUIPMENT_SLOT.amulet] = null;
574 if (message.coinGroundItemId != null)
575 {
576 drops.push({
577 groundItemId: message.coinGroundItemId,
578 stack: {
579 itemId: JewelryItemId.rubyAmulet,
580 quantity: 1,
581 origins: amulet.origins ?? []
582 }
583 });
584 }
585 privateBag = bagView(this.ecs, handle);
586 }
587 }
588 else
589 {
590 const stripped = stripCarriedCoinsForDeath(this, message.characterId);
591 privateBag = stripped.private;
592 if (stripped.stack && message.coinGroundItemId != null)
593 {
594 drops.push({
595 groundItemId: message.coinGroundItemId,
596 stack: stripped.stack
597 });
598 }
599 }
600 }
601 for (const drop of drops)
602 {
603 const stack = drop.stack ?? { itemId: drop.itemId, quantity: 1 };
604 const item = {
605 groundItemId: drop.groundItemId,
606 tileX: message.tileX,
607 tileY: message.tileY,
608 stack,
609 droppedAt: message.now,
610 expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000),
611 source: "player-death",
612 droppedByCharacterId: message.characterId
613 };
614 addGroundItem(this, item);
615 events.push({
616 type: "ground-item-appear",
617 ...publicGroundItem(item),
618 stack: item.stack,
619 droppedAt: item.droppedAt,
620 source: item.source,
621 droppedByCharacterId: item.droppedByCharacterId,
622 expiresAt: item.expiresAt
623 });
624 }
625 return { events, private: privateBag };
626 }
627
628 #applyRespawn (message)
629 {
630 const handle = this.ecs.handleOf(message.entityId);
631 if (handle == null || !this.ecs.has(handle, Component.dead))
632 { return { accepted: false }; }
633 const position = this.ecs.get(handle, Component.position);
634 const fromTileX = position.tileX;
635 const fromTileY = position.tileY;
636 const health = this.ecs.get(handle, Component.health);
637 const stamina = this.ecs.get(handle, Component.stamina);
638 if (health)
639 {
640 health.max = message.maxHealth;
641 health.current = message.maxHealth;
642 }
643 if (stamina)
644 {
645 stamina.max = message.maxStamina;
646 stamina.current = message.maxStamina;
647 }
648 else
649 { this.ecs.add(handle, Component.stamina, { current: message.maxStamina, max: message.maxStamina }); }
650 this.ecs.remove(handle, Component.dead);
651 clearEngage(this.ecs, message.entityId);
652 const path = this.ecs.get(handle, Component.path);
653 if (path)
654 { path.tiles = []; }
655 clearFollow(this.ecs, message.entityId);
656
657 const destRegionX = tileToRegion(message.tileX);
658 const destRegionY = tileToRegion(message.tileY);
659 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
660 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
661 {
662 this.frozen.add(message.entityId);
663 return {
664 accepted: true,
665 transferRequest: {
666 entityId: message.entityId,
667 fromTileX,
668 fromTileY,
669 destTileX: message.tileX,
670 destTileY: message.tileY,
671 toRegionX: destRegionX,
672 toRegionY: destRegionY,
673 dimensionId,
674 payload: serializeEntity(this.ecs, message.entityId)
675 }
676 };
677 }
678 if (!this.isEnterable(message.tileX, message.tileY, dimensionId))
679 { return { accepted: false }; }
680 this.#vacate(message.entityId, fromTileX, fromTileY);
681 position.tileX = message.tileX;
682 position.tileY = message.tileY;
683 syncCharacterChunkPresence(this.ecs, handle, Date.now());
684 this.#occupy(message.entityId, position.tileX, position.tileY);
685 return {
686 accepted: true,
687 event: {
688 type: "entity-move",
689 entityId: message.entityId,
690 fromTileX,
691 fromTileY,
692 tileX: position.tileX,
693 tileY: position.tileY,
694 dimensionId,
695 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
696 }
697 };
698 }
699
700 /** Move an entity to a tile/dimension; clears path and updates occupancy. */
701 #relocateEntity (message)
702 {
703 const handle = this.ecs.handleOf(message.entityId);
704 if (handle == null)
705 { return { accepted: false }; }
706 const position = this.ecs.get(handle, Component.position);
707 if (!position)
708 { return { accepted: false }; }
709 const fromTileX = position.tileX;
710 const fromTileY = position.tileY;
711 const fromDimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
712 const destTileX = message.tileX | 0;
713 const destTileY = message.tileY | 0;
714 const dimensionId = normalizeDimensionId(message.dimensionId ?? fromDimensionId);
715
716 clearEngage(this.ecs, message.entityId);
717 const path = this.ecs.get(handle, Component.path);
718 if (path)
719 { path.tiles = []; }
720 clearFollow(this.ecs, message.entityId);
721
722 const destRegionX = tileToRegion(destTileX);
723 const destRegionY = tileToRegion(destTileY);
724 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
725 {
726 this.frozen.add(message.entityId);
727 const payload = serializeEntity(this.ecs, message.entityId);
728 if (payload.components?.position)
729 {
730 payload.components.position.tileX = destTileX;
731 payload.components.position.tileY = destTileY;
732 payload.components.position.dimensionId = dimensionId;
733 }
734 return {
735 accepted: true,
736 transferRequest: {
737 entityId: message.entityId,
738 fromTileX,
739 fromTileY,
740 fromDimensionId,
741 destTileX,
742 destTileY,
743 toRegionX: destRegionX,
744 toRegionY: destRegionY,
745 dimensionId,
746 payload
747 }
748 };
749 }
750 if (!this.isEnterable(destTileX, destTileY, dimensionId))
751 { return { accepted: false }; }
752 if (!this.#isFlying(handle))
753 { this.#vacate(message.entityId, fromTileX, fromTileY); }
754 position.tileX = destTileX;
755 position.tileY = destTileY;
756 position.dimensionId = dimensionId;
757 syncCharacterChunkPresence(this.ecs, handle, Date.now());
758 if (!this.#isFlying(handle))
759 { this.#occupy(message.entityId, destTileX, destTileY); }
760 return {
761 accepted: true,
762 event: {
763 type: "entity-move",
764 entityId: message.entityId,
765 fromTileX,
766 fromTileY,
767 fromDimensionId,
768 tileX: destTileX,
769 tileY: destTileY,
770 dimensionId,
771 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
772 }
773 };
774 }
775
776 #inspectBag (entityId)
777 {
778 const handle = this.ecs.handleOf(entityId);
779 if (handle == null)
780 { return null; }
781 return bagView(this.ecs, handle);
782 }
783
784 #inspectSkills (entityId)
785 {
786 const handle = this.ecs.handleOf(entityId);
787 if (handle == null)
788 { return null; }
789 const skills = this.ecs.get(handle, Component.skills);
790 if (!skills?.xp)
791 { return null; }
792 return skills;
793 }
794
795 #inspectSpells (entityId)
796 {
797 const handle = this.ecs.handleOf(entityId);
798 if (handle == null)
799 { return null; }
800 const spells = this.ecs.get(handle, Component.spells);
801 const skills = this.ecs.get(handle, Component.skills);
802 const casting = this.ecs.get(handle, Component.spellcasting);
803 if (!spells)
804 { return null; }
805 return {
806 spells: publicSpellsView(spells, skills),
807 favorites: Array.isArray(spells.favorites) ? [...spells.favorites] : [],
808 autoCast: !!spells.autoCast,
809 armedSpellId: casting?.armedSpellId ?? null
810 };
811 }
812
813 #inspectStamina (entityId)
814 {
815 const handle = this.ecs.handleOf(entityId);
816 if (handle == null)
817 { return null; }
818 const stamina = this.ecs.get(handle, Component.stamina);
819 const movement = this.ecs.get(handle, Component.movement);
820 if (!stamina)
821 { return null; }
822 return {
823 ...publicStaminaView(stamina),
824 gait: movement?.gait ?? GAIT.walk
825 };
826 }
827
828 #applyBag (entityId, bag)
829 {
830 const handle = this.ecs.handleOf(entityId);
831 if (handle == null)
832 { return null; }
833 return applyBagView(this.ecs, handle, bag);
834 }
835
836 #applyAppearance (entityId, appearancePatch)
837 {
838 const handle = this.ecs.handleOf(entityId);
839 if (handle == null)
840 { return null; }
841 const appearance = this.ecs.get(handle, Component.appearance);
842 if (!appearance)
843 { return null; }
844 Object.assign(appearance, appearancePatch ?? {});
845 return publicEntityView(this.ecs, entityId);
846 }
847
848 #updateFlight (entityId, flightPatch, now = Date.now())
849 {
850 const handle = this.ecs.handleOf(entityId);
851 if (handle == null)
852 { return null; }
853 let flight = this.ecs.get(handle, Component.flight);
854 if (!flight)
855 { flight = this.ecs.add(handle, Component.flight, { ...flightPatch }); }
856 else
857 { Object.assign(flight, flightPatch); }
858 const position = this.ecs.get(handle, Component.position);
859 const movement = this.ecs.get(handle, Component.movement);
860 const fromTileX = position.tileX;
861 const fromTileY = position.tileY;
862 const tileX = Math.floor(flight.x);
863 const tileY = Math.floor(flight.y);
864 position.tileX = tileX;
865 position.tileY = tileY;
866 syncCharacterChunkPresence(this.ecs, handle, now);
867 const destRegionX = tileToRegion(tileX);
868 const destRegionY = tileToRegion(tileY);
869 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
870 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
871 {
872 this.frozen.add(entityId);
873 return {
874 transferRequest: {
875 type: "transfer-request",
876 entityId,
877 fromTileX,
878 fromTileY,
879 destTileX: tileX,
880 destTileY: tileY,
881 toRegionX: destRegionX,
882 toRegionY: destRegionY,
883 dimensionId
884 }
885 };
886 }
887 const dt = flight.lastAt && now > flight.lastAt
888 ? Math.min(0.25, (now - flight.lastAt) / 1000)
889 : 1 / 20;
890 return {
891 event: {
892 type: "entity-move",
893 entityId,
894 fromTileX,
895 fromTileY,
896 tileX,
897 tileY,
898 worldX: flight.x,
899 worldY: flight.y,
900 gait: movement?.gait ?? "walk",
901 lerpMs: Math.max(50, Math.round(dt * 1000)),
902 freeFlight: true
903 }
904 };
905 }
906
907 #moveTo (sessionId, characterId, tileX, tileY)
908 {
909 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
910 if (this.frozen.has(entityId))
911 { return { events: [] }; }
912 clearEngage(this.ecs, entityId);
913 clearFollow(this.ecs, entityId);
914 cancelGather(this.ecs, handle);
915 cancelJewelryTeleport(this, characterId);
916 clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting));
917 const position = this.ecs.get(handle, Component.position);
918 const movement = this.ecs.get(handle, Component.movement);
919 let path = this.ecs.get(handle, Component.path);
920 if (!path)
921 { path = this.ecs.add(handle, Component.path, { tiles: [] }); }
922 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
923 path.tiles = findPath(
924 position.tileX,
925 position.tileY,
926 tileX,
927 tileY,
928 (x, y) => this.walkableFor(entityId, x, y),
929 bounds.minX,
930 bounds.minY,
931 bounds.maxX,
932 bounds.maxY,
933 this.pathfindOptions({ preferVertical: true, preferPaths: true, entityId })
934 );
935 movement.walkCarry = 0;
936 const events = [];
937 /** Open immediately when the next step is a door (player already adjacent). */
938 const first = path.tiles[0];
939 if (first)
940 {
941 const doorDelta = maybeOpenDoorOnApproach(this, entityId, first.x, first.y);
942 if (doorDelta)
943 { events.push(doorDelta); }
944 }
945 return { events };
946 }
947
948 #attack (sessionId, characterId, targetEntityId, now)
949 {
950 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
951 if (targetEntityId === entityId)
952 {
953 const error = new Error("Cannot attack yourself.");
954 error.userFacing = true;
955 throw error;
956 }
957 const target = resolveCombatTarget(this, targetEntityId);
958 if (!target)
959 {
960 const error = new Error("Target is not here.");
961 error.userFacing = true;
962 throw error;
963 }
964 if (target.health && target.health.current <= 0)
965 {
966 const error = new Error("That cannot be attacked.");
967 error.userFacing = true;
968 throw error;
969 }
970 if (!this.ecs.get(handle, Component.combat))
971 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
972 clearFollow(this.ecs, entityId);
973 cancelGather(this.ecs, handle);
974 // Staff + favorite attack spell: hold spell range via auto-cast (same as retaliate).
975 if (tryArmStaffSpellAttack(this.ecs, entityId, targetEntityId))
976 { return { events: [] }; }
977 clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting));
978 engageTarget(this.ecs, entityId, targetEntityId, now);
979 const position = this.ecs.get(handle, Component.position);
980 const profile = attackProfileOf(this.ecs, handle);
981 if (position && target.pos)
982 {
983 if (profile.mode === "ranged")
984 {
985 queueStandInRangeApproach(
986 this,
987 entityId,
988 handle,
989 position,
990 target.pos.tileX,
991 target.pos.tileY,
992 profile.rangeTiles | 0 || COMBAT_RANGE_TILES,
993 1
994 );
995 }
996 else if (profile.mode === "melee")
997 {
998 queueMeleeApproach(this, entityId, handle, position, target.pos);
999 }
1000 }
1001 return { events: [] };
1002 }
1003
1004 #remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() })
1005 {
1006 // Kept for cross-worker hooks; retaliation happens on swing resolution, not Attack click.
1007 void attackerEntityId;
1008 void targetEntityId;
1009 void now;
1010 return { events: [] };
1011 }
1012
1013 #engageTargetMessage ({ attackerEntityId, targetEntityId, now = Date.now() })
1014 {
1015 if (this.ecs.handleOf(attackerEntityId) == null)
1016 { return { ok: false }; }
1017 engageTarget(this.ecs, attackerEntityId, targetEntityId, now);
1018 return { ok: true };
1019 }
1020
1021 /**
1022 * Idle town-guard entity ids from spawners whose wander range covers (tileX, tileY).
1023 * Optionally restrict to one spawnerId.
1024 */
1025 #listTownGuardsNear ({ tileX, tileY, spawnerId = null, limit = 8 })
1026 {
1027 const guards = [];
1028 for (const entity of this.ecs.query(Component.spawnOrigin, Component.creature, Component.combat, Component.position))
1029 {
1030 if (!entity.spawnOrigin?.townGuard)
1031 { continue; }
1032 if (spawnerId != null && entity.spawnOrigin.spawnerId !== spawnerId)
1033 { continue; }
1034 const originX = entity.spawnOrigin.originTileX;
1035 const originY = entity.spawnOrigin.originTileY;
1036 const range = entity.spawnOrigin.wanderRangeTiles | 0;
1037 const dx = Math.abs(tileX - originX);
1038 const dy = Math.abs(tileY - originY);
1039 if (Math.max(dx, dy) > range)
1040 { continue; }
1041 const health = this.ecs.get(entity.handle, Component.health);
1042 if (health && health.current <= 0)
1043 { continue; }
1044 if (this.ecs.has(entity.handle, Component.dead))
1045 { continue; }
1046 guards.push({
1047 entityId: entity.entityId,
1048 spawnerId: entity.spawnOrigin.spawnerId,
1049 busy: entity.combat?.targetEntityId != null
1050 });
1051 if (guards.length >= limit)
1052 { break; }
1053 }
1054 return { guards };
1055 }
1056
1057 #applyRemoteMelee (payload)
1058 {
1059 return applyRemoteMeleeSwing(this, payload);
1060 }
1061
1062 #applyRemoteRanged (payload)
1063 {
1064 return applyRemoteRangedShot(this, payload);
1065 }
1066
1067 #applyCombatHitXp ({ entityId, profile, damage })
1068 {
1069 const handle = this.ecs.handleOf(entityId);
1070 if (handle == null)
1071 { return { events: [] }; }
1072 const character = this.ecs.get(handle, Component.character);
1073 if (!character)
1074 { return { events: [] }; }
1075 const xpAward = awardCombatHitXp(this.ecs, handle, profile, damage);
1076 if (!xpAward)
1077 { return { events: [] }; }
1078 return {
1079 events: [{
1080 type: "skills-updated",
1081 entityId,
1082 characterId: character.characterId,
1083 skills: xpAward.skills,
1084 combatLevel: xpAward.combatLevel,
1085 stored: xpAward.stored,
1086 levelUps: xpAward.levelUps ?? []
1087 }]
1088 };
1089 }
1090
1091 #cancelAttack (sessionId, characterId)
1092 {
1093 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
1094 clearEngage(this.ecs, entityId);
1095 clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting));
1096 return { events: [] };
1097 }
1098
1099 #interact (sessionId, characterId, targetEntityId, purpose = null)
1100 {
1101 this.#requireOwnedEntity(sessionId, characterId);
1102 const targetHandle = this.ecs.handleOf(targetEntityId);
1103 if (targetHandle == null)
1104 {
1105 const error = new Error("Target is not here.");
1106 error.userFacing = true;
1107 throw error;
1108 }
1109 if (isUntargetable(this.ecs, targetHandle))
1110 {
1111 const error = new Error("Nothing to say.");
1112 error.userFacing = true;
1113 throw error;
1114 }
1115 const creature = this.ecs.get(targetHandle, Component.creature);
1116 const def = creature ? mobDefinition(creature.mobTypeId) : null;
1117 const shop = this.ecs.get(targetHandle, Component.shop);
1118 const hasShop = shopHasInterface(shop);
1119 const origin = this.ecs.get(targetHandle, Component.spawnOrigin);
1120 const dialogueId = origin?.dialogueId ? String(origin.dialogueId) : "";
1121 const intent = purpose === "shop" || purpose === "talk" ? purpose : null;
1122
1123 if (intent === "shop" && hasShop)
1124 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
1125 if (intent === "talk" && dialogueId)
1126 {
1127 // Pin in-worker before return so wander cannot start before the sim thread pins.
1128 this.#pinDialogue(targetEntityId, characterId);
1129 return {
1130 events: [{
1131 type: "open-dialogue",
1132 sessionId,
1133 characterId,
1134 entityId: targetEntityId,
1135 dialogueId
1136 }]
1137 };
1138 }
1139 if (intent === "talk" && hasShop)
1140 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
1141
1142 // Default click: prefer dialogue when assigned, else shop, else talkable no-op.
1143 if (dialogueId)
1144 {
1145 this.#pinDialogue(targetEntityId, characterId);
1146 return {
1147 events: [{
1148 type: "open-dialogue",
1149 sessionId,
1150 characterId,
1151 entityId: targetEntityId,
1152 dialogueId
1153 }]
1154 };
1155 }
1156 if (hasShop)
1157 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
1158 if (!def?.talkable)
1159 {
1160 const error = new Error("They have nothing to say.");
1161 error.userFacing = true;
1162 throw error;
1163 }
1164 return { events: [] };
1165 }
1166
1167 #follow (sessionId, characterId, targetEntityId)
1168 {
1169 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
1170 const targetHandle = this.ecs.handleOf(targetEntityId);
1171 if (targetHandle == null)
1172 {
1173 const error = new Error("Target is not here.");
1174 error.userFacing = true;
1175 throw error;
1176 }
1177 if (targetEntityId === entityId)
1178 {
1179 const error = new Error("Cannot follow yourself.");
1180 error.userFacing = true;
1181 throw error;
1182 }
1183 if (!this.ecs.get(targetHandle, Component.position))
1184 {
1185 const error = new Error("That cannot be followed.");
1186 error.userFacing = true;
1187 throw error;
1188 }
1189 clearEngage(this.ecs, entityId);
1190 setFollow(this.ecs, entityId, targetEntityId);
1191 const path = this.ecs.get(handle, Component.path);
1192 if (path)
1193 { path.tiles = []; }
1194 return { events: [] };
1195 }
1196
1197 #cancelFollow (sessionId, characterId)
1198 {
1199 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
1200 clearFollow(this.ecs, entityId);
1201 return { events: [] };
1202 }
1203
1204 #setGait (sessionId, characterId, gait)
1205 {
1206 if (gait !== GAIT.walk && gait !== GAIT.run)
1207 {
1208 const error = new Error("Gait must be walk or run.");
1209 error.userFacing = true;
1210 throw error;
1211 }
1212 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
1213 const movement = this.ecs.get(handle, Component.movement);
1214 const stamina = this.ecs.get(handle, Component.stamina);
1215 if (gait === GAIT.run && !(Number(stamina?.current) > 0))
1216 {
1217 const error = new Error("You are too exhausted to run.");
1218 error.userFacing = true;
1219 throw error;
1220 }
1221 movement.gait = gait;
1222 const character = this.ecs.get(handle, Component.character);
1223 return {
1224 events: character
1225 ? [this.#staminaEvent(handle, character.characterId, movement.gait)]
1226 : []
1227 };
1228 }
1229
1230 #staminaEvent (handle, characterId, gait = null)
1231 {
1232 const stamina = this.ecs.get(handle, Component.stamina);
1233 const movement = this.ecs.get(handle, Component.movement);
1234 return {
1235 type: "stamina",
1236 characterId,
1237 ...publicStaminaView(stamina),
1238 gait: gait ?? movement?.gait ?? GAIT.walk
1239 };
1240 }
1241
1242 #consumeRunStamina (handle, events)
1243 {
1244 const character = this.ecs.get(handle, Component.character);
1245 if (!character)
1246 { return; }
1247 let stamina = this.ecs.get(handle, Component.stamina);
1248 if (!stamina)
1249 {
1250 stamina = this.ecs.add(handle, Component.stamina, { current: 1, max: 1, xpDebt: 0 });
1251 }
1252 const skills = this.ecs.get(handle, Component.skills);
1253 syncPlayerStamina(this.ecs, handle);
1254 const position = this.ecs.get(handle, Component.position);
1255 const onPath = position
1256 ? this.groundTypeAt(position.tileX, position.tileY, position.dimensionId) === GroundType.path
1257 : false;
1258 const cost = staminaCostPerRunStep(this.settings?.walkTilesPerSecond, { onPath });
1259 stamina.current = Math.max(0, (Number(stamina.current) || 0) - cost);
1260 stamina.xpDebt = (Number(stamina.xpDebt) || 0) + cost;
1261 let skillsChanged = false;
1262 const levelUps = [];
1263 while (stamina.xpDebt >= 1 && skills?.xp)
1264 {
1265 stamina.xpDebt -= 1;
1266 const result = applySkillXp(skills, SkillId.stamina, STAMINA_XP_PER_POINT_SPENT);
1267 if (result.changed)
1268 {
1269 skillsChanged = true;
1270 syncPlayerStamina(this.ecs, handle);
1271 }
1272 if (result.levelUp)
1273 { levelUps.push(result.levelUp); }
1274 }
1275 const movement = this.ecs.get(handle, Component.movement);
1276 if (stamina.current <= 0 && movement)
1277 {
1278 stamina.current = 0;
1279 movement.gait = GAIT.walk;
1280 }
1281 events.push(this.#staminaEvent(handle, character.characterId));
1282 if (skillsChanged)
1283 {
1284 events.push({
1285 type: "skills-updated",
1286 entityId: this.ecs.entityIdOf(handle),
1287 characterId: character.characterId,
1288 ...publicSkillsPayload(skills),
1289 stored: storedSkillXp(skills),
1290 levelUps
1291 });
1292 }
1293 }
1294
1295 #regenStamina (dt, events)
1296 {
1297 if (!(dt > 0))
1298 { return; }
1299 for (const entity of this.ecs.query(Component.character, Component.stamina, Component.movement))
1300 {
1301 const { handle, character, stamina, movement } = entity;
1302 if (this.ecs.has(handle, Component.dead))
1303 { continue; }
1304 const status = this.ecs.get(handle, Component.statusEffects);
1305 if (hasStatusEffect(status, StatusEffectType.staminaBlock, Date.now()))
1306 { continue; }
1307 // Run gait only blocks regen while actually stepping along a path.
1308 const path = this.ecs.get(handle, Component.path);
1309 if (movement.gait === GAIT.run && path?.tiles?.length)
1310 { continue; }
1311 syncPlayerStamina(this.ecs, handle);
1312 const before = Number(stamina.current) || 0;
1313 if (before >= stamina.max)
1314 { continue; }
1315 stamina.current = Math.min(
1316 stamina.max,
1317 before + dt * STAMINA_REGEN_PER_SECOND * passiveStaminaRegenMultiplier(
1318 this.ecs.get(handle, Component.equipment)
1319 )
1320 );
1321 const after = Number(stamina.current) || 0;
1322 // Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam.
1323 if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max))
1324 { events.push(this.#staminaEvent(handle, character.characterId)); }
1325 }
1326 }
1327
1328 #requireOwnedEntity (sessionId, characterId)
1329 {
1330 const entityId = this.characterEntities.get(characterId);
1331 if (!entityId)
1332 {
1333 const error = new Error("Character is not in the world.");
1334 error.userFacing = true;
1335 throw error;
1336 }
1337 const handle = this.ecs.handleOf(entityId);
1338 const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null;
1339 if (!identity || identity.sessionId !== sessionId)
1340 {
1341 const error = new Error("Character is not in the world.");
1342 error.userFacing = true;
1343 throw error;
1344 }
1345 if (this.ecs.has(handle, Component.dead))
1346 {
1347 const error = new Error("You are dead.");
1348 error.userFacing = true;
1349 throw error;
1350 }
1351 return { handle, entityId };
1352 }
1353
1354 #stepSystems (now = Date.now(), dt = 1 / 20)
1355 {
1356 const events = [];
1357 const transferRequests = [];
1358 this.#regenStamina(dt, events);
1359 events.push(...stepStatusEffects(this, now, dt));
1360 events.push(...stepPassiveHealthRegen(this, now, dt));
1361 const flight = stepFreeFlight(this, now);
1362 for (const event of flight)
1363 {
1364 if (event.type === "transfer-request")
1365 {
1366 const payload = serializeEntity(this.ecs, event.entityId);
1367 transferRequests.push({
1368 entityId: event.entityId,
1369 fromTileX: event.fromTileX,
1370 fromTileY: event.fromTileY,
1371 destTileX: event.destTileX,
1372 destTileY: event.destTileY,
1373 toRegionX: event.toRegionX,
1374 toRegionY: event.toRegionY,
1375 dimensionId: event.dimensionId ?? OVERWORLD_ID,
1376 payload
1377 });
1378 continue;
1379 }
1380 events.push(event);
1381 }
1382 stepAggression(this, now);
1383 events.push(...stepCombat(this, now));
1384 events.push(...stepPendingSpellCast(this, now));
1385 events.push(...processSpellImpacts(this, now));
1386 events.push(...stepSpellAutoCast(this, now));
1387 events.push(...tickSpellLights(this, now));
1388 const summons = stepSummons(this, now);
1389 events.push(...(summons.events ?? []));
1390 for (const entityId of summons.despawnIds ?? [])
1391 {
1392 const dropped = this.#destroyEntity(entityId);
1393 if (dropped)
1394 { events.push({ type: "entity-despawn", entityId }); }
1395 }
1396 const fairies = stepJadeiteFairies(this, now);
1397 events.push(...(fairies.events ?? []));
1398 for (const entityId of fairies.despawnIds ?? [])
1399 {
1400 const dropped = this.#destroyEntity(entityId);
1401 if (dropped)
1402 { events.push({ type: "entity-despawn", entityId }); }
1403 }
1404 events.push(...stepJewelryTeleports(this, now).events);
1405 stepFollow(this);
1406 const gather = stepGather(this, now);
1407 events.push(...gather.events);
1408 for (const entry of gather.privates ?? [])
1409 {
1410 events.push({
1411 type: "inventory",
1412 characterId: entry.characterId,
1413 ...entry.bag
1414 });
1415 }
1416 const fire = stepFirestarting(this, now);
1417 events.push(...fire.events);
1418 for (const entry of fire.privates ?? [])
1419 {
1420 events.push({
1421 type: "inventory",
1422 characterId: entry.characterId,
1423 ...entry.bag
1424 });
1425 }
1426 const fishing = stepFishing(this, now);
1427 events.push(...fishing.events);
1428 for (const entry of fishing.privates ?? [])
1429 {
1430 events.push({
1431 type: "inventory",
1432 characterId: entry.characterId,
1433 ...entry.bag
1434 });
1435 }
1436 const shearing = stepShearing(this, now);
1437 events.push(...shearing.events);
1438 for (const entry of shearing.privates ?? [])
1439 {
1440 events.push({
1441 type: "inventory",
1442 characterId: entry.characterId,
1443 ...entry.bag
1444 });
1445 }
1446 const craft = stepCrafting(this, now);
1447 events.push(...craft.events);
1448 for (const entry of craft.privates ?? [])
1449 {
1450 events.push({
1451 type: "inventory",
1452 characterId: entry.characterId,
1453 ...entry.bag
1454 });
1455 }
1456 events.push(...stepDoors(this));
1457 return { events, transferRequests };
1458 }
1459
1460 #stepMovement (now = Date.now())
1461 {
1462 const events = expireGroundItems(this, now);
1463 const transferRequests = [];
1464 events.push(...pruneShopBrowsers(this));
1465 events.push(...this.#pruneDialogueBrowsers());
1466 this.#queueAmbientWander();
1467 this.#queueSpawnerWander();
1468 this.#queueExchangeStations();
1469 for (const entity of this.ecs.query(Component.position, Component.movement))
1470 {
1471 const { handle, entityId, position, movement } = entity;
1472 if (this.ecs.has(handle, Component.dead))
1473 { continue; }
1474 if (this.ecs.has(handle, Component.flight))
1475 { continue; }
1476 const path = this.ecs.get(handle, Component.path);
1477 const tiles = path?.tiles;
1478 if (this.frozen.has(entityId) || !tiles?.length)
1479 {
1480 if (path)
1481 { path.stuckSince = null; }
1482 continue;
1483 }
1484 if (!this.chunkIsSimulating(position.tileX, position.tileY, position.dimensionId ?? OVERWORLD_ID))
1485 { continue; }
1486
1487 this.#repathIfNavigationStuck(entityId, position, movement, path, now);
1488
1489 const stamina = this.ecs.get(handle, Component.stamina);
1490 if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0))
1491 { movement.gait = GAIT.walk; }
1492 const isWalk = movement.gait !== GAIT.run;
1493 if (isWalk)
1494 {
1495 movement.walkCarry = (movement.walkCarry + 1) % 2;
1496 if (movement.walkCarry !== 0)
1497 { continue; }
1498 }
1499
1500 const next = tiles[0];
1501 if (!next)
1502 { continue; }
1503 const destRegionX = tileToRegion(next.x);
1504 const destRegionY = tileToRegion(next.y);
1505 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
1506 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
1507 {
1508 this.frozen.add(entityId);
1509 transferRequests.push({
1510 entityId,
1511 fromTileX: position.tileX,
1512 fromTileY: position.tileY,
1513 destTileX: next.x,
1514 destTileY: next.y,
1515 toRegionX: destRegionX,
1516 toRegionY: destRegionY,
1517 dimensionId,
1518 payload: serializeEntity(this.ecs, entityId)
1519 });
1520 continue;
1521 }
1522
1523 if (!this.walkableFor(entityId, next.x, next.y))
1524 {
1525 const combat = this.ecs.get(handle, Component.combat);
1526 if (combat?.targetEntityId != null)
1527 {
1528 const targetHandle = this.ecs.handleOf(combat.targetEntityId);
1529 const targetPos = targetHandle != null
1530 ? this.ecs.get(targetHandle, Component.position)
1531 : null;
1532 const blockedByTarget = targetPos
1533 && next.x === targetPos.tileX
1534 && next.y === targetPos.tileY;
1535 if (!blockedByTarget)
1536 { path.tiles = []; }
1537 }
1538 continue;
1539 }
1540
1541 const doorDelta = maybeOpenDoorOnApproach(this, entityId, next.x, next.y);
1542 if (doorDelta)
1543 { events.push(doorDelta); }
1544
1545 const combat = this.ecs.get(handle, Component.combat);
1546 if (combat?.targetEntityId != null && !this.isClearStanding(entityId, next.x, next.y))
1547 { continue; }
1548
1549 const fromTileX = position.tileX;
1550 const fromTileY = position.tileY;
1551 const flying = this.#isFlying(handle);
1552 if (!flying)
1553 { this.#vacate(entityId, fromTileX, fromTileY); }
1554 position.tileX = next.x;
1555 position.tileY = next.y;
1556 tiles.shift();
1557 if (!flying)
1558 { this.#occupy(entityId, position.tileX, position.tileY, now); }
1559 path.stuckSince = now;
1560 path.stuckTileX = position.tileX;
1561 path.stuckTileY = position.tileY;
1562 recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
1563 consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
1564 syncCharacterChunkPresence(this.ecs, handle, now);
1565 if (!isWalk)
1566 { this.#consumeRunStamina(handle, events); }
1567 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
1568 }
1569 return { events, transferRequests };
1570 }
1571
1572 /**
1573 * If we still have a destination but have not left this tile for NAV_STUCK_MS,
1574 * recompute A* to the same goal (around whoever is blocking the old route).
1575 */
1576 #repathIfNavigationStuck (entityId, position, movement, path, now)
1577 {
1578 if (!path?.tiles?.length)
1579 {
1580 path.stuckSince = null;
1581 return;
1582 }
1583 if (
1584 path.stuckSince == null
1585 || path.stuckTileX !== position.tileX
1586 || path.stuckTileY !== position.tileY
1587 )
1588 {
1589 path.stuckSince = now;
1590 path.stuckTileX = position.tileX;
1591 path.stuckTileY = position.tileY;
1592 return;
1593 }
1594 if (now - path.stuckSince < NAV_STUCK_MS)
1595 { return; }
1596
1597 const goal = path.tiles[path.tiles.length - 1];
1598 if (!goal || (goal.x === position.tileX && goal.y === position.tileY))
1599 {
1600 path.tiles = [];
1601 path.stuckSince = null;
1602 return;
1603 }
1604 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1605 const stuckHandle = this.ecs.handleOf(entityId);
1606 const inCombat = stuckHandle != null
1607 && this.ecs.get(stuckHandle, Component.combat)?.targetEntityId != null;
1608 path.tiles = findPath(
1609 position.tileX,
1610 position.tileY,
1611 goal.x,
1612 goal.y,
1613 (x, y) => this.isClearStanding(entityId, x, y),
1614 bounds.minX,
1615 bounds.minY,
1616 bounds.maxX,
1617 bounds.maxY,
1618 this.pathfindOptions({
1619 preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character),
1620 preferPaths: !inCombat,
1621 entityId
1622 })
1623 );
1624 path.stuckSince = now;
1625 path.stuckTileX = position.tileX;
1626 path.stuckTileY = position.tileY;
1627 if (movement)
1628 { movement.walkCarry = 0; }
1629 }
1630
1631 #queueAmbientWander ()
1632 {
1633 for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature))
1634 {
1635 const def = mobDefinition(entity.creature.mobTypeId);
1636 if (!def?.ambient || def.freeFlight)
1637 { continue; }
1638 if (this.ecs.get(entity.handle, Component.spawnOrigin))
1639 { continue; }
1640 const path = this.ecs.get(entity.handle, Component.path);
1641 if (!path)
1642 { continue; }
1643 if (path.tiles?.length)
1644 { continue; }
1645 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1646 { continue; }
1647 if (Math.random() > 0.35)
1648 { continue; }
1649 const dirs = [
1650 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
1651 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
1652 ];
1653 const dir = dirs[Math.floor(Math.random() * dirs.length)];
1654 const nextX = entity.position.tileX + dir.x;
1655 const nextY = entity.position.tileY + dir.y;
1656 if (!this.isClearStanding(entity.entityId, nextX, nextY))
1657 { continue; }
1658 path.tiles = [{ x: nextX, y: nextY }];
1659 }
1660 }
1661
1662 /** Idle wander for spawner mobs: goals must stay within maxWanderRange of the spawner. Combat chase is unrestricted. */
1663 #queueSpawnerWander ()
1664 {
1665 for (const entity of this.ecs.query(Component.position, Component.movement, Component.spawnOrigin))
1666 {
1667 const combat = this.ecs.get(entity.handle, Component.combat);
1668 if (combat?.targetEntityId != null)
1669 { continue; }
1670 const follow = this.ecs.get(entity.handle, Component.follow);
1671 if (follow?.targetEntityId != null)
1672 { continue; }
1673 const shop = this.ecs.get(entity.handle, Component.shop);
1674 if (shopHasActiveBrowsers(shop))
1675 { continue; }
1676 const origin = entity.spawnOrigin;
1677 if (originIsBusyPinned(origin))
1678 { continue; }
1679 if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1680 { continue; }
1681 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
1682 if (def?.freeFlight)
1683 { continue; }
1684 const path = this.ecs.get(entity.handle, Component.path);
1685 if (!path || path.tiles?.length)
1686 { continue; }
1687 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1688 { continue; }
1689
1690 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
1691 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
1692 const range = Math.max(0, origin.wanderRangeTiles | 0);
1693 const homeDist = Math.max(
1694 Math.abs(entity.position.tileX - originX),
1695 Math.abs(entity.position.tileY - originY)
1696 );
1697 const tooFar = homeDist > range;
1698
1699 // Outside the leash: always try to step home. Inside: mostly idle.
1700 if (!tooFar && Math.random() > 0.1)
1701 { continue; }
1702
1703 if (tooFar)
1704 {
1705 if (this.#queueReturnTowardSpawn(entity.entityId, entity.handle, entity.position, path, originX, originY))
1706 { continue; }
1707 queueLocalRandomWanderStep(this, entity.entityId, entity.position, path);
1708 continue;
1709 }
1710
1711 const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range);
1712 if (!goal)
1713 { continue; }
1714 if (goal.tileX === entity.position.tileX && goal.tileY === entity.position.tileY)
1715 { continue; }
1716 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
1717 const tiles = findPath(
1718 entity.position.tileX,
1719 entity.position.tileY,
1720 goal.tileX,
1721 goal.tileY,
1722 (x, y) => this.walkableFor(entity.entityId, x, y),
1723 bounds.minX,
1724 bounds.minY,
1725 bounds.maxX,
1726 bounds.maxY,
1727 this.pathfindOptions({ preferPaths: true, entityId: entity.entityId })
1728 );
1729 if (!tiles?.length)
1730 { continue; }
1731 path.tiles = tiles;
1732 }
1733 }
1734
1735 /**
1736 * Path toward the spawner within the current pathfinding window (chunk-step home).
1737 * @returns {boolean} true if a return path was queued
1738 */
1739 #queueReturnTowardSpawn (entityId, handle, position, path, originX, originY)
1740 {
1741 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1742 const goal = pickClearGoalToward(
1743 this,
1744 entityId,
1745 position.tileX,
1746 position.tileY,
1747 originX,
1748 originY,
1749 bounds
1750 );
1751 if (!goal)
1752 { return false; }
1753 if (goal.tileX === position.tileX && goal.tileY === position.tileY)
1754 { return false; }
1755 const tiles = findPath(
1756 position.tileX,
1757 position.tileY,
1758 goal.tileX,
1759 goal.tileY,
1760 (x, y) => this.walkableFor(entityId, x, y),
1761 bounds.minX,
1762 bounds.minY,
1763 bounds.maxX,
1764 bounds.maxY,
1765 this.pathfindOptions({ preferPaths: true, entityId })
1766 );
1767 if (!tiles?.length)
1768 { return false; }
1769 path.tiles = tiles;
1770 const movement = this.ecs.get(handle, Component.movement);
1771 if (movement)
1772 { movement.walkCarry = 0; }
1773 return true;
1774 }
1775
1776 /**
1777 * Send an idle Central Exchange clerk to the staff-side tile of a counter.
1778 * message: { stationTileX, stationTileY }
1779 */
1780 #stationExchangeClerk (message)
1781 {
1782 const stationTileX = message.stationTileX | 0;
1783 const stationTileY = message.stationTileY | 0;
1784 if (!this.isEnterable(stationTileX, stationTileY))
1785 { return { ok: false, reason: "blocked" }; }
1786
1787 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1788 {
1789 if (!entity.spawnOrigin?.centralExchange)
1790 { continue; }
1791 if (
1792 Number.isInteger(entity.spawnOrigin.stationTileX)
1793 && entity.spawnOrigin.stationTileX === stationTileX
1794 && entity.spawnOrigin.stationTileY === stationTileY
1795 )
1796 { return { ok: true, entityId: entity.entityId, already: true }; }
1797 }
1798
1799 let best = null;
1800 let bestDist = Infinity;
1801 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
1802 {
1803 if (!entity.spawnOrigin?.centralExchange)
1804 { continue; }
1805 if (Number.isInteger(entity.spawnOrigin.stationTileX))
1806 { continue; }
1807 const dist = Math.max(
1808 Math.abs(entity.position.tileX - stationTileX),
1809 Math.abs(entity.position.tileY - stationTileY)
1810 );
1811 if (dist < bestDist)
1812 {
1813 bestDist = dist;
1814 best = entity;
1815 }
1816 }
1817 if (!best)
1818 { return { ok: false, reason: "none-available" }; }
1819
1820 const bounds = chunkBoundsAround(best.position.tileX, best.position.tileY, VISIBLE_CHUNK_RADIUS);
1821 const tiles = findPath(
1822 best.position.tileX,
1823 best.position.tileY,
1824 stationTileX,
1825 stationTileY,
1826 (x, y) => this.walkableFor(best.entityId, x, y),
1827 bounds.minX,
1828 bounds.minY,
1829 bounds.maxX,
1830 bounds.maxY,
1831 this.pathfindOptions({ preferPaths: true, entityId: best.entityId })
1832 );
1833 best.spawnOrigin.stationTileX = stationTileX;
1834 best.spawnOrigin.stationTileY = stationTileY;
1835 if (tiles?.length)
1836 { best.path.tiles = tiles; }
1837 else if (best.position.tileX === stationTileX && best.position.tileY === stationTileY)
1838 { best.path.tiles = []; }
1839 else
1840 { return { ok: false, reason: "no-path" }; }
1841 return { ok: true, entityId: best.entityId };
1842 }
1843
1844 /**
1845 * Clear a CE clerk's station assignment so wander can resume.
1846 * message: { stationTileX, stationTileY }
1847 */
1848 #releaseExchangeClerk (message)
1849 {
1850 const stationTileX = message.stationTileX | 0;
1851 const stationTileY = message.stationTileY | 0;
1852 let released = 0;
1853 for (const entity of this.ecs.query(Component.spawnOrigin, Component.path))
1854 {
1855 if (!entity.spawnOrigin?.centralExchange)
1856 { continue; }
1857 if (
1858 entity.spawnOrigin.stationTileX !== stationTileX
1859 || entity.spawnOrigin.stationTileY !== stationTileY
1860 )
1861 { continue; }
1862 entity.spawnOrigin.stationTileX = null;
1863 entity.spawnOrigin.stationTileY = null;
1864 entity.path.tiles = [];
1865 released += 1;
1866 }
1867 return { ok: true, released };
1868 }
1869
1870 #pinDialogue (entityId, characterId)
1871 {
1872 const handle = this.ecs.handleOf(entityId | 0);
1873 if (handle == null)
1874 { return { ok: false }; }
1875 const origin = this.ecs.get(handle, Component.spawnOrigin);
1876 if (!origin)
1877 { return { ok: false }; }
1878 if (!origin.dialogueBrowsers || typeof origin.dialogueBrowsers !== "object")
1879 { origin.dialogueBrowsers = Object.create(null); }
1880 origin.dialogueBrowsers[characterId | 0] = true;
1881 const path = this.ecs.get(handle, Component.path);
1882 if (path)
1883 { path.tiles = []; }
1884 return { ok: true };
1885 }
1886
1887 #unpinDialogue (entityId, characterId)
1888 {
1889 const handle = this.ecs.handleOf(entityId | 0);
1890 if (handle == null)
1891 { return { ok: false }; }
1892 const origin = this.ecs.get(handle, Component.spawnOrigin);
1893 if (!origin?.dialogueBrowsers)
1894 { return { ok: true }; }
1895 delete origin.dialogueBrowsers[characterId | 0];
1896 return { ok: true };
1897 }
1898
1899 #pruneDialogueBrowsers ()
1900 {
1901 const events = [];
1902 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1903 {
1904 const browsers = entity.spawnOrigin?.dialogueBrowsers;
1905 const shearBrowsers = entity.spawnOrigin?.shearBrowsers;
1906 const dialogueIds = browsers && typeof browsers === "object"
1907 ? Object.keys(browsers).map((id) => Number(id))
1908 : [];
1909 const shearIds = shearBrowsers && typeof shearBrowsers === "object"
1910 ? Object.keys(shearBrowsers).map((id) => Number(id))
1911 : [];
1912 if (!dialogueIds.length && !shearIds.length)
1913 { continue; }
1914 const path = this.ecs.get(entity.handle, Component.path);
1915 if (path)
1916 { path.tiles = []; }
1917 for (const characterId of dialogueIds)
1918 {
1919 const playerEntityId = this.characterEntities.get(characterId);
1920 if (playerEntityId == null)
1921 {
1922 delete browsers[characterId];
1923 continue;
1924 }
1925 const playerHandle = this.ecs.handleOf(playerEntityId);
1926 const playerPos = this.ecs.get(playerHandle, Component.position);
1927 const stillNear = playerPos
1928 && chebyshev(
1929 playerPos.tileX,
1930 playerPos.tileY,
1931 entity.position.tileX,
1932 entity.position.tileY
1933 ) <= 1;
1934 if (stillNear)
1935 { continue; }
1936 delete browsers[characterId];
1937 const identity = this.ecs.get(playerHandle, Component.networkIdentity);
1938 events.push({
1939 type: "dialogue-walk-away",
1940 sessionId: identity?.sessionId ?? null,
1941 characterId,
1942 npcEntityId: entity.entityId
1943 });
1944 }
1945 for (const characterId of shearIds)
1946 {
1947 const playerEntityId = this.characterEntities.get(characterId);
1948 if (playerEntityId == null)
1949 {
1950 delete shearBrowsers[characterId];
1951 continue;
1952 }
1953 const playerHandle = this.ecs.handleOf(playerEntityId);
1954 const playerPos = this.ecs.get(playerHandle, Component.position);
1955 const stillNear = playerPos
1956 && chebyshev(
1957 playerPos.tileX,
1958 playerPos.tileY,
1959 entity.position.tileX,
1960 entity.position.tileY
1961 ) <= 1;
1962 if (stillNear)
1963 { continue; }
1964 delete shearBrowsers[characterId];
1965 }
1966 }
1967 return events;
1968 }
1969
1970 /** Keep stationed CE clerks at their counter tile. */
1971 #queueExchangeStations ()
1972 {
1973 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
1974 {
1975 if (!entity.spawnOrigin?.centralExchange)
1976 { continue; }
1977 const sx = entity.spawnOrigin.stationTileX;
1978 const sy = entity.spawnOrigin.stationTileY;
1979 if (!Number.isInteger(sx) || !Number.isInteger(sy))
1980 { continue; }
1981 if (entity.position.tileX === sx && entity.position.tileY === sy)
1982 {
1983 entity.path.tiles = [];
1984 continue;
1985 }
1986 if (entity.path.tiles?.length)
1987 { continue; }
1988 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
1989 const tiles = findPath(
1990 entity.position.tileX,
1991 entity.position.tileY,
1992 sx,
1993 sy,
1994 (x, y) => this.walkableFor(entity.entityId, x, y),
1995 bounds.minX,
1996 bounds.minY,
1997 bounds.maxX,
1998 bounds.maxY,
1999 this.pathfindOptions({ preferPaths: true, entityId: entity.entityId })
2000 );
2001 if (tiles?.length)
2002 { entity.path.tiles = tiles; }
2003 }
2004 }
2005
2006 #applyTransfer (message)
2007 {
2008 const payload = message.payload;
2009 const entityId = payload.entityId;
2010 if (this.ecs.hasEntity(entityId))
2011 { return { accepted: false, reason: "already-present" }; }
2012
2013 const position = payload.components?.position;
2014 const destTileX = message.destTileX ?? position?.tileX;
2015 const destTileY = message.destTileY ?? position?.tileY;
2016 const dimensionId = normalizeDimensionId(
2017 message.dimensionId ?? position?.dimensionId ?? OVERWORLD_ID
2018 );
2019 if (destTileX == null || destTileY == null)
2020 { return { accepted: false, reason: "missing-destination" }; }
2021 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY), dimensionId))
2022 { return { accepted: false, reason: "not-owner" }; }
2023
2024 const creature = payload.components?.creature;
2025 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
2026 if (flying)
2027 {
2028 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY), dimensionId);
2029 if (!data?.open)
2030 { return { accepted: false, reason: "blocked" }; }
2031 }
2032 else if (!this.isEnterable(destTileX, destTileY, dimensionId))
2033 { return { accepted: false, reason: "blocked" }; }
2034
2035 deserializeEntity(this.ecs, payload);
2036 const handle = this.ecs.handleOf(entityId);
2037 const livePosition = this.ecs.get(handle, Component.position);
2038 const path = this.ecs.get(handle, Component.path);
2039 livePosition.tileX = destTileX;
2040 livePosition.tileY = destTileY;
2041 livePosition.dimensionId = dimensionId;
2042 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
2043 { path.tiles.shift(); }
2044 if (!flying)
2045 { this.#occupy(entityId, destTileX, destTileY); }
2046 const character = this.ecs.get(handle, Component.character);
2047 if (character?.characterId)
2048 { this.characterEntities.set(character.characterId, entityId); }
2049 this.frozen.delete(entityId);
2050 return {
2051 accepted: true,
2052 entity: publicEntityView(this.ecs, entityId)
2053 };
2054 }
2055
2056 #commitTransfer (entityId)
2057 {
2058 if (!this.ecs.hasEntity(entityId))
2059 { return null; }
2060 return this.#destroyEntity(entityId);
2061 }
2062
2063 #abortTransfer (entityId)
2064 {
2065 this.frozen.delete(entityId);
2066 return publicEntityView(this.ecs, entityId);
2067 }
2068
2069 #listLoaders ()
2070 {
2071 return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({
2072 entityId: entity.entityId,
2073 tileX: entity.position.tileX,
2074 tileY: entity.position.tileY,
2075 dimensionId: normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID),
2076 chunkLoader: { ...entity.chunkLoader }
2077 }));
2078 }
2079
2080 #listPublicEntities ()
2081 {
2082 const out = [];
2083 for (const entity of this.ecs.query(Component.position))
2084 {
2085 if (this.ecs.has(entity.handle, Component.dead))
2086 { continue; }
2087 const view = publicEntityView(this.ecs, entity.entityId);
2088 if (view)
2089 { out.push(view); }
2090 }
2091 return out;
2092 }
2093
2094 #entitiesInRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
2095 {
2096 const dim = normalizeDimensionId(dimensionId);
2097 const records = [];
2098 for (const entity of this.ecs.query(Component.position))
2099 {
2100 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
2101 if (entityDim !== dim)
2102 { continue; }
2103 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
2104 { continue; }
2105 records.push({
2106 ...publicEntityView(this.ecs, entity.entityId),
2107 persistent: this.ecs.has(entity.handle, Component.persistent),
2108 payload: serializeEntity(this.ecs, entity.entityId)
2109 });
2110 }
2111 return records;
2112 }
2113
2114 #chunkSnapshot (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID)
2115 {
2116 const dim = normalizeDimensionId(dimensionId);
2117 const data = this.#chunkData(chunkX, chunkY, dim);
2118 if (staticOnly)
2119 {
2120 return {
2121 chunkX,
2122 chunkY,
2123 dimensionId: dim,
2124 open: data.open,
2125 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open),
2126 grounds: data.grounds,
2127 blocks: data.blocks,
2128 light: data.light,
2129 occlusion: data.occlusion,
2130 entities: [],
2131 groundItems: []
2132 };
2133 }
2134 const entities = [];
2135 for (const entity of this.ecs.query(Component.position, Component.appearance))
2136 {
2137 if (this.ecs.has(entity.handle, Component.dead))
2138 { continue; }
2139 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
2140 if (entityDim !== dim)
2141 { continue; }
2142 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
2143 { continue; }
2144 entities.push(publicEntityView(this.ecs, entity.entityId));
2145 }
2146 return {
2147 chunkX,
2148 chunkY,
2149 dimensionId: dim,
2150 open: data.open,
2151 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open),
2152 grounds: data.grounds,
2153 blocks: data.blocks,
2154 light: data.light,
2155 occlusion: data.occlusion,
2156 entities,
2157 groundItems: groundItemsInChunk(this, chunkX, chunkY)
2158 };
2159 }
2160
2161 #moveEvent (entityId, fromTileX, fromTileY)
2162 {
2163 const view = publicEntityView(this.ecs, entityId);
2164 return {
2165 type: "entity-move",
2166 entityId,
2167 fromTileX,
2168 fromTileY,
2169 tileX: view.tileX,
2170 tileY: view.tileY,
2171 worldX: view.worldX,
2172 worldY: view.worldY,
2173 gait: view.gait,
2174 freeFlight: !!view.freeFlight
2175 };
2176 }
2177
2178 chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
2179 {
2180 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId));
2181 return !!chunk && !chunk.replica && chunk.simulating;
2182 }
2183
2184 walkableFor (entityId, tileX, tileY)
2185 {
2186 const dim = this.#entityDimensionId(entityId);
2187 const handle = this.ecs.handleOf(entityId);
2188 if (this.#isFlying(handle))
2189 {
2190 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
2191 return !!data?.open;
2192 }
2193 // Entities pass through each other; only terrain / closed chunks block movement.
2194 return this.isEnterable(tileX, tileY, dim, {
2195 canOpenDoors: entityCanOpenDoors(this.ecs, entityId)
2196 });
2197 }
2198
2199 /** Ground type id at a world tile (defaults to world default ground). */
2200 groundTypeAt (tileX, tileY, dimensionId = OVERWORLD_ID)
2201 {
2202 const dim = normalizeDimensionId(dimensionId) ?? OVERWORLD_ID;
2203 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
2204 const entry = normalizeGround(data.grounds[tileIndex(tileToLocal(tileX), tileToLocal(tileY))]);
2205 return entry?.typeId ?? this.settings.defaultGroundTypeId ?? GroundType.grass;
2206 }
2207
2208 /**
2209 * @param {{ preferVertical?: boolean, preferPaths?: boolean, entityId?: number | null }} [options]
2210 */
2211 pathfindOptions ({ preferVertical = false, preferPaths = false, entityId = null } = {})
2212 {
2213 const options = { preferVertical: !!preferVertical };
2214 const now = Date.now();
2215 const dimensionId = entityId != null ? this.#entityDimensionId(entityId) : OVERWORLD_ID;
2216 options.stepCost = (x, y) => stepCostForGround(
2217 this.groundTypeAt(x, y, dimensionId),
2218 {
2219 preferPaths: !!preferPaths,
2220 softOccupied: entityId != null && this.#isSoftOccupiedTile(x, y, dimensionId, entityId, now)
2221 }
2222 );
2223 options.minStepCost = preferPaths ? PATH_GROUND_STEP_COST : 1;
2224 return options;
2225 }
2226
2227 /**
2228 * True when another living occupant has stood on this tile for SOFT_OCCUPIED_DWELL_MS+.
2229 * Soft cost only — never blocks pathing.
2230 */
2231 #isSoftOccupiedTile (tileX, tileY, dimensionId, selfEntityId, now = Date.now())
2232 {
2233 const key = tileKey(tileX, tileY, dimensionId);
2234 const local = this.occupancy.get(key);
2235 if (!local?.size)
2236 { return false; }
2237 for (const id of local)
2238 {
2239 if (id === selfEntityId)
2240 { continue; }
2241 const handle = this.ecs.handleOf(id);
2242 if (handle == null)
2243 { continue; }
2244 const position = this.ecs.get(handle, Component.position);
2245 const enteredAt = position?.tileEnteredAt;
2246 if (enteredAt == null)
2247 { continue; }
2248 if (now - enteredAt >= SOFT_OCCUPIED_DWELL_MS)
2249 { return true; }
2250 }
2251 return false;
2252 }
2253
2254 /**
2255 * Standing tile with no other mob/player (self allowed). Used for wander goals
2256 * and melee attack stance.
2257 */
2258 isClearStanding (entityId, tileX, tileY)
2259 {
2260 const dim = this.#entityDimensionId(entityId);
2261 if (!this.isEnterable(tileX, tileY, dim, {
2262 canOpenDoors: entityCanOpenDoors(this.ecs, entityId)
2263 }))
2264 { return false; }
2265 return !this.#hasOtherOccupant(entityId, tileX, tileY, dim);
2266 }
2267
2268 destroyEntity (entityId)
2269 {
2270 return this.#destroyEntity(entityId);
2271 }
2272
2273 occupied (tileX, tileY, dimensionId = OVERWORLD_ID)
2274 {
2275 return this.#anyOccupant(tileX, tileY, dimensionId);
2276 }
2277
2278 #chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
2279 {
2280 return this.chunkIsSimulating(tileX, tileY, dimensionId);
2281 }
2282
2283 #chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2284 {
2285 const loaded = this.chunks.get(chunkKey(chunkX, chunkY, dimensionId));
2286 if (loaded)
2287 { return loaded.data; }
2288 return createEmptyChunkData(this.settings.defaultGroundTypeId);
2289 }
2290
2291 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID, { canOpenDoors = false } = {})
2292 {
2293 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2294 if (!data.open)
2295 { return false; }
2296 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY), { canOpenDoors });
2297 }
2298
2299 isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID)
2300 {
2301 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2302 if (!data.open)
2303 { return false; }
2304 return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY));
2305 }
2306
2307 #walkableFor (entityId, tileX, tileY)
2308 {
2309 return this.walkableFor(entityId, tileX, tileY);
2310 }
2311
2312 #isFlying (handle)
2313 {
2314 if (handle == null)
2315 { return false; }
2316 const creature = this.ecs.get(handle, Component.creature);
2317 return !!mobDefinition(creature?.mobTypeId)?.flying;
2318 }
2319
2320 #entityDimensionId (entityId)
2321 {
2322 const handle = this.ecs.handleOf(entityId);
2323 const position = handle != null ? this.ecs.get(handle, Component.position) : null;
2324 return normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID);
2325 }
2326
2327 #occupy (entityId, tileX, tileY, now = Date.now())
2328 {
2329 const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId));
2330 let set = this.occupancy.get(key);
2331 if (!set)
2332 {
2333 set = new Set();
2334 this.occupancy.set(key, set);
2335 }
2336 set.add(entityId);
2337 const handle = this.ecs.handleOf(entityId);
2338 const position = handle != null ? this.ecs.get(handle, Component.position) : null;
2339 if (position)
2340 { position.tileEnteredAt = now; }
2341 }
2342
2343 #vacate (entityId, tileX, tileY)
2344 {
2345 const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId));
2346 const set = this.occupancy.get(key);
2347 if (!set)
2348 { return; }
2349 set.delete(entityId);
2350 if (set.size === 0)
2351 { this.occupancy.delete(key); }
2352 }
2353
2354 #anyOccupant (tileX, tileY, dimensionId = OVERWORLD_ID)
2355 {
2356 const key = tileKey(tileX, tileY, dimensionId);
2357 const local = this.occupancy.get(key);
2358 if (local?.size)
2359 { return local.values().next().value; }
2360 const ghosts = this.ghostOccupancy.get(key);
2361 if (ghosts?.size)
2362 { return ghosts.values().next().value; }
2363 return null;
2364 }
2365
2366 #hasOtherOccupant (entityId, tileX, tileY, dimensionId = null)
2367 {
2368 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : this.#entityDimensionId(entityId);
2369 const key = tileKey(tileX, tileY, dim);
2370 const local = this.occupancy.get(key);
2371 if (local)
2372 {
2373 for (const id of local)
2374 {
2375 if (id !== entityId)
2376 { return true; }
2377 }
2378 }
2379 const ghosts = this.ghostOccupancy.get(key);
2380 if (ghosts)
2381 {
2382 for (const id of ghosts)
2383 {
2384 if (id !== entityId)
2385 { return true; }
2386 }
2387 }
2388 return false;
2389 }
2390
2391 /** @deprecated use #anyOccupant — kept name for call sites expecting a single id */
2392 #occupied (tileX, tileY, dimensionId = OVERWORLD_ID)
2393 {
2394 return this.#anyOccupant(tileX, tileY, dimensionId);
2395 }
2396}
2397
2398function pickWanderGoalInRange (world, entityId, originX, originY, range)
2399{
2400 const radius = Math.max(0, range | 0);
2401 for (let attempt = 0; attempt < 24; attempt++)
2402 {
2403 const tileX = originX + randInt(-radius, radius);
2404 const tileY = originY + randInt(-radius, radius);
2405 if (!world.isClearStanding(entityId, tileX, tileY))
2406 { continue; }
2407 return { tileX, tileY };
2408 }
2409 return null;
2410}
2411
2412/**
2413 * Clearest standable tile in pathfinding bounds, pulled toward (destX, destY).
2414 * When the destination is outside the window this becomes a chunk-step toward home.
2415 */
2416function pickClearGoalToward (world, entityId, fromX, fromY, destX, destY, bounds)
2417{
2418 const idealX = Math.max(bounds.minX, Math.min(bounds.maxX, destX | 0));
2419 const idealY = Math.max(bounds.minY, Math.min(bounds.maxY, destY | 0));
2420 if (world.isClearStanding(entityId, idealX, idealY))
2421 { return { tileX: idealX, tileY: idealY }; }
2422 for (let radius = 1; radius <= 4; radius++)
2423 {
2424 for (let dy = -radius; dy <= radius; dy++)
2425 {
2426 for (let dx = -radius; dx <= radius; dx++)
2427 {
2428 if (Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
2429 { continue; }
2430 const tileX = idealX + dx;
2431 const tileY = idealY + dy;
2432 if (tileX < bounds.minX || tileX > bounds.maxX || tileY < bounds.minY || tileY > bounds.maxY)
2433 { continue; }
2434 if (tileX === fromX && tileY === fromY)
2435 { continue; }
2436 if (!world.isClearStanding(entityId, tileX, tileY))
2437 { continue; }
2438 return { tileX, tileY };
2439 }
2440 }
2441 }
2442 return null;
2443}
2444
2445/** One random adjacent step so a stranded mob does not freeze in place. */
2446function queueLocalRandomWanderStep (world, entityId, position, path)
2447{
2448 const dirs = [
2449 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
2450 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
2451 ];
2452 for (let i = dirs.length - 1; i > 0; i--)
2453 {
2454 const j = Math.floor(Math.random() * (i + 1));
2455 const tmp = dirs[i];
2456 dirs[i] = dirs[j];
2457 dirs[j] = tmp;
2458 }
2459 for (const dir of dirs)
2460 {
2461 const nextX = position.tileX + dir.x;
2462 const nextY = position.tileY + dir.y;
2463 if (!world.isClearStanding(entityId, nextX, nextY))
2464 { continue; }
2465 path.tiles = [{ x: nextX, y: nextY }];
2466 return true;
2467 }
2468 return false;
2469}
2470
2471function hasDialogueBrowsers (origin)
2472{
2473 return originIsBusyPinned(origin);
2474}
2475
2476function randInt (min, max)
2477{
2478 return min + Math.floor(Math.random() * (max - min + 1));
2479}
2480
2481export function replicaNeededForOwnedChunks (ownedChunkKeys)
2482{
2483 const needed = new Set();
2484 for (const key of ownedChunkKeys)
2485 {
2486 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
2487 for (let dy = -1; dy <= 1; dy++)
2488 {
2489 for (let dx = -1; dx <= 1; dx++)
2490 {
2491 if (dx === 0 && dy === 0)
2492 { continue; }
2493 needed.add(chunkKey(chunkX + dx, chunkY + dy, dimensionId));
2494 }
2495 }
2496 }
2497 return needed;
2498}