BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

workerWorld.js 16.9 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 {
21 bagView,
22 expireGroundItems,
23 groundItemsInChunk,
24 groundItemsInRegion,
25 handleItemCommand,
26 removeGroundItem,
27 setGroundItemsForRegion
28} from "../items/bags.js";
29
30export class WorkerWorld
31{
32 constructor (workerId)
33 {
34 this.workerId = workerId;
35 this.ecs = new EcsWorld();
36 this.chunks = new Map();
37 this.ownedRegions = new Set();
38 this.occupancy = new Map();
39 this.ghosts = new Map();
40 this.ghostOccupancy = new Map();
41 this.characterEntities = new Map();
42 this.frozen = new Set();
43 this.groundItems = new Map();
44 this.groundByTile = new Map();
45 this.settings = { ...DEFAULT_WORLD_SETTINGS };
46 this.activeRevisionId = 1;
47 }
48
49 handle (message)
50 {
51 switch (message.type)
52 {
53 case WorkerMessage.configure:
54 return this.#configure(message);
55 case WorkerMessage.assignRegion:
56 return this.#assignRegion(message);
57 case WorkerMessage.dropRegion:
58 return this.#dropRegion(message);
59 case WorkerMessage.replaceRegionChunks:
60 return this.#replaceRegionChunks(message);
61 case WorkerMessage.setReplicas:
62 return this.#setReplicas(message);
63 case WorkerMessage.setSimulatingChunks:
64 return this.#setSimulatingChunks(message);
65 case WorkerMessage.setGhosts:
66 return this.#setGhosts(message);
67 case WorkerMessage.spawn:
68 return this.#spawn(message);
69 case WorkerMessage.despawn:
70 return this.#despawn(message.entityId);
71 case WorkerMessage.despawnCharacter:
72 return this.#despawnCharacter(message.characterId);
73 case WorkerMessage.command:
74 return this.#command(message);
75 case WorkerMessage.stepMovement:
76 return this.#stepMovement(message.now);
77 case WorkerMessage.stepSpawners:
78 return { spawnRequests: collectSpawnRequests(this) };
79 case WorkerMessage.setGroundItems:
80 setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion);
81 return { ok: true };
82 case WorkerMessage.inspectBag:
83 return this.#inspectBag(message.entityId);
84 case WorkerMessage.applyTransfer:
85 return this.#applyTransfer(message);
86 case WorkerMessage.commitTransfer:
87 return this.#commitTransfer(message.entityId);
88 case WorkerMessage.abortTransfer:
89 return this.#abortTransfer(message.entityId);
90 case WorkerMessage.snapshotChunk:
91 return this.#chunkSnapshot(message.chunkX, message.chunkY);
92 case WorkerMessage.listLoaders:
93 return this.#listLoaders();
94 case WorkerMessage.listPublicEntities:
95 return this.#listPublicEntities();
96 case WorkerMessage.entitiesInRegion:
97 return this.#entitiesInRegion(message.regionX, message.regionY);
98 case WorkerMessage.inspect:
99 return publicEntityView(this.ecs, message.entityId);
100 default:
101 throw new Error(`Unknown worker message ${message.type}`);
102 }
103 }
104
105 ownsRegion (regionX, regionY)
106 {
107 return this.ownedRegions.has(regionKey(regionX, regionY));
108 }
109
110 requireOwnedEntity (sessionId, characterId)
111 {
112 return this.#requireOwnedEntity(sessionId, characterId);
113 }
114
115 chunkData (chunkX, chunkY)
116 {
117 return this.#chunkData(chunkX, chunkY);
118 }
119
120 occupied (tileX, tileY)
121 {
122 return this.#occupied(tileX, tileY);
123 }
124
125 #configure (message)
126 {
127 if (message.settings)
128 { this.settings = { ...this.settings, ...message.settings }; }
129 if (message.activeRevisionId != null)
130 { this.activeRevisionId = message.activeRevisionId; }
131 return { ok: true };
132 }
133
134 #assignRegion (message)
135 {
136 this.ownedRegions.add(regionKey(message.regionX, message.regionY));
137 for (const chunk of message.chunks ?? [])
138 {
139 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
140 data: cloneChunkData(chunk.data),
141 simulating: false,
142 replica: false
143 });
144 }
145 return { ok: true };
146 }
147
148 #replaceRegionChunks (message)
149 {
150 for (const chunk of message.chunks ?? [])
151 {
152 const key = chunkKey(chunk.chunkX, chunk.chunkY);
153 const existing = this.chunks.get(key);
154 this.chunks.set(key, {
155 data: cloneChunkData(chunk.data),
156 simulating: existing?.simulating ?? false,
157 replica: existing?.replica ?? false
158 });
159 }
160 return { ok: true };
161 }
162
163 #dropRegion (message)
164 {
165 const dropped = [];
166 for (const record of this.#entitiesInRegion(message.regionX, message.regionY))
167 {
168 dropped.push(record);
169 this.#destroyEntity(record.entityId);
170 }
171 const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion);
172 for (const item of groundItems)
173 { removeGroundItem(this, item.groundItemId); }
174 for (const [key, chunk] of [...this.chunks.entries()])
175 {
176 const { chunkX, chunkY } = parseChunkKey(key);
177 if (chunk.replica)
178 { continue; }
179 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
180 { this.chunks.delete(key); }
181 }
182 this.ownedRegions.delete(regionKey(message.regionX, message.regionY));
183 return { dropped, groundItems };
184 }
185
186 #setReplicas (message)
187 {
188 const keep = new Set();
189 for (const chunk of message.chunks ?? [])
190 {
191 const key = chunkKey(chunk.chunkX, chunk.chunkY);
192 keep.add(key);
193 const existing = this.chunks.get(key);
194 if (existing && !existing.replica)
195 { continue; }
196 this.chunks.set(key, {
197 data: cloneChunkData(chunk.data),
198 simulating: false,
199 replica: true
200 });
201 }
202 for (const [key, chunk] of [...this.chunks.entries()])
203 {
204 if (chunk.replica && !keep.has(key))
205 { this.chunks.delete(key); }
206 }
207 return { ok: true };
208 }
209
210 #setSimulatingChunks (message)
211 {
212 const simulating = new Set(message.chunkKeys ?? []);
213 for (const [key, chunk] of this.chunks)
214 {
215 if (chunk.replica)
216 {
217 chunk.simulating = false;
218 continue;
219 }
220 chunk.simulating = simulating.has(key);
221 }
222 return { ok: true };
223 }
224
225 #setGhosts (message)
226 {
227 this.ghosts.clear();
228 this.ghostOccupancy.clear();
229 for (const ghost of message.ghosts ?? [])
230 {
231 this.ghosts.set(ghost.entityId, ghost);
232 this.ghostOccupancy.set(tileKey(ghost.tileX, ghost.tileY), ghost.entityId);
233 }
234 return { ok: true };
235 }
236
237 #spawn (message)
238 {
239 const entityId = deserializeEntity(this.ecs, message);
240 const handle = this.ecs.handleOf(entityId);
241 const position = this.ecs.get(handle, Component.position);
242 if (!position)
243 {
244 this.ecs.destroy(handle);
245 throw new Error("Spawned entity is missing position.");
246 }
247 const occupant = this.#occupied(position.tileX, position.tileY);
248 if (occupant && occupant !== entityId)
249 {
250 this.ecs.destroy(handle);
251 const error = new Error("That tile is occupied.");
252 error.userFacing = true;
253 throw error;
254 }
255 this.#occupy(entityId, position.tileX, position.tileY);
256 const character = this.ecs.get(handle, Component.character);
257 if (character?.characterId)
258 { this.characterEntities.set(character.characterId, entityId); }
259 return publicEntityView(this.ecs, entityId);
260 }
261
262 #despawn (entityId)
263 {
264 return this.#destroyEntity(entityId);
265 }
266
267 #despawnCharacter (characterId)
268 {
269 const entityId = this.characterEntities.get(characterId);
270 if (!entityId)
271 { return null; }
272 return this.#destroyEntity(entityId);
273 }
274
275 #destroyEntity (entityId)
276 {
277 const handle = this.ecs.handleOf(entityId);
278 if (handle == null)
279 { return null; }
280 const view = publicEntityView(this.ecs, entityId);
281 const position = this.ecs.get(handle, Component.position);
282 const character = this.ecs.get(handle, Component.character);
283 if (position)
284 { this.#vacate(entityId, position.tileX, position.tileY); }
285 if (character?.characterId)
286 { this.characterEntities.delete(character.characterId); }
287 this.frozen.delete(entityId);
288 this.ecs.destroy(handle);
289 return view;
290 }
291
292 #command (message)
293 {
294 const { sessionId, command } = message;
295 switch (command.type)
296 {
297 case "move-to":
298 this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
299 return { events: [] };
300 case "set-gait":
301 this.#setGait(sessionId, command.characterId, command.gait);
302 return { events: [] };
303 default:
304 {
305 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
306 return result ?? { events: [] };
307 }
308 }
309 }
310
311 #inspectBag (entityId)
312 {
313 const handle = this.ecs.handleOf(entityId);
314 if (handle == null)
315 { return null; }
316 return bagView(this.ecs, handle);
317 }
318
319 #moveTo (sessionId, characterId, tileX, tileY)
320 {
321 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
322 if (this.frozen.has(entityId))
323 { return; }
324 const position = this.ecs.get(handle, Component.position);
325 const movement = this.ecs.get(handle, Component.movement);
326 let path = this.ecs.get(handle, Component.path);
327 if (!path)
328 { path = this.ecs.add(handle, Component.path, { tiles: [] }); }
329 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
330 path.tiles = findPath(
331 position.tileX,
332 position.tileY,
333 tileX,
334 tileY,
335 (x, y) => this.#walkableFor(entityId, x, y),
336 bounds.minX,
337 bounds.minY,
338 bounds.maxX,
339 bounds.maxY
340 );
341 movement.walkCarry = 0;
342 }
343
344 #setGait (sessionId, characterId, gait)
345 {
346 if (gait !== GAIT.walk && gait !== GAIT.run)
347 {
348 const error = new Error("Gait must be walk or run.");
349 error.userFacing = true;
350 throw error;
351 }
352 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
353 this.ecs.get(handle, Component.movement).gait = gait;
354 }
355
356 #requireOwnedEntity (sessionId, characterId)
357 {
358 const entityId = this.characterEntities.get(characterId);
359 if (!entityId)
360 {
361 const error = new Error("Character is not in the world.");
362 error.userFacing = true;
363 throw error;
364 }
365 const handle = this.ecs.handleOf(entityId);
366 const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null;
367 if (!identity || identity.sessionId !== sessionId)
368 {
369 const error = new Error("Character is not in the world.");
370 error.userFacing = true;
371 throw error;
372 }
373 return { handle, entityId };
374 }
375
376 #stepMovement (now = Date.now())
377 {
378 const events = expireGroundItems(this, now);
379 const transferRequests = [];
380 for (const entity of this.ecs.query(Component.position, Component.movement))
381 {
382 const { handle, entityId, position, movement } = entity;
383 const path = this.ecs.get(handle, Component.path);
384 const tiles = path?.tiles;
385 if (this.frozen.has(entityId) || !tiles?.length)
386 { continue; }
387 if (!this.#chunkIsSimulating(position.tileX, position.tileY))
388 { continue; }
389
390 const isWalk = movement.gait !== GAIT.run;
391 if (isWalk)
392 {
393 movement.walkCarry = (movement.walkCarry + 1) % 2;
394 if (movement.walkCarry !== 0)
395 { continue; }
396 }
397
398 const next = tiles[0];
399 const destRegionX = tileToRegion(next.x);
400 const destRegionY = tileToRegion(next.y);
401 if (!this.ownsRegion(destRegionX, destRegionY))
402 {
403 this.frozen.add(entityId);
404 transferRequests.push({
405 entityId,
406 fromTileX: position.tileX,
407 fromTileY: position.tileY,
408 destTileX: next.x,
409 destTileY: next.y,
410 toRegionX: destRegionX,
411 toRegionY: destRegionY,
412 payload: serializeEntity(this.ecs, entityId)
413 });
414 continue;
415 }
416
417 if (!this.#walkableFor(entityId, next.x, next.y))
418 { continue; }
419
420 const fromTileX = position.tileX;
421 const fromTileY = position.tileY;
422 this.#vacate(entityId, fromTileX, fromTileY);
423 position.tileX = next.x;
424 position.tileY = next.y;
425 tiles.shift();
426 this.#occupy(entityId, position.tileX, position.tileY);
427 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
428 }
429 return { events, transferRequests };
430 }
431
432 #applyTransfer (message)
433 {
434 const payload = message.payload;
435 const entityId = payload.entityId;
436 if (this.ecs.hasEntity(entityId))
437 { return { accepted: false, reason: "already-present" }; }
438
439 const position = payload.components?.position;
440 const destTileX = message.destTileX ?? position?.tileX;
441 const destTileY = message.destTileY ?? position?.tileY;
442 if (destTileX == null || destTileY == null)
443 { return { accepted: false, reason: "missing-destination" }; }
444 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY)))
445 { return { accepted: false, reason: "not-owner" }; }
446 if (!this.isEnterable(destTileX, destTileY) || this.#occupied(destTileX, destTileY))
447 { return { accepted: false, reason: "blocked" }; }
448
449 deserializeEntity(this.ecs, payload);
450 const handle = this.ecs.handleOf(entityId);
451 const livePosition = this.ecs.get(handle, Component.position);
452 const path = this.ecs.get(handle, Component.path);
453 livePosition.tileX = destTileX;
454 livePosition.tileY = destTileY;
455 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
456 { path.tiles.shift(); }
457 this.#occupy(entityId, destTileX, destTileY);
458 const character = this.ecs.get(handle, Component.character);
459 if (character?.characterId)
460 { this.characterEntities.set(character.characterId, entityId); }
461 this.frozen.delete(entityId);
462 return {
463 accepted: true,
464 entity: publicEntityView(this.ecs, entityId)
465 };
466 }
467
468 #commitTransfer (entityId)
469 {
470 if (!this.ecs.hasEntity(entityId))
471 { return null; }
472 return this.#destroyEntity(entityId);
473 }
474
475 #abortTransfer (entityId)
476 {
477 this.frozen.delete(entityId);
478 return publicEntityView(this.ecs, entityId);
479 }
480
481 #listLoaders ()
482 {
483 return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({
484 entityId: entity.entityId,
485 tileX: entity.position.tileX,
486 tileY: entity.position.tileY,
487 chunkLoader: { ...entity.chunkLoader }
488 }));
489 }
490
491 #listPublicEntities ()
492 {
493 return this.ecs.query(Component.position).map((entity) => publicEntityView(this.ecs, entity.entityId)).filter(Boolean);
494 }
495
496 #entitiesInRegion (regionX, regionY)
497 {
498 const records = [];
499 for (const entity of this.ecs.query(Component.position))
500 {
501 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
502 { continue; }
503 records.push({
504 ...publicEntityView(this.ecs, entity.entityId),
505 persistent: this.ecs.has(entity.handle, Component.persistent),
506 payload: serializeEntity(this.ecs, entity.entityId)
507 });
508 }
509 return records;
510 }
511
512 #chunkSnapshot (chunkX, chunkY)
513 {
514 const data = this.#chunkData(chunkX, chunkY);
515 const entities = [];
516 for (const entity of this.ecs.query(Component.position, Component.appearance))
517 {
518 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
519 { continue; }
520 entities.push(publicEntityView(this.ecs, entity.entityId));
521 }
522 return {
523 chunkX,
524 chunkY,
525 open: data.open,
526 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
527 grounds: data.grounds,
528 blocks: data.blocks,
529 light: data.light,
530 entities,
531 groundItems: groundItemsInChunk(this, chunkX, chunkY)
532 };
533 }
534
535 #moveEvent (entityId, fromTileX, fromTileY)
536 {
537 const view = publicEntityView(this.ecs, entityId);
538 return {
539 type: "entity-move",
540 entityId,
541 fromTileX,
542 fromTileY,
543 tileX: view.tileX,
544 tileY: view.tileY,
545 gait: view.gait
546 };
547 }
548
549 #chunkIsSimulating (tileX, tileY)
550 {
551 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY)));
552 return !!chunk && !chunk.replica && chunk.simulating;
553 }
554
555 #chunkData (chunkX, chunkY)
556 {
557 const loaded = this.chunks.get(chunkKey(chunkX, chunkY));
558 if (loaded)
559 { return loaded.data; }
560 return createEmptyChunkData(this.settings.defaultGroundTypeId);
561 }
562
563 isEnterable (tileX, tileY)
564 {
565 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
566 if (!data.open)
567 { return false; }
568 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
569 }
570
571 #walkableFor (entityId, tileX, tileY)
572 {
573 if (!this.isEnterable(tileX, tileY))
574 { return false; }
575 const occupant = this.#occupied(tileX, tileY);
576 return !occupant || occupant === entityId;
577 }
578
579 #occupy (entityId, tileX, tileY)
580 {
581 this.occupancy.set(tileKey(tileX, tileY), entityId);
582 }
583
584 #vacate (entityId, tileX, tileY)
585 {
586 const key = tileKey(tileX, tileY);
587 if (this.occupancy.get(key) === entityId)
588 { this.occupancy.delete(key); }
589 }
590
591 #occupied (tileX, tileY)
592 {
593 return this.occupancy.get(tileKey(tileX, tileY))
594 ?? this.ghostOccupancy.get(tileKey(tileX, tileY))
595 ?? null;
596 }
597}
598
599export function replicaNeededForOwnedChunks (ownedChunkKeys)
600{
601 const needed = new Set();
602 for (const key of ownedChunkKeys)
603 {
604 const { chunkX, chunkY } = parseChunkKey(key);
605 for (let dy = -1; dy <= 1; dy++)
606 {
607 for (let dx = -1; dx <= 1; dx++)
608 {
609 if (dx === 0 && dy === 0)
610 { continue; }
611 needed.add(chunkKey(chunkX + dx, chunkY + dy));
612 }
613 }
614 }
615 return needed;
616}