BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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