BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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