BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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