BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

workerWorld.js 32.3 KiB Download Raw
1import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS } 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 {
34 applyRemoteMeleeSwing,
35 clearEngage,
36 engageTarget,
37 ensureMobCombat,
38 isUntargetable,
39 resolveCombatTarget,
40 stepCombat
41} from "../combat/service.js";
42import { awardCombatHitXp } from "../skills/service.js";
43import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
44import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
45
46export class WorkerWorld
47{
48 constructor (workerId)
49 {
50 this.workerId = workerId;
51 this.ecs = new EcsWorld();
52 this.chunks = new Map();
53 this.ownedRegions = new Set();
54 this.occupancy = new Map();
55 this.ghosts = new Map();
56 this.ghostOccupancy = new Map();
57 this.characterEntities = new Map();
58 this.frozen = new Set();
59 this.groundItems = new Map();
60 this.groundByTile = new Map();
61 this.settings = { ...DEFAULT_WORLD_SETTINGS };
62 this.activeRevisionId = 1;
63 }
64
65 handle (message)
66 {
67 switch (message.type)
68 {
69 case WorkerMessage.configure:
70 return this.#configure(message);
71 case WorkerMessage.assignRegion:
72 return this.#assignRegion(message);
73 case WorkerMessage.dropRegion:
74 return this.#dropRegion(message);
75 case WorkerMessage.replaceRegionChunks:
76 return this.#replaceRegionChunks(message);
77 case WorkerMessage.setReplicas:
78 return this.#setReplicas(message);
79 case WorkerMessage.setSimulatingChunks:
80 return this.#setSimulatingChunks(message);
81 case WorkerMessage.setGhosts:
82 return this.#setGhosts(message);
83 case WorkerMessage.spawn:
84 return this.#spawn(message);
85 case WorkerMessage.despawn:
86 return this.#despawn(message.entityId);
87 case WorkerMessage.despawnCharacter:
88 return this.#despawnCharacter(message.characterId);
89 case WorkerMessage.command:
90 return this.#command(message);
91 case WorkerMessage.stepMovement:
92 return this.#stepMovement(message.now);
93 case WorkerMessage.stepSystems:
94 return this.#stepSystems(message.now);
95 case WorkerMessage.stepSpawners:
96 return { spawnRequests: collectSpawnRequests(this) };
97 case WorkerMessage.setGroundItems:
98 setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion);
99 return { ok: true };
100 case WorkerMessage.inspectBag:
101 return this.#inspectBag(message.entityId);
102 case WorkerMessage.inspectSkills:
103 return this.#inspectSkills(message.entityId);
104 case WorkerMessage.applyBag:
105 return this.#applyBag(message.entityId, message.bag);
106 case WorkerMessage.updateFlight:
107 return this.#updateFlight(message.entityId, message.flight, message.now);
108 case WorkerMessage.chunkIsSimulating:
109 return this.chunkIsSimulating(message.tileX, message.tileY);
110 case WorkerMessage.applyTransfer:
111 return this.#applyTransfer(message);
112 case WorkerMessage.commitTransfer:
113 return this.#commitTransfer(message.entityId);
114 case WorkerMessage.abortTransfer:
115 return this.#abortTransfer(message.entityId);
116 case WorkerMessage.snapshotChunk:
117 return this.#chunkSnapshot(message.chunkX, message.chunkY);
118 case WorkerMessage.listLoaders:
119 return this.#listLoaders();
120 case WorkerMessage.listPublicEntities:
121 return this.#listPublicEntities();
122 case WorkerMessage.entitiesInRegion:
123 return this.#entitiesInRegion(message.regionX, message.regionY);
124 case WorkerMessage.inspect:
125 return publicEntityView(this.ecs, message.entityId);
126 case WorkerMessage.remoteCombatEngage:
127 return this.#remoteCombatEngage(message);
128 case WorkerMessage.applyRemoteMelee:
129 return this.#applyRemoteMelee(message);
130 case WorkerMessage.applyCombatHitXp:
131 return this.#applyCombatHitXp(message);
132 case WorkerMessage.spawnCorpseDrops:
133 return this.#spawnCorpseDrops(message);
134 case WorkerMessage.applyRespawn:
135 return this.#applyRespawn(message);
136 case WorkerMessage.clearCombat:
137 clearEngage(this.ecs, message.entityId);
138 for (const entity of this.ecs.query(Component.combat))
139 {
140 if (entity.combat.targetEntityId === message.targetEntityId)
141 { entity.combat.targetEntityId = null; }
142 }
143 return { ok: true };
144 default:
145 throw new Error(`Unknown worker message ${message.type}`);
146 }
147 }
148
149 ownsRegion (regionX, regionY)
150 {
151 return this.ownedRegions.has(regionKey(regionX, regionY));
152 }
153
154 requireOwnedEntity (sessionId, characterId)
155 {
156 return this.#requireOwnedEntity(sessionId, characterId);
157 }
158
159 chunkData (chunkX, chunkY)
160 {
161 return this.#chunkData(chunkX, chunkY);
162 }
163
164 occupied (tileX, tileY)
165 {
166 return this.#occupied(tileX, tileY);
167 }
168
169 #configure (message)
170 {
171 if (message.settings)
172 { this.settings = { ...this.settings, ...message.settings }; }
173 if (message.activeRevisionId != null)
174 { this.activeRevisionId = message.activeRevisionId; }
175 return { ok: true };
176 }
177
178 #assignRegion (message)
179 {
180 this.ownedRegions.add(regionKey(message.regionX, message.regionY));
181 for (const chunk of message.chunks ?? [])
182 {
183 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
184 data: cloneChunkData(chunk.data),
185 simulating: false,
186 replica: false
187 });
188 }
189 return { ok: true };
190 }
191
192 #replaceRegionChunks (message)
193 {
194 for (const chunk of message.chunks ?? [])
195 {
196 const key = chunkKey(chunk.chunkX, chunk.chunkY);
197 const existing = this.chunks.get(key);
198 this.chunks.set(key, {
199 data: cloneChunkData(chunk.data),
200 simulating: existing?.simulating ?? false,
201 replica: existing?.replica ?? false
202 });
203 }
204 return { ok: true };
205 }
206
207 #dropRegion (message)
208 {
209 const dropped = [];
210 for (const record of this.#entitiesInRegion(message.regionX, message.regionY))
211 {
212 const components = record.payload?.components;
213 if (components?.creature && !components?.character && components?.health)
214 { components.health.current = components.health.max; }
215 dropped.push(record);
216 this.#destroyEntity(record.entityId);
217 }
218 const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion);
219 for (const item of groundItems)
220 { removeGroundItem(this, item.groundItemId); }
221 for (const [key, chunk] of [...this.chunks.entries()])
222 {
223 const { chunkX, chunkY } = parseChunkKey(key);
224 if (chunk.replica)
225 { continue; }
226 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
227 { this.chunks.delete(key); }
228 }
229 this.ownedRegions.delete(regionKey(message.regionX, message.regionY));
230 return { dropped, groundItems };
231 }
232
233 #setReplicas (message)
234 {
235 const keep = new Set();
236 for (const chunk of message.chunks ?? [])
237 {
238 const key = chunkKey(chunk.chunkX, chunk.chunkY);
239 keep.add(key);
240 const existing = this.chunks.get(key);
241 if (existing && !existing.replica)
242 { continue; }
243 this.chunks.set(key, {
244 data: cloneChunkData(chunk.data),
245 simulating: false,
246 replica: true
247 });
248 }
249 for (const [key, chunk] of [...this.chunks.entries()])
250 {
251 if (chunk.replica && !keep.has(key))
252 { this.chunks.delete(key); }
253 }
254 return { ok: true };
255 }
256
257 #setSimulatingChunks (message)
258 {
259 const simulating = new Set(message.chunkKeys ?? []);
260 for (const [key, chunk] of this.chunks)
261 {
262 if (chunk.replica)
263 {
264 chunk.simulating = false;
265 continue;
266 }
267 chunk.simulating = simulating.has(key);
268 }
269 return { ok: true };
270 }
271
272 #setGhosts (message)
273 {
274 this.ghosts.clear();
275 this.ghostOccupancy.clear();
276 for (const ghost of message.ghosts ?? [])
277 {
278 this.ghosts.set(ghost.entityId, ghost);
279 this.ghostOccupancy.set(tileKey(ghost.tileX, ghost.tileY), ghost.entityId);
280 }
281 return { ok: true };
282 }
283
284 #spawn (message)
285 {
286 const entityId = deserializeEntity(this.ecs, message);
287 const handle = this.ecs.handleOf(entityId);
288 const position = this.ecs.get(handle, Component.position);
289 if (!position)
290 {
291 this.ecs.destroy(handle);
292 throw new Error("Spawned entity is missing position.");
293 }
294 const flying = this.#isFlying(handle);
295 if (!flying)
296 {
297 const occupant = this.#occupied(position.tileX, position.tileY);
298 if (occupant && occupant !== entityId)
299 {
300 this.ecs.destroy(handle);
301 const error = new Error("That tile is occupied.");
302 error.userFacing = true;
303 throw error;
304 }
305 this.#occupy(entityId, position.tileX, position.tileY);
306 }
307 const creature = this.ecs.get(handle, Component.creature);
308 const def = creature ? mobDefinition(creature.mobTypeId) : null;
309 if (def?.freeFlight)
310 { ensureFlightComponent(this.ecs, handle, position, def); }
311 const character = this.ecs.get(handle, Component.character);
312 if (character?.characterId)
313 { this.characterEntities.set(character.characterId, entityId); }
314 return publicEntityView(this.ecs, entityId);
315 }
316
317 #despawn (entityId)
318 {
319 return this.#destroyEntity(entityId);
320 }
321
322 #despawnCharacter (characterId)
323 {
324 const entityId = this.characterEntities.get(characterId);
325 if (!entityId)
326 { return null; }
327 return this.#destroyEntity(entityId);
328 }
329
330 #destroyEntity (entityId)
331 {
332 const handle = this.ecs.handleOf(entityId);
333 if (handle == null)
334 { return null; }
335 const view = publicEntityView(this.ecs, entityId);
336 const position = this.ecs.get(handle, Component.position);
337 const character = this.ecs.get(handle, Component.character);
338 if (position && !this.#isFlying(handle))
339 { this.#vacate(entityId, position.tileX, position.tileY); }
340 if (character?.characterId)
341 { this.characterEntities.delete(character.characterId); }
342 this.frozen.delete(entityId);
343 this.ecs.destroy(handle);
344 return view;
345 }
346
347 #command (message)
348 {
349 const { sessionId, command } = message;
350 switch (command.type)
351 {
352 case "move-to":
353 this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
354 return { events: [] };
355 case "set-gait":
356 this.#setGait(sessionId, command.characterId, command.gait);
357 return { events: [] };
358 case "attack":
359 return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
360 case "cancel-attack":
361 return this.#cancelAttack(sessionId, command.characterId);
362 case "interact":
363 return this.#interact(sessionId, command.characterId, command.targetEntityId);
364 case "follow":
365 return this.#follow(sessionId, command.characterId, command.targetEntityId);
366 case "cancel-follow":
367 return this.#cancelFollow(sessionId, command.characterId);
368 default:
369 {
370 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
371 return result ?? { events: [] };
372 }
373 }
374 }
375
376 #spawnCorpseDrops (message)
377 {
378 const events = [];
379 for (const drop of message.drops ?? [])
380 {
381 const item = {
382 groundItemId: drop.groundItemId,
383 tileX: message.tileX,
384 tileY: message.tileY,
385 stack: { itemId: drop.itemId, quantity: 1 },
386 droppedAt: message.now,
387 expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000),
388 source: "player-death",
389 droppedByCharacterId: message.characterId
390 };
391 addGroundItem(this, item);
392 events.push({
393 type: "ground-item-appear",
394 ...publicGroundItem(item),
395 stack: item.stack,
396 droppedAt: item.droppedAt,
397 source: item.source,
398 droppedByCharacterId: item.droppedByCharacterId,
399 expiresAt: item.expiresAt
400 });
401 }
402 return { events };
403 }
404
405 #applyRespawn (message)
406 {
407 const handle = this.ecs.handleOf(message.entityId);
408 if (handle == null || !this.ecs.has(handle, Component.dead))
409 { return { accepted: false }; }
410 const position = this.ecs.get(handle, Component.position);
411 const fromTileX = position.tileX;
412 const fromTileY = position.tileY;
413 const health = this.ecs.get(handle, Component.health);
414 const stamina = this.ecs.get(handle, Component.stamina);
415 if (health)
416 {
417 health.max = message.maxHealth;
418 health.current = message.maxHealth;
419 }
420 if (stamina)
421 {
422 stamina.max = message.maxStamina;
423 stamina.current = message.maxStamina;
424 }
425 else
426 { this.ecs.add(handle, Component.stamina, { current: message.maxStamina, max: message.maxStamina }); }
427 this.ecs.remove(handle, Component.dead);
428 clearEngage(this.ecs, message.entityId);
429 const path = this.ecs.get(handle, Component.path);
430 if (path)
431 { path.tiles = []; }
432 clearFollow(this.ecs, message.entityId);
433
434 const destRegionX = tileToRegion(message.tileX);
435 const destRegionY = tileToRegion(message.tileY);
436 if (!this.ownsRegion(destRegionX, destRegionY))
437 {
438 this.frozen.add(message.entityId);
439 return {
440 accepted: true,
441 transferRequest: {
442 entityId: message.entityId,
443 fromTileX,
444 fromTileY,
445 destTileX: message.tileX,
446 destTileY: message.tileY,
447 toRegionX: destRegionX,
448 toRegionY: destRegionY,
449 payload: serializeEntity(this.ecs, message.entityId)
450 }
451 };
452 }
453 const occupant = this.#occupied(message.tileX, message.tileY);
454 if (!this.isEnterable(message.tileX, message.tileY)
455 || (occupant && occupant !== message.entityId))
456 { return { accepted: false }; }
457 this.#vacate(message.entityId, fromTileX, fromTileY);
458 position.tileX = message.tileX;
459 position.tileY = message.tileY;
460 this.#occupy(message.entityId, position.tileX, position.tileY);
461 return {
462 accepted: true,
463 event: {
464 type: "entity-move",
465 entityId: message.entityId,
466 fromTileX,
467 fromTileY,
468 tileX: position.tileX,
469 tileY: position.tileY,
470 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
471 }
472 };
473 }
474
475 #inspectBag (entityId)
476 {
477 const handle = this.ecs.handleOf(entityId);
478 if (handle == null)
479 { return null; }
480 return bagView(this.ecs, handle);
481 }
482
483 #inspectSkills (entityId)
484 {
485 const handle = this.ecs.handleOf(entityId);
486 if (handle == null)
487 { return null; }
488 const skills = this.ecs.get(handle, Component.skills);
489 if (!skills?.xp)
490 { return null; }
491 return skills;
492 }
493
494 #applyBag (entityId, bag)
495 {
496 const handle = this.ecs.handleOf(entityId);
497 if (handle == null)
498 { return null; }
499 return applyBagView(this.ecs, handle, bag);
500 }
501
502 #updateFlight (entityId, flightPatch, now = Date.now())
503 {
504 const handle = this.ecs.handleOf(entityId);
505 if (handle == null)
506 { return null; }
507 let flight = this.ecs.get(handle, Component.flight);
508 if (!flight)
509 { flight = this.ecs.add(handle, Component.flight, { ...flightPatch }); }
510 else
511 { Object.assign(flight, flightPatch); }
512 const position = this.ecs.get(handle, Component.position);
513 const movement = this.ecs.get(handle, Component.movement);
514 const fromTileX = position.tileX;
515 const fromTileY = position.tileY;
516 const tileX = Math.floor(flight.x);
517 const tileY = Math.floor(flight.y);
518 position.tileX = tileX;
519 position.tileY = tileY;
520 const destRegionX = tileToRegion(tileX);
521 const destRegionY = tileToRegion(tileY);
522 if (!this.ownsRegion(destRegionX, destRegionY))
523 {
524 this.frozen.add(entityId);
525 return {
526 transferRequest: {
527 type: "transfer-request",
528 entityId,
529 fromTileX,
530 fromTileY,
531 destTileX: tileX,
532 destTileY: tileY,
533 toRegionX: destRegionX,
534 toRegionY: destRegionY
535 }
536 };
537 }
538 const dt = flight.lastAt && now > flight.lastAt
539 ? Math.min(0.25, (now - flight.lastAt) / 1000)
540 : 1 / 20;
541 return {
542 event: {
543 type: "entity-move",
544 entityId,
545 fromTileX,
546 fromTileY,
547 tileX,
548 tileY,
549 worldX: flight.x,
550 worldY: flight.y,
551 gait: movement?.gait ?? "walk",
552 lerpMs: Math.max(50, Math.round(dt * 1000)),
553 freeFlight: true
554 }
555 };
556 }
557
558 #moveTo (sessionId, characterId, tileX, tileY)
559 {
560 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
561 if (this.frozen.has(entityId))
562 { return; }
563 clearEngage(this.ecs, entityId);
564 clearFollow(this.ecs, entityId);
565 const position = this.ecs.get(handle, Component.position);
566 const movement = this.ecs.get(handle, Component.movement);
567 let path = this.ecs.get(handle, Component.path);
568 if (!path)
569 { path = this.ecs.add(handle, Component.path, { tiles: [] }); }
570 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
571 path.tiles = findPath(
572 position.tileX,
573 position.tileY,
574 tileX,
575 tileY,
576 (x, y) => this.walkableFor(entityId, x, y),
577 bounds.minX,
578 bounds.minY,
579 bounds.maxX,
580 bounds.maxY
581 );
582 movement.walkCarry = 0;
583 }
584
585 #attack (sessionId, characterId, targetEntityId, now)
586 {
587 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
588 if (targetEntityId === entityId)
589 {
590 const error = new Error("Cannot attack yourself.");
591 error.userFacing = true;
592 throw error;
593 }
594 const target = resolveCombatTarget(this, targetEntityId);
595 if (!target)
596 {
597 const error = new Error("Target is not here.");
598 error.userFacing = true;
599 throw error;
600 }
601 if (target.health && target.health.current <= 0)
602 {
603 const error = new Error("That cannot be attacked.");
604 error.userFacing = true;
605 throw error;
606 }
607 if (!this.ecs.get(handle, Component.combat))
608 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
609 clearFollow(this.ecs, entityId);
610 engageTarget(this.ecs, entityId, targetEntityId, now);
611 if (target.local)
612 {
613 if (ensureMobCombat(this.ecs, targetEntityId))
614 { engageTarget(this.ecs, targetEntityId, entityId, now); }
615 const targetPath = this.ecs.get(target.handle, Component.path);
616 if (targetPath)
617 { targetPath.tiles = []; }
618 }
619 const path = this.ecs.get(handle, Component.path);
620 if (path)
621 { path.tiles = []; }
622 return { events: [] };
623 }
624
625 #remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() })
626 {
627 const targetHandle = this.ecs.handleOf(targetEntityId);
628 if (targetHandle == null)
629 { return { events: [] }; }
630 if (ensureMobCombat(this.ecs, targetEntityId))
631 {
632 engageTarget(this.ecs, targetEntityId, attackerEntityId, now);
633 const targetPath = this.ecs.get(targetHandle, Component.path);
634 if (targetPath)
635 { targetPath.tiles = []; }
636 }
637 else if (this.ecs.get(targetHandle, Component.character))
638 {
639 engageTarget(this.ecs, targetEntityId, attackerEntityId, now);
640 const targetPath = this.ecs.get(targetHandle, Component.path);
641 if (targetPath)
642 { targetPath.tiles = []; }
643 }
644 return { events: [] };
645 }
646
647 #applyRemoteMelee (payload)
648 {
649 return applyRemoteMeleeSwing(this, payload);
650 }
651
652 #applyCombatHitXp ({ entityId, profile })
653 {
654 const handle = this.ecs.handleOf(entityId);
655 if (handle == null)
656 { return { events: [] }; }
657 const character = this.ecs.get(handle, Component.character);
658 if (!character)
659 { return { events: [] }; }
660 const xpAward = awardCombatHitXp(this.ecs, handle, profile);
661 if (!xpAward)
662 { return { events: [] }; }
663 return {
664 events: [{
665 type: "skills-updated",
666 entityId,
667 characterId: character.characterId,
668 skills: xpAward.view,
669 stored: xpAward.stored
670 }]
671 };
672 }
673
674 #cancelAttack (sessionId, characterId)
675 {
676 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
677 clearEngage(this.ecs, entityId);
678 return { events: [] };
679 }
680
681 #interact (sessionId, characterId, targetEntityId)
682 {
683 this.#requireOwnedEntity(sessionId, characterId);
684 const targetHandle = this.ecs.handleOf(targetEntityId);
685 if (targetHandle == null)
686 {
687 const error = new Error("Target is not here.");
688 error.userFacing = true;
689 throw error;
690 }
691 if (isUntargetable(this.ecs, targetHandle))
692 {
693 const error = new Error("Nothing to say.");
694 error.userFacing = true;
695 throw error;
696 }
697 const creature = this.ecs.get(targetHandle, Component.creature);
698 const def = creature ? mobDefinition(creature.mobTypeId) : null;
699 if (!def?.talkable)
700 {
701 const error = new Error("They have nothing to say.");
702 error.userFacing = true;
703 throw error;
704 }
705 return { events: [] };
706 }
707
708 #follow (sessionId, characterId, targetEntityId)
709 {
710 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
711 const targetHandle = this.ecs.handleOf(targetEntityId);
712 if (targetHandle == null)
713 {
714 const error = new Error("Target is not here.");
715 error.userFacing = true;
716 throw error;
717 }
718 if (targetEntityId === entityId)
719 {
720 const error = new Error("Cannot follow yourself.");
721 error.userFacing = true;
722 throw error;
723 }
724 if (!this.ecs.get(targetHandle, Component.position))
725 {
726 const error = new Error("That cannot be followed.");
727 error.userFacing = true;
728 throw error;
729 }
730 clearEngage(this.ecs, entityId);
731 setFollow(this.ecs, entityId, targetEntityId);
732 const path = this.ecs.get(handle, Component.path);
733 if (path)
734 { path.tiles = []; }
735 return { events: [] };
736 }
737
738 #cancelFollow (sessionId, characterId)
739 {
740 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
741 clearFollow(this.ecs, entityId);
742 return { events: [] };
743 }
744
745 #setGait (sessionId, characterId, gait)
746 {
747 if (gait !== GAIT.walk && gait !== GAIT.run)
748 {
749 const error = new Error("Gait must be walk or run.");
750 error.userFacing = true;
751 throw error;
752 }
753 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
754 this.ecs.get(handle, Component.movement).gait = gait;
755 }
756
757 #requireOwnedEntity (sessionId, characterId)
758 {
759 const entityId = this.characterEntities.get(characterId);
760 if (!entityId)
761 {
762 const error = new Error("Character is not in the world.");
763 error.userFacing = true;
764 throw error;
765 }
766 const handle = this.ecs.handleOf(entityId);
767 const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null;
768 if (!identity || identity.sessionId !== sessionId)
769 {
770 const error = new Error("Character is not in the world.");
771 error.userFacing = true;
772 throw error;
773 }
774 if (this.ecs.has(handle, Component.dead))
775 {
776 const error = new Error("You are dead.");
777 error.userFacing = true;
778 throw error;
779 }
780 return { handle, entityId };
781 }
782
783 #stepSystems (now = Date.now())
784 {
785 const events = [];
786 const transferRequests = [];
787 const flight = stepFreeFlight(this, now);
788 for (const event of flight)
789 {
790 if (event.type === "transfer-request")
791 {
792 const payload = serializeEntity(this.ecs, event.entityId);
793 transferRequests.push({
794 entityId: event.entityId,
795 fromTileX: event.fromTileX,
796 fromTileY: event.fromTileY,
797 destTileX: event.destTileX,
798 destTileY: event.destTileY,
799 toRegionX: event.toRegionX,
800 toRegionY: event.toRegionY,
801 payload
802 });
803 continue;
804 }
805 events.push(event);
806 }
807 events.push(...stepCombat(this, now));
808 stepFollow(this);
809 return { events, transferRequests };
810 }
811
812 #stepMovement (now = Date.now())
813 {
814 const events = expireGroundItems(this, now);
815 const transferRequests = [];
816 this.#queueAmbientWander();
817 for (const entity of this.ecs.query(Component.position, Component.movement))
818 {
819 const { handle, entityId, position, movement } = entity;
820 if (this.ecs.has(handle, Component.dead))
821 { continue; }
822 if (this.ecs.has(handle, Component.flight))
823 { continue; }
824 const path = this.ecs.get(handle, Component.path);
825 const tiles = path?.tiles;
826 if (this.frozen.has(entityId) || !tiles?.length)
827 { continue; }
828 if (!this.chunkIsSimulating(position.tileX, position.tileY))
829 { continue; }
830
831 const isWalk = movement.gait !== GAIT.run;
832 if (isWalk)
833 {
834 movement.walkCarry = (movement.walkCarry + 1) % 2;
835 if (movement.walkCarry !== 0)
836 { continue; }
837 }
838
839 const next = tiles[0];
840 const destRegionX = tileToRegion(next.x);
841 const destRegionY = tileToRegion(next.y);
842 if (!this.ownsRegion(destRegionX, destRegionY))
843 {
844 this.frozen.add(entityId);
845 transferRequests.push({
846 entityId,
847 fromTileX: position.tileX,
848 fromTileY: position.tileY,
849 destTileX: next.x,
850 destTileY: next.y,
851 toRegionX: destRegionX,
852 toRegionY: destRegionY,
853 payload: serializeEntity(this.ecs, entityId)
854 });
855 continue;
856 }
857
858 if (!this.walkableFor(entityId, next.x, next.y))
859 {
860 const combat = this.ecs.get(handle, Component.combat);
861 if (combat?.targetEntityId != null)
862 {
863 const targetHandle = this.ecs.handleOf(combat.targetEntityId);
864 const targetPos = targetHandle != null
865 ? this.ecs.get(targetHandle, Component.position)
866 : null;
867 const blockedByTarget = targetPos
868 && next.x === targetPos.tileX
869 && next.y === targetPos.tileY;
870 if (!blockedByTarget)
871 { path.tiles = []; }
872 }
873 continue;
874 }
875
876 const fromTileX = position.tileX;
877 const fromTileY = position.tileY;
878 const flying = this.#isFlying(handle);
879 if (!flying)
880 { this.#vacate(entityId, fromTileX, fromTileY); }
881 position.tileX = next.x;
882 position.tileY = next.y;
883 tiles.shift();
884 if (!flying)
885 { this.#occupy(entityId, position.tileX, position.tileY); }
886 recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
887 consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
888 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
889 }
890 return { events, transferRequests };
891 }
892
893 #queueAmbientWander ()
894 {
895 for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature))
896 {
897 const def = mobDefinition(entity.creature.mobTypeId);
898 if (!def?.ambient || def.freeFlight)
899 { continue; }
900 const path = this.ecs.get(entity.handle, Component.path);
901 if (!path)
902 { continue; }
903 if (path.tiles?.length)
904 { continue; }
905 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
906 { continue; }
907 if (Math.random() > 0.35)
908 { continue; }
909 const dirs = [
910 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
911 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
912 ];
913 const dir = dirs[Math.floor(Math.random() * dirs.length)];
914 const nextX = entity.position.tileX + dir.x;
915 const nextY = entity.position.tileY + dir.y;
916 if (!this.walkableFor(entity.entityId, nextX, nextY))
917 { continue; }
918 path.tiles = [{ x: nextX, y: nextY }];
919 }
920 }
921
922 #applyTransfer (message)
923 {
924 const payload = message.payload;
925 const entityId = payload.entityId;
926 if (this.ecs.hasEntity(entityId))
927 { return { accepted: false, reason: "already-present" }; }
928
929 const position = payload.components?.position;
930 const destTileX = message.destTileX ?? position?.tileX;
931 const destTileY = message.destTileY ?? position?.tileY;
932 if (destTileX == null || destTileY == null)
933 { return { accepted: false, reason: "missing-destination" }; }
934 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY)))
935 { return { accepted: false, reason: "not-owner" }; }
936
937 const creature = payload.components?.creature;
938 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
939 if (flying)
940 {
941 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY));
942 if (!data?.open)
943 { return { accepted: false, reason: "blocked" }; }
944 }
945 else if (!this.isEnterable(destTileX, destTileY) || this.#occupied(destTileX, destTileY))
946 { return { accepted: false, reason: "blocked" }; }
947
948 deserializeEntity(this.ecs, payload);
949 const handle = this.ecs.handleOf(entityId);
950 const livePosition = this.ecs.get(handle, Component.position);
951 const path = this.ecs.get(handle, Component.path);
952 livePosition.tileX = destTileX;
953 livePosition.tileY = destTileY;
954 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
955 { path.tiles.shift(); }
956 if (!flying)
957 { this.#occupy(entityId, destTileX, destTileY); }
958 const character = this.ecs.get(handle, Component.character);
959 if (character?.characterId)
960 { this.characterEntities.set(character.characterId, entityId); }
961 this.frozen.delete(entityId);
962 return {
963 accepted: true,
964 entity: publicEntityView(this.ecs, entityId)
965 };
966 }
967
968 #commitTransfer (entityId)
969 {
970 if (!this.ecs.hasEntity(entityId))
971 { return null; }
972 return this.#destroyEntity(entityId);
973 }
974
975 #abortTransfer (entityId)
976 {
977 this.frozen.delete(entityId);
978 return publicEntityView(this.ecs, entityId);
979 }
980
981 #listLoaders ()
982 {
983 return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({
984 entityId: entity.entityId,
985 tileX: entity.position.tileX,
986 tileY: entity.position.tileY,
987 chunkLoader: { ...entity.chunkLoader }
988 }));
989 }
990
991 #listPublicEntities ()
992 {
993 return this.ecs.query(Component.position).map((entity) => publicEntityView(this.ecs, entity.entityId)).filter(Boolean);
994 }
995
996 #entitiesInRegion (regionX, regionY)
997 {
998 const records = [];
999 for (const entity of this.ecs.query(Component.position))
1000 {
1001 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
1002 { continue; }
1003 records.push({
1004 ...publicEntityView(this.ecs, entity.entityId),
1005 persistent: this.ecs.has(entity.handle, Component.persistent),
1006 payload: serializeEntity(this.ecs, entity.entityId)
1007 });
1008 }
1009 return records;
1010 }
1011
1012 #chunkSnapshot (chunkX, chunkY)
1013 {
1014 const data = this.#chunkData(chunkX, chunkY);
1015 const entities = [];
1016 for (const entity of this.ecs.query(Component.position, Component.appearance))
1017 {
1018 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
1019 { continue; }
1020 entities.push(publicEntityView(this.ecs, entity.entityId));
1021 }
1022 return {
1023 chunkX,
1024 chunkY,
1025 open: data.open,
1026 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
1027 grounds: data.grounds,
1028 blocks: data.blocks,
1029 light: data.light,
1030 entities,
1031 groundItems: groundItemsInChunk(this, chunkX, chunkY)
1032 };
1033 }
1034
1035 #moveEvent (entityId, fromTileX, fromTileY)
1036 {
1037 const view = publicEntityView(this.ecs, entityId);
1038 return {
1039 type: "entity-move",
1040 entityId,
1041 fromTileX,
1042 fromTileY,
1043 tileX: view.tileX,
1044 tileY: view.tileY,
1045 worldX: view.worldX,
1046 worldY: view.worldY,
1047 gait: view.gait,
1048 freeFlight: !!view.freeFlight
1049 };
1050 }
1051
1052 chunkIsSimulating (tileX, tileY)
1053 {
1054 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY)));
1055 return !!chunk && !chunk.replica && chunk.simulating;
1056 }
1057
1058 chunkData (chunkX, chunkY)
1059 {
1060 return this.#chunkData(chunkX, chunkY);
1061 }
1062
1063 walkableFor (entityId, tileX, tileY)
1064 {
1065 const handle = this.ecs.handleOf(entityId);
1066 if (this.#isFlying(handle))
1067 {
1068 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1069 return !!data?.open;
1070 }
1071 if (!this.isEnterable(tileX, tileY))
1072 { return false; }
1073 const occupant = this.#occupied(tileX, tileY);
1074 return !occupant || occupant === entityId;
1075 }
1076
1077 destroyEntity (entityId)
1078 {
1079 return this.#destroyEntity(entityId);
1080 }
1081
1082 occupied (tileX, tileY)
1083 {
1084 return this.#occupied(tileX, tileY);
1085 }
1086
1087 #chunkIsSimulating (tileX, tileY)
1088 {
1089 return this.chunkIsSimulating(tileX, tileY);
1090 }
1091
1092 #chunkData (chunkX, chunkY)
1093 {
1094 const loaded = this.chunks.get(chunkKey(chunkX, chunkY));
1095 if (loaded)
1096 { return loaded.data; }
1097 return createEmptyChunkData(this.settings.defaultGroundTypeId);
1098 }
1099
1100 isEnterable (tileX, tileY)
1101 {
1102 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1103 if (!data.open)
1104 { return false; }
1105 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1106 }
1107
1108 #walkableFor (entityId, tileX, tileY)
1109 {
1110 return this.walkableFor(entityId, tileX, tileY);
1111 }
1112
1113 #isFlying (handle)
1114 {
1115 if (handle == null)
1116 { return false; }
1117 const creature = this.ecs.get(handle, Component.creature);
1118 return !!mobDefinition(creature?.mobTypeId)?.flying;
1119 }
1120
1121 #occupy (entityId, tileX, tileY)
1122 {
1123 this.occupancy.set(tileKey(tileX, tileY), entityId);
1124 }
1125
1126 #vacate (entityId, tileX, tileY)
1127 {
1128 const key = tileKey(tileX, tileY);
1129 if (this.occupancy.get(key) === entityId)
1130 { this.occupancy.delete(key); }
1131 }
1132
1133 #occupied (tileX, tileY)
1134 {
1135 return this.occupancy.get(tileKey(tileX, tileY))
1136 ?? this.ghostOccupancy.get(tileKey(tileX, tileY))
1137 ?? null;
1138 }
1139}
1140
1141export function replicaNeededForOwnedChunks (ownedChunkKeys)
1142{
1143 const needed = new Set();
1144 for (const key of ownedChunkKeys)
1145 {
1146 const { chunkX, chunkY } = parseChunkKey(key);
1147 for (let dy = -1; dy <= 1; dy++)
1148 {
1149 for (let dx = -1; dx <= 1; dx++)
1150 {
1151 if (dx === 0 && dy === 0)
1152 { continue; }
1153 needed.add(chunkKey(chunkX + dx, chunkY + dy));
1154 }
1155 }
1156 }
1157 return needed;
1158}