BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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