BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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