BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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