| 1 | import { |
| 2 | CHUNK_SIZE, |
| 3 | DEFAULT_CHUNK_LOADER, |
| 4 | GAIT, |
| 5 | REGION_RUNTIME_STATE, |
| 6 | VISIBLE_CHUNK_RADIUS, |
| 7 | WORLD_YEAR_OFFSET |
| 8 | } from "../../../shared/protocol/constants.js"; |
| 9 | import { |
| 10 | chunkKey, |
| 11 | chunkToRegion, |
| 12 | chunksInRegion, |
| 13 | parseChunkKey, |
| 14 | parseRegionKey, |
| 15 | regionKey, |
| 16 | regionTileBounds, |
| 17 | tileToChunk, |
| 18 | tileToLocal, |
| 19 | tileToRegion, |
| 20 | visibleChunkCoords |
| 21 | } from "../world/coordinates.js"; |
| 22 | import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js"; |
| 23 | import { closedNeighborEdges } from "../world/chunkFlags.js"; |
| 24 | import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js"; |
| 25 | import { InProcessWorker } from "./inProcessWorker.js"; |
| 26 | import { ThreadWorker } from "./threadWorker.js"; |
| 27 | import { WorkerMessage } from "./protocol.js"; |
| 28 | import { replicaNeededForOwnedChunks } from "./workerWorld.js"; |
| 29 | import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js"; |
| 30 | import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js"; |
| 31 | import { mobComponents } from "./spawners.js"; |
| 32 | import { defaultPlayerSkills } from "../../../shared/skills/state.js"; |
| 33 | import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js"; |
| 34 | import { BlockType } from "../../../shared/definitions/tiles.js"; |
| 35 | import { ItemId } from "../../../shared/definitions/items.js"; |
| 36 | import { CourierService } from "../courier/service.js"; |
| 37 | import { findReservedChequeIndex } from "../items/bags.js"; |
| 38 | |
| 39 | export class Simulation |
| 40 | { |
| 41 | constructor (worldDb, stateDb, options = {}) |
| 42 | { |
| 43 | this.worldDb = worldDb; |
| 44 | this.stateDb = stateDb; |
| 45 | this.workerCount = Math.max(1, Math.round(options.workerCount ?? Number(process.env.SIMULATION_WORKERS ?? 2))); |
| 46 | this.workerMode = options.workerMode ?? process.env.SIMULATION_WORKER_MODE ?? "inprocess"; |
| 47 | this.pinRegion = options.pinRegion ?? null; |
| 48 | this.nowFn = options.now ?? (() => Date.now()); |
| 49 | this.workers = []; |
| 50 | this.regionOwner = new Map(); |
| 51 | this.regionGraceUntil = new Map(); |
| 52 | this.directory = new Map(); |
| 53 | this.characterEntities = new Map(); |
| 54 | this.commandQueue = []; |
| 55 | this.replication = []; |
| 56 | this.pendingPrivate = []; |
| 57 | this.courier = null; |
| 58 | this.altarTiles = []; |
| 59 | this.authoredCache = new Map(); |
| 60 | this.nextEntityId = 1; |
| 61 | this.nextGroundItemId = stateDb.nextGroundItemId(); |
| 62 | this.tickIndex = 0; |
| 63 | this.movementTickCounter = 0; |
| 64 | this.lastTickAt = null; |
| 65 | this.movementAccumulator = 0; |
| 66 | this.activeRevisionId = worldDb.getActiveRevisionId(); |
| 67 | this.settings = worldDb.getLiveSettings(); |
| 68 | |
| 69 | const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker; |
| 70 | for (let workerId = 0; workerId < this.workerCount; workerId++) |
| 71 | { |
| 72 | const worker = new WorkerImpl(workerId); |
| 73 | worker.call({ |
| 74 | type: WorkerMessage.configure, |
| 75 | settings: this.settings, |
| 76 | activeRevisionId: this.activeRevisionId |
| 77 | }); |
| 78 | this.workers.push(worker); |
| 79 | } |
| 80 | for (const worker of this.workers) |
| 81 | { |
| 82 | if (!worker.world) |
| 83 | { continue; } |
| 84 | worker.world.releaseChequeReservation = (issuerId, chequeId) => this.releaseChequeReservation(issuerId, chequeId); |
| 85 | worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack); |
| 86 | } |
| 87 | this.courier = new CourierService({ |
| 88 | stateDb: this.stateDb, |
| 89 | worldDb: this.worldDb, |
| 90 | simulation: this |
| 91 | }); |
| 92 | this.#refreshAltarIndex(); |
| 93 | } |
| 94 | |
| 95 | get now () |
| 96 | { |
| 97 | return this.nowFn(); |
| 98 | } |
| 99 | |
| 100 | applySettings (settings) |
| 101 | { |
| 102 | this.settings = { ...this.settings, ...settings }; |
| 103 | this.#configureWorkers(); |
| 104 | } |
| 105 | |
| 106 | reloadWorld () |
| 107 | { |
| 108 | this.activeRevisionId = this.worldDb.getActiveRevisionId(); |
| 109 | this.settings = this.worldDb.getLiveSettings(); |
| 110 | this.authoredCache.clear(); |
| 111 | this.#configureWorkers(); |
| 112 | for (const [key, workerId] of this.regionOwner) |
| 113 | { |
| 114 | const { regionX, regionY } = parseRegionKey(key); |
| 115 | this.workers[workerId].call({ |
| 116 | type: WorkerMessage.replaceRegionChunks, |
| 117 | chunks: this.#regionChunkBlobs(regionX, regionY) |
| 118 | }); |
| 119 | } |
| 120 | this.#syncAllReplicas(); |
| 121 | this.courier?.refreshBankIndex(); |
| 122 | this.#refreshAltarIndex(); |
| 123 | } |
| 124 | |
| 125 | enqueue (sessionId, command) |
| 126 | { |
| 127 | this.commandQueue.push({ sessionId, command, receivedAt: this.now }); |
| 128 | } |
| 129 | |
| 130 | step (now = this.now) |
| 131 | { |
| 132 | this.tickIndex += 1; |
| 133 | const events = []; |
| 134 | const commands = this.commandQueue.splice(0); |
| 135 | for (const item of commands) |
| 136 | { |
| 137 | try |
| 138 | { |
| 139 | events.push(...this.#routeCommand(item)); |
| 140 | } |
| 141 | catch (error) |
| 142 | { |
| 143 | events.push({ |
| 144 | sessionId: item.sessionId, |
| 145 | type: "command-error", |
| 146 | message: error.userFacing ? error.message : "Command failed." |
| 147 | }); |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | this.#recalculateActivation(now); |
| 152 | |
| 153 | const simHz = Math.max(1, this.settings.simulationTickHz || 20); |
| 154 | const expectedDt = 1 / simHz; |
| 155 | const dt = (this.lastTickAt == null || now <= this.lastTickAt) |
| 156 | ? expectedDt |
| 157 | : Math.min(0.25, (now - this.lastTickAt) / 1000); |
| 158 | this.lastTickAt = now; |
| 159 | |
| 160 | { |
| 161 | const transfers = []; |
| 162 | const remoteMelee = []; |
| 163 | for (const worker of this.workers) |
| 164 | { |
| 165 | const result = worker.call({ type: WorkerMessage.stepSystems, now }); |
| 166 | for (const event of result?.events ?? []) |
| 167 | { |
| 168 | if (event.type === "remote-melee-resolve") |
| 169 | { |
| 170 | remoteMelee.push(event); |
| 171 | continue; |
| 172 | } |
| 173 | if (event.type === "entity-move") |
| 174 | { this.#applyMoveToDirectory(event); } |
| 175 | if (event.type === "entity-despawn") |
| 176 | { this.#forget(event.entityId); } |
| 177 | if (event.type === "skills-updated") |
| 178 | { this.#applySkillsUpdated(event); } |
| 179 | if (event.type === "player-died") |
| 180 | { |
| 181 | events.push(...this.#applyPlayerDeath(event)); |
| 182 | continue; |
| 183 | } |
| 184 | this.#persistGroundEvent(event); |
| 185 | if (event.type !== "skills-updated") |
| 186 | { events.push(event); } |
| 187 | } |
| 188 | for (const request of result?.transferRequests ?? []) |
| 189 | { transfers.push({ ...request, fromWorkerId: worker.workerId }); } |
| 190 | } |
| 191 | for (const payload of remoteMelee) |
| 192 | { events.push(...this.#applyRemoteMelee(payload)); } |
| 193 | if (transfers.length) |
| 194 | { |
| 195 | events.push(...this.#applyTransfers(transfers)); |
| 196 | this.#recalculateActivation(now); |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2); |
| 201 | this.movementAccumulator += dt * movementHz; |
| 202 | while (this.movementAccumulator >= 1) |
| 203 | { |
| 204 | this.movementAccumulator -= 1; |
| 205 | this.movementTickCounter += 1; |
| 206 | const transfers = []; |
| 207 | for (const worker of this.workers) |
| 208 | { |
| 209 | const result = worker.call({ type: WorkerMessage.stepMovement, now }); |
| 210 | for (const event of result?.events ?? []) |
| 211 | { |
| 212 | if (event.type === "entity-move") |
| 213 | { this.#applyMoveToDirectory(event); } |
| 214 | this.#persistGroundEvent(event); |
| 215 | events.push(event); |
| 216 | } |
| 217 | for (const request of result?.transferRequests ?? []) |
| 218 | { transfers.push({ ...request, fromWorkerId: worker.workerId }); } |
| 219 | } |
| 220 | events.push(...this.#applyTransfers(transfers)); |
| 221 | this.#recalculateActivation(now); |
| 222 | } |
| 223 | |
| 224 | if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0) |
| 225 | { events.push(...this.#stepSpawners()); } |
| 226 | |
| 227 | if (this.courier) |
| 228 | { events.push(...this.courier.step(now, dt)); } |
| 229 | |
| 230 | this.#syncGhosts(); |
| 231 | events.push(...this.pendingPrivate.splice(0)); |
| 232 | return { now, events, replication: this.drainReplication() }; |
| 233 | } |
| 234 | |
| 235 | drainReplication () |
| 236 | { |
| 237 | return this.replication.splice(0); |
| 238 | } |
| 239 | |
| 240 | worldTime (now = this.now) |
| 241 | { |
| 242 | const date = new Date(now); |
| 243 | date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET); |
| 244 | return { |
| 245 | unixMs: now, |
| 246 | worldUnixMs: date.getTime(), |
| 247 | iso: date.toISOString(), |
| 248 | hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600 |
| 249 | }; |
| 250 | } |
| 251 | |
| 252 | spawnCharacter (sessionId, character) |
| 253 | { |
| 254 | this.despawnCharacter(character.character_id); |
| 255 | // Despawn may have just written the live tile; never trust a stale row snapshot. |
| 256 | const row = this.stateDb.getCharacter(character.character_id) ?? character; |
| 257 | let tileX = row.tile_x; |
| 258 | let tileY = row.tile_y; |
| 259 | const gait = row.gait || character.gait || GAIT.walk; |
| 260 | const preferred = this.#findResumeTile(tileX, tileY); |
| 261 | if (!preferred) |
| 262 | { |
| 263 | const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first."); |
| 264 | error.userFacing = true; |
| 265 | throw error; |
| 266 | } |
| 267 | if (preferred.tileX !== tileX || preferred.tileY !== tileY) |
| 268 | { |
| 269 | tileX = preferred.tileX; |
| 270 | tileY = preferred.tileY; |
| 271 | this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait); |
| 272 | } |
| 273 | |
| 274 | const bag = this.stateDb.getBag(character.character_id) ?? { |
| 275 | inventory: emptySlots(), |
| 276 | equipment: emptyEquipment(), |
| 277 | vault: [], |
| 278 | vaultReserved: [] |
| 279 | }; |
| 280 | const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills(); |
| 281 | const maxHealth = playerMaxHealth(skills); |
| 282 | const maxStamina = playerMaxStamina(skills); |
| 283 | const isDead = !!row.is_dead; |
| 284 | const entityId = this.nextEntityId++; |
| 285 | const components = { |
| 286 | position: { tileX, tileY }, |
| 287 | movement: { gait, walkCarry: 0 }, |
| 288 | path: { tiles: [] }, |
| 289 | appearance: { |
| 290 | sex: character.sex ?? row.sex, |
| 291 | firstName: character.first_name ?? row.first_name, |
| 292 | lastName: character.last_name ?? row.last_name |
| 293 | }, |
| 294 | character: { |
| 295 | characterId: character.character_id ?? row.character_id, |
| 296 | accountId: character.account_id ?? row.account_id |
| 297 | }, |
| 298 | networkIdentity: { sessionId }, |
| 299 | chunkLoader: { ...DEFAULT_CHUNK_LOADER }, |
| 300 | inventory: { slots: bag.inventory ?? emptySlots() }, |
| 301 | equipment: bag.equipment ?? emptyEquipment(), |
| 302 | vault: { |
| 303 | slots: bag.vault ?? [], |
| 304 | reserved: bag.vaultReserved ?? [] |
| 305 | }, |
| 306 | health: { current: isDead ? 0 : maxHealth, max: maxHealth }, |
| 307 | stamina: { current: maxStamina, max: maxStamina }, |
| 308 | combat: { targetEntityId: null, nextSwingAt: 0 }, |
| 309 | skills, |
| 310 | }; |
| 311 | if (isDead) |
| 312 | { components.dead = {}; } |
| 313 | this.#ensureCoverage(tileX, tileY, components.chunkLoader); |
| 314 | const workerId = this.#ownerOfTile(tileX, tileY); |
| 315 | const view = this.workers[workerId].call({ |
| 316 | type: WorkerMessage.spawn, |
| 317 | entityId, |
| 318 | components |
| 319 | }); |
| 320 | this.#remember(view, workerId); |
| 321 | this.#queueReplication(replicationSpawn(view)); |
| 322 | this.#recalculateActivation(this.now); |
| 323 | this.#syncGhosts(); |
| 324 | return entityId; |
| 325 | } |
| 326 | |
| 327 | spawnEntity (components, options = {}) |
| 328 | { |
| 329 | const entityId = options.entityId ?? this.nextEntityId++; |
| 330 | this.nextEntityId = Math.max(this.nextEntityId, entityId + 1); |
| 331 | const position = components.position; |
| 332 | if (!position) |
| 333 | { throw new Error("spawnEntity requires position."); } |
| 334 | if (options.requireResident) |
| 335 | { |
| 336 | const workerId = this.#ownerOfTile(position.tileX, position.tileY); |
| 337 | if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY)) |
| 338 | { return null; } |
| 339 | const view = this.workers[workerId].call({ |
| 340 | type: WorkerMessage.spawn, |
| 341 | entityId, |
| 342 | components |
| 343 | }); |
| 344 | this.#remember(view, workerId); |
| 345 | if (components.appearance) |
| 346 | { this.#queueReplication(replicationSpawn(view)); } |
| 347 | this.#syncGhosts(); |
| 348 | return entityId; |
| 349 | } |
| 350 | if (components.chunkLoader) |
| 351 | { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader); } |
| 352 | else |
| 353 | { |
| 354 | this.#ensureRegion( |
| 355 | tileToRegion(position.tileX), |
| 356 | tileToRegion(position.tileY), |
| 357 | null |
| 358 | ); |
| 359 | } |
| 360 | const workerId = this.#ownerOfTile(position.tileX, position.tileY); |
| 361 | const view = this.workers[workerId].call({ |
| 362 | type: WorkerMessage.spawn, |
| 363 | entityId, |
| 364 | components |
| 365 | }); |
| 366 | this.#remember(view, workerId); |
| 367 | if (components.appearance) |
| 368 | { this.#queueReplication(replicationSpawn(view)); } |
| 369 | this.#recalculateActivation(this.now); |
| 370 | this.#syncGhosts(); |
| 371 | return entityId; |
| 372 | } |
| 373 | |
| 374 | despawnEntity (entityId) |
| 375 | { |
| 376 | const record = this.directory.get(entityId); |
| 377 | if (!record) |
| 378 | { return; } |
| 379 | const dropped = this.workers[record.workerId].call({ |
| 380 | type: WorkerMessage.despawn, |
| 381 | entityId |
| 382 | }); |
| 383 | if (dropped) |
| 384 | { this.#queueReplication(replicationDespawn(dropped)); } |
| 385 | this.#forget(entityId); |
| 386 | } |
| 387 | |
| 388 | chunkIsSimulating (tileX, tileY) |
| 389 | { |
| 390 | const loaders = this.#allLoaders(); |
| 391 | const { chunkSim } = accumulateLoaderRefs(loaders); |
| 392 | return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY))) ?? 0) > 0; |
| 393 | } |
| 394 | |
| 395 | updateCourierFlight (entityId, flightPatch, now = this.now) |
| 396 | { |
| 397 | const record = this.directory.get(entityId); |
| 398 | if (!record) |
| 399 | { return { despawned: true, entityId }; } |
| 400 | const tileX = Math.floor(flightPatch.x); |
| 401 | const tileY = Math.floor(flightPatch.y); |
| 402 | const owner = this.#ownerOfTile(tileX, tileY); |
| 403 | if (owner == null || owner !== record.workerId) |
| 404 | { |
| 405 | this.despawnEntity(entityId); |
| 406 | return { despawned: true, entityId }; |
| 407 | } |
| 408 | const result = this.workers[owner].call({ |
| 409 | type: WorkerMessage.updateFlight, |
| 410 | entityId, |
| 411 | flight: flightPatch, |
| 412 | now |
| 413 | }); |
| 414 | if (result?.transferRequest) |
| 415 | { |
| 416 | const events = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: owner }]); |
| 417 | this.#recalculateActivation(now); |
| 418 | const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId); |
| 419 | if (move) |
| 420 | { |
| 421 | this.#applyMoveToDirectory(move); |
| 422 | return { event: { ...move, worldX: flightPatch.x, worldY: flightPatch.y, freeFlight: true } }; |
| 423 | } |
| 424 | this.despawnEntity(entityId); |
| 425 | return { despawned: true, entityId }; |
| 426 | } |
| 427 | if (result?.event) |
| 428 | { |
| 429 | this.#applyMoveToDirectory(result.event); |
| 430 | return { event: result.event }; |
| 431 | } |
| 432 | return null; |
| 433 | } |
| 434 | |
| 435 | applyBag (entityId, bag) |
| 436 | { |
| 437 | const record = this.directory.get(entityId); |
| 438 | if (!record) |
| 439 | { return null; } |
| 440 | return this.workers[record.workerId].call({ |
| 441 | type: WorkerMessage.applyBag, |
| 442 | entityId, |
| 443 | bag |
| 444 | }); |
| 445 | } |
| 446 | |
| 447 | pushSkills (characterId, skills) |
| 448 | { |
| 449 | this.pendingPrivate.push({ |
| 450 | type: "skills", |
| 451 | characterId, |
| 452 | skills |
| 453 | }); |
| 454 | } |
| 455 | |
| 456 | skillsOf (entityId) |
| 457 | { |
| 458 | const record = this.directory.get(entityId); |
| 459 | if (!record) |
| 460 | { return null; } |
| 461 | return this.workers[record.workerId].call({ |
| 462 | type: WorkerMessage.inspectSkills, |
| 463 | entityId |
| 464 | }); |
| 465 | } |
| 466 | |
| 467 | pushInventory (characterId, bag) |
| 468 | { |
| 469 | this.pendingPrivate.push({ |
| 470 | type: "inventory", |
| 471 | characterId, |
| 472 | inventory: bag.inventory, |
| 473 | equipment: bag.equipment, |
| 474 | vault: bag.vault, |
| 475 | vaultReserved: bag.vaultReserved |
| 476 | }); |
| 477 | } |
| 478 | |
| 479 | dispatchPigeon ({ characterId, destination, cargo }) |
| 480 | { |
| 481 | const entityId = this.characterEntities.get(characterId); |
| 482 | const position = entityId ? this.positionOf(entityId) : null; |
| 483 | if (!position) |
| 484 | { |
| 485 | const error = new Error("Enter the world before sending a pigeon."); |
| 486 | error.userFacing = true; |
| 487 | throw error; |
| 488 | } |
| 489 | return this.courier.dispatchFromPlayer({ |
| 490 | characterId, |
| 491 | originTileX: position.tileX, |
| 492 | originTileY: position.tileY, |
| 493 | destination, |
| 494 | cargo |
| 495 | }); |
| 496 | } |
| 497 | |
| 498 | despawnCharacter (characterId) |
| 499 | { |
| 500 | const entityId = this.characterEntities.get(characterId); |
| 501 | if (!entityId) |
| 502 | { return; } |
| 503 | const record = this.directory.get(entityId); |
| 504 | if (!record) |
| 505 | { |
| 506 | this.characterEntities.delete(characterId); |
| 507 | return; |
| 508 | } |
| 509 | this.#saveBag(entityId, record.workerId); |
| 510 | const dropped = this.workers[record.workerId].call({ |
| 511 | type: WorkerMessage.despawnCharacter, |
| 512 | characterId |
| 513 | }); |
| 514 | if (dropped) |
| 515 | { |
| 516 | this.stateDb.saveCharacterPosition( |
| 517 | characterId, |
| 518 | dropped.tileX, |
| 519 | dropped.tileY, |
| 520 | dropped.gait ?? GAIT.walk |
| 521 | ); |
| 522 | this.#queueReplication(replicationDespawn(dropped)); |
| 523 | } |
| 524 | this.#forget(entityId); |
| 525 | this.#recalculateActivation(this.now); |
| 526 | this.#syncGhosts(); |
| 527 | } |
| 528 | |
| 529 | entityForCharacter (characterId) |
| 530 | { |
| 531 | return this.characterEntities.get(characterId) ?? null; |
| 532 | } |
| 533 | |
| 534 | entityRecord (entityId) |
| 535 | { |
| 536 | const record = this.directory.get(entityId); |
| 537 | return record ? { ...record } : null; |
| 538 | } |
| 539 | |
| 540 | positionOf (entityId) |
| 541 | { |
| 542 | const record = this.directory.get(entityId); |
| 543 | return record ? { tileX: record.tileX, tileY: record.tileY } : null; |
| 544 | } |
| 545 | |
| 546 | bagOf (entityId) |
| 547 | { |
| 548 | const record = this.directory.get(entityId); |
| 549 | if (!record) |
| 550 | { return null; } |
| 551 | return this.workers[record.workerId].call({ |
| 552 | type: WorkerMessage.inspectBag, |
| 553 | entityId |
| 554 | }); |
| 555 | } |
| 556 | |
| 557 | snapshotFor (entityId) |
| 558 | { |
| 559 | const record = this.directory.get(entityId); |
| 560 | if (!record) |
| 561 | { return []; } |
| 562 | const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS); |
| 563 | return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY)); |
| 564 | } |
| 565 | |
| 566 | snapshotChunk (chunkX, chunkY) |
| 567 | { |
| 568 | const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)); |
| 569 | if (owner == null) |
| 570 | { return this.#syntheticSnapshot(chunkX, chunkY); } |
| 571 | return this.workers[owner].call({ |
| 572 | type: WorkerMessage.snapshotChunk, |
| 573 | chunkX, |
| 574 | chunkY |
| 575 | }); |
| 576 | } |
| 577 | |
| 578 | findOpenSpawn () |
| 579 | { |
| 580 | const coords = this.worldDb.listChunkCoords(this.activeRevisionId); |
| 581 | for (const coord of coords) |
| 582 | { |
| 583 | const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y); |
| 584 | if (!data.open) |
| 585 | { continue; } |
| 586 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 587 | { |
| 588 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 589 | { |
| 590 | const tileX = coord.chunk_x * CHUNK_SIZE + localX; |
| 591 | const tileY = coord.chunk_y * CHUNK_SIZE + localY; |
| 592 | if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY)) |
| 593 | { return { tileX, tileY }; } |
| 594 | } |
| 595 | } |
| 596 | } |
| 597 | return null; |
| 598 | } |
| 599 | |
| 600 | /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */ |
| 601 | #findResumeTile (tileX, tileY, radius = 24) |
| 602 | { |
| 603 | return this.#findNearbyEnterable(tileX, tileY, radius) ?? this.findOpenSpawn(); |
| 604 | } |
| 605 | |
| 606 | #findNearbyEnterable (originX, originY, maxRadius) |
| 607 | { |
| 608 | for (let radius = 0; radius <= maxRadius; radius++) |
| 609 | { |
| 610 | for (let dy = -radius; dy <= radius; dy++) |
| 611 | { |
| 612 | for (let dx = -radius; dx <= radius; dx++) |
| 613 | { |
| 614 | if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius) |
| 615 | { continue; } |
| 616 | const tileX = originX + dx; |
| 617 | const tileY = originY + dy; |
| 618 | if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY)) |
| 619 | { return { tileX, tileY }; } |
| 620 | } |
| 621 | } |
| 622 | } |
| 623 | return null; |
| 624 | } |
| 625 | |
| 626 | isEnterable (tileX, tileY) |
| 627 | { |
| 628 | const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY)); |
| 629 | if (!data.open) |
| 630 | { return false; } |
| 631 | return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY)); |
| 632 | } |
| 633 | |
| 634 | debugWorld () |
| 635 | { |
| 636 | const loaders = this.#allLoaders(); |
| 637 | const { chunkSim, regionRes } = accumulateLoaderRefs(loaders); |
| 638 | const simulatingChunks = [...chunkSim.entries()] |
| 639 | .filter(([, count]) => count > 0) |
| 640 | .map(([key]) => key) |
| 641 | .sort(); |
| 642 | return { |
| 643 | tickIndex: this.tickIndex, |
| 644 | workerCount: this.workers.length, |
| 645 | workerMode: this.workerMode, |
| 646 | simulatingChunks, |
| 647 | regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({ |
| 648 | ...parseRegionKey(key), |
| 649 | workerId, |
| 650 | state: REGION_RUNTIME_STATE.resident, |
| 651 | refs: regionRes.get(key) ?? 0, |
| 652 | graceUntil: this.regionGraceUntil.get(key) ?? null |
| 653 | })), |
| 654 | entities: [...this.directory.values()].map((entity) => ({ |
| 655 | entityId: entity.entityId, |
| 656 | workerId: entity.workerId, |
| 657 | tileX: entity.tileX, |
| 658 | tileY: entity.tileY, |
| 659 | characterId: entity.characterId |
| 660 | })) |
| 661 | }; |
| 662 | } |
| 663 | |
| 664 | async shutdown () |
| 665 | { |
| 666 | for (const characterId of [...this.characterEntities.keys()]) |
| 667 | { this.despawnCharacter(characterId); } |
| 668 | this.forceUnloadAll(); |
| 669 | await Promise.all(this.workers.map((worker) => worker.terminate())); |
| 670 | } |
| 671 | |
| 672 | forceUnloadAll () |
| 673 | { |
| 674 | for (const key of [...this.regionOwner.keys()]) |
| 675 | { |
| 676 | const { regionX, regionY } = parseRegionKey(key); |
| 677 | this.#unloadRegion(regionX, regionY); |
| 678 | } |
| 679 | } |
| 680 | |
| 681 | #configureWorkers () |
| 682 | { |
| 683 | for (const worker of this.workers) |
| 684 | { |
| 685 | worker.call({ |
| 686 | type: WorkerMessage.configure, |
| 687 | settings: this.settings, |
| 688 | activeRevisionId: this.activeRevisionId |
| 689 | }); |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | #routeCommand (item) |
| 694 | { |
| 695 | if (item.command.type === "respawn") |
| 696 | { return this.#respawnCharacter(item.sessionId, item.command.characterId); } |
| 697 | const entityId = this.characterEntities.get(item.command.characterId); |
| 698 | const record = entityId ? this.directory.get(entityId) : null; |
| 699 | if (!record) |
| 700 | { |
| 701 | const error = new Error("Character is not in the world."); |
| 702 | error.userFacing = true; |
| 703 | throw error; |
| 704 | } |
| 705 | if (item.command.type === "drop-item" && item.command.groundItemId == null) |
| 706 | { item.command.groundItemId = this.nextGroundItemId++; } |
| 707 | if (item.command.type === "attack") |
| 708 | { |
| 709 | const targetRecord = this.directory.get(item.command.targetEntityId); |
| 710 | if (!targetRecord) |
| 711 | { |
| 712 | const error = new Error("Target is not here."); |
| 713 | error.userFacing = true; |
| 714 | throw error; |
| 715 | } |
| 716 | const events = this.#finishRoutedCommand(item, record); |
| 717 | if (targetRecord.workerId !== record.workerId) |
| 718 | { |
| 719 | this.workers[targetRecord.workerId].call({ |
| 720 | type: WorkerMessage.remoteCombatEngage, |
| 721 | attackerEntityId: record.entityId, |
| 722 | targetEntityId: item.command.targetEntityId, |
| 723 | now: item.receivedAt ?? this.now |
| 724 | }); |
| 725 | } |
| 726 | return events; |
| 727 | } |
| 728 | return this.#finishRoutedCommand(item, record); |
| 729 | } |
| 730 | |
| 731 | #finishRoutedCommand (item, record) |
| 732 | { |
| 733 | const result = this.workers[record.workerId].call({ |
| 734 | type: WorkerMessage.command, |
| 735 | sessionId: item.sessionId, |
| 736 | command: item.command, |
| 737 | now: item.receivedAt ?? this.now |
| 738 | }); |
| 739 | const view = this.workers[record.workerId].call({ |
| 740 | type: WorkerMessage.inspect, |
| 741 | entityId: record.entityId |
| 742 | }); |
| 743 | if (view) |
| 744 | { this.#remember(view, record.workerId); } |
| 745 | if (result?.private) |
| 746 | { this.#saveBagFromView(item.command.characterId, result.private); } |
| 747 | if (result?.appearanceChanged && view) |
| 748 | { this.#queueReplication(replicationAppearance(view)); } |
| 749 | if (result?.remainder) |
| 750 | { |
| 751 | this.stateDb.saveInheritance( |
| 752 | this.stateDb.getCharacter(item.command.characterId).account_id, |
| 753 | { slots: result.remainder } |
| 754 | ); |
| 755 | } |
| 756 | for (const event of result?.events ?? []) |
| 757 | { this.#persistGroundEvent(event); } |
| 758 | const events = [...(result?.events ?? [])]; |
| 759 | if (result?.private) |
| 760 | { |
| 761 | events.push({ |
| 762 | type: "inventory", |
| 763 | sessionId: item.sessionId, |
| 764 | bank: !!result.bank, |
| 765 | ...result.private |
| 766 | }); |
| 767 | } |
| 768 | return events; |
| 769 | } |
| 770 | |
| 771 | #applyRemoteMelee (payload) |
| 772 | { |
| 773 | const targetRecord = this.directory.get(payload.targetId); |
| 774 | if (!targetRecord) |
| 775 | { return []; } |
| 776 | const result = this.workers[targetRecord.workerId].call({ |
| 777 | ...payload, |
| 778 | type: WorkerMessage.applyRemoteMelee |
| 779 | }); |
| 780 | const events = []; |
| 781 | for (const event of result?.events ?? []) |
| 782 | { |
| 783 | if (event.type === "entity-despawn") |
| 784 | { this.#forget(event.entityId); } |
| 785 | if (event.type === "skills-updated") |
| 786 | { this.#applySkillsUpdated(event); } |
| 787 | if (event.type === "player-died") |
| 788 | { |
| 789 | events.push(...this.#applyPlayerDeath(event)); |
| 790 | continue; |
| 791 | } |
| 792 | this.#persistGroundEvent(event); |
| 793 | if (event.type !== "skills-updated") |
| 794 | { events.push(event); } |
| 795 | } |
| 796 | for (const forward of result?.forwards ?? []) |
| 797 | { |
| 798 | if (forward.type !== "forward-combat-xp") |
| 799 | { continue; } |
| 800 | const attackerRecord = this.directory.get(forward.entityId); |
| 801 | if (!attackerRecord) |
| 802 | { continue; } |
| 803 | const xpResult = this.workers[attackerRecord.workerId].call({ |
| 804 | type: WorkerMessage.applyCombatHitXp, |
| 805 | entityId: forward.entityId, |
| 806 | profile: forward.profile |
| 807 | }); |
| 808 | for (const xpEvent of xpResult?.events ?? []) |
| 809 | { |
| 810 | if (xpEvent.type === "skills-updated") |
| 811 | { this.#applySkillsUpdated(xpEvent); } |
| 812 | if (xpEvent.type !== "skills-updated") |
| 813 | { events.push(xpEvent); } |
| 814 | } |
| 815 | } |
| 816 | return events; |
| 817 | } |
| 818 | |
| 819 | #applyPlayerDeath (event) |
| 820 | { |
| 821 | const record = this.directory.get(event.entityId); |
| 822 | if (!record) |
| 823 | { return [event]; } |
| 824 | this.stateDb.setCharacterDead(event.characterId, true); |
| 825 | this.stateDb.saveCharacterPosition( |
| 826 | event.characterId, |
| 827 | event.tileX, |
| 828 | event.tileY, |
| 829 | record.gait ?? GAIT.walk |
| 830 | ); |
| 831 | for (const worker of this.workers) |
| 832 | { |
| 833 | worker.call({ |
| 834 | type: WorkerMessage.clearCombat, |
| 835 | entityId: event.entityId, |
| 836 | targetEntityId: event.entityId |
| 837 | }); |
| 838 | } |
| 839 | const result = this.workers[record.workerId].call({ |
| 840 | type: WorkerMessage.spawnCorpseDrops, |
| 841 | characterId: event.characterId, |
| 842 | tileX: event.tileX, |
| 843 | tileY: event.tileY, |
| 844 | now: this.now, |
| 845 | drops: [ |
| 846 | { groundItemId: this.nextGroundItemId++, itemId: ItemId.bones }, |
| 847 | { groundItemId: this.nextGroundItemId++, itemId: ItemId.skull } |
| 848 | ] |
| 849 | }); |
| 850 | const events = [event]; |
| 851 | for (const dropEvent of result?.events ?? []) |
| 852 | { |
| 853 | this.#persistGroundEvent(dropEvent); |
| 854 | events.push(dropEvent); |
| 855 | } |
| 856 | return events; |
| 857 | } |
| 858 | |
| 859 | #respawnCharacter (sessionId, characterId) |
| 860 | { |
| 861 | const row = this.stateDb.getCharacter(characterId); |
| 862 | if (!row?.is_dead) |
| 863 | { |
| 864 | const error = new Error("You are not dead."); |
| 865 | error.userFacing = true; |
| 866 | throw error; |
| 867 | } |
| 868 | const entityId = this.characterEntities.get(characterId); |
| 869 | const record = entityId ? this.directory.get(entityId) : null; |
| 870 | if (!record) |
| 871 | { |
| 872 | const error = new Error("Character is not in the world."); |
| 873 | error.userFacing = true; |
| 874 | throw error; |
| 875 | } |
| 876 | const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId); |
| 877 | if (!destination) |
| 878 | { |
| 879 | const error = new Error("No open tile is available for respawn."); |
| 880 | error.userFacing = true; |
| 881 | throw error; |
| 882 | } |
| 883 | const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills(); |
| 884 | const loader = { ...DEFAULT_CHUNK_LOADER }; |
| 885 | this.#ensureCoverage(destination.tileX, destination.tileY, loader); |
| 886 | const result = this.workers[record.workerId].call({ |
| 887 | type: WorkerMessage.applyRespawn, |
| 888 | entityId, |
| 889 | sessionId, |
| 890 | tileX: destination.tileX, |
| 891 | tileY: destination.tileY, |
| 892 | maxHealth: playerMaxHealth(skills), |
| 893 | maxStamina: playerMaxStamina(skills) |
| 894 | }); |
| 895 | if (!result?.accepted) |
| 896 | { |
| 897 | const error = new Error("That respawn tile is no longer available."); |
| 898 | error.userFacing = true; |
| 899 | throw error; |
| 900 | } |
| 901 | let moveEvents = []; |
| 902 | if (result.transferRequest) |
| 903 | { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); } |
| 904 | else if (result.event) |
| 905 | { |
| 906 | this.#applyMoveToDirectory(result.event); |
| 907 | moveEvents = [result.event]; |
| 908 | const view = this.workers[record.workerId].call({ |
| 909 | type: WorkerMessage.inspect, |
| 910 | entityId |
| 911 | }); |
| 912 | if (view) |
| 913 | { this.#remember(view, record.workerId); } |
| 914 | } |
| 915 | if (!moveEvents.length) |
| 916 | { |
| 917 | const error = new Error("Respawn transfer failed."); |
| 918 | error.userFacing = true; |
| 919 | throw error; |
| 920 | } |
| 921 | this.stateDb.setCharacterDead(characterId, false); |
| 922 | this.stateDb.saveCharacterPosition( |
| 923 | characterId, |
| 924 | destination.tileX, |
| 925 | destination.tileY, |
| 926 | record.gait ?? GAIT.walk |
| 927 | ); |
| 928 | this.#recalculateActivation(this.now); |
| 929 | this.#syncGhosts(); |
| 930 | return [ |
| 931 | ...moveEvents, |
| 932 | { |
| 933 | type: "player-respawned", |
| 934 | entityId, |
| 935 | characterId, |
| 936 | sessionId, |
| 937 | tileX: destination.tileX, |
| 938 | tileY: destination.tileY, |
| 939 | health: playerMaxHealth(skills), |
| 940 | maxHealth: playerMaxHealth(skills), |
| 941 | stamina: playerMaxStamina(skills), |
| 942 | maxStamina: playerMaxStamina(skills) |
| 943 | } |
| 944 | ]; |
| 945 | } |
| 946 | |
| 947 | #refreshAltarIndex () |
| 948 | { |
| 949 | const altars = []; |
| 950 | for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId)) |
| 951 | { |
| 952 | const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y); |
| 953 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 954 | { |
| 955 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 956 | { |
| 957 | const block = data.blocks[localY * CHUNK_SIZE + localX]; |
| 958 | if (block?.typeId !== BlockType.churchAltar) |
| 959 | { continue; } |
| 960 | altars.push({ |
| 961 | tileX: coord.chunk_x * CHUNK_SIZE + localX, |
| 962 | tileY: coord.chunk_y * CHUNK_SIZE + localY |
| 963 | }); |
| 964 | } |
| 965 | } |
| 966 | } |
| 967 | this.altarTiles = altars; |
| 968 | } |
| 969 | |
| 970 | #findRespawnDestination (originX, originY, entityId) |
| 971 | { |
| 972 | const ordered = [...this.altarTiles].sort((left, right) => |
| 973 | Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY)) |
| 974 | - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY)) |
| 975 | ); |
| 976 | for (const altar of ordered) |
| 977 | { |
| 978 | const adjacent = []; |
| 979 | for (let dy = -1; dy <= 1; dy++) |
| 980 | { |
| 981 | for (let dx = -1; dx <= 1; dx++) |
| 982 | { |
| 983 | if (dx === 0 && dy === 0) |
| 984 | { continue; } |
| 985 | adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy }); |
| 986 | } |
| 987 | } |
| 988 | adjacent.sort((left, right) => |
| 989 | Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY)) |
| 990 | - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY)) |
| 991 | ); |
| 992 | const tile = adjacent.find((entry) => |
| 993 | this.isEnterable(entry.tileX, entry.tileY) |
| 994 | && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId) |
| 995 | ); |
| 996 | if (tile) |
| 997 | { return tile; } |
| 998 | } |
| 999 | for (let radius = 0; radius <= 24; radius++) |
| 1000 | { |
| 1001 | for (let dy = -radius; dy <= radius; dy++) |
| 1002 | { |
| 1003 | for (let dx = -radius; dx <= radius; dx++) |
| 1004 | { |
| 1005 | if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius) |
| 1006 | { continue; } |
| 1007 | const tileX = originX + dx; |
| 1008 | const tileY = originY + dy; |
| 1009 | if (this.isEnterable(tileX, tileY) |
| 1010 | && !this.#occupiedByOther(tileX, tileY, entityId)) |
| 1011 | { return { tileX, tileY }; } |
| 1012 | } |
| 1013 | } |
| 1014 | } |
| 1015 | return this.findOpenSpawn(); |
| 1016 | } |
| 1017 | |
| 1018 | #occupiedByOther (tileX, tileY, entityId) |
| 1019 | { |
| 1020 | for (const record of this.directory.values()) |
| 1021 | { |
| 1022 | if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY) |
| 1023 | { return true; } |
| 1024 | } |
| 1025 | return false; |
| 1026 | } |
| 1027 | |
| 1028 | #recalculateActivation (now) |
| 1029 | { |
| 1030 | const loaders = this.#allLoaders(); |
| 1031 | const { chunkSim, regionRes } = accumulateLoaderRefs(loaders); |
| 1032 | |
| 1033 | for (const [key, count] of regionRes) |
| 1034 | { |
| 1035 | if (count <= 0) |
| 1036 | { continue; } |
| 1037 | const { regionX, regionY } = parseRegionKey(key); |
| 1038 | this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY)); |
| 1039 | this.regionGraceUntil.delete(key); |
| 1040 | } |
| 1041 | |
| 1042 | for (const [key] of [...this.regionOwner.entries()]) |
| 1043 | { |
| 1044 | if ((regionRes.get(key) ?? 0) > 0) |
| 1045 | { continue; } |
| 1046 | if (!this.regionGraceUntil.has(key)) |
| 1047 | { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); } |
| 1048 | if (now >= this.regionGraceUntil.get(key)) |
| 1049 | { |
| 1050 | const { regionX, regionY } = parseRegionKey(key); |
| 1051 | this.#unloadRegion(regionX, regionY); |
| 1052 | } |
| 1053 | } |
| 1054 | |
| 1055 | for (const [workerId, worker] of this.workers.entries()) |
| 1056 | { |
| 1057 | const chunkKeys = []; |
| 1058 | for (const [key, count] of chunkSim) |
| 1059 | { |
| 1060 | if (count <= 0) |
| 1061 | { continue; } |
| 1062 | const { chunkX, chunkY } = parseChunkKey(key); |
| 1063 | if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)) === workerId) |
| 1064 | { chunkKeys.push(key); } |
| 1065 | } |
| 1066 | worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys }); |
| 1067 | } |
| 1068 | this.#syncAllReplicas(); |
| 1069 | } |
| 1070 | |
| 1071 | #ensureCoverage (tileX, tileY, loader) |
| 1072 | { |
| 1073 | const coverage = loaderCoverage(tileX, tileY, loader); |
| 1074 | let preferred = this.#ownerOfTile(tileX, tileY); |
| 1075 | for (const region of coverage.residentRegions) |
| 1076 | { |
| 1077 | const owner = this.#ensureRegion(region.regionX, region.regionY, preferred); |
| 1078 | if (preferred == null) |
| 1079 | { preferred = owner; } |
| 1080 | } |
| 1081 | } |
| 1082 | |
| 1083 | #ensureRegion (regionX, regionY, preferredWorkerId) |
| 1084 | { |
| 1085 | const key = regionKey(regionX, regionY); |
| 1086 | if (this.regionOwner.has(key)) |
| 1087 | { return this.regionOwner.get(key); } |
| 1088 | const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId); |
| 1089 | this.workers[workerId].call({ |
| 1090 | type: WorkerMessage.assignRegion, |
| 1091 | regionX, |
| 1092 | regionY, |
| 1093 | chunks: this.#regionChunkBlobs(regionX, regionY) |
| 1094 | }); |
| 1095 | this.regionOwner.set(key, workerId); |
| 1096 | this.#restorePersistent(regionX, regionY, workerId); |
| 1097 | this.#restoreGroundItems(regionX, regionY, workerId); |
| 1098 | return workerId; |
| 1099 | } |
| 1100 | |
| 1101 | #unloadRegion (regionX, regionY) |
| 1102 | { |
| 1103 | const key = regionKey(regionX, regionY); |
| 1104 | const workerId = this.regionOwner.get(key); |
| 1105 | if (workerId == null) |
| 1106 | { return; } |
| 1107 | const bounds = regionTileBounds(regionX, regionY); |
| 1108 | const { dropped, groundItems } = this.workers[workerId].call({ |
| 1109 | type: WorkerMessage.dropRegion, |
| 1110 | regionX, |
| 1111 | regionY |
| 1112 | }); |
| 1113 | const persistent = []; |
| 1114 | for (const record of dropped ?? []) |
| 1115 | { |
| 1116 | if (record.characterId) |
| 1117 | { |
| 1118 | this.stateDb.saveCharacterPosition( |
| 1119 | record.characterId, |
| 1120 | record.tileX, |
| 1121 | record.tileY, |
| 1122 | record.gait ?? GAIT.walk |
| 1123 | ); |
| 1124 | } |
| 1125 | if (record.persistent) |
| 1126 | { persistent.push(record); } |
| 1127 | this.#forget(record.entityId); |
| 1128 | } |
| 1129 | this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent); |
| 1130 | for (const item of groundItems ?? []) |
| 1131 | { this.stateDb.upsertGroundItem(item); } |
| 1132 | this.regionOwner.delete(key); |
| 1133 | this.regionGraceUntil.delete(key); |
| 1134 | } |
| 1135 | |
| 1136 | #restorePersistent (regionX, regionY, workerId) |
| 1137 | { |
| 1138 | const bounds = regionTileBounds(regionX, regionY); |
| 1139 | const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY); |
| 1140 | for (const row of rows) |
| 1141 | { |
| 1142 | if (this.directory.has(row.entity_id)) |
| 1143 | { continue; } |
| 1144 | const components = JSON.parse(row.components_blob); |
| 1145 | const view = this.workers[workerId].call({ |
| 1146 | type: WorkerMessage.spawn, |
| 1147 | entityId: row.entity_id, |
| 1148 | components |
| 1149 | }); |
| 1150 | this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1); |
| 1151 | this.#remember(view, workerId); |
| 1152 | } |
| 1153 | } |
| 1154 | |
| 1155 | #applyTransfers (requests) |
| 1156 | { |
| 1157 | const events = []; |
| 1158 | for (const request of requests) |
| 1159 | { |
| 1160 | const destWorkerId = this.#ensureRegion(request.toRegionX, request.toRegionY, request.fromWorkerId); |
| 1161 | if (destWorkerId === request.fromWorkerId) |
| 1162 | { |
| 1163 | this.workers[request.fromWorkerId].call({ |
| 1164 | type: WorkerMessage.abortTransfer, |
| 1165 | entityId: request.entityId |
| 1166 | }); |
| 1167 | continue; |
| 1168 | } |
| 1169 | let result; |
| 1170 | try |
| 1171 | { |
| 1172 | result = this.workers[destWorkerId].call({ |
| 1173 | type: WorkerMessage.applyTransfer, |
| 1174 | payload: request.payload, |
| 1175 | destTileX: request.destTileX, |
| 1176 | destTileY: request.destTileY |
| 1177 | }); |
| 1178 | } |
| 1179 | catch |
| 1180 | { |
| 1181 | result = { accepted: false }; |
| 1182 | } |
| 1183 | if (!result?.accepted) |
| 1184 | { |
| 1185 | this.workers[request.fromWorkerId].call({ |
| 1186 | type: WorkerMessage.abortTransfer, |
| 1187 | entityId: request.entityId |
| 1188 | }); |
| 1189 | continue; |
| 1190 | } |
| 1191 | this.workers[request.fromWorkerId].call({ |
| 1192 | type: WorkerMessage.commitTransfer, |
| 1193 | entityId: request.entityId |
| 1194 | }); |
| 1195 | this.#remember(result.entity, destWorkerId); |
| 1196 | events.push({ |
| 1197 | type: "entity-move", |
| 1198 | entityId: request.entityId, |
| 1199 | fromTileX: request.fromTileX, |
| 1200 | fromTileY: request.fromTileY, |
| 1201 | tileX: result.entity.tileX, |
| 1202 | tileY: result.entity.tileY, |
| 1203 | gait: result.entity.gait |
| 1204 | }); |
| 1205 | } |
| 1206 | return events; |
| 1207 | } |
| 1208 | |
| 1209 | #syncAllReplicas () |
| 1210 | { |
| 1211 | for (const [workerId, worker] of this.workers.entries()) |
| 1212 | { |
| 1213 | const ownedKeys = new Set(); |
| 1214 | for (const [key, owner] of this.regionOwner) |
| 1215 | { |
| 1216 | if (owner !== workerId) |
| 1217 | { continue; } |
| 1218 | const { regionX, regionY } = parseRegionKey(key); |
| 1219 | for (const chunk of chunksInRegion(regionX, regionY)) |
| 1220 | { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY)); } |
| 1221 | } |
| 1222 | const replicas = []; |
| 1223 | for (const key of replicaNeededForOwnedChunks(ownedKeys)) |
| 1224 | { |
| 1225 | if (ownedKeys.has(key)) |
| 1226 | { continue; } |
| 1227 | const { chunkX, chunkY } = parseChunkKey(key); |
| 1228 | replicas.push({ |
| 1229 | chunkX, |
| 1230 | chunkY, |
| 1231 | data: this.#authoredChunk(chunkX, chunkY) |
| 1232 | }); |
| 1233 | } |
| 1234 | worker.call({ type: WorkerMessage.setReplicas, chunks: replicas }); |
| 1235 | } |
| 1236 | } |
| 1237 | |
| 1238 | #syncGhosts () |
| 1239 | { |
| 1240 | const entities = []; |
| 1241 | for (const worker of this.workers) |
| 1242 | { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); } |
| 1243 | for (const [workerId, worker] of this.workers.entries()) |
| 1244 | { |
| 1245 | const ghosts = entities.filter((entity) => |
| 1246 | { |
| 1247 | if (this.#ownerOfTile(entity.tileX, entity.tileY) === workerId) |
| 1248 | { return false; } |
| 1249 | return this.#nearWorker(workerId, entity.tileX, entity.tileY); |
| 1250 | }); |
| 1251 | worker.call({ type: WorkerMessage.setGhosts, ghosts }); |
| 1252 | } |
| 1253 | } |
| 1254 | |
| 1255 | #nearWorker (workerId, tileX, tileY) |
| 1256 | { |
| 1257 | const chunkX = tileToChunk(tileX); |
| 1258 | const chunkY = tileToChunk(tileY); |
| 1259 | for (const [key, owner] of this.regionOwner) |
| 1260 | { |
| 1261 | if (owner !== workerId) |
| 1262 | { continue; } |
| 1263 | const { regionX, regionY } = parseRegionKey(key); |
| 1264 | for (const chunk of chunksInRegion(regionX, regionY)) |
| 1265 | { |
| 1266 | if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2) |
| 1267 | { return true; } |
| 1268 | } |
| 1269 | } |
| 1270 | return false; |
| 1271 | } |
| 1272 | |
| 1273 | #allLoaders () |
| 1274 | { |
| 1275 | const loaders = []; |
| 1276 | for (const worker of this.workers) |
| 1277 | { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); } |
| 1278 | return loaders; |
| 1279 | } |
| 1280 | |
| 1281 | #preferredWorkerForRegion (loaders, regionX, regionY) |
| 1282 | { |
| 1283 | const votes = new Map(); |
| 1284 | for (const loader of loaders) |
| 1285 | { |
| 1286 | const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader); |
| 1287 | if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY)) |
| 1288 | { continue; } |
| 1289 | const record = this.directory.get(loader.entityId); |
| 1290 | if (record?.workerId == null) |
| 1291 | { continue; } |
| 1292 | votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1); |
| 1293 | } |
| 1294 | let best = null; |
| 1295 | let bestVotes = -1; |
| 1296 | for (const [workerId, count] of votes) |
| 1297 | { |
| 1298 | if (count > bestVotes) |
| 1299 | { |
| 1300 | best = workerId; |
| 1301 | bestVotes = count; |
| 1302 | } |
| 1303 | } |
| 1304 | return best; |
| 1305 | } |
| 1306 | |
| 1307 | #pickWorker (regionX, regionY, preferredWorkerId) |
| 1308 | { |
| 1309 | const pinned = this.pinRegion?.(regionX, regionY); |
| 1310 | if (pinned != null) |
| 1311 | { return pinned; } |
| 1312 | |
| 1313 | const neighborOwners = []; |
| 1314 | for (let dy = -1; dy <= 1; dy++) |
| 1315 | { |
| 1316 | for (let dx = -1; dx <= 1; dx++) |
| 1317 | { |
| 1318 | if (dx === 0 && dy === 0) |
| 1319 | { continue; } |
| 1320 | const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy)); |
| 1321 | if (owner != null) |
| 1322 | { neighborOwners.push(owner); } |
| 1323 | } |
| 1324 | } |
| 1325 | |
| 1326 | const scores = this.workers.map((_, workerId) => ({ |
| 1327 | workerId, |
| 1328 | neighbors: neighborOwners.filter((owner) => owner === workerId).length, |
| 1329 | load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length |
| 1330 | })); |
| 1331 | |
| 1332 | if (preferredWorkerId != null && scores[preferredWorkerId]) |
| 1333 | { |
| 1334 | const preferred = scores[preferredWorkerId]; |
| 1335 | if (preferred.neighbors > 0 || neighborOwners.length === 0) |
| 1336 | { return preferredWorkerId; } |
| 1337 | } |
| 1338 | |
| 1339 | scores.sort((left, right) => |
| 1340 | right.neighbors - left.neighbors |
| 1341 | || left.load - right.load |
| 1342 | || left.workerId - right.workerId |
| 1343 | ); |
| 1344 | return scores[0].workerId; |
| 1345 | } |
| 1346 | |
| 1347 | #ownerOfTile (tileX, tileY) |
| 1348 | { |
| 1349 | return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY))) ?? null; |
| 1350 | } |
| 1351 | |
| 1352 | #regionKeyForChunk (chunkX, chunkY) |
| 1353 | { |
| 1354 | return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY)); |
| 1355 | } |
| 1356 | |
| 1357 | #regionChunkBlobs (regionX, regionY) |
| 1358 | { |
| 1359 | return chunksInRegion(regionX, regionY).map((coord) => ({ |
| 1360 | chunkX: coord.chunkX, |
| 1361 | chunkY: coord.chunkY, |
| 1362 | data: this.#authoredChunk(coord.chunkX, coord.chunkY) |
| 1363 | })); |
| 1364 | } |
| 1365 | |
| 1366 | #authoredChunk (chunkX, chunkY) |
| 1367 | { |
| 1368 | const key = chunkKey(chunkX, chunkY); |
| 1369 | if (this.authoredCache.has(key)) |
| 1370 | { return this.authoredCache.get(key); } |
| 1371 | const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId); |
| 1372 | const data = row |
| 1373 | ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId) |
| 1374 | : createEmptyChunkData(this.settings.defaultGroundTypeId); |
| 1375 | this.authoredCache.set(key, data); |
| 1376 | return data; |
| 1377 | } |
| 1378 | |
| 1379 | #syntheticSnapshot (chunkX, chunkY) |
| 1380 | { |
| 1381 | const data = this.#authoredChunk(chunkX, chunkY); |
| 1382 | return { |
| 1383 | chunkX, |
| 1384 | chunkY, |
| 1385 | open: data.open, |
| 1386 | closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y).open), |
| 1387 | grounds: data.grounds, |
| 1388 | blocks: data.blocks, |
| 1389 | light: data.light, |
| 1390 | entities: [], |
| 1391 | groundItems: [] |
| 1392 | }; |
| 1393 | } |
| 1394 | |
| 1395 | #occupiedTile (tileX, tileY) |
| 1396 | { |
| 1397 | for (const record of this.directory.values()) |
| 1398 | { |
| 1399 | if (record.tileX === tileX && record.tileY === tileY) |
| 1400 | { return record.entityId; } |
| 1401 | } |
| 1402 | return null; |
| 1403 | } |
| 1404 | |
| 1405 | #queueReplication (event) |
| 1406 | { |
| 1407 | if (event) |
| 1408 | { this.replication.push(event); } |
| 1409 | } |
| 1410 | |
| 1411 | #stepSpawners () |
| 1412 | { |
| 1413 | const events = []; |
| 1414 | for (const worker of this.workers) |
| 1415 | { |
| 1416 | const result = worker.call({ type: WorkerMessage.stepSpawners }); |
| 1417 | for (const request of result?.spawnRequests ?? []) |
| 1418 | { |
| 1419 | try |
| 1420 | { |
| 1421 | this.spawnEntity(mobComponents(request), { requireResident: true }); |
| 1422 | } |
| 1423 | catch |
| 1424 | { continue; } |
| 1425 | } |
| 1426 | } |
| 1427 | return events; |
| 1428 | } |
| 1429 | |
| 1430 | #restoreGroundItems (regionX, regionY, workerId) |
| 1431 | { |
| 1432 | const bounds = regionTileBounds(regionX, regionY); |
| 1433 | const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY) |
| 1434 | .filter((item) => item.expiresAt > this.now); |
| 1435 | this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId()); |
| 1436 | this.workers[workerId].call({ |
| 1437 | type: WorkerMessage.setGroundItems, |
| 1438 | regionX, |
| 1439 | regionY, |
| 1440 | items |
| 1441 | }); |
| 1442 | } |
| 1443 | |
| 1444 | #persistGroundEvent (event) |
| 1445 | { |
| 1446 | if (event.type === "ground-item-appear") |
| 1447 | { |
| 1448 | this.stateDb.upsertGroundItem({ |
| 1449 | groundItemId: event.groundItemId, |
| 1450 | tileX: event.tileX, |
| 1451 | tileY: event.tileY, |
| 1452 | stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity }, |
| 1453 | droppedAt: event.droppedAt ?? this.now, |
| 1454 | expiresAt: event.expiresAt, |
| 1455 | source: event.source ?? "player-drop", |
| 1456 | droppedByCharacterId: event.droppedByCharacterId ?? null |
| 1457 | }); |
| 1458 | } |
| 1459 | if (event.type === "ground-item-despawn") |
| 1460 | { this.stateDb.deleteGroundItem(event.groundItemId); } |
| 1461 | } |
| 1462 | |
| 1463 | #saveBag (entityId, workerId) |
| 1464 | { |
| 1465 | const record = this.directory.get(entityId); |
| 1466 | const bag = this.workers[workerId].call({ |
| 1467 | type: WorkerMessage.inspectBag, |
| 1468 | entityId |
| 1469 | }); |
| 1470 | if (!bag || !record?.characterId) |
| 1471 | { return; } |
| 1472 | this.#saveBagFromView(record.characterId, bag); |
| 1473 | const skills = this.workers[workerId].call({ |
| 1474 | type: WorkerMessage.inspectSkills, |
| 1475 | entityId |
| 1476 | }); |
| 1477 | if (skills) |
| 1478 | { this.stateDb.saveSkills(record.characterId, skills); } |
| 1479 | } |
| 1480 | |
| 1481 | #applySkillsUpdated (event) |
| 1482 | { |
| 1483 | if (!event?.characterId || !event.stored) |
| 1484 | { return; } |
| 1485 | this.stateDb.saveSkills(event.characterId, { xp: event.stored }); |
| 1486 | this.pushSkills(event.characterId, event.skills ?? []); |
| 1487 | } |
| 1488 | |
| 1489 | #saveBagFromView (characterId, bag) |
| 1490 | { |
| 1491 | this.stateDb.saveBag(characterId, { |
| 1492 | inventory: bag.inventory, |
| 1493 | equipment: bag.equipment, |
| 1494 | vault: bag.vault, |
| 1495 | vaultReserved: bag.vaultReserved |
| 1496 | }); |
| 1497 | } |
| 1498 | |
| 1499 | releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null) |
| 1500 | { |
| 1501 | const onlineId = this.characterEntities.get(issuerCharacterId); |
| 1502 | const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId); |
| 1503 | if (!bag) |
| 1504 | { return { ok: false, error: "Issuer vault not found." }; } |
| 1505 | const reserved = [...(bag.vaultReserved ?? [])]; |
| 1506 | const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId }); |
| 1507 | if (index < 0) |
| 1508 | { return { ok: false, error: "That cheque cannot be redeemed." }; } |
| 1509 | const [stack] = reserved.splice(index, 1); |
| 1510 | bag.vaultReserved = reserved; |
| 1511 | this.stateDb.saveBag(issuerCharacterId, bag); |
| 1512 | if (onlineId) |
| 1513 | { |
| 1514 | this.applyBag(onlineId, bag); |
| 1515 | this.pushInventory(issuerCharacterId, bag); |
| 1516 | } |
| 1517 | return { ok: true, stack }; |
| 1518 | } |
| 1519 | |
| 1520 | restoreChequeReservation (issuerCharacterId, stack) |
| 1521 | { |
| 1522 | const onlineId = this.characterEntities.get(issuerCharacterId); |
| 1523 | const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId); |
| 1524 | if (!bag) |
| 1525 | { return; } |
| 1526 | bag.vaultReserved = [...(bag.vaultReserved ?? []), stack]; |
| 1527 | this.stateDb.saveBag(issuerCharacterId, bag); |
| 1528 | if (onlineId) |
| 1529 | { |
| 1530 | this.applyBag(onlineId, bag); |
| 1531 | this.pushInventory(issuerCharacterId, bag); |
| 1532 | } |
| 1533 | } |
| 1534 | |
| 1535 | #remember (view, workerId) |
| 1536 | { |
| 1537 | if (!view) |
| 1538 | { return; } |
| 1539 | this.directory.set(view.entityId, { ...view, workerId }); |
| 1540 | if (view.characterId) |
| 1541 | { this.characterEntities.set(view.characterId, view.entityId); } |
| 1542 | } |
| 1543 | |
| 1544 | #applyMoveToDirectory (event) |
| 1545 | { |
| 1546 | const record = this.directory.get(event.entityId); |
| 1547 | if (!record) |
| 1548 | { return; } |
| 1549 | record.tileX = event.tileX; |
| 1550 | record.tileY = event.tileY; |
| 1551 | record.gait = event.gait; |
| 1552 | if (event.worldX != null) |
| 1553 | { record.worldX = event.worldX; } |
| 1554 | if (event.worldY != null) |
| 1555 | { record.worldY = event.worldY; } |
| 1556 | if (event.freeFlight != null) |
| 1557 | { record.freeFlight = !!event.freeFlight; } |
| 1558 | } |
| 1559 | |
| 1560 | #forget (entityId) |
| 1561 | { |
| 1562 | const record = this.directory.get(entityId); |
| 1563 | if (record?.characterId) |
| 1564 | { this.characterEntities.delete(record.characterId); } |
| 1565 | this.directory.delete(entityId); |
| 1566 | } |
| 1567 | } |