BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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