BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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