BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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