BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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