BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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