| 1 | import |
| 2 | { |
| 3 | CHUNK_SIZE, |
| 4 | DEFAULT_CHUNK_LOADER, |
| 5 | GAIT, |
| 6 | REGION_RUNTIME_STATE, |
| 7 | VISIBLE_CHUNK_RADIUS, |
| 8 | STATIC_CHUNK_RADIUS, |
| 9 | WORLD_YEAR_OFFSET |
| 10 | } from "../../../shared/protocol/constants.js"; |
| 11 | import { OVERWORLD_ID, normalizeDimensionId, defaultDimensionRecord } from "../../../shared/world/dimensions.js"; |
| 12 | import |
| 13 | { |
| 14 | chunkKey, |
| 15 | chunkToRegion, |
| 16 | chunksInRegion, |
| 17 | parseChunkKey, |
| 18 | parseRegionKey, |
| 19 | regionKey, |
| 20 | regionTileBounds, |
| 21 | tileToChunk, |
| 22 | tileToLocal, |
| 23 | tileToRegion, |
| 24 | visibleChunkCoords |
| 25 | } from "../world/coordinates.js"; |
| 26 | import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js"; |
| 27 | import { closedNeighborEdges } from "../world/chunkFlags.js"; |
| 28 | import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js"; |
| 29 | import { InProcessWorker } from "./inProcessWorker.js"; |
| 30 | import { ThreadWorker } from "./threadWorker.js"; |
| 31 | import { WorkerMessage } from "./protocol.js"; |
| 32 | import { replicaNeededForOwnedChunks } from "./workerWorld.js"; |
| 33 | import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js"; |
| 34 | import { emptyEquipment, emptySlots, insertStackGrowable } from "../../../shared/items/inventory.js"; |
| 35 | import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js"; |
| 36 | import { skullValue, decayKillCounter, SKULL_KILL_BONUS } from "../../../shared/combat/skull.js"; |
| 37 | import { COMBAT_LOGOUT_MS } from "../../../shared/combat/combatLogout.js"; |
| 38 | import |
| 39 | { |
| 40 | applyCombatLogoutCowardice, |
| 41 | coinsDroppedFromDeathEvents, |
| 42 | dispatchChurchOfflineResurrectionLetter |
| 43 | } from "../combat/combatLogout.js"; |
| 44 | import { mobComponents } from "./spawners.js"; |
| 45 | import { shadeSummonComponents } from "../spells/summons.js"; |
| 46 | import { jadeiteFairyComponents } from "../spells/jadeiteFairy.js"; |
| 47 | import { MobId } from "../../../shared/definitions/mobs.js"; |
| 48 | import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js"; |
| 49 | import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js"; |
| 50 | import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js"; |
| 51 | import { BlockType } from "../../../shared/definitions/tiles.js"; |
| 52 | import { ItemId, itemDefinition } from "../../../shared/definitions/items.js"; |
| 53 | import { seasonIdAt } from "../../../shared/world/season.js"; |
| 54 | import { CourierService } from "../courier/service.js"; |
| 55 | import { MarketService } from "../market/service.js"; |
| 56 | import { TradeService } from "../trade/service.js"; |
| 57 | import { BountyService } from "../bounty/service.js"; |
| 58 | import { BarberService } from "../barber/service.js"; |
| 59 | import { findReservedChequeIndex } from "../items/bags.js"; |
| 60 | import { hairFromCharacterRow, appearanceHairFields } from "../../../shared/appearance/hair.js"; |
| 61 | import { QuestContentCache } from "../quests/contentCache.js"; |
| 62 | import { QuestRuntime } from "../quests/runtime.js"; |
| 63 | import { isAdjacentTile } from "../../../shared/navigation/adjacency.js"; |
| 64 | |
| 65 | export class Simulation |
| 66 | { |
| 67 | constructor(worldDb, stateDb, options = {}) |
| 68 | { |
| 69 | this.worldDb = worldDb; |
| 70 | this.stateDb = stateDb; |
| 71 | this.workerCount = Math.max(1, Math.round(options.workerCount ?? Number(process.env.SIMULATION_WORKERS ?? 2))); |
| 72 | this.workerMode = options.workerMode ?? process.env.SIMULATION_WORKER_MODE ?? "inprocess"; |
| 73 | this.pinRegion = options.pinRegion ?? null; |
| 74 | this.nowFn = options.now ?? (() => Date.now()); |
| 75 | this.workers = []; |
| 76 | this.regionOwner = new Map(); |
| 77 | this.regionGraceUntil = new Map(); |
| 78 | this.directory = new Map(); |
| 79 | this.characterEntities = new Map(); |
| 80 | /** @type {Map<number, { lastCombatEndedAt: number|null, lastOutboundAttackAt: number|null, lastCombatActivityAt: number|null, pvpInvolved: boolean, wasInCombat: boolean }>} */ |
| 81 | this.combatTracking = new Map(); |
| 82 | /** @type {Map<number, { savedAutoCast: boolean, pendingCowardice: boolean, startedAt: number }>} */ |
| 83 | this.combatLogouts = new Map(); |
| 84 | this.commandQueue = []; |
| 85 | this.replication = []; |
| 86 | this.pendingPrivate = []; |
| 87 | this.courier = null; |
| 88 | this.market = null; |
| 89 | this.altarTiles = []; |
| 90 | this.authoredCache = new Map(); |
| 91 | this.simulatingChunkKeys = new Set(); |
| 92 | this.nextEntityId = 1; |
| 93 | this.nextGroundItemId = stateDb.nextGroundItemId(); |
| 94 | this.tickIndex = 0; |
| 95 | this.movementTickCounter = 0; |
| 96 | this.lastTickAt = null; |
| 97 | this.movementAccumulator = 0; |
| 98 | this.activeRevisionId = worldDb.getActiveRevisionId(); |
| 99 | this.settings = worldDb.getLiveSettings(); |
| 100 | this.questContent = new QuestContentCache(worldDb); |
| 101 | this.dimensions = this.#loadDimensionsCache(); |
| 102 | this.quests = null; |
| 103 | |
| 104 | const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker; |
| 105 | for (let workerId = 0; workerId < this.workerCount; workerId++) |
| 106 | { |
| 107 | const worker = new WorkerImpl(workerId); |
| 108 | worker.call({ |
| 109 | type: WorkerMessage.configure, |
| 110 | settings: this.settings, |
| 111 | activeRevisionId: this.activeRevisionId |
| 112 | }); |
| 113 | this.workers.push(worker); |
| 114 | } |
| 115 | for (const worker of this.workers) |
| 116 | { |
| 117 | if (!worker.world) |
| 118 | { continue; } |
| 119 | worker.world.releaseChequeReservation = (issuerId, chequeId, instance) => |
| 120 | this.releaseChequeReservation(issuerId, chequeId, instance); |
| 121 | worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack); |
| 122 | worker.world.voidFilledCheque = (stack) => this.voidFilledCheque(stack); |
| 123 | } |
| 124 | this.courier = new CourierService({ |
| 125 | stateDb: this.stateDb, |
| 126 | worldDb: this.worldDb, |
| 127 | simulation: this |
| 128 | }); |
| 129 | this.market = new MarketService({ |
| 130 | stateDb: this.stateDb, |
| 131 | worldDb: this.worldDb, |
| 132 | simulation: this |
| 133 | }); |
| 134 | this.trade = new TradeService({ |
| 135 | stateDb: this.stateDb, |
| 136 | simulation: this |
| 137 | }); |
| 138 | this.bounty = new BountyService(this.stateDb, this, this.courier); |
| 139 | this.barber = new BarberService(this.stateDb, this); |
| 140 | this.quests = new QuestRuntime({ |
| 141 | stateDb: this.stateDb, |
| 142 | content: this.questContent, |
| 143 | simulation: this |
| 144 | }); |
| 145 | this.#refreshAltarIndex(); |
| 146 | } |
| 147 | |
| 148 | get now () |
| 149 | { |
| 150 | return this.nowFn(); |
| 151 | } |
| 152 | |
| 153 | applySettings (settings, { grantInitialQuests = false } = {}) |
| 154 | { |
| 155 | this.settings = { ...this.settings, ...settings }; |
| 156 | this.#configureWorkers(); |
| 157 | if (grantInitialQuests) |
| 158 | { this.quests?.grantInitialQuestsToAllCharacters?.(); } |
| 159 | } |
| 160 | |
| 161 | /** Sparse last-sale map for editor base-price readouts. */ |
| 162 | itemLastSalesSnapshot () |
| 163 | { |
| 164 | return this.market?.snapshot?.() ?? {}; |
| 165 | } |
| 166 | |
| 167 | syncItemLastSales (lastSales) |
| 168 | { |
| 169 | const sales = {}; |
| 170 | for (const [itemId, sale] of lastSales?.entries?.() ?? []) |
| 171 | { sales[String(itemId)] = sale; } |
| 172 | for (const worker of this.workers) |
| 173 | { |
| 174 | worker.call({ |
| 175 | type: WorkerMessage.setItemLastSales, |
| 176 | sales |
| 177 | }); |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | reloadWorld () |
| 182 | { |
| 183 | this.activeRevisionId = this.worldDb.getActiveRevisionId(); |
| 184 | this.settings = this.worldDb.getLiveSettings(); |
| 185 | this.dimensions = this.#loadDimensionsCache(); |
| 186 | this.authoredCache.clear(); |
| 187 | this.#configureWorkers(); |
| 188 | for (const [key, workerId] of this.regionOwner) |
| 189 | { |
| 190 | const { regionX, regionY, dimensionId } = parseRegionKey(key); |
| 191 | this.workers[workerId].call({ |
| 192 | type: WorkerMessage.replaceRegionChunks, |
| 193 | regionX, |
| 194 | regionY, |
| 195 | dimensionId, |
| 196 | chunks: this.#regionChunkBlobs(regionX, regionY, dimensionId) |
| 197 | }); |
| 198 | } |
| 199 | this.#syncAllReplicas(); |
| 200 | this.courier?.refreshBankIndex(); |
| 201 | this.courier?.refreshBountyOfficeIndex(); |
| 202 | this.market?.refreshIndex(); |
| 203 | this.questContent.reload(); |
| 204 | this.quests?.closeAllSessions(); |
| 205 | this.#refreshAltarIndex(); |
| 206 | } |
| 207 | |
| 208 | enqueue (sessionId, command) |
| 209 | { |
| 210 | this.commandQueue.push({ sessionId, command, receivedAt: this.now }); |
| 211 | } |
| 212 | |
| 213 | step (now = this.now) |
| 214 | { |
| 215 | this.tickIndex += 1; |
| 216 | if ((this.tickIndex % 1200) === 0) |
| 217 | { this.worldDb.purgeExpiredDimensions(now); } |
| 218 | const events = []; |
| 219 | const commands = this.commandQueue.splice(0); |
| 220 | for (const item of commands) |
| 221 | { |
| 222 | try |
| 223 | { |
| 224 | events.push(...this.#routeCommand(item)); |
| 225 | } |
| 226 | catch (error) |
| 227 | { |
| 228 | events.push({ |
| 229 | sessionId: item.sessionId, |
| 230 | type: "command-error", |
| 231 | message: error.userFacing ? error.message : "Command failed." |
| 232 | }); |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | this.#recalculateActivation(now); |
| 237 | |
| 238 | const simHz = Math.max(1, this.settings.simulationTickHz || 20); |
| 239 | const expectedDt = 1 / simHz; |
| 240 | const dt = (this.lastTickAt == null || now <= this.lastTickAt) |
| 241 | ? expectedDt |
| 242 | : Math.min(0.25, (now - this.lastTickAt) / 1000); |
| 243 | this.lastTickAt = now; |
| 244 | |
| 245 | { |
| 246 | const transfers = []; |
| 247 | const remoteMelee = []; |
| 248 | const remoteRanged = []; |
| 249 | for (const worker of this.workers) |
| 250 | { |
| 251 | const result = worker.call({ type: WorkerMessage.stepSystems, now, dt }); |
| 252 | for (const event of result?.events ?? []) |
| 253 | { |
| 254 | if (event.type === "remote-melee-resolve") |
| 255 | { |
| 256 | remoteMelee.push(event); |
| 257 | continue; |
| 258 | } |
| 259 | if (event.type === "remote-ranged-resolve") |
| 260 | { |
| 261 | remoteRanged.push(event); |
| 262 | continue; |
| 263 | } |
| 264 | if (event.type === "summon-entity") |
| 265 | { |
| 266 | events.push(...this.#applySummonEntity(event)); |
| 267 | continue; |
| 268 | } |
| 269 | if (event.type === "jewelry-teleport-finish") |
| 270 | { |
| 271 | events.push(...this.#applyJewelryTeleport(event)); |
| 272 | continue; |
| 273 | } |
| 274 | if (event.type === "entity-move") |
| 275 | { this.#applyMoveToDirectory(event); } |
| 276 | if (event.type === "entity-despawn") |
| 277 | { this.#forget(event.entityId); } |
| 278 | if (event.type === "skills-updated") |
| 279 | { |
| 280 | this.#applySkillsUpdated(event); |
| 281 | events.push(...this.#skillLevelUpEvents(event)); |
| 282 | continue; |
| 283 | } |
| 284 | if (event.type === "spells-updated") |
| 285 | { |
| 286 | this.#applySpellsUpdated(event); |
| 287 | continue; |
| 288 | } |
| 289 | if (event.type === "inventory" && event.characterId) |
| 290 | { |
| 291 | this.#saveBagFromView(event.characterId, { |
| 292 | inventory: event.inventory, |
| 293 | equipment: event.equipment, |
| 294 | vault: event.vault, |
| 295 | vaultReserved: event.vaultReserved |
| 296 | }); |
| 297 | } |
| 298 | if (event.type === "player-died") |
| 299 | { |
| 300 | events.push(...this.#applyPlayerDeath(event)); |
| 301 | continue; |
| 302 | } |
| 303 | if ( |
| 304 | event.type === "combat-hit" |
| 305 | || event.type === "combat-miss" |
| 306 | || event.type === "combat-block" |
| 307 | || event.type === "combat-swing" |
| 308 | ) |
| 309 | { this.#noteCombatEvent(event); } |
| 310 | if (event.type === "mob-killed") |
| 311 | { |
| 312 | events.push(...this.#applyMobKilled(event)); |
| 313 | continue; |
| 314 | } |
| 315 | if (event.type === "dialogue-walk-away") |
| 316 | { |
| 317 | const closed = this.quests?.closeDialogue(event.characterId, "walk-away"); |
| 318 | events.push(...this.#mapQuestPrivateEvents( |
| 319 | closed?.events ?? [], |
| 320 | event.sessionId, |
| 321 | event.characterId |
| 322 | )); |
| 323 | continue; |
| 324 | } |
| 325 | this.#persistGroundEvent(event); |
| 326 | if (event.type !== "skills-updated") |
| 327 | { events.push(event); } |
| 328 | } |
| 329 | for (const request of result?.transferRequests ?? []) |
| 330 | { transfers.push({ ...request, fromWorkerId: worker.workerId }); } |
| 331 | } |
| 332 | for (const payload of remoteMelee) |
| 333 | { events.push(...this.#applyRemoteMelee(payload)); } |
| 334 | for (const payload of remoteRanged) |
| 335 | { events.push(...this.#applyRemoteRanged(payload)); } |
| 336 | if (transfers.length) |
| 337 | { |
| 338 | events.push(...this.#applyTransfers(transfers)); |
| 339 | this.#recalculateActivation(now); |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2); |
| 344 | this.movementAccumulator += dt * movementHz; |
| 345 | while (this.movementAccumulator >= 1) |
| 346 | { |
| 347 | this.movementAccumulator -= 1; |
| 348 | this.movementTickCounter += 1; |
| 349 | const transfers = []; |
| 350 | for (const worker of this.workers) |
| 351 | { |
| 352 | const result = worker.call({ type: WorkerMessage.stepMovement, now }); |
| 353 | for (const event of result?.events ?? []) |
| 354 | { |
| 355 | if (event.type === "entity-move") |
| 356 | { this.#applyMoveToDirectory(event); } |
| 357 | if (event.type === "skills-updated") |
| 358 | { |
| 359 | this.#applySkillsUpdated(event); |
| 360 | events.push(...this.#skillLevelUpEvents(event)); |
| 361 | continue; |
| 362 | } |
| 363 | if (event.type === "spells-updated") |
| 364 | { |
| 365 | this.#applySpellsUpdated(event); |
| 366 | continue; |
| 367 | } |
| 368 | this.#persistGroundEvent(event); |
| 369 | if (event.type !== "skills-updated") |
| 370 | { events.push(event); } |
| 371 | } |
| 372 | for (const request of result?.transferRequests ?? []) |
| 373 | { transfers.push({ ...request, fromWorkerId: worker.workerId }); } |
| 374 | } |
| 375 | events.push(...this.#applyTransfers(transfers)); |
| 376 | this.#recalculateActivation(now); |
| 377 | } |
| 378 | |
| 379 | if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0) |
| 380 | { events.push(...this.#stepSpawners()); } |
| 381 | |
| 382 | if (this.tickIndex % Math.max(1, Math.round(simHz)) === 0) |
| 383 | { |
| 384 | this.#stepSkullDecay(); |
| 385 | events.push(...this.#stepCombatLogout()); |
| 386 | } |
| 387 | |
| 388 | if (this.courier) |
| 389 | { events.push(...this.courier.step(now, dt)); } |
| 390 | if (this.market) |
| 391 | { events.push(...this.market.step(now)); } |
| 392 | if (this.trade) |
| 393 | { events.push(...this.trade.step(now)); } |
| 394 | |
| 395 | this.#syncGhosts(); |
| 396 | events.push(...this.pendingPrivate.splice(0)); |
| 397 | return { now, events, replication: this.drainReplication() }; |
| 398 | } |
| 399 | |
| 400 | drainReplication () |
| 401 | { |
| 402 | return this.replication.splice(0); |
| 403 | } |
| 404 | |
| 405 | worldTime (now = this.now) |
| 406 | { |
| 407 | const date = new Date(now); |
| 408 | date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET); |
| 409 | return { |
| 410 | unixMs: now, |
| 411 | worldUnixMs: date.getTime(), |
| 412 | iso: date.toISOString(), |
| 413 | hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600, |
| 414 | season: seasonIdAt(now) |
| 415 | }; |
| 416 | } |
| 417 | |
| 418 | spawnCharacter (sessionId, character) |
| 419 | { |
| 420 | this.despawnCharacter(character.character_id); |
| 421 | // Despawn may have just written the live tile; never trust a stale row snapshot. |
| 422 | const row = this.stateDb.getCharacter(character.character_id) ?? character; |
| 423 | let tileX = row.tile_x; |
| 424 | let tileY = row.tile_y; |
| 425 | let dimensionId = normalizeDimensionId(row.dimension_id ?? OVERWORLD_ID); |
| 426 | const gait = row.gait || character.gait || GAIT.walk; |
| 427 | |
| 428 | // Soft-deleted / purged interiors eject to overworld spawn. |
| 429 | if (!this.#isDimensionUsable(dimensionId)) |
| 430 | { |
| 431 | dimensionId = OVERWORLD_ID; |
| 432 | const spawn = this.findOpenSpawn(); |
| 433 | if (!spawn) |
| 434 | { |
| 435 | const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first."); |
| 436 | error.userFacing = true; |
| 437 | throw error; |
| 438 | } |
| 439 | tileX = spawn.tileX; |
| 440 | tileY = spawn.tileY; |
| 441 | this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId); |
| 442 | } |
| 443 | |
| 444 | const preferred = this.#findResumeTile(tileX, tileY, 24, dimensionId); |
| 445 | if (!preferred) |
| 446 | { |
| 447 | const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first."); |
| 448 | error.userFacing = true; |
| 449 | throw error; |
| 450 | } |
| 451 | if ( |
| 452 | preferred.tileX !== tileX |
| 453 | || preferred.tileY !== tileY |
| 454 | || normalizeDimensionId(preferred.dimensionId ?? dimensionId) !== dimensionId |
| 455 | ) |
| 456 | { |
| 457 | tileX = preferred.tileX; |
| 458 | tileY = preferred.tileY; |
| 459 | dimensionId = normalizeDimensionId(preferred.dimensionId ?? dimensionId); |
| 460 | this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId); |
| 461 | } |
| 462 | |
| 463 | const bag = this.stateDb.getBag(character.character_id) ?? { |
| 464 | inventory: emptySlots(), |
| 465 | equipment: emptyEquipment(), |
| 466 | vault: [], |
| 467 | vaultReserved: [] |
| 468 | }; |
| 469 | const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills(); |
| 470 | const spells = this.stateDb.getSpells(character.character_id) ?? defaultPlayerSpells(); |
| 471 | // Login floor: Health ≥ 5, every other skill ≥ 1 (persist if raised). |
| 472 | if (enforceMinimumSkillLevels(skills)) |
| 473 | { this.stateDb.saveSkills(character.character_id, skills); } |
| 474 | const maxHealth = playerMaxHealth(skills); |
| 475 | const maxStamina = playerMaxStamina(skills); |
| 476 | const isDead = !!row.is_dead; |
| 477 | const savedHealth = row.health_current; |
| 478 | const currentHealth = isDead |
| 479 | ? 0 |
| 480 | : savedHealth != null |
| 481 | ? Math.max(0, Math.min(maxHealth, savedHealth | 0)) |
| 482 | : maxHealth; |
| 483 | const entityId = this.nextEntityId++; |
| 484 | const components = { |
| 485 | position: { tileX, tileY, dimensionId }, |
| 486 | movement: { gait, walkCarry: 0 }, |
| 487 | path: { tiles: [] }, |
| 488 | appearance: { |
| 489 | sex: character.sex ?? row.sex, |
| 490 | firstName: character.first_name ?? row.first_name, |
| 491 | lastName: character.last_name ?? row.last_name, |
| 492 | ...appearanceHairFields(hairFromCharacterRow(row) ?? hairFromCharacterRow(character)) |
| 493 | }, |
| 494 | character: { |
| 495 | characterId: character.character_id ?? row.character_id, |
| 496 | accountId: character.account_id ?? row.account_id, |
| 497 | skullValue: this.characterSkullValue(character.character_id ?? row.character_id) |
| 498 | }, |
| 499 | networkIdentity: { sessionId }, |
| 500 | chunkLoader: { ...DEFAULT_CHUNK_LOADER }, |
| 501 | inventory: { slots: bag.inventory ?? emptySlots() }, |
| 502 | equipment: bag.equipment ?? emptyEquipment(), |
| 503 | vault: { |
| 504 | slots: bag.vault ?? [], |
| 505 | reserved: bag.vaultReserved ?? [] |
| 506 | }, |
| 507 | health: { current: currentHealth, max: maxHealth }, |
| 508 | stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 }, |
| 509 | combat: { targetEntityId: null, nextSwingAt: 0 }, |
| 510 | skills, |
| 511 | spells, |
| 512 | spellcasting: { |
| 513 | armedSpellId: null, |
| 514 | repeatSpellId: null, |
| 515 | repeatTargetEntityId: null, |
| 516 | repeatTileX: null, |
| 517 | repeatTileY: null, |
| 518 | nextCastAt: 0, |
| 519 | pendingCast: null |
| 520 | }, |
| 521 | chunkPresence: { |
| 522 | chunkX: tileToChunk(tileX), |
| 523 | chunkY: tileToChunk(tileY), |
| 524 | dimensionId, |
| 525 | sinceMs: this.now |
| 526 | }, |
| 527 | }; |
| 528 | if (isDead) |
| 529 | { components.dead = {}; } |
| 530 | this.#ensureCoverage(tileX, tileY, components.chunkLoader, dimensionId); |
| 531 | const workerId = this.#ownerOfTile(tileX, tileY, dimensionId); |
| 532 | const view = this.workers[workerId].call({ |
| 533 | type: WorkerMessage.spawn, |
| 534 | entityId, |
| 535 | components |
| 536 | }); |
| 537 | this.#remember(view, workerId); |
| 538 | this.#attachSkullToRecord(view.entityId, character.character_id ?? row.character_id); |
| 539 | this.stateDb.markDimensionVisited(character.character_id, dimensionId); |
| 540 | this.#queueReplication(replicationSpawn(this.directory.get(view.entityId) ?? view)); |
| 541 | this.#recalculateActivation(this.now); |
| 542 | this.#syncGhosts(); |
| 543 | this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY); |
| 544 | this.quests?.ensureInitialQuests?.(character.character_id ?? row.character_id); |
| 545 | return entityId; |
| 546 | } |
| 547 | |
| 548 | characterSkullValue (characterId, now = this.now) |
| 549 | { |
| 550 | const bounty = this.stateDb.getCharacterBounty(characterId, now); |
| 551 | const killCounter = this.stateDb.peekKillCounter(characterId, now); |
| 552 | return skullValue(bounty, killCounter); |
| 553 | } |
| 554 | |
| 555 | refreshCharacterSkull (characterId, { force = false } = {}) |
| 556 | { |
| 557 | const id = characterId | 0; |
| 558 | if (!id) |
| 559 | { return null; } |
| 560 | const state = this.stateDb.getKillCounterState(id); |
| 561 | const elapsed = Math.max(0, this.now - (state.updatedAt | 0)); |
| 562 | const decayed = decayKillCounter(state.killCounter, elapsed); |
| 563 | if (decayed.killCounter !== state.killCounter) |
| 564 | { this.stateDb.setKillCounter(id, decayed.killCounter, this.now); } |
| 565 | const value = this.characterSkullValue(id); |
| 566 | const entityId = this.characterEntities.get(id); |
| 567 | const record = entityId ? this.directory.get(entityId) : null; |
| 568 | if (!record) |
| 569 | { return null; } |
| 570 | if (!force && (record.skullValue | 0) === value) |
| 571 | { return null; } |
| 572 | record.skullValue = value; |
| 573 | this.workers[record.workerId]?.call({ |
| 574 | type: WorkerMessage.applySkullValue, |
| 575 | entityId, |
| 576 | skullValue: value |
| 577 | }); |
| 578 | const event = { |
| 579 | type: "entity-skull", |
| 580 | entityId, |
| 581 | skullValue: value, |
| 582 | tileX: record.tileX, |
| 583 | tileY: record.tileY, |
| 584 | dimensionId: record.dimensionId ?? OVERWORLD_ID |
| 585 | }; |
| 586 | this.#queueReplication(event); |
| 587 | return event; |
| 588 | } |
| 589 | |
| 590 | #attachSkullToRecord (entityId, characterId) |
| 591 | { |
| 592 | const record = this.directory.get(entityId); |
| 593 | if (!record) |
| 594 | { return; } |
| 595 | const value = this.characterSkullValue(characterId); |
| 596 | record.skullValue = value; |
| 597 | this.workers[record.workerId]?.call({ |
| 598 | type: WorkerMessage.applySkullValue, |
| 599 | entityId, |
| 600 | skullValue: value |
| 601 | }); |
| 602 | } |
| 603 | |
| 604 | #stepSkullDecay () |
| 605 | { |
| 606 | for (const characterId of this.characterEntities.keys()) |
| 607 | { |
| 608 | const state = this.stateDb.getKillCounterState(characterId); |
| 609 | if (!(state.killCounter > 0)) |
| 610 | { continue; } |
| 611 | this.refreshCharacterSkull(characterId); |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | isCharacterOnline (characterId) |
| 616 | { |
| 617 | const id = characterId | 0; |
| 618 | return this.characterEntities.has(id) && !this.combatLogouts.has(id); |
| 619 | } |
| 620 | |
| 621 | /** True while the entity exists, including combat-logout ghosts without a session. */ |
| 622 | isCharacterInWorld (characterId) |
| 623 | { |
| 624 | return this.characterEntities.has(characterId | 0); |
| 625 | } |
| 626 | |
| 627 | isCombatLogout (characterId) |
| 628 | { |
| 629 | return this.combatLogouts.has(characterId | 0); |
| 630 | } |
| 631 | |
| 632 | /** Apply a worker `player-died` event (also used by combat-logout tests). */ |
| 633 | applyPlayerDiedEvent (event) |
| 634 | { |
| 635 | return this.#applyPlayerDeath(event); |
| 636 | } |
| 637 | |
| 638 | /** |
| 639 | * Keep the character fighting after the controlling session leaves. |
| 640 | * @returns {boolean} true when the character stayed in the world |
| 641 | */ |
| 642 | beginCombatLogout (characterId) |
| 643 | { |
| 644 | const id = characterId | 0; |
| 645 | if (!this.characterEntities.has(id)) |
| 646 | { return false; } |
| 647 | if (this.combatLogouts.has(id)) |
| 648 | { return true; } |
| 649 | const row = this.stateDb.getCharacter(id); |
| 650 | if (row?.is_dead) |
| 651 | { return false; } |
| 652 | if (!this.#shouldStayOnLeave(id)) |
| 653 | { return false; } |
| 654 | this.market?.leaveExchangeStations?.(id); |
| 655 | const track = this.#ensureCombatTrack(id); |
| 656 | const spells = this.#setCharacterAutoCast(id, true); |
| 657 | this.combatLogouts.set(id, { |
| 658 | savedAutoCast: spells?.previousAutoCast ?? false, |
| 659 | pendingCowardice: !!track.pvpInvolved, |
| 660 | startedAt: this.now |
| 661 | }); |
| 662 | return true; |
| 663 | } |
| 664 | |
| 665 | /** |
| 666 | * Player reclaimed the character. Restore prefs and apply pending PvP cowardice. |
| 667 | */ |
| 668 | endCombatLogout (characterId, { applyCowardice = true } = {}) |
| 669 | { |
| 670 | const id = characterId | 0; |
| 671 | const logout = this.combatLogouts.get(id); |
| 672 | if (!logout) |
| 673 | { return { ended: false }; } |
| 674 | let cowardice = null; |
| 675 | // Apply while still marked combat-logout so system letters stay held offline. |
| 676 | if (applyCowardice && logout.pendingCowardice) |
| 677 | { cowardice = applyCombatLogoutCowardice(this, id, { now: this.now }); } |
| 678 | this.#restoreCombatLogoutAutoCast(id, logout); |
| 679 | this.combatLogouts.delete(id); |
| 680 | return { ended: true, cowardice }; |
| 681 | } |
| 682 | |
| 683 | reattachCharacterSession (characterId, sessionId) |
| 684 | { |
| 685 | const entityId = this.characterEntities.get(characterId | 0); |
| 686 | if (!entityId) |
| 687 | { return null; } |
| 688 | const record = this.directory.get(entityId); |
| 689 | if (!record) |
| 690 | { return null; } |
| 691 | const result = this.workers[record.workerId].call({ |
| 692 | type: WorkerMessage.reattachSession, |
| 693 | characterId, |
| 694 | sessionId |
| 695 | }); |
| 696 | if (!result?.ok) |
| 697 | { return null; } |
| 698 | this.market?.reattachSession?.(characterId, sessionId); |
| 699 | if (this.combatLogouts.has(characterId | 0)) |
| 700 | { this.endCombatLogout(characterId, { applyCowardice: true }); } |
| 701 | return entityId; |
| 702 | } |
| 703 | |
| 704 | #ensureCombatTrack (characterId) |
| 705 | { |
| 706 | const id = characterId | 0; |
| 707 | let track = this.combatTracking.get(id); |
| 708 | if (!track) |
| 709 | { |
| 710 | track = { |
| 711 | lastCombatEndedAt: null, |
| 712 | lastOutboundAttackAt: null, |
| 713 | lastCombatActivityAt: null, |
| 714 | pvpInvolved: false, |
| 715 | wasInCombat: false |
| 716 | }; |
| 717 | this.combatTracking.set(id, track); |
| 718 | } |
| 719 | return track; |
| 720 | } |
| 721 | |
| 722 | #notePlayerAttack (characterId, targetEntityId) |
| 723 | { |
| 724 | const id = characterId | 0; |
| 725 | if (!id) |
| 726 | { return; } |
| 727 | const track = this.#ensureCombatTrack(id); |
| 728 | const now = this.now; |
| 729 | track.lastOutboundAttackAt = now; |
| 730 | track.lastCombatActivityAt = now; |
| 731 | track.wasInCombat = true; |
| 732 | const targetRecord = this.directory.get(targetEntityId); |
| 733 | if (targetRecord?.characterId) |
| 734 | { |
| 735 | track.pvpInvolved = true; |
| 736 | const logout = this.combatLogouts.get(id); |
| 737 | if (logout) |
| 738 | { logout.pendingCowardice = true; } |
| 739 | const other = this.#ensureCombatTrack(targetRecord.characterId); |
| 740 | other.pvpInvolved = true; |
| 741 | other.lastCombatActivityAt = now; |
| 742 | other.wasInCombat = true; |
| 743 | const otherLogout = this.combatLogouts.get(targetRecord.characterId | 0); |
| 744 | if (otherLogout) |
| 745 | { otherLogout.pendingCowardice = true; } |
| 746 | } |
| 747 | } |
| 748 | |
| 749 | #noteCombatEvent (event) |
| 750 | { |
| 751 | const attackerId = event.attackerId; |
| 752 | const targetId = event.targetId; |
| 753 | const attackerRecord = attackerId != null ? this.directory.get(attackerId) : null; |
| 754 | const targetRecord = targetId != null ? this.directory.get(targetId) : null; |
| 755 | const pvp = !!(attackerRecord?.characterId && targetRecord?.characterId); |
| 756 | const now = this.now; |
| 757 | if (attackerRecord?.characterId) |
| 758 | { |
| 759 | const track = this.#ensureCombatTrack(attackerRecord.characterId); |
| 760 | track.lastOutboundAttackAt = now; |
| 761 | track.lastCombatActivityAt = now; |
| 762 | track.wasInCombat = true; |
| 763 | if (pvp) |
| 764 | { |
| 765 | track.pvpInvolved = true; |
| 766 | const logout = this.combatLogouts.get(attackerRecord.characterId | 0); |
| 767 | if (logout) |
| 768 | { logout.pendingCowardice = true; } |
| 769 | } |
| 770 | } |
| 771 | if (targetRecord?.characterId && event.type !== "combat-swing") |
| 772 | { |
| 773 | const track = this.#ensureCombatTrack(targetRecord.characterId); |
| 774 | track.lastCombatActivityAt = now; |
| 775 | track.wasInCombat = true; |
| 776 | if (pvp) |
| 777 | { |
| 778 | track.pvpInvolved = true; |
| 779 | const logout = this.combatLogouts.get(targetRecord.characterId | 0); |
| 780 | if (logout) |
| 781 | { logout.pendingCowardice = true; } |
| 782 | } |
| 783 | } |
| 784 | } |
| 785 | |
| 786 | #characterInCombat (entityId) |
| 787 | { |
| 788 | const record = this.directory.get(entityId); |
| 789 | if (!record) |
| 790 | { return false; } |
| 791 | const state = this.workers[record.workerId].call({ |
| 792 | type: WorkerMessage.inspectCombatState, |
| 793 | entityId |
| 794 | }); |
| 795 | return !!state?.inCombat; |
| 796 | } |
| 797 | |
| 798 | #shouldStayOnLeave (characterId) |
| 799 | { |
| 800 | const id = characterId | 0; |
| 801 | const entityId = this.characterEntities.get(id); |
| 802 | if (!entityId) |
| 803 | { return false; } |
| 804 | const inCombat = this.#characterInCombat(entityId); |
| 805 | if (inCombat) |
| 806 | { return true; } |
| 807 | const track = this.combatTracking.get(id); |
| 808 | if (!track) |
| 809 | { return false; } |
| 810 | const now = this.now; |
| 811 | const endedRecently = track.lastCombatEndedAt != null |
| 812 | && (now - track.lastCombatEndedAt) <= COMBAT_LOGOUT_MS; |
| 813 | const attackedRecently = track.lastOutboundAttackAt != null |
| 814 | && (now - track.lastOutboundAttackAt) <= COMBAT_LOGOUT_MS; |
| 815 | return endedRecently && attackedRecently; |
| 816 | } |
| 817 | |
| 818 | #setCharacterAutoCast (characterId, autoCast) |
| 819 | { |
| 820 | const entityId = this.characterEntities.get(characterId | 0); |
| 821 | const record = entityId ? this.directory.get(entityId) : null; |
| 822 | if (!record) |
| 823 | { return null; } |
| 824 | return this.workers[record.workerId].call({ |
| 825 | type: WorkerMessage.setSpellAutoCast, |
| 826 | entityId, |
| 827 | autoCast: !!autoCast |
| 828 | }); |
| 829 | } |
| 830 | |
| 831 | #restoreCombatLogoutAutoCast (characterId, logout) |
| 832 | { |
| 833 | if (!logout) |
| 834 | { return; } |
| 835 | this.#setCharacterAutoCast(characterId, !!logout.savedAutoCast); |
| 836 | const stored = this.stateDb.getSpells(characterId); |
| 837 | if (stored) |
| 838 | { |
| 839 | this.stateDb.saveSpells(characterId, { |
| 840 | ...stored, |
| 841 | autoCast: !!logout.savedAutoCast |
| 842 | }); |
| 843 | } |
| 844 | } |
| 845 | |
| 846 | #stepCombatLogout () |
| 847 | { |
| 848 | const events = []; |
| 849 | const now = this.now; |
| 850 | for (const [characterId, entityId] of this.characterEntities) |
| 851 | { |
| 852 | const inCombat = this.#characterInCombat(entityId); |
| 853 | const track = this.#ensureCombatTrack(characterId); |
| 854 | if (track.wasInCombat && !inCombat) |
| 855 | { track.lastCombatEndedAt = now; } |
| 856 | track.wasInCombat = inCombat; |
| 857 | } |
| 858 | for (const [characterId, logout] of [...this.combatLogouts.entries()]) |
| 859 | { |
| 860 | const track = this.combatTracking.get(characterId); |
| 861 | const lastActivity = track?.lastCombatActivityAt ?? logout.startedAt; |
| 862 | if ((now - lastActivity) < COMBAT_LOGOUT_MS) |
| 863 | { continue; } |
| 864 | if (logout.pendingCowardice) |
| 865 | { applyCombatLogoutCowardice(this, characterId, { now }); } |
| 866 | this.#restoreCombatLogoutAutoCast(characterId, logout); |
| 867 | this.combatLogouts.delete(characterId); |
| 868 | this.despawnCharacter(characterId); |
| 869 | } |
| 870 | return events; |
| 871 | } |
| 872 | |
| 873 | despawnCharacter (characterId) |
| 874 | { |
| 875 | this.market?.leaveExchangeStations?.(characterId); |
| 876 | const tradeEvents = this.trade?.onCharacterGone?.(characterId) ?? []; |
| 877 | if (tradeEvents.length) |
| 878 | { this.pendingPrivate.push(...tradeEvents); } |
| 879 | const entityId = this.characterEntities.get(characterId); |
| 880 | if (!entityId) |
| 881 | { |
| 882 | this.combatLogouts.delete(characterId | 0); |
| 883 | return; |
| 884 | } |
| 885 | const record = this.directory.get(entityId); |
| 886 | if (!record) |
| 887 | { |
| 888 | this.characterEntities.delete(characterId); |
| 889 | this.combatLogouts.delete(characterId | 0); |
| 890 | return; |
| 891 | } |
| 892 | this.#saveBag(entityId, record.workerId); |
| 893 | const dropped = this.workers[record.workerId].call({ |
| 894 | type: WorkerMessage.despawnCharacter, |
| 895 | characterId |
| 896 | }); |
| 897 | if (dropped) |
| 898 | { |
| 899 | this.stateDb.saveCharacterPosition( |
| 900 | characterId, |
| 901 | dropped.tileX, |
| 902 | dropped.tileY, |
| 903 | dropped.gait ?? GAIT.walk, |
| 904 | dropped.dimensionId ?? OVERWORLD_ID |
| 905 | ); |
| 906 | if (dropped.health != null) |
| 907 | { this.stateDb.saveCharacterHealth(characterId, dropped.health); } |
| 908 | this.#queueReplication(replicationDespawn(dropped)); |
| 909 | } |
| 910 | this.#forget(entityId); |
| 911 | this.combatLogouts.delete(characterId | 0); |
| 912 | this.#recalculateActivation(this.now); |
| 913 | this.#syncGhosts(); |
| 914 | } |
| 915 | |
| 916 | spawnEntity (components, options = {}) |
| 917 | { |
| 918 | const entityId = options.entityId ?? this.nextEntityId++; |
| 919 | this.nextEntityId = Math.max(this.nextEntityId, entityId + 1); |
| 920 | const position = components.position; |
| 921 | if (!position) |
| 922 | { throw new Error("spawnEntity requires position."); } |
| 923 | const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); |
| 924 | position.dimensionId = dimensionId; |
| 925 | if (options.requireResident) |
| 926 | { |
| 927 | const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId); |
| 928 | if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY, dimensionId)) |
| 929 | { return null; } |
| 930 | const view = this.workers[workerId].call({ |
| 931 | type: WorkerMessage.spawn, |
| 932 | entityId, |
| 933 | components |
| 934 | }); |
| 935 | this.#remember(view, workerId); |
| 936 | if (components.appearance) |
| 937 | { this.#queueReplication(replicationSpawn(view)); } |
| 938 | this.#syncGhosts(); |
| 939 | return entityId; |
| 940 | } |
| 941 | if (components.chunkLoader) |
| 942 | { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader, dimensionId); } |
| 943 | else |
| 944 | { |
| 945 | this.#ensureRegion( |
| 946 | tileToRegion(position.tileX), |
| 947 | tileToRegion(position.tileY), |
| 948 | null, |
| 949 | dimensionId |
| 950 | ); |
| 951 | } |
| 952 | const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId); |
| 953 | const view = this.workers[workerId].call({ |
| 954 | type: WorkerMessage.spawn, |
| 955 | entityId, |
| 956 | components |
| 957 | }); |
| 958 | this.#remember(view, workerId); |
| 959 | if (components.appearance) |
| 960 | { this.#queueReplication(replicationSpawn(view)); } |
| 961 | this.#recalculateActivation(this.now); |
| 962 | this.#syncGhosts(); |
| 963 | return entityId; |
| 964 | } |
| 965 | |
| 966 | despawnEntity (entityId) |
| 967 | { |
| 968 | const record = this.directory.get(entityId); |
| 969 | if (!record) |
| 970 | { return; } |
| 971 | const dropped = this.workers[record.workerId].call({ |
| 972 | type: WorkerMessage.despawn, |
| 973 | entityId |
| 974 | }); |
| 975 | if (dropped) |
| 976 | { this.#queueReplication(replicationDespawn(dropped)); } |
| 977 | this.#forget(entityId); |
| 978 | } |
| 979 | |
| 980 | chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 981 | { |
| 982 | const loaders = this.#allLoaders(); |
| 983 | const { chunkSim } = accumulateLoaderRefs(loaders); |
| 984 | return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId)) ?? 0) > 0; |
| 985 | } |
| 986 | |
| 987 | updateCourierFlight (entityId, flightPatch, now = this.now) |
| 988 | { |
| 989 | const record = this.directory.get(entityId); |
| 990 | if (!record) |
| 991 | { return { despawned: true, entityId }; } |
| 992 | const tileX = Math.floor(flightPatch.x); |
| 993 | const tileY = Math.floor(flightPatch.y); |
| 994 | const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); |
| 995 | const owner = this.#ownerOfTile(tileX, tileY, dimensionId); |
| 996 | if (owner == null || owner !== record.workerId) |
| 997 | { |
| 998 | this.despawnEntity(entityId); |
| 999 | return { despawned: true, entityId }; |
| 1000 | } |
| 1001 | const result = this.workers[owner].call({ |
| 1002 | type: WorkerMessage.updateFlight, |
| 1003 | entityId, |
| 1004 | flight: flightPatch, |
| 1005 | now |
| 1006 | }); |
| 1007 | if (result?.transferRequest) |
| 1008 | { |
| 1009 | const events = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: owner }]); |
| 1010 | this.#recalculateActivation(now); |
| 1011 | const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId); |
| 1012 | if (move) |
| 1013 | { |
| 1014 | this.#applyMoveToDirectory(move); |
| 1015 | return { event: { ...move, worldX: flightPatch.x, worldY: flightPatch.y, freeFlight: true } }; |
| 1016 | } |
| 1017 | this.despawnEntity(entityId); |
| 1018 | return { despawned: true, entityId }; |
| 1019 | } |
| 1020 | if (result?.event) |
| 1021 | { |
| 1022 | this.#applyMoveToDirectory(result.event); |
| 1023 | return { event: result.event }; |
| 1024 | } |
| 1025 | return null; |
| 1026 | } |
| 1027 | |
| 1028 | applyBag (entityId, bag) |
| 1029 | { |
| 1030 | const record = this.directory.get(entityId); |
| 1031 | if (!record) |
| 1032 | { return null; } |
| 1033 | return this.workers[record.workerId].call({ |
| 1034 | type: WorkerMessage.applyBag, |
| 1035 | entityId, |
| 1036 | bag |
| 1037 | }); |
| 1038 | } |
| 1039 | |
| 1040 | /** |
| 1041 | * Persist hair + patch live appearance; returns public view. |
| 1042 | */ |
| 1043 | setCharacterHair (characterId, hair) |
| 1044 | { |
| 1045 | const row = this.stateDb.updateCharacterHair(characterId, hair); |
| 1046 | const entityId = this.characterEntities.get(characterId); |
| 1047 | if (!entityId) |
| 1048 | { return { row, view: null }; } |
| 1049 | const fields = appearanceHairFields({ |
| 1050 | sex: row.sex, |
| 1051 | style: hair.style, |
| 1052 | hue: hair.hue, |
| 1053 | saturation: hair.saturation, |
| 1054 | darkness: hair.darkness |
| 1055 | }); |
| 1056 | const record = this.directory.get(entityId); |
| 1057 | if (!record) |
| 1058 | { return { row, view: null }; } |
| 1059 | const view = this.workers[record.workerId].call({ |
| 1060 | type: WorkerMessage.applyAppearance, |
| 1061 | entityId, |
| 1062 | appearance: fields |
| 1063 | }); |
| 1064 | if (view) |
| 1065 | { |
| 1066 | this.#remember(view, record.workerId); |
| 1067 | this.#queueReplication(replicationAppearance(view)); |
| 1068 | } |
| 1069 | return { row, view }; |
| 1070 | } |
| 1071 | |
| 1072 | pushSkills (characterId, skills, combatLevel) |
| 1073 | { |
| 1074 | this.pendingPrivate.push({ |
| 1075 | type: "skills", |
| 1076 | characterId, |
| 1077 | skills, |
| 1078 | combatLevel |
| 1079 | }); |
| 1080 | } |
| 1081 | |
| 1082 | pushSpells (characterId, payload) |
| 1083 | { |
| 1084 | this.pendingPrivate.push({ |
| 1085 | type: "spells", |
| 1086 | characterId, |
| 1087 | ...payload |
| 1088 | }); |
| 1089 | } |
| 1090 | |
| 1091 | skillsOf (entityId) |
| 1092 | { |
| 1093 | const record = this.directory.get(entityId); |
| 1094 | if (!record) |
| 1095 | { return null; } |
| 1096 | return this.workers[record.workerId].call({ |
| 1097 | type: WorkerMessage.inspectSkills, |
| 1098 | entityId |
| 1099 | }); |
| 1100 | } |
| 1101 | |
| 1102 | spellsOf (entityId) |
| 1103 | { |
| 1104 | const record = this.directory.get(entityId); |
| 1105 | if (!record) |
| 1106 | { return null; } |
| 1107 | return this.workers[record.workerId].call({ |
| 1108 | type: WorkerMessage.inspectSpells, |
| 1109 | entityId |
| 1110 | }); |
| 1111 | } |
| 1112 | |
| 1113 | staminaOf (entityId) |
| 1114 | { |
| 1115 | const record = this.directory.get(entityId); |
| 1116 | if (!record) |
| 1117 | { return null; } |
| 1118 | return this.workers[record.workerId].call({ |
| 1119 | type: WorkerMessage.inspectStamina, |
| 1120 | entityId |
| 1121 | }); |
| 1122 | } |
| 1123 | |
| 1124 | pushInventory (characterId, bag) |
| 1125 | { |
| 1126 | this.pendingPrivate.push({ |
| 1127 | type: "inventory", |
| 1128 | characterId, |
| 1129 | inventory: bag.inventory, |
| 1130 | equipment: bag.equipment, |
| 1131 | vault: bag.vault, |
| 1132 | vaultReserved: bag.vaultReserved |
| 1133 | }); |
| 1134 | } |
| 1135 | |
| 1136 | dispatchPigeon ({ characterId, destination, cargo }) |
| 1137 | { |
| 1138 | const entityId = this.characterEntities.get(characterId); |
| 1139 | const position = entityId ? this.positionOf(entityId) : null; |
| 1140 | if (!position) |
| 1141 | { |
| 1142 | const error = new Error("Enter the world before sending a pigeon."); |
| 1143 | error.userFacing = true; |
| 1144 | throw error; |
| 1145 | } |
| 1146 | return this.courier.dispatchFromPlayer({ |
| 1147 | characterId, |
| 1148 | originTileX: position.tileX, |
| 1149 | originTileY: position.tileY, |
| 1150 | destination, |
| 1151 | cargo |
| 1152 | }); |
| 1153 | } |
| 1154 | |
| 1155 | /** |
| 1156 | * Path an idle CE clerk to a staff-side station tile. |
| 1157 | */ |
| 1158 | stationExchangeClerk (stationTileX, stationTileY) |
| 1159 | { |
| 1160 | const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID); |
| 1161 | if (owner == null) |
| 1162 | { return { ok: false, reason: "unowned" }; } |
| 1163 | return this.workers[owner].call({ |
| 1164 | type: WorkerMessage.stationExchangeClerk, |
| 1165 | stationTileX, |
| 1166 | stationTileY |
| 1167 | }); |
| 1168 | } |
| 1169 | |
| 1170 | /** |
| 1171 | * When a player uses a marketplace counter, path idle CE clerks to the |
| 1172 | * opposite side of each adjacent counter (staff side). |
| 1173 | */ |
| 1174 | stationExchangeClerks (playerTileX, playerTileY) |
| 1175 | { |
| 1176 | const results = []; |
| 1177 | for (const tile of this.market?.marketTiles ?? []) |
| 1178 | { |
| 1179 | if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1) |
| 1180 | { continue; } |
| 1181 | if (tile.tileX === playerTileX && tile.tileY === playerTileY) |
| 1182 | { continue; } |
| 1183 | const stationTileX = tile.tileX + (tile.tileX - playerTileX); |
| 1184 | const stationTileY = tile.tileY + (tile.tileY - playerTileY); |
| 1185 | if (stationTileX === playerTileX && stationTileY === playerTileY) |
| 1186 | { continue; } |
| 1187 | results.push(this.stationExchangeClerk(stationTileX, stationTileY)); |
| 1188 | } |
| 1189 | return results; |
| 1190 | } |
| 1191 | |
| 1192 | /** Release a CE clerk stationed at the given staff-side tile. */ |
| 1193 | releaseExchangeClerk (stationTileX, stationTileY) |
| 1194 | { |
| 1195 | const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID); |
| 1196 | if (owner == null) |
| 1197 | { return { ok: false, reason: "unowned" }; } |
| 1198 | return this.workers[owner].call({ |
| 1199 | type: WorkerMessage.releaseExchangeClerk, |
| 1200 | stationTileX, |
| 1201 | stationTileY |
| 1202 | }); |
| 1203 | } |
| 1204 | |
| 1205 | entityForCharacter (characterId) |
| 1206 | { |
| 1207 | return this.characterEntities.get(characterId) ?? null; |
| 1208 | } |
| 1209 | |
| 1210 | entityRecord (entityId) |
| 1211 | { |
| 1212 | const record = this.directory.get(entityId); |
| 1213 | return record ? { ...record } : null; |
| 1214 | } |
| 1215 | |
| 1216 | positionOf (entityId) |
| 1217 | { |
| 1218 | const record = this.directory.get(entityId); |
| 1219 | return record |
| 1220 | ? { |
| 1221 | tileX: record.tileX, |
| 1222 | tileY: record.tileY, |
| 1223 | dimensionId: normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID) |
| 1224 | } |
| 1225 | : null; |
| 1226 | } |
| 1227 | |
| 1228 | bagOf (entityId) |
| 1229 | { |
| 1230 | const record = this.directory.get(entityId); |
| 1231 | if (!record) |
| 1232 | { return null; } |
| 1233 | return this.workers[record.workerId].call({ |
| 1234 | type: WorkerMessage.inspectBag, |
| 1235 | entityId |
| 1236 | }); |
| 1237 | } |
| 1238 | |
| 1239 | snapshotFor (entityId) |
| 1240 | { |
| 1241 | const record = this.directory.get(entityId); |
| 1242 | if (!record) |
| 1243 | { return []; } |
| 1244 | const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); |
| 1245 | const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS); |
| 1246 | return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false, dimensionId)); |
| 1247 | } |
| 1248 | |
| 1249 | /** Client view: map ring uses `staticRadius` (default STATIC_CHUNK_RADIUS); entities stay at VISIBLE_CHUNK_RADIUS. */ |
| 1250 | snapshotsForView (entityId, staticRadius = STATIC_CHUNK_RADIUS) |
| 1251 | { |
| 1252 | const record = this.directory.get(entityId); |
| 1253 | if (!record) |
| 1254 | { return []; } |
| 1255 | const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); |
| 1256 | const centerChunkX = tileToChunk(record.tileX); |
| 1257 | const centerChunkY = tileToChunk(record.tileY); |
| 1258 | const mapRadius = Math.max(VISIBLE_CHUNK_RADIUS, staticRadius | 0); |
| 1259 | const entityKeys = new Set( |
| 1260 | visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS) |
| 1261 | .map((coord) => chunkKey(coord.chunkX, coord.chunkY, dimensionId)) |
| 1262 | ); |
| 1263 | return visibleChunkCoords(centerChunkX, centerChunkY, mapRadius) |
| 1264 | .map((coord) => |
| 1265 | { |
| 1266 | const key = chunkKey(coord.chunkX, coord.chunkY, dimensionId); |
| 1267 | const staticOnly = !entityKeys.has(key); |
| 1268 | const snapshot = this.snapshotChunk(coord.chunkX, coord.chunkY, staticOnly, dimensionId); |
| 1269 | const entities = (snapshot.entities ?? []).map((entity) => |
| 1270 | { |
| 1271 | const known = this.directory.get(entity.entityId); |
| 1272 | if (!known || entity.characterId == null) |
| 1273 | { return entity; } |
| 1274 | return { ...entity, skullValue: known.skullValue | 0 }; |
| 1275 | }); |
| 1276 | return { ...snapshot, entities, staticOnly }; |
| 1277 | }); |
| 1278 | } |
| 1279 | |
| 1280 | snapshotChunk (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID) |
| 1281 | { |
| 1282 | const dim = normalizeDimensionId(dimensionId); |
| 1283 | const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dim)); |
| 1284 | if (owner == null) |
| 1285 | { return this.#syntheticSnapshot(chunkX, chunkY, dim); } |
| 1286 | return this.workers[owner].call({ |
| 1287 | type: WorkerMessage.snapshotChunk, |
| 1288 | chunkX, |
| 1289 | chunkY, |
| 1290 | dimensionId: dim, |
| 1291 | staticOnly: !!staticOnly |
| 1292 | }); |
| 1293 | } |
| 1294 | |
| 1295 | findOpenSpawn () |
| 1296 | { |
| 1297 | const coords = this.worldDb.listChunkCoords(this.activeRevisionId, OVERWORLD_ID); |
| 1298 | for (const coord of coords) |
| 1299 | { |
| 1300 | const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, OVERWORLD_ID); |
| 1301 | if (!data.open) |
| 1302 | { continue; } |
| 1303 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 1304 | { |
| 1305 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 1306 | { |
| 1307 | const tileX = coord.chunk_x * CHUNK_SIZE + localX; |
| 1308 | const tileY = coord.chunk_y * CHUNK_SIZE + localY; |
| 1309 | if (this.isEnterable(tileX, tileY, OVERWORLD_ID) && !this.#occupiedTile(tileX, tileY, OVERWORLD_ID)) |
| 1310 | { return { tileX, tileY, dimensionId: OVERWORLD_ID }; } |
| 1311 | } |
| 1312 | } |
| 1313 | } |
| 1314 | return null; |
| 1315 | } |
| 1316 | |
| 1317 | /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */ |
| 1318 | #findResumeTile (tileX, tileY, radius = 24, dimensionId = OVERWORLD_ID) |
| 1319 | { |
| 1320 | const dim = normalizeDimensionId(dimensionId); |
| 1321 | return this.#findNearbyEnterable(tileX, tileY, radius, dim) |
| 1322 | ?? (dim === OVERWORLD_ID ? this.findOpenSpawn() : this.findOpenSpawn()); |
| 1323 | } |
| 1324 | |
| 1325 | #isDimensionUsable (dimensionId) |
| 1326 | { |
| 1327 | const dim = normalizeDimensionId(dimensionId); |
| 1328 | if (dim === OVERWORLD_ID) |
| 1329 | { return true; } |
| 1330 | const record = this.getDimensionRecord(dim); |
| 1331 | if (!record) |
| 1332 | { return false; } |
| 1333 | if (record.deletedAt != null) |
| 1334 | { return false; } |
| 1335 | if (record.purgeAfter != null && record.purgeAfter <= this.now) |
| 1336 | { return false; } |
| 1337 | return true; |
| 1338 | } |
| 1339 | |
| 1340 | #loadDimensionsCache () |
| 1341 | { |
| 1342 | const map = new Map(); |
| 1343 | for (const dim of this.worldDb.listDimensions(this.activeRevisionId)) |
| 1344 | { map.set(dim.dimensionId, dim); } |
| 1345 | if (!map.has(OVERWORLD_ID)) |
| 1346 | { |
| 1347 | map.set(OVERWORLD_ID, defaultDimensionRecord(OVERWORLD_ID, { |
| 1348 | defaultGroundTypeId: this.settings.defaultGroundTypeId |
| 1349 | })); |
| 1350 | } |
| 1351 | return map; |
| 1352 | } |
| 1353 | |
| 1354 | getDimensionRecord (dimensionId) |
| 1355 | { |
| 1356 | const dim = normalizeDimensionId(dimensionId); |
| 1357 | return this.dimensions?.get(dim) |
| 1358 | ?? this.worldDb.getDimensionAtOrBefore(this.activeRevisionId, dim) |
| 1359 | ?? (dim === OVERWORLD_ID |
| 1360 | ? defaultDimensionRecord(OVERWORLD_ID, { |
| 1361 | defaultGroundTypeId: this.settings.defaultGroundTypeId |
| 1362 | }) |
| 1363 | : null); |
| 1364 | } |
| 1365 | |
| 1366 | listDimensionRecords () |
| 1367 | { |
| 1368 | return [...(this.dimensions?.values?.() ?? this.worldDb.listDimensions(this.activeRevisionId))]; |
| 1369 | } |
| 1370 | |
| 1371 | #findNearbyEnterable (originX, originY, maxRadius, dimensionId = OVERWORLD_ID) |
| 1372 | { |
| 1373 | const dim = normalizeDimensionId(dimensionId); |
| 1374 | for (let radius = 0; radius <= maxRadius; radius++) |
| 1375 | { |
| 1376 | for (let dy = -radius; dy <= radius; dy++) |
| 1377 | { |
| 1378 | for (let dx = -radius; dx <= radius; dx++) |
| 1379 | { |
| 1380 | if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius) |
| 1381 | { continue; } |
| 1382 | const tileX = originX + dx; |
| 1383 | const tileY = originY + dy; |
| 1384 | if (this.isEnterable(tileX, tileY, dim) && !this.#occupiedTile(tileX, tileY, dim)) |
| 1385 | { return { tileX, tileY, dimensionId: dim }; } |
| 1386 | } |
| 1387 | } |
| 1388 | } |
| 1389 | return null; |
| 1390 | } |
| 1391 | |
| 1392 | isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 1393 | { |
| 1394 | const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), dimensionId); |
| 1395 | if (!data.open) |
| 1396 | { return false; } |
| 1397 | return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY)); |
| 1398 | } |
| 1399 | |
| 1400 | debugWorld () |
| 1401 | { |
| 1402 | const loaders = this.#allLoaders(); |
| 1403 | const { chunkSim, regionRes } = accumulateLoaderRefs(loaders); |
| 1404 | const simulatingChunks = [...chunkSim.entries()] |
| 1405 | .filter(([, count]) => count > 0) |
| 1406 | .map(([key]) => key) |
| 1407 | .sort(); |
| 1408 | return { |
| 1409 | tickIndex: this.tickIndex, |
| 1410 | workerCount: this.workers.length, |
| 1411 | workerMode: this.workerMode, |
| 1412 | simulatingChunks, |
| 1413 | regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({ |
| 1414 | ...parseRegionKey(key), |
| 1415 | workerId, |
| 1416 | state: REGION_RUNTIME_STATE.resident, |
| 1417 | refs: regionRes.get(key) ?? 0, |
| 1418 | graceUntil: this.regionGraceUntil.get(key) ?? null |
| 1419 | })), |
| 1420 | entities: [...this.directory.values()].map((entity) => ({ |
| 1421 | entityId: entity.entityId, |
| 1422 | workerId: entity.workerId, |
| 1423 | tileX: entity.tileX, |
| 1424 | tileY: entity.tileY, |
| 1425 | characterId: entity.characterId |
| 1426 | })) |
| 1427 | }; |
| 1428 | } |
| 1429 | |
| 1430 | async shutdown () |
| 1431 | { |
| 1432 | for (const characterId of [...this.characterEntities.keys()]) |
| 1433 | { this.despawnCharacter(characterId); } |
| 1434 | this.forceUnloadAll(); |
| 1435 | await Promise.all(this.workers.map((worker) => worker.terminate())); |
| 1436 | } |
| 1437 | |
| 1438 | forceUnloadAll () |
| 1439 | { |
| 1440 | for (const key of [...this.regionOwner.keys()]) |
| 1441 | { |
| 1442 | const { regionX, regionY } = parseRegionKey(key); |
| 1443 | this.#unloadRegion(regionX, regionY); |
| 1444 | } |
| 1445 | } |
| 1446 | |
| 1447 | #configureWorkers () |
| 1448 | { |
| 1449 | for (const worker of this.workers) |
| 1450 | { |
| 1451 | worker.call({ |
| 1452 | type: WorkerMessage.configure, |
| 1453 | settings: this.settings, |
| 1454 | activeRevisionId: this.activeRevisionId |
| 1455 | }); |
| 1456 | } |
| 1457 | } |
| 1458 | |
| 1459 | #routeCommand (item) |
| 1460 | { |
| 1461 | if (item.command.type === "respawn") |
| 1462 | { return this.#respawnCharacter(item.sessionId, item.command.characterId); } |
| 1463 | const routedCharacterId = item.command.characterId | 0; |
| 1464 | if (routedCharacterId && this.stateDb.getCharacter(routedCharacterId)?.is_dead) |
| 1465 | { |
| 1466 | // Queued intents after death (drop/use/send/craft/…) are discarded. |
| 1467 | return []; |
| 1468 | } |
| 1469 | if (item.command.type === "enter-doorway") |
| 1470 | { |
| 1471 | return this.#relocateCharacterThroughDoorway( |
| 1472 | item.sessionId, |
| 1473 | item.command.characterId, |
| 1474 | item.command.tileX, |
| 1475 | item.command.tileY |
| 1476 | ); |
| 1477 | } |
| 1478 | if ( |
| 1479 | item.command.type === "open-market" |
| 1480 | || item.command.type === "place-market-sell" |
| 1481 | || item.command.type === "place-market-buy" |
| 1482 | || item.command.type === "cancel-market-order" |
| 1483 | || item.command.type === "close-market" |
| 1484 | ) |
| 1485 | { |
| 1486 | const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now); |
| 1487 | return result?.events ?? []; |
| 1488 | } |
| 1489 | if ( |
| 1490 | item.command.type === "trade-request" |
| 1491 | || item.command.type === "trade-respond-invite" |
| 1492 | || item.command.type === "trade-offer-set" |
| 1493 | || item.command.type === "trade-offer-remove" |
| 1494 | || item.command.type === "trade-accept" |
| 1495 | || item.command.type === "trade-cancel" |
| 1496 | ) |
| 1497 | { |
| 1498 | const result = this.trade.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now); |
| 1499 | return result?.events ?? []; |
| 1500 | } |
| 1501 | if ( |
| 1502 | item.command.type === "open-bounty" |
| 1503 | || item.command.type === "raise-bounty" |
| 1504 | || item.command.type === "pay-bounty" |
| 1505 | || item.command.type === "get-character-bounty" |
| 1506 | || item.command.type === "close-bounty" |
| 1507 | ) |
| 1508 | { |
| 1509 | const result = this.bounty.handleCommand(item.sessionId, item.command); |
| 1510 | return result?.events ?? []; |
| 1511 | } |
| 1512 | if ( |
| 1513 | item.command.type === "open-barber" |
| 1514 | || item.command.type === "set-hair" |
| 1515 | || item.command.type === "close-barber" |
| 1516 | ) |
| 1517 | { |
| 1518 | const result = this.barber.handleCommand(item.sessionId, item.command); |
| 1519 | return result?.events ?? []; |
| 1520 | } |
| 1521 | if ( |
| 1522 | item.command.type === "dialogue-choose" |
| 1523 | || item.command.type === "dialogue-advance" |
| 1524 | || item.command.type === "close-dialogue" |
| 1525 | || item.command.type === "request-quests" |
| 1526 | ) |
| 1527 | { return this.#handleQuestCommand(item); } |
| 1528 | const entityId = this.characterEntities.get(item.command.characterId); |
| 1529 | const record = entityId ? this.directory.get(entityId) : null; |
| 1530 | if (!record) |
| 1531 | { |
| 1532 | const error = new Error("Character is not in the world."); |
| 1533 | error.userFacing = true; |
| 1534 | throw error; |
| 1535 | } |
| 1536 | if (item.command.type === "drop-item" && item.command.groundItemId == null) |
| 1537 | { item.command.groundItemId = this.nextGroundItemId++; } |
| 1538 | if (item.command.type === "attack") |
| 1539 | { |
| 1540 | const targetRecord = this.directory.get(item.command.targetEntityId); |
| 1541 | if (!targetRecord) |
| 1542 | { |
| 1543 | const error = new Error("Target is not here."); |
| 1544 | error.userFacing = true; |
| 1545 | throw error; |
| 1546 | } |
| 1547 | const events = this.#finishRoutedCommand(item, record); |
| 1548 | if (targetRecord.workerId !== record.workerId) |
| 1549 | { |
| 1550 | this.workers[targetRecord.workerId].call({ |
| 1551 | type: WorkerMessage.remoteCombatEngage, |
| 1552 | attackerEntityId: record.entityId, |
| 1553 | targetEntityId: item.command.targetEntityId, |
| 1554 | now: item.receivedAt ?? this.now |
| 1555 | }); |
| 1556 | } |
| 1557 | return events; |
| 1558 | } |
| 1559 | return this.#finishRoutedCommand(item, record); |
| 1560 | } |
| 1561 | |
| 1562 | #finishRoutedCommand (item, record) |
| 1563 | { |
| 1564 | const result = this.workers[record.workerId].call({ |
| 1565 | type: WorkerMessage.command, |
| 1566 | sessionId: item.sessionId, |
| 1567 | command: item.command, |
| 1568 | now: item.receivedAt ?? this.now |
| 1569 | }); |
| 1570 | const view = this.workers[record.workerId].call({ |
| 1571 | type: WorkerMessage.inspect, |
| 1572 | entityId: record.entityId |
| 1573 | }); |
| 1574 | if (view) |
| 1575 | { this.#remember(view, record.workerId); } |
| 1576 | if (result?.private) |
| 1577 | { this.#saveBagFromView(item.command.characterId, result.private); } |
| 1578 | if (result?.appearanceChanged && view) |
| 1579 | { this.#queueReplication(replicationAppearance(view)); } |
| 1580 | if (result?.remainder) |
| 1581 | { |
| 1582 | this.stateDb.saveInheritance( |
| 1583 | this.stateDb.getCharacter(item.command.characterId).account_id, |
| 1584 | { slots: result.remainder } |
| 1585 | ); |
| 1586 | } |
| 1587 | for (const event of result?.events ?? []) |
| 1588 | { this.#persistGroundEvent(event); } |
| 1589 | const events = []; |
| 1590 | for (const event of result?.events ?? []) |
| 1591 | { |
| 1592 | if (event.type === "skills-updated") |
| 1593 | { |
| 1594 | this.#applySkillsUpdated(event); |
| 1595 | events.push(...this.#skillLevelUpEvents(event)); |
| 1596 | continue; |
| 1597 | } |
| 1598 | if (event.type === "spells-updated") |
| 1599 | { |
| 1600 | this.#applySpellsUpdated(event); |
| 1601 | continue; |
| 1602 | } |
| 1603 | if (event.type === "open-dialogue") |
| 1604 | { |
| 1605 | events.push(...this.#handleOpenDialogue(event)); |
| 1606 | continue; |
| 1607 | } |
| 1608 | if ( |
| 1609 | event.type === "combat-hit" |
| 1610 | || event.type === "combat-miss" |
| 1611 | || event.type === "combat-block" |
| 1612 | || event.type === "combat-swing" |
| 1613 | ) |
| 1614 | { this.#noteCombatEvent(event); } |
| 1615 | if (event.type === "player-died") |
| 1616 | { |
| 1617 | events.push(...this.#applyPlayerDeath(event)); |
| 1618 | continue; |
| 1619 | } |
| 1620 | events.push(event); |
| 1621 | } |
| 1622 | if (item.command.type === "attack" && item.command.targetEntityId != null) |
| 1623 | { |
| 1624 | this.#notePlayerAttack(item.command.characterId, item.command.targetEntityId); |
| 1625 | events.push(...this.#mapQuestPrivateEvents( |
| 1626 | this.quests?.interruptDialogueForEntity(item.command.targetEntityId) ?? [] |
| 1627 | )); |
| 1628 | } |
| 1629 | if ( |
| 1630 | (item.command.type === "cast-spell-entity") |
| 1631 | && item.command.targetEntityId != null |
| 1632 | ) |
| 1633 | { this.#notePlayerAttack(item.command.characterId, item.command.targetEntityId); } |
| 1634 | if (result?.private) |
| 1635 | { |
| 1636 | events.push({ |
| 1637 | type: "inventory", |
| 1638 | sessionId: item.sessionId, |
| 1639 | bank: !!result.bank, |
| 1640 | cauldron: result.cauldron, |
| 1641 | cauldronState: result.cauldronState ?? null, |
| 1642 | alchemyResult: result.alchemyResult ?? null, |
| 1643 | dyeConfirm: result.dyeConfirm ?? null, |
| 1644 | ...result.private |
| 1645 | }); |
| 1646 | } |
| 1647 | if (result?.statusEffectsChanged && view) |
| 1648 | { |
| 1649 | events.push({ |
| 1650 | type: "status-effects", |
| 1651 | sessionId: item.sessionId, |
| 1652 | characterId: view.characterId ?? item.command.characterId, |
| 1653 | effects: view.statusEffects ?? [], |
| 1654 | blind: (view.statusEffects ?? []).some((entry) => entry.type === "blind") |
| 1655 | }); |
| 1656 | } |
| 1657 | if (result?.healthChanged && view) |
| 1658 | { |
| 1659 | events.push({ |
| 1660 | type: "entity-health", |
| 1661 | entityId: view.entityId, |
| 1662 | characterId: view.characterId ?? item.command.characterId, |
| 1663 | health: view.health, |
| 1664 | maxHealth: view.maxHealth, |
| 1665 | tileX: view.tileX, |
| 1666 | tileY: view.tileY |
| 1667 | }); |
| 1668 | } |
| 1669 | return events; |
| 1670 | } |
| 1671 | |
| 1672 | #applyRemoteMelee (payload) |
| 1673 | { |
| 1674 | const targetRecord = this.directory.get(payload.targetId); |
| 1675 | if (!targetRecord) |
| 1676 | { return []; } |
| 1677 | const result = this.workers[targetRecord.workerId].call({ |
| 1678 | ...payload, |
| 1679 | type: WorkerMessage.applyRemoteMelee |
| 1680 | }); |
| 1681 | const events = []; |
| 1682 | for (const event of result?.events ?? []) |
| 1683 | { |
| 1684 | if (event.type === "entity-despawn") |
| 1685 | { this.#forget(event.entityId); } |
| 1686 | if (event.type === "skills-updated") |
| 1687 | { |
| 1688 | this.#applySkillsUpdated(event); |
| 1689 | events.push(...this.#skillLevelUpEvents(event)); |
| 1690 | continue; |
| 1691 | } |
| 1692 | if (event.type === "spells-updated") |
| 1693 | { |
| 1694 | this.#applySpellsUpdated(event); |
| 1695 | continue; |
| 1696 | } |
| 1697 | if (event.type === "player-died") |
| 1698 | { |
| 1699 | events.push(...this.#applyPlayerDeath(event)); |
| 1700 | continue; |
| 1701 | } |
| 1702 | if ( |
| 1703 | event.type === "combat-hit" |
| 1704 | || event.type === "combat-miss" |
| 1705 | || event.type === "combat-block" |
| 1706 | || event.type === "combat-swing" |
| 1707 | ) |
| 1708 | { this.#noteCombatEvent(event); } |
| 1709 | if (event.type === "mob-killed") |
| 1710 | { |
| 1711 | events.push(...this.#applyMobKilled(event)); |
| 1712 | continue; |
| 1713 | } |
| 1714 | this.#persistGroundEvent(event); |
| 1715 | if (event.type !== "skills-updated") |
| 1716 | { events.push(event); } |
| 1717 | } |
| 1718 | for (const forward of result?.forwards ?? []) |
| 1719 | { |
| 1720 | if (forward.type !== "forward-combat-xp") |
| 1721 | { continue; } |
| 1722 | const attackerRecord = this.directory.get(forward.entityId); |
| 1723 | if (!attackerRecord) |
| 1724 | { continue; } |
| 1725 | const xpResult = this.workers[attackerRecord.workerId].call({ |
| 1726 | type: WorkerMessage.applyCombatHitXp, |
| 1727 | entityId: forward.entityId, |
| 1728 | profile: forward.profile, |
| 1729 | damage: forward.damage |
| 1730 | }); |
| 1731 | for (const xpEvent of xpResult?.events ?? []) |
| 1732 | { |
| 1733 | if (xpEvent.type === "skills-updated") |
| 1734 | { |
| 1735 | this.#applySkillsUpdated(xpEvent); |
| 1736 | events.push(...this.#skillLevelUpEvents(xpEvent)); |
| 1737 | continue; |
| 1738 | } |
| 1739 | events.push(xpEvent); |
| 1740 | } |
| 1741 | } |
| 1742 | return events; |
| 1743 | } |
| 1744 | |
| 1745 | #applyRemoteRanged (payload) |
| 1746 | { |
| 1747 | const targetRecord = this.directory.get(payload.targetId); |
| 1748 | if (!targetRecord) |
| 1749 | { return []; } |
| 1750 | const result = this.workers[targetRecord.workerId].call({ |
| 1751 | ...payload, |
| 1752 | type: WorkerMessage.applyRemoteRanged |
| 1753 | }); |
| 1754 | const events = []; |
| 1755 | for (const event of result?.events ?? []) |
| 1756 | { |
| 1757 | if (event.type === "entity-despawn") |
| 1758 | { this.#forget(event.entityId); } |
| 1759 | if (event.type === "skills-updated") |
| 1760 | { |
| 1761 | this.#applySkillsUpdated(event); |
| 1762 | events.push(...this.#skillLevelUpEvents(event)); |
| 1763 | continue; |
| 1764 | } |
| 1765 | if (event.type === "spells-updated") |
| 1766 | { |
| 1767 | this.#applySpellsUpdated(event); |
| 1768 | continue; |
| 1769 | } |
| 1770 | if (event.type === "player-died") |
| 1771 | { |
| 1772 | events.push(...this.#applyPlayerDeath(event)); |
| 1773 | continue; |
| 1774 | } |
| 1775 | if ( |
| 1776 | event.type === "combat-hit" |
| 1777 | || event.type === "combat-miss" |
| 1778 | || event.type === "combat-block" |
| 1779 | || event.type === "combat-swing" |
| 1780 | ) |
| 1781 | { this.#noteCombatEvent(event); } |
| 1782 | if (event.type === "mob-killed") |
| 1783 | { |
| 1784 | events.push(...this.#applyMobKilled(event)); |
| 1785 | continue; |
| 1786 | } |
| 1787 | this.#persistGroundEvent(event); |
| 1788 | if (event.type !== "skills-updated") |
| 1789 | { events.push(event); } |
| 1790 | } |
| 1791 | for (const forward of result?.forwards ?? []) |
| 1792 | { |
| 1793 | if (forward.type !== "forward-combat-xp") |
| 1794 | { continue; } |
| 1795 | const attackerRecord = this.directory.get(forward.entityId); |
| 1796 | if (!attackerRecord) |
| 1797 | { continue; } |
| 1798 | const xpResult = this.workers[attackerRecord.workerId].call({ |
| 1799 | type: WorkerMessage.applyCombatHitXp, |
| 1800 | entityId: forward.entityId, |
| 1801 | profile: forward.profile, |
| 1802 | damage: forward.damage |
| 1803 | }); |
| 1804 | for (const xpEvent of xpResult?.events ?? []) |
| 1805 | { |
| 1806 | if (xpEvent.type === "skills-updated") |
| 1807 | { |
| 1808 | this.#applySkillsUpdated(xpEvent); |
| 1809 | events.push(...this.#skillLevelUpEvents(xpEvent)); |
| 1810 | continue; |
| 1811 | } |
| 1812 | events.push(xpEvent); |
| 1813 | } |
| 1814 | } |
| 1815 | return events; |
| 1816 | } |
| 1817 | |
| 1818 | #handleQuestCommand (item) |
| 1819 | { |
| 1820 | const characterId = item.command.characterId | 0; |
| 1821 | const sessionId = item.sessionId; |
| 1822 | if (!this.quests) |
| 1823 | { return []; } |
| 1824 | if (item.command.type === "request-quests") |
| 1825 | { |
| 1826 | const snap = this.quests.questSnapshot(characterId); |
| 1827 | return [{ type: "quests-snapshot", sessionId, characterId, ...snap }]; |
| 1828 | } |
| 1829 | if (item.command.type === "close-dialogue") |
| 1830 | { |
| 1831 | const closed = this.quests.closeDialogue(characterId, "client"); |
| 1832 | return this.#mapQuestPrivateEvents(closed.events, sessionId, characterId); |
| 1833 | } |
| 1834 | if (item.command.type === "dialogue-choose") |
| 1835 | { |
| 1836 | const result = this.quests.chooseDialogue(characterId, item.command.trigger); |
| 1837 | if (!result.ok) |
| 1838 | { |
| 1839 | const error = new Error(result.error || "Choice failed."); |
| 1840 | error.userFacing = true; |
| 1841 | throw error; |
| 1842 | } |
| 1843 | return this.#mapQuestPrivateEvents(result.events, sessionId, characterId); |
| 1844 | } |
| 1845 | if (item.command.type === "dialogue-advance") |
| 1846 | { |
| 1847 | const result = this.quests.advanceDialogue(characterId); |
| 1848 | if (!result.ok) |
| 1849 | { |
| 1850 | const error = new Error(result.error || "Cannot advance."); |
| 1851 | error.userFacing = true; |
| 1852 | throw error; |
| 1853 | } |
| 1854 | return this.#mapQuestPrivateEvents(result.events, sessionId, characterId); |
| 1855 | } |
| 1856 | return []; |
| 1857 | } |
| 1858 | |
| 1859 | #handleOpenDialogue (event) |
| 1860 | { |
| 1861 | const result = this.quests.tryOpenDialogue(event.characterId, event.entityId, event.dialogueId); |
| 1862 | if (!result.ok) |
| 1863 | { |
| 1864 | return [{ |
| 1865 | type: "toast", |
| 1866 | characterId: event.characterId, |
| 1867 | sessionId: event.sessionId, |
| 1868 | message: result.error || "Nothing to say." |
| 1869 | }]; |
| 1870 | } |
| 1871 | this.#pinDialogueNpc(event.entityId, event.characterId); |
| 1872 | return this.#mapQuestPrivateEvents(result.events, event.sessionId, event.characterId); |
| 1873 | } |
| 1874 | |
| 1875 | #pinDialogueNpc (entityId, characterId) |
| 1876 | { |
| 1877 | const record = this.directory.get(entityId | 0); |
| 1878 | if (!record) |
| 1879 | { return; } |
| 1880 | this.workers[record.workerId]?.call?.({ |
| 1881 | type: WorkerMessage.pinDialogue, |
| 1882 | entityId: entityId | 0, |
| 1883 | characterId: characterId | 0 |
| 1884 | }); |
| 1885 | } |
| 1886 | |
| 1887 | #unpinDialogueNpc (entityId, characterId) |
| 1888 | { |
| 1889 | const record = this.directory.get(entityId | 0); |
| 1890 | if (!record) |
| 1891 | { return; } |
| 1892 | this.workers[record.workerId]?.call?.({ |
| 1893 | type: WorkerMessage.unpinDialogue, |
| 1894 | entityId: entityId | 0, |
| 1895 | characterId: characterId | 0 |
| 1896 | }); |
| 1897 | } |
| 1898 | |
| 1899 | #mapQuestPrivateEvents (events, sessionId = null, characterId = null) |
| 1900 | { |
| 1901 | const out = []; |
| 1902 | let needSnapshot = false; |
| 1903 | for (const event of events ?? []) |
| 1904 | { |
| 1905 | const cid = event.characterId ?? characterId; |
| 1906 | const sid = sessionId ?? this.#sessionIdForCharacter(cid); |
| 1907 | if (event.type === "dialogueStep") |
| 1908 | { |
| 1909 | out.push({ |
| 1910 | type: "dialogue-step", |
| 1911 | sessionId: sid, |
| 1912 | characterId: cid, |
| 1913 | dialogueId: event.dialogueId, |
| 1914 | stepId: event.stepId, |
| 1915 | label: event.label, |
| 1916 | npcEntityId: event.npcEntityId, |
| 1917 | lines: event.lines |
| 1918 | }); |
| 1919 | } |
| 1920 | else if (event.type === "dialogueChoices") |
| 1921 | { |
| 1922 | out.push({ |
| 1923 | type: "dialogue-choices", |
| 1924 | sessionId: sid, |
| 1925 | characterId: cid, |
| 1926 | dialogueId: event.dialogueId, |
| 1927 | stepId: event.stepId, |
| 1928 | npcEntityId: event.npcEntityId, |
| 1929 | triggers: event.triggers |
| 1930 | }); |
| 1931 | } |
| 1932 | else if (event.type === "dialogueItemRewards") |
| 1933 | { |
| 1934 | out.push({ |
| 1935 | type: "dialogue-item-rewards", |
| 1936 | sessionId: sid, |
| 1937 | characterId: cid, |
| 1938 | dialogueId: event.dialogueId, |
| 1939 | stepId: event.stepId, |
| 1940 | npcEntityId: event.npcEntityId, |
| 1941 | messages: event.messages ?? [] |
| 1942 | }); |
| 1943 | } |
| 1944 | else if (event.type === "dialogueClose") |
| 1945 | { |
| 1946 | if (event.npcEntityId != null && cid != null) |
| 1947 | { this.#unpinDialogueNpc(event.npcEntityId, cid); } |
| 1948 | out.push({ |
| 1949 | type: "dialogue-close", |
| 1950 | sessionId: sid, |
| 1951 | characterId: cid, |
| 1952 | reason: event.reason |
| 1953 | }); |
| 1954 | } |
| 1955 | else if (event.type === "questStepComplete") |
| 1956 | { |
| 1957 | out.push({ |
| 1958 | type: "quest-step-complete", |
| 1959 | sessionId: sid, |
| 1960 | characterId: cid, |
| 1961 | questId: event.questId, |
| 1962 | title: event.title |
| 1963 | }); |
| 1964 | needSnapshot = true; |
| 1965 | } |
| 1966 | else if (event.type === "questsDirty") |
| 1967 | { needSnapshot = true; } |
| 1968 | else if (event.type === "inventoryDirty" && cid != null) |
| 1969 | { |
| 1970 | const onlineId = this.characterEntities.get(cid | 0); |
| 1971 | if (onlineId) |
| 1972 | { |
| 1973 | const live = this.bagOf(onlineId); |
| 1974 | if (live) |
| 1975 | { this.pushInventory(cid, live); } |
| 1976 | } |
| 1977 | } |
| 1978 | } |
| 1979 | if (needSnapshot && characterId != null) |
| 1980 | { |
| 1981 | const snap = this.quests.questSnapshot(characterId); |
| 1982 | out.push({ |
| 1983 | type: "quests-snapshot", |
| 1984 | sessionId: sessionId ?? this.#sessionIdForCharacter(characterId), |
| 1985 | characterId, |
| 1986 | ...snap |
| 1987 | }); |
| 1988 | } |
| 1989 | return out; |
| 1990 | } |
| 1991 | |
| 1992 | #sessionIdForCharacter (characterId) |
| 1993 | { |
| 1994 | const entityId = this.characterEntities.get(characterId | 0); |
| 1995 | const record = entityId != null ? this.directory.get(entityId) : null; |
| 1996 | return record?.sessionId ?? null; |
| 1997 | } |
| 1998 | |
| 1999 | #applyMobKilled (event) |
| 2000 | { |
| 2001 | const out = [event]; |
| 2002 | const attackerRecord = this.directory.get(event.attackerId); |
| 2003 | const killerCharacterId = attackerRecord?.characterId ?? null; |
| 2004 | const killerPos = attackerRecord |
| 2005 | ? { tileX: attackerRecord.tileX, tileY: attackerRecord.tileY } |
| 2006 | : null; |
| 2007 | if (killerCharacterId && this.quests) |
| 2008 | { |
| 2009 | out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, { |
| 2010 | mobTypeId: event.mobTypeId, |
| 2011 | spawnerId: event.spawnerId |
| 2012 | }))); |
| 2013 | } |
| 2014 | out.push(...this.#mapQuestPrivateEvents( |
| 2015 | this.quests?.interruptDialogueForEntity(event.entityId) ?? [] |
| 2016 | )); |
| 2017 | let bountyAwarded = 0; |
| 2018 | if (killerCharacterId && (event.bounty | 0) > 0) |
| 2019 | { |
| 2020 | bountyAwarded = event.bounty | 0; |
| 2021 | const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded); |
| 2022 | this.refreshCharacterSkull(killerCharacterId); |
| 2023 | out.push({ |
| 2024 | type: "toast", |
| 2025 | characterId: killerCharacterId, |
| 2026 | message: `Bounty +${bountyAwarded} (total ${total})` |
| 2027 | }); |
| 2028 | } |
| 2029 | |
| 2030 | if (killerCharacterId && killerPos) |
| 2031 | { |
| 2032 | if (bountyAwarded > 0) |
| 2033 | { this.#dispatchTownGuards(event.attackerId, killerPos, null, 1); } |
| 2034 | if (event.townGuard) |
| 2035 | { this.#dispatchTownGuards(event.attackerId, killerPos, event.spawnerId, 2); } |
| 2036 | } |
| 2037 | return out; |
| 2038 | } |
| 2039 | |
| 2040 | /** |
| 2041 | * Send up to `count` town guards at the killer. Prefer idle guards. |
| 2042 | * When `spawnerId` is set, only that spawner's guards are used. |
| 2043 | */ |
| 2044 | #dispatchTownGuards (targetEntityId, killerPos, spawnerId, count) |
| 2045 | { |
| 2046 | const want = Math.max(0, count | 0); |
| 2047 | if (want <= 0 || targetEntityId == null || !killerPos) |
| 2048 | { return; } |
| 2049 | const candidates = []; |
| 2050 | for (const worker of this.workers) |
| 2051 | { |
| 2052 | const result = worker.call({ |
| 2053 | type: WorkerMessage.listTownGuardsNear, |
| 2054 | tileX: killerPos.tileX, |
| 2055 | tileY: killerPos.tileY, |
| 2056 | spawnerId, |
| 2057 | limit: 32 |
| 2058 | }); |
| 2059 | for (const guard of result?.guards ?? []) |
| 2060 | { candidates.push(guard); } |
| 2061 | } |
| 2062 | candidates.sort((a, b) => Number(a.busy) - Number(b.busy)); |
| 2063 | let sent = 0; |
| 2064 | for (const guard of candidates) |
| 2065 | { |
| 2066 | if (sent >= want) |
| 2067 | { break; } |
| 2068 | if (guard.entityId === targetEntityId) |
| 2069 | { continue; } |
| 2070 | const record = this.directory.get(guard.entityId); |
| 2071 | if (!record) |
| 2072 | { continue; } |
| 2073 | this.workers[record.workerId].call({ |
| 2074 | type: WorkerMessage.engageTarget, |
| 2075 | attackerEntityId: guard.entityId, |
| 2076 | targetEntityId, |
| 2077 | now: this.now |
| 2078 | }); |
| 2079 | sent += 1; |
| 2080 | } |
| 2081 | } |
| 2082 | |
| 2083 | #applyPlayerDeath (event) |
| 2084 | { |
| 2085 | const record = this.directory.get(event.entityId); |
| 2086 | if (!record) |
| 2087 | { return [event]; } |
| 2088 | this.stateDb.setCharacterDead(event.characterId, true); |
| 2089 | this.stateDb.saveCharacterPosition( |
| 2090 | event.characterId, |
| 2091 | event.tileX, |
| 2092 | event.tileY, |
| 2093 | record.gait ?? GAIT.walk, |
| 2094 | record.dimensionId ?? OVERWORLD_ID |
| 2095 | ); |
| 2096 | this.bounty?.settleKill( |
| 2097 | event.characterId, |
| 2098 | event.attackerId, |
| 2099 | event.tileX, |
| 2100 | event.tileY |
| 2101 | ); |
| 2102 | const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null; |
| 2103 | const killerCharacterId = Number(attackerRecord?.characterId) || 0; |
| 2104 | if (killerCharacterId && killerCharacterId !== (event.characterId | 0)) |
| 2105 | { this.stateDb.addKillCounter(killerCharacterId, SKULL_KILL_BONUS, this.now); } |
| 2106 | const events = [event]; |
| 2107 | const closedDialogue = this.quests?.closeDialogue(event.characterId, "death"); |
| 2108 | if (closedDialogue?.events?.length) |
| 2109 | { |
| 2110 | events.push(...this.#mapQuestPrivateEvents( |
| 2111 | closedDialogue.events, |
| 2112 | event.sessionId, |
| 2113 | event.characterId |
| 2114 | )); |
| 2115 | } |
| 2116 | if (event.sessionId != null) |
| 2117 | { |
| 2118 | for (const commandType of ["cancel-craft", "cauldron-close"]) |
| 2119 | { |
| 2120 | try |
| 2121 | { |
| 2122 | this.workers[record.workerId].call({ |
| 2123 | type: WorkerMessage.command, |
| 2124 | sessionId: event.sessionId, |
| 2125 | command: { type: commandType, characterId: event.characterId }, |
| 2126 | now: this.now |
| 2127 | }); |
| 2128 | } |
| 2129 | catch |
| 2130 | { /* best-effort session cleanup */ } |
| 2131 | } |
| 2132 | } |
| 2133 | // Bounty is cleared instantly on non-friend PvP death; only kill-counter decays over time. |
| 2134 | const victimSkull = this.refreshCharacterSkull(event.characterId, { force: true }); |
| 2135 | if (victimSkull) |
| 2136 | { events.push(victimSkull); } |
| 2137 | for (const worker of this.workers) |
| 2138 | { |
| 2139 | worker.call({ |
| 2140 | type: WorkerMessage.clearCombat, |
| 2141 | entityId: event.entityId, |
| 2142 | targetEntityId: event.entityId |
| 2143 | }); |
| 2144 | } |
| 2145 | const victimName = `${record.firstName ?? "someone"} ${record.lastName ?? ""}`.trim() |
| 2146 | || "someone"; |
| 2147 | const killerName = `${attackerRecord?.firstName ?? ""} ${attackerRecord?.lastName ?? ""}`.trim() |
| 2148 | || "someone"; |
| 2149 | const corpseOrigin = lootOrigin(victimName, killerName); |
| 2150 | const result = this.workers[record.workerId].call({ |
| 2151 | type: WorkerMessage.spawnCorpseDrops, |
| 2152 | characterId: event.characterId, |
| 2153 | tileX: event.tileX, |
| 2154 | tileY: event.tileY, |
| 2155 | now: this.now, |
| 2156 | dropCarriedCoins: true, |
| 2157 | coinGroundItemId: this.nextGroundItemId++, |
| 2158 | drops: [ |
| 2159 | { |
| 2160 | groundItemId: this.nextGroundItemId++, |
| 2161 | stack: attachOrigins({ |
| 2162 | itemId: ItemId.bones, |
| 2163 | quantity: 1, |
| 2164 | origins: [{ origin: corpseOrigin, quantity: 1 }] |
| 2165 | }) |
| 2166 | }, |
| 2167 | { |
| 2168 | groundItemId: this.nextGroundItemId++, |
| 2169 | stack: attachOrigins({ |
| 2170 | itemId: ItemId.skull, |
| 2171 | quantity: 1, |
| 2172 | origins: [{ origin: corpseOrigin, quantity: 1 }] |
| 2173 | }) |
| 2174 | } |
| 2175 | ] |
| 2176 | }); |
| 2177 | if (killerCharacterId && killerCharacterId !== (event.characterId | 0)) |
| 2178 | { |
| 2179 | const skullEvent = this.refreshCharacterSkull(killerCharacterId, { force: true }); |
| 2180 | if (skullEvent) |
| 2181 | { events.push(skullEvent); } |
| 2182 | } |
| 2183 | events.push({ |
| 2184 | type: "entity-despawn", |
| 2185 | entityId: event.entityId, |
| 2186 | tileX: event.tileX, |
| 2187 | tileY: event.tileY, |
| 2188 | cause: "death" |
| 2189 | }); |
| 2190 | for (const dropEvent of result?.events ?? []) |
| 2191 | { |
| 2192 | this.#persistGroundEvent(dropEvent); |
| 2193 | events.push(dropEvent); |
| 2194 | } |
| 2195 | if (result?.private) |
| 2196 | { |
| 2197 | this.#saveBagFromView(event.characterId, result.private); |
| 2198 | if (event.sessionId != null) |
| 2199 | { |
| 2200 | events.push({ |
| 2201 | type: "inventory", |
| 2202 | sessionId: event.sessionId, |
| 2203 | ...result.private |
| 2204 | }); |
| 2205 | } |
| 2206 | } |
| 2207 | const coinsDropped = coinsDroppedFromDeathEvents(events); |
| 2208 | if (this.combatLogouts.has(event.characterId | 0)) |
| 2209 | { events.push(...this.#finishCombatLogoutDeath(event, coinsDropped)); } |
| 2210 | return events; |
| 2211 | } |
| 2212 | |
| 2213 | #finishCombatLogoutDeath (event, coinsDropped) |
| 2214 | { |
| 2215 | const characterId = event.characterId | 0; |
| 2216 | const logout = this.combatLogouts.get(characterId); |
| 2217 | const events = []; |
| 2218 | if (logout?.pendingCowardice) |
| 2219 | { |
| 2220 | applyCombatLogoutCowardice(this, characterId, { |
| 2221 | coinsDropped, |
| 2222 | now: this.now |
| 2223 | }); |
| 2224 | } |
| 2225 | dispatchChurchOfflineResurrectionLetter( |
| 2226 | this, |
| 2227 | characterId, |
| 2228 | event.tileX | 0, |
| 2229 | event.tileY | 0 |
| 2230 | ); |
| 2231 | try |
| 2232 | { events.push(...this.#respawnCharacter(event.sessionId ?? null, characterId)); } |
| 2233 | catch |
| 2234 | { |
| 2235 | // Respawn can fail without an altar tile; still despawn the corpse session. |
| 2236 | } |
| 2237 | this.#restoreCombatLogoutAutoCast(characterId, logout); |
| 2238 | this.combatLogouts.delete(characterId); |
| 2239 | this.combatTracking.delete(characterId); |
| 2240 | this.despawnCharacter(characterId); |
| 2241 | return events; |
| 2242 | } |
| 2243 | |
| 2244 | #relocateCharacterThroughDoorway (sessionId, characterId, doorwayTileX, doorwayTileY) |
| 2245 | { |
| 2246 | const entityId = this.characterEntities.get(characterId); |
| 2247 | const record = entityId ? this.directory.get(entityId) : null; |
| 2248 | if (!record) |
| 2249 | { |
| 2250 | const error = new Error("Character is not in the world."); |
| 2251 | error.userFacing = true; |
| 2252 | throw error; |
| 2253 | } |
| 2254 | const tileX = doorwayTileX | 0; |
| 2255 | const tileY = doorwayTileY | 0; |
| 2256 | if (!isAdjacentTile(record.tileX, record.tileY, tileX, tileY)) |
| 2257 | { |
| 2258 | const error = new Error("You are too far from that doorway."); |
| 2259 | error.userFacing = true; |
| 2260 | throw error; |
| 2261 | } |
| 2262 | const fromDimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); |
| 2263 | const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), fromDimensionId); |
| 2264 | const block = data.blocks[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)]; |
| 2265 | if (block?.typeId !== BlockType.doorway) |
| 2266 | { |
| 2267 | const error = new Error("There is no doorway there."); |
| 2268 | error.userFacing = true; |
| 2269 | throw error; |
| 2270 | } |
| 2271 | const config = block.config && typeof block.config === "object" ? block.config : null; |
| 2272 | const targetRaw = config?.targetDimensionId; |
| 2273 | if (targetRaw == null || String(targetRaw).trim() === "") |
| 2274 | { |
| 2275 | const error = new Error("That doorway leads nowhere."); |
| 2276 | error.userFacing = true; |
| 2277 | throw error; |
| 2278 | } |
| 2279 | const targetDimensionId = normalizeDimensionId(targetRaw); |
| 2280 | const destTileX = Number(config.tileX); |
| 2281 | const destTileY = Number(config.tileY); |
| 2282 | if (!Number.isFinite(destTileX) || !Number.isFinite(destTileY)) |
| 2283 | { |
| 2284 | const error = new Error("That doorway leads nowhere."); |
| 2285 | error.userFacing = true; |
| 2286 | throw error; |
| 2287 | } |
| 2288 | const destX = destTileX | 0; |
| 2289 | const destY = destTileY | 0; |
| 2290 | if (!this.#isDimensionUsable(targetDimensionId)) |
| 2291 | { |
| 2292 | const error = new Error("That place is no longer reachable."); |
| 2293 | error.userFacing = true; |
| 2294 | throw error; |
| 2295 | } |
| 2296 | if (!this.isEnterable(destX, destY, targetDimensionId)) |
| 2297 | { |
| 2298 | const error = new Error("The other side is blocked."); |
| 2299 | error.userFacing = true; |
| 2300 | throw error; |
| 2301 | } |
| 2302 | |
| 2303 | const events = []; |
| 2304 | if (this.quests) |
| 2305 | { |
| 2306 | const closed = this.quests.closeDialogue(characterId, "doorway"); |
| 2307 | if (closed?.events?.length) |
| 2308 | { events.push(...this.#mapQuestPrivateEvents(closed.events, sessionId, characterId)); } |
| 2309 | } |
| 2310 | |
| 2311 | const loader = { ...DEFAULT_CHUNK_LOADER }; |
| 2312 | this.#ensureCoverage(destX, destY, loader, targetDimensionId); |
| 2313 | const result = this.workers[record.workerId].call({ |
| 2314 | type: WorkerMessage.relocateEntity, |
| 2315 | entityId, |
| 2316 | tileX: destX, |
| 2317 | tileY: destY, |
| 2318 | dimensionId: targetDimensionId |
| 2319 | }); |
| 2320 | if (!result?.accepted) |
| 2321 | { |
| 2322 | const error = new Error("Could not enter that doorway."); |
| 2323 | error.userFacing = true; |
| 2324 | throw error; |
| 2325 | } |
| 2326 | let moveEvents = []; |
| 2327 | if (result.transferRequest) |
| 2328 | { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); } |
| 2329 | else if (result.event) |
| 2330 | { |
| 2331 | this.#applyMoveToDirectory(result.event); |
| 2332 | moveEvents = [result.event]; |
| 2333 | const view = this.workers[record.workerId].call({ |
| 2334 | type: WorkerMessage.inspect, |
| 2335 | entityId |
| 2336 | }); |
| 2337 | if (view) |
| 2338 | { this.#remember(view, record.workerId); } |
| 2339 | } |
| 2340 | if (!moveEvents.length) |
| 2341 | { |
| 2342 | const error = new Error("Could not enter that doorway."); |
| 2343 | error.userFacing = true; |
| 2344 | throw error; |
| 2345 | } |
| 2346 | this.stateDb.saveCharacterPosition( |
| 2347 | characterId, |
| 2348 | destX, |
| 2349 | destY, |
| 2350 | record.gait ?? GAIT.walk, |
| 2351 | targetDimensionId |
| 2352 | ); |
| 2353 | this.stateDb.markDimensionVisited(characterId, targetDimensionId); |
| 2354 | this.#recalculateActivation(this.now); |
| 2355 | this.#syncGhosts(); |
| 2356 | const dimRecord = this.getDimensionRecord(targetDimensionId); |
| 2357 | events.push(...moveEvents, { |
| 2358 | type: "dimension-changed", |
| 2359 | sessionId, |
| 2360 | characterId, |
| 2361 | entityId, |
| 2362 | dimensionId: targetDimensionId, |
| 2363 | tileX: destX, |
| 2364 | tileY: destY, |
| 2365 | lightingMode: dimRecord?.lightingMode ?? "dayNight", |
| 2366 | seasonMode: dimRecord?.seasonMode ?? "auto" |
| 2367 | }); |
| 2368 | return events; |
| 2369 | } |
| 2370 | |
| 2371 | #respawnCharacter (sessionId, characterId) |
| 2372 | { |
| 2373 | const row = this.stateDb.getCharacter(characterId); |
| 2374 | if (!row?.is_dead) |
| 2375 | { |
| 2376 | const error = new Error("You are not dead."); |
| 2377 | error.userFacing = true; |
| 2378 | throw error; |
| 2379 | } |
| 2380 | const entityId = this.characterEntities.get(characterId); |
| 2381 | const record = entityId ? this.directory.get(entityId) : null; |
| 2382 | if (!record) |
| 2383 | { |
| 2384 | const error = new Error("Character is not in the world."); |
| 2385 | error.userFacing = true; |
| 2386 | throw error; |
| 2387 | } |
| 2388 | const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId); |
| 2389 | if (!destination) |
| 2390 | { |
| 2391 | const error = new Error("No open tile is available for respawn."); |
| 2392 | error.userFacing = true; |
| 2393 | throw error; |
| 2394 | } |
| 2395 | const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills(); |
| 2396 | const loader = { ...DEFAULT_CHUNK_LOADER }; |
| 2397 | this.#ensureCoverage(destination.tileX, destination.tileY, loader, destination.dimensionId ?? OVERWORLD_ID); |
| 2398 | const result = this.workers[record.workerId].call({ |
| 2399 | type: WorkerMessage.applyRespawn, |
| 2400 | entityId, |
| 2401 | sessionId, |
| 2402 | tileX: destination.tileX, |
| 2403 | tileY: destination.tileY, |
| 2404 | maxHealth: playerMaxHealth(skills), |
| 2405 | maxStamina: playerMaxStamina(skills) |
| 2406 | }); |
| 2407 | if (!result?.accepted) |
| 2408 | { |
| 2409 | const error = new Error("That respawn tile is no longer available."); |
| 2410 | error.userFacing = true; |
| 2411 | throw error; |
| 2412 | } |
| 2413 | let moveEvents = []; |
| 2414 | if (result.transferRequest) |
| 2415 | { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); } |
| 2416 | else if (result.event) |
| 2417 | { |
| 2418 | this.#applyMoveToDirectory(result.event); |
| 2419 | moveEvents = [result.event]; |
| 2420 | const view = this.workers[record.workerId].call({ |
| 2421 | type: WorkerMessage.inspect, |
| 2422 | entityId |
| 2423 | }); |
| 2424 | if (view) |
| 2425 | { this.#remember(view, record.workerId); } |
| 2426 | } |
| 2427 | if (!moveEvents.length) |
| 2428 | { |
| 2429 | const error = new Error("Respawn transfer failed."); |
| 2430 | error.userFacing = true; |
| 2431 | throw error; |
| 2432 | } |
| 2433 | this.stateDb.setCharacterDead(characterId, false); |
| 2434 | const respawnHealth = playerMaxHealth(skills); |
| 2435 | this.stateDb.saveCharacterHealth(characterId, respawnHealth); |
| 2436 | this.stateDb.saveCharacterPosition( |
| 2437 | characterId, |
| 2438 | destination.tileX, |
| 2439 | destination.tileY, |
| 2440 | record.gait ?? GAIT.walk, |
| 2441 | destination.dimensionId ?? record.dimensionId ?? OVERWORLD_ID |
| 2442 | ); |
| 2443 | this.#recalculateActivation(this.now); |
| 2444 | this.#syncGhosts(); |
| 2445 | const skullEvent = this.refreshCharacterSkull(characterId, { force: true }); |
| 2446 | const skullPoints = this.directory.get(entityId)?.skullValue | 0; |
| 2447 | const spawnView = this.workers[record.workerId].call({ |
| 2448 | type: WorkerMessage.inspect, |
| 2449 | entityId |
| 2450 | }); |
| 2451 | const spawn = spawnView |
| 2452 | ? replicationSpawn({ ...spawnView, skullValue: skullPoints }) |
| 2453 | : null; |
| 2454 | return [ |
| 2455 | ...moveEvents, |
| 2456 | ...(spawn ? [spawn] : []), |
| 2457 | ...(skullEvent ? [skullEvent] : []), |
| 2458 | { |
| 2459 | type: "player-respawned", |
| 2460 | entityId, |
| 2461 | characterId, |
| 2462 | sessionId, |
| 2463 | tileX: destination.tileX, |
| 2464 | tileY: destination.tileY, |
| 2465 | health: playerMaxHealth(skills), |
| 2466 | maxHealth: playerMaxHealth(skills), |
| 2467 | stamina: playerMaxStamina(skills), |
| 2468 | maxStamina: playerMaxStamina(skills), |
| 2469 | skullValue: skullPoints |
| 2470 | } |
| 2471 | ]; |
| 2472 | } |
| 2473 | |
| 2474 | #refreshAltarIndex () |
| 2475 | { |
| 2476 | const altars = []; |
| 2477 | for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId)) |
| 2478 | { |
| 2479 | const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID); |
| 2480 | const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, dim); |
| 2481 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 2482 | { |
| 2483 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 2484 | { |
| 2485 | const block = data.blocks[localY * CHUNK_SIZE + localX]; |
| 2486 | if (block?.typeId !== BlockType.churchAltar) |
| 2487 | { continue; } |
| 2488 | altars.push({ |
| 2489 | tileX: coord.chunk_x * CHUNK_SIZE + localX, |
| 2490 | tileY: coord.chunk_y * CHUNK_SIZE + localY, |
| 2491 | dimensionId: dim |
| 2492 | }); |
| 2493 | } |
| 2494 | } |
| 2495 | } |
| 2496 | this.altarTiles = altars; |
| 2497 | } |
| 2498 | |
| 2499 | #findRespawnDestination (originX, originY, entityId) |
| 2500 | { |
| 2501 | const record = this.directory.get(entityId); |
| 2502 | const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID); |
| 2503 | const ordered = [...this.altarTiles].sort((left, right) => |
| 2504 | Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY)) |
| 2505 | - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY)) |
| 2506 | ); |
| 2507 | for (const altar of ordered) |
| 2508 | { |
| 2509 | const adjacent = []; |
| 2510 | for (let dy = -1; dy <= 1; dy++) |
| 2511 | { |
| 2512 | for (let dx = -1; dx <= 1; dx++) |
| 2513 | { |
| 2514 | if (dx === 0 && dy === 0) |
| 2515 | { continue; } |
| 2516 | adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy, dimensionId }); |
| 2517 | } |
| 2518 | } |
| 2519 | adjacent.sort((left, right) => |
| 2520 | Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY)) |
| 2521 | - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY)) |
| 2522 | ); |
| 2523 | const tile = adjacent.find((entry) => |
| 2524 | this.isEnterable(entry.tileX, entry.tileY, dimensionId) |
| 2525 | && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId) |
| 2526 | ); |
| 2527 | if (tile) |
| 2528 | { return tile; } |
| 2529 | } |
| 2530 | for (let radius = 0; radius <= 24; radius++) |
| 2531 | { |
| 2532 | for (let dy = -radius; dy <= radius; dy++) |
| 2533 | { |
| 2534 | for (let dx = -radius; dx <= radius; dx++) |
| 2535 | { |
| 2536 | if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius) |
| 2537 | { continue; } |
| 2538 | const tileX = originX + dx; |
| 2539 | const tileY = originY + dy; |
| 2540 | if (this.isEnterable(tileX, tileY, dimensionId) |
| 2541 | && !this.#occupiedByOther(tileX, tileY, entityId, dimensionId)) |
| 2542 | { return { tileX, tileY, dimensionId }; } |
| 2543 | } |
| 2544 | } |
| 2545 | } |
| 2546 | return this.findOpenSpawn(); |
| 2547 | } |
| 2548 | |
| 2549 | #occupiedByOther (tileX, tileY, entityId, dimensionId = OVERWORLD_ID) |
| 2550 | { |
| 2551 | const dim = normalizeDimensionId(dimensionId); |
| 2552 | for (const record of this.directory.values()) |
| 2553 | { |
| 2554 | const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); |
| 2555 | if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY && recordDim === dim) |
| 2556 | { return true; } |
| 2557 | } |
| 2558 | return false; |
| 2559 | } |
| 2560 | |
| 2561 | #recalculateActivation (now) |
| 2562 | { |
| 2563 | const loaders = this.#allLoaders(); |
| 2564 | const { chunkSim, regionRes } = accumulateLoaderRefs(loaders); |
| 2565 | |
| 2566 | for (const [key, count] of regionRes) |
| 2567 | { |
| 2568 | if (count <= 0) |
| 2569 | { continue; } |
| 2570 | const { regionX, regionY, dimensionId } = parseRegionKey(key); |
| 2571 | this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY, dimensionId), dimensionId); |
| 2572 | this.regionGraceUntil.delete(key); |
| 2573 | } |
| 2574 | |
| 2575 | for (const [key] of [...this.regionOwner.entries()]) |
| 2576 | { |
| 2577 | if ((regionRes.get(key) ?? 0) > 0) |
| 2578 | { continue; } |
| 2579 | if (!this.regionGraceUntil.has(key)) |
| 2580 | { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); } |
| 2581 | if (now >= this.regionGraceUntil.get(key)) |
| 2582 | { |
| 2583 | const { regionX, regionY, dimensionId } = parseRegionKey(key); |
| 2584 | this.#unloadRegion(regionX, regionY, dimensionId); |
| 2585 | } |
| 2586 | } |
| 2587 | |
| 2588 | for (const [workerId, worker] of this.workers.entries()) |
| 2589 | { |
| 2590 | const chunkKeys = []; |
| 2591 | for (const [key, count] of chunkSim) |
| 2592 | { |
| 2593 | if (count <= 0) |
| 2594 | { continue; } |
| 2595 | const { chunkX, chunkY, dimensionId } = parseChunkKey(key); |
| 2596 | if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dimensionId)) === workerId) |
| 2597 | { chunkKeys.push(key); } |
| 2598 | } |
| 2599 | worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys }); |
| 2600 | } |
| 2601 | this.#syncAllReplicas(); |
| 2602 | |
| 2603 | const nextSimulating = new Set(); |
| 2604 | for (const [key, count] of chunkSim) |
| 2605 | { |
| 2606 | if (count > 0) |
| 2607 | { nextSimulating.add(key); } |
| 2608 | } |
| 2609 | let preheated = false; |
| 2610 | for (const key of nextSimulating) |
| 2611 | { |
| 2612 | if (!this.simulatingChunkKeys.has(key)) |
| 2613 | { |
| 2614 | preheated = true; |
| 2615 | break; |
| 2616 | } |
| 2617 | } |
| 2618 | this.simulatingChunkKeys = nextSimulating; |
| 2619 | if (preheated) |
| 2620 | { this.#stepSpawners(); } |
| 2621 | } |
| 2622 | |
| 2623 | #ensureCoverage (tileX, tileY, loader, dimensionId = OVERWORLD_ID) |
| 2624 | { |
| 2625 | const dim = normalizeDimensionId(dimensionId); |
| 2626 | const coverage = loaderCoverage(tileX, tileY, loader, dim); |
| 2627 | let preferred = this.#ownerOfTile(tileX, tileY, dim); |
| 2628 | for (const region of coverage.residentRegions) |
| 2629 | { |
| 2630 | const owner = this.#ensureRegion(region.regionX, region.regionY, preferred, dim); |
| 2631 | if (preferred == null) |
| 2632 | { preferred = owner; } |
| 2633 | } |
| 2634 | } |
| 2635 | |
| 2636 | #ensureRegion (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID) |
| 2637 | { |
| 2638 | const dim = normalizeDimensionId(dimensionId); |
| 2639 | const key = regionKey(regionX, regionY, dim); |
| 2640 | if (this.regionOwner.has(key)) |
| 2641 | { return this.regionOwner.get(key); } |
| 2642 | const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId, dim); |
| 2643 | this.workers[workerId].call({ |
| 2644 | type: WorkerMessage.assignRegion, |
| 2645 | regionX, |
| 2646 | regionY, |
| 2647 | dimensionId: dim, |
| 2648 | chunks: this.#regionChunkBlobs(regionX, regionY, dim) |
| 2649 | }); |
| 2650 | this.regionOwner.set(key, workerId); |
| 2651 | this.#restorePersistent(regionX, regionY, workerId); |
| 2652 | this.#restoreGroundItems(regionX, regionY, workerId); |
| 2653 | return workerId; |
| 2654 | } |
| 2655 | |
| 2656 | #unloadRegion (regionX, regionY, dimensionId = OVERWORLD_ID) |
| 2657 | { |
| 2658 | const dim = normalizeDimensionId(dimensionId); |
| 2659 | const key = regionKey(regionX, regionY, dim); |
| 2660 | const workerId = this.regionOwner.get(key); |
| 2661 | if (workerId == null) |
| 2662 | { return; } |
| 2663 | const bounds = regionTileBounds(regionX, regionY); |
| 2664 | const { dropped, groundItems } = this.workers[workerId].call({ |
| 2665 | type: WorkerMessage.dropRegion, |
| 2666 | regionX, |
| 2667 | regionY, |
| 2668 | dimensionId: dim |
| 2669 | }); |
| 2670 | const persistent = []; |
| 2671 | for (const record of dropped ?? []) |
| 2672 | { |
| 2673 | if (record.characterId) |
| 2674 | { |
| 2675 | this.stateDb.saveCharacterPosition( |
| 2676 | record.characterId, |
| 2677 | record.tileX, |
| 2678 | record.tileY, |
| 2679 | record.gait ?? GAIT.walk, |
| 2680 | record.dimensionId ?? OVERWORLD_ID |
| 2681 | ); |
| 2682 | } |
| 2683 | if (record.persistent) |
| 2684 | { persistent.push(record); } |
| 2685 | this.#forget(record.entityId); |
| 2686 | } |
| 2687 | this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent); |
| 2688 | for (const item of groundItems ?? []) |
| 2689 | { this.stateDb.upsertGroundItem(item); } |
| 2690 | this.regionOwner.delete(key); |
| 2691 | this.regionGraceUntil.delete(key); |
| 2692 | } |
| 2693 | |
| 2694 | #restorePersistent (regionX, regionY, workerId) |
| 2695 | { |
| 2696 | const bounds = regionTileBounds(regionX, regionY); |
| 2697 | const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY); |
| 2698 | for (const row of rows) |
| 2699 | { |
| 2700 | if (this.directory.has(row.entity_id)) |
| 2701 | { continue; } |
| 2702 | const components = JSON.parse(row.components_blob); |
| 2703 | const view = this.workers[workerId].call({ |
| 2704 | type: WorkerMessage.spawn, |
| 2705 | entityId: row.entity_id, |
| 2706 | components |
| 2707 | }); |
| 2708 | this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1); |
| 2709 | this.#remember(view, workerId); |
| 2710 | } |
| 2711 | } |
| 2712 | |
| 2713 | #applyTransfers (requests) |
| 2714 | { |
| 2715 | const events = []; |
| 2716 | for (const request of requests) |
| 2717 | { |
| 2718 | const destWorkerId = this.#ensureRegion( |
| 2719 | request.toRegionX, |
| 2720 | request.toRegionY, |
| 2721 | request.fromWorkerId, |
| 2722 | request.dimensionId ?? OVERWORLD_ID |
| 2723 | ); |
| 2724 | if (destWorkerId === request.fromWorkerId) |
| 2725 | { |
| 2726 | this.workers[request.fromWorkerId].call({ |
| 2727 | type: WorkerMessage.abortTransfer, |
| 2728 | entityId: request.entityId |
| 2729 | }); |
| 2730 | continue; |
| 2731 | } |
| 2732 | let result; |
| 2733 | try |
| 2734 | { |
| 2735 | result = this.workers[destWorkerId].call({ |
| 2736 | type: WorkerMessage.applyTransfer, |
| 2737 | payload: request.payload, |
| 2738 | destTileX: request.destTileX, |
| 2739 | destTileY: request.destTileY, |
| 2740 | dimensionId: request.dimensionId ?? OVERWORLD_ID |
| 2741 | }); |
| 2742 | } |
| 2743 | catch |
| 2744 | { |
| 2745 | result = { accepted: false }; |
| 2746 | } |
| 2747 | if (!result?.accepted) |
| 2748 | { |
| 2749 | this.workers[request.fromWorkerId].call({ |
| 2750 | type: WorkerMessage.abortTransfer, |
| 2751 | entityId: request.entityId |
| 2752 | }); |
| 2753 | continue; |
| 2754 | } |
| 2755 | this.workers[request.fromWorkerId].call({ |
| 2756 | type: WorkerMessage.commitTransfer, |
| 2757 | entityId: request.entityId |
| 2758 | }); |
| 2759 | this.#remember(result.entity, destWorkerId); |
| 2760 | events.push({ |
| 2761 | type: "entity-move", |
| 2762 | entityId: request.entityId, |
| 2763 | fromTileX: request.fromTileX, |
| 2764 | fromTileY: request.fromTileY, |
| 2765 | fromDimensionId: request.fromDimensionId ?? request.payload?.components?.position?.dimensionId, |
| 2766 | tileX: result.entity.tileX, |
| 2767 | tileY: result.entity.tileY, |
| 2768 | dimensionId: result.entity.dimensionId ?? request.dimensionId ?? OVERWORLD_ID, |
| 2769 | gait: result.entity.gait |
| 2770 | }); |
| 2771 | } |
| 2772 | return events; |
| 2773 | } |
| 2774 | |
| 2775 | #syncAllReplicas () |
| 2776 | { |
| 2777 | for (const [workerId, worker] of this.workers.entries()) |
| 2778 | { |
| 2779 | const ownedKeys = new Set(); |
| 2780 | for (const [key, owner] of this.regionOwner) |
| 2781 | { |
| 2782 | if (owner !== workerId) |
| 2783 | { continue; } |
| 2784 | const { regionX, regionY, dimensionId } = parseRegionKey(key); |
| 2785 | for (const chunk of chunksInRegion(regionX, regionY)) |
| 2786 | { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY, dimensionId)); } |
| 2787 | } |
| 2788 | const replicas = []; |
| 2789 | for (const key of replicaNeededForOwnedChunks(ownedKeys)) |
| 2790 | { |
| 2791 | if (ownedKeys.has(key)) |
| 2792 | { continue; } |
| 2793 | const { chunkX, chunkY, dimensionId } = parseChunkKey(key); |
| 2794 | replicas.push({ |
| 2795 | chunkX, |
| 2796 | chunkY, |
| 2797 | dimensionId, |
| 2798 | data: this.#authoredChunk(chunkX, chunkY, dimensionId) |
| 2799 | }); |
| 2800 | } |
| 2801 | worker.call({ type: WorkerMessage.setReplicas, chunks: replicas }); |
| 2802 | } |
| 2803 | } |
| 2804 | |
| 2805 | #syncGhosts () |
| 2806 | { |
| 2807 | const entities = []; |
| 2808 | for (const worker of this.workers) |
| 2809 | { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); } |
| 2810 | for (const [workerId, worker] of this.workers.entries()) |
| 2811 | { |
| 2812 | const ghosts = entities.filter((entity) => |
| 2813 | { |
| 2814 | const dim = normalizeDimensionId(entity.dimensionId ?? OVERWORLD_ID); |
| 2815 | if (this.#ownerOfTile(entity.tileX, entity.tileY, dim) === workerId) |
| 2816 | { return false; } |
| 2817 | return this.#nearWorker(workerId, entity.tileX, entity.tileY, dim); |
| 2818 | }); |
| 2819 | worker.call({ type: WorkerMessage.setGhosts, ghosts }); |
| 2820 | } |
| 2821 | } |
| 2822 | |
| 2823 | #nearWorker (workerId, tileX, tileY, dimensionId = OVERWORLD_ID) |
| 2824 | { |
| 2825 | const dim = normalizeDimensionId(dimensionId); |
| 2826 | const chunkX = tileToChunk(tileX); |
| 2827 | const chunkY = tileToChunk(tileY); |
| 2828 | for (const [key, owner] of this.regionOwner) |
| 2829 | { |
| 2830 | if (owner !== workerId) |
| 2831 | { continue; } |
| 2832 | const { regionX, regionY, dimensionId: regionDim } = parseRegionKey(key); |
| 2833 | if (regionDim !== dim) |
| 2834 | { continue; } |
| 2835 | for (const chunk of chunksInRegion(regionX, regionY)) |
| 2836 | { |
| 2837 | if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2) |
| 2838 | { return true; } |
| 2839 | } |
| 2840 | } |
| 2841 | return false; |
| 2842 | } |
| 2843 | |
| 2844 | #allLoaders () |
| 2845 | { |
| 2846 | const loaders = []; |
| 2847 | for (const worker of this.workers) |
| 2848 | { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); } |
| 2849 | return loaders; |
| 2850 | } |
| 2851 | |
| 2852 | #preferredWorkerForRegion (loaders, regionX, regionY, dimensionId = OVERWORLD_ID) |
| 2853 | { |
| 2854 | const dim = normalizeDimensionId(dimensionId); |
| 2855 | const votes = new Map(); |
| 2856 | for (const loader of loaders) |
| 2857 | { |
| 2858 | const loaderDim = normalizeDimensionId(loader.dimensionId ?? OVERWORLD_ID); |
| 2859 | if (loaderDim !== dim) |
| 2860 | { continue; } |
| 2861 | const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader, dim); |
| 2862 | if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY)) |
| 2863 | { continue; } |
| 2864 | const record = this.directory.get(loader.entityId); |
| 2865 | if (record?.workerId == null) |
| 2866 | { continue; } |
| 2867 | votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1); |
| 2868 | } |
| 2869 | let best = null; |
| 2870 | let bestVotes = -1; |
| 2871 | for (const [workerId, count] of votes) |
| 2872 | { |
| 2873 | if (count > bestVotes) |
| 2874 | { |
| 2875 | best = workerId; |
| 2876 | bestVotes = count; |
| 2877 | } |
| 2878 | } |
| 2879 | return best; |
| 2880 | } |
| 2881 | |
| 2882 | #pickWorker (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID) |
| 2883 | { |
| 2884 | const dim = normalizeDimensionId(dimensionId); |
| 2885 | const pinned = this.pinRegion?.(regionX, regionY, dim); |
| 2886 | if (pinned != null) |
| 2887 | { return pinned; } |
| 2888 | |
| 2889 | const neighborOwners = []; |
| 2890 | for (let dy = -1; dy <= 1; dy++) |
| 2891 | { |
| 2892 | for (let dx = -1; dx <= 1; dx++) |
| 2893 | { |
| 2894 | if (dx === 0 && dy === 0) |
| 2895 | { continue; } |
| 2896 | const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy, dim)); |
| 2897 | if (owner != null) |
| 2898 | { neighborOwners.push(owner); } |
| 2899 | } |
| 2900 | } |
| 2901 | |
| 2902 | const scores = this.workers.map((_, workerId) => ({ |
| 2903 | workerId, |
| 2904 | neighbors: neighborOwners.filter((owner) => owner === workerId).length, |
| 2905 | load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length |
| 2906 | })); |
| 2907 | |
| 2908 | if (preferredWorkerId != null && scores[preferredWorkerId]) |
| 2909 | { |
| 2910 | const preferred = scores[preferredWorkerId]; |
| 2911 | if (preferred.neighbors > 0 || neighborOwners.length === 0) |
| 2912 | { return preferredWorkerId; } |
| 2913 | } |
| 2914 | |
| 2915 | scores.sort((left, right) => |
| 2916 | right.neighbors - left.neighbors |
| 2917 | || left.load - right.load |
| 2918 | || left.workerId - right.workerId |
| 2919 | ); |
| 2920 | return scores[0].workerId; |
| 2921 | } |
| 2922 | |
| 2923 | #ownerOfTile (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 2924 | { |
| 2925 | return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY), dimensionId)) ?? null; |
| 2926 | } |
| 2927 | |
| 2928 | #regionKeyForChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID) |
| 2929 | { |
| 2930 | return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY), dimensionId); |
| 2931 | } |
| 2932 | |
| 2933 | #regionChunkBlobs (regionX, regionY, dimensionId = OVERWORLD_ID) |
| 2934 | { |
| 2935 | const dim = normalizeDimensionId(dimensionId); |
| 2936 | return chunksInRegion(regionX, regionY).map((coord) => ({ |
| 2937 | chunkX: coord.chunkX, |
| 2938 | chunkY: coord.chunkY, |
| 2939 | dimensionId: dim, |
| 2940 | data: this.#authoredChunk(coord.chunkX, coord.chunkY, dim) |
| 2941 | })); |
| 2942 | } |
| 2943 | |
| 2944 | #authoredChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID) |
| 2945 | { |
| 2946 | const dim = normalizeDimensionId(dimensionId); |
| 2947 | const key = chunkKey(chunkX, chunkY, dim); |
| 2948 | if (this.authoredCache.has(key)) |
| 2949 | { return this.authoredCache.get(key); } |
| 2950 | const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId, dim); |
| 2951 | const dimRecord = this.getDimensionRecord(dim); |
| 2952 | const defaultGroundTypeId = dimRecord?.defaultGroundTypeId ?? this.settings.defaultGroundTypeId; |
| 2953 | const data = row |
| 2954 | ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY) |
| 2955 | : createEmptyChunkData(defaultGroundTypeId); |
| 2956 | this.authoredCache.set(key, data); |
| 2957 | return data; |
| 2958 | } |
| 2959 | |
| 2960 | #syntheticSnapshot (chunkX, chunkY, dimensionId = OVERWORLD_ID) |
| 2961 | { |
| 2962 | const dim = normalizeDimensionId(dimensionId); |
| 2963 | const data = this.#authoredChunk(chunkX, chunkY, dim); |
| 2964 | return { |
| 2965 | chunkX, |
| 2966 | chunkY, |
| 2967 | dimensionId: dim, |
| 2968 | open: data.open, |
| 2969 | closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y, dim).open), |
| 2970 | grounds: data.grounds, |
| 2971 | blocks: data.blocks, |
| 2972 | light: data.light, |
| 2973 | entities: [], |
| 2974 | groundItems: [] |
| 2975 | }; |
| 2976 | } |
| 2977 | |
| 2978 | #occupiedTile (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 2979 | { |
| 2980 | const dim = normalizeDimensionId(dimensionId); |
| 2981 | for (const record of this.directory.values()) |
| 2982 | { |
| 2983 | const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); |
| 2984 | if (record.tileX === tileX && record.tileY === tileY && recordDim === dim) |
| 2985 | { return record.entityId; } |
| 2986 | } |
| 2987 | return null; |
| 2988 | } |
| 2989 | |
| 2990 | #queueReplication (event) |
| 2991 | { |
| 2992 | if (event) |
| 2993 | { this.replication.push(event); } |
| 2994 | } |
| 2995 | |
| 2996 | #stepSpawners () |
| 2997 | { |
| 2998 | const events = []; |
| 2999 | for (const worker of this.workers) |
| 3000 | { |
| 3001 | const result = worker.call({ type: WorkerMessage.stepSpawners }); |
| 3002 | for (const request of result?.spawnRequests ?? []) |
| 3003 | { |
| 3004 | try |
| 3005 | { |
| 3006 | this.spawnEntity(mobComponents(request), { requireResident: true }); |
| 3007 | } |
| 3008 | catch |
| 3009 | { continue; } |
| 3010 | } |
| 3011 | } |
| 3012 | return events; |
| 3013 | } |
| 3014 | |
| 3015 | #restoreGroundItems (regionX, regionY, workerId) |
| 3016 | { |
| 3017 | const bounds = regionTileBounds(regionX, regionY); |
| 3018 | const items = []; |
| 3019 | for (const item of this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)) |
| 3020 | { |
| 3021 | if (item.expiresAt > this.now) |
| 3022 | { |
| 3023 | items.push(item); |
| 3024 | continue; |
| 3025 | } |
| 3026 | // Expired while unloaded: destroy and free any cheque reservation. |
| 3027 | this.#destroyExpiredGroundItem(item); |
| 3028 | } |
| 3029 | this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId()); |
| 3030 | this.workers[workerId].call({ |
| 3031 | type: WorkerMessage.setGroundItems, |
| 3032 | regionX, |
| 3033 | regionY, |
| 3034 | items |
| 3035 | }); |
| 3036 | } |
| 3037 | |
| 3038 | /** Cheque paper that no longer exists must free reserved vault goods. */ |
| 3039 | voidFilledCheque (stack) |
| 3040 | { |
| 3041 | if ((stack?.itemId | 0) !== ItemId.filledCheque || stack?.instance?.kind !== "filled-cheque") |
| 3042 | { return { ok: false }; } |
| 3043 | const issuerId = stack.instance.issuerCharacterId | 0; |
| 3044 | const chequeId = stack.instance.chequeId; |
| 3045 | const release = this.releaseChequeReservation(issuerId, chequeId, stack.instance); |
| 3046 | if (!release?.ok || !release.stack) |
| 3047 | { |
| 3048 | // Already redeemed/voided — treat as success so despawn stays idempotent. |
| 3049 | return { ok: true, alreadyReleased: true }; |
| 3050 | } |
| 3051 | const onlineId = this.characterEntities.get(issuerId); |
| 3052 | const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerId); |
| 3053 | if (!bag) |
| 3054 | { return { ok: false, error: "Issuer vault not found." }; } |
| 3055 | const goodsDef = itemDefinition(release.stack.itemId); |
| 3056 | if (!goodsDef) |
| 3057 | { return { ok: false, error: "Unknown reserved goods." }; } |
| 3058 | const goods = attachOrigins({ |
| 3059 | itemId: release.stack.itemId, |
| 3060 | quantity: release.stack.quantity, |
| 3061 | instance: release.stack.instance ? structuredClone(release.stack.instance) : null, |
| 3062 | origins: release.stack.origins |
| 3063 | }); |
| 3064 | const inserted = insertStackGrowable(bag.vault ?? [], goods, goodsDef); |
| 3065 | bag.vault = inserted.slots; |
| 3066 | this.stateDb.saveBag(issuerId, bag); |
| 3067 | if (onlineId) |
| 3068 | { |
| 3069 | this.applyBag(onlineId, bag); |
| 3070 | this.pushInventory(issuerId, bag); |
| 3071 | } |
| 3072 | this.pendingPrivate.push({ |
| 3073 | type: "toast", |
| 3074 | characterId: issuerId, |
| 3075 | message: "An uncashed cheque expired. Reserved goods returned to your vault." |
| 3076 | }); |
| 3077 | return { ok: true }; |
| 3078 | } |
| 3079 | |
| 3080 | #destroyExpiredGroundItem (item) |
| 3081 | { |
| 3082 | if (item?.stack?.itemId === ItemId.filledCheque && item.stack?.instance?.kind === "filled-cheque") |
| 3083 | { this.voidFilledCheque(item.stack); } |
| 3084 | this.stateDb.deleteGroundItem(item.groundItemId); |
| 3085 | } |
| 3086 | |
| 3087 | #persistGroundEvent (event) |
| 3088 | { |
| 3089 | if (event.type === "ground-item-appear") |
| 3090 | { |
| 3091 | this.stateDb.upsertGroundItem({ |
| 3092 | groundItemId: event.groundItemId, |
| 3093 | tileX: event.tileX, |
| 3094 | tileY: event.tileY, |
| 3095 | stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity }, |
| 3096 | droppedAt: event.droppedAt ?? this.now, |
| 3097 | expiresAt: event.expiresAt, |
| 3098 | source: event.source ?? "player-drop", |
| 3099 | droppedByCharacterId: event.droppedByCharacterId ?? null |
| 3100 | }); |
| 3101 | } |
| 3102 | if (event.type === "ground-item-despawn") |
| 3103 | { this.stateDb.deleteGroundItem(event.groundItemId); } |
| 3104 | } |
| 3105 | |
| 3106 | #saveBag (entityId, workerId) |
| 3107 | { |
| 3108 | const record = this.directory.get(entityId); |
| 3109 | const bag = this.workers[workerId].call({ |
| 3110 | type: WorkerMessage.inspectBag, |
| 3111 | entityId |
| 3112 | }); |
| 3113 | if (!bag || !record?.characterId) |
| 3114 | { return; } |
| 3115 | this.#saveBagFromView(record.characterId, bag); |
| 3116 | const skills = this.workers[workerId].call({ |
| 3117 | type: WorkerMessage.inspectSkills, |
| 3118 | entityId |
| 3119 | }); |
| 3120 | if (skills) |
| 3121 | { this.stateDb.saveSkills(record.characterId, skills); } |
| 3122 | } |
| 3123 | |
| 3124 | #applySkillsUpdated (event) |
| 3125 | { |
| 3126 | if (!event?.characterId || !event.stored) |
| 3127 | { return; } |
| 3128 | this.stateDb.saveSkills(event.characterId, { xp: event.stored }); |
| 3129 | this.pushSkills(event.characterId, event.skills ?? [], event.combatLevel ?? 0); |
| 3130 | } |
| 3131 | |
| 3132 | #applySpellsUpdated (event) |
| 3133 | { |
| 3134 | if (!event?.characterId || !event.stored) |
| 3135 | { return; } |
| 3136 | this.stateDb.saveSpells(event.characterId, event.stored); |
| 3137 | this.pushSpells(event.characterId, { |
| 3138 | spells: event.spells ?? [], |
| 3139 | favorites: event.favorites ?? [], |
| 3140 | autoCast: !!event.autoCast |
| 3141 | }); |
| 3142 | } |
| 3143 | |
| 3144 | #applySummonEntity (event) |
| 3145 | { |
| 3146 | const isFairy = event.mobTypeId === MobId.fairy || event.mobTypeId === "fairy"; |
| 3147 | const components = isFairy |
| 3148 | ? jadeiteFairyComponents({ |
| 3149 | tileX: event.tileX | 0, |
| 3150 | tileY: event.tileY | 0, |
| 3151 | level: event.level | 0 || 1, |
| 3152 | ownerEntityId: event.ownerEntityId, |
| 3153 | ownerCharacterId: event.ownerCharacterId ?? null, |
| 3154 | ownerName: event.ownerName, |
| 3155 | dimensionId: event.dimensionId |
| 3156 | }) |
| 3157 | : shadeSummonComponents({ |
| 3158 | tileX: event.tileX | 0, |
| 3159 | tileY: event.tileY | 0, |
| 3160 | level: event.level | 0 || 1, |
| 3161 | ownerEntityId: event.ownerEntityId, |
| 3162 | expiresAt: event.expiresAt, |
| 3163 | dimensionId: event.dimensionId |
| 3164 | }); |
| 3165 | try |
| 3166 | { |
| 3167 | const entityId = this.spawnEntity(components, { requireResident: true }); |
| 3168 | if (entityId == null) |
| 3169 | { return []; } |
| 3170 | return []; |
| 3171 | } |
| 3172 | catch |
| 3173 | { |
| 3174 | return []; |
| 3175 | } |
| 3176 | } |
| 3177 | |
| 3178 | #applyJewelryTeleport (event) |
| 3179 | { |
| 3180 | const entityId = event.entityId ?? this.characterEntities.get(event.characterId); |
| 3181 | const record = entityId ? this.directory.get(entityId) : null; |
| 3182 | if (!record) |
| 3183 | { return []; } |
| 3184 | const destination = this.#findJewelryTeleportDestination( |
| 3185 | event.fromTileX | 0, |
| 3186 | event.fromTileY | 0, |
| 3187 | entityId, |
| 3188 | event.destination |
| 3189 | ); |
| 3190 | if (!destination) |
| 3191 | { |
| 3192 | return [{ |
| 3193 | type: "command-error", |
| 3194 | sessionId: event.sessionId, |
| 3195 | message: event.destination === "bank" |
| 3196 | ? "No bank is available." |
| 3197 | : "No church altar is available." |
| 3198 | }]; |
| 3199 | } |
| 3200 | const loader = { ...DEFAULT_CHUNK_LOADER }; |
| 3201 | this.#ensureCoverage( |
| 3202 | destination.tileX, |
| 3203 | destination.tileY, |
| 3204 | loader, |
| 3205 | destination.dimensionId ?? OVERWORLD_ID |
| 3206 | ); |
| 3207 | const result = this.workers[record.workerId].call({ |
| 3208 | type: WorkerMessage.relocateEntity, |
| 3209 | entityId, |
| 3210 | tileX: destination.tileX, |
| 3211 | tileY: destination.tileY, |
| 3212 | dimensionId: destination.dimensionId ?? OVERWORLD_ID |
| 3213 | }); |
| 3214 | if (!result?.accepted) |
| 3215 | { |
| 3216 | return [{ |
| 3217 | type: "command-error", |
| 3218 | sessionId: event.sessionId, |
| 3219 | message: "The destination is no longer available." |
| 3220 | }]; |
| 3221 | } |
| 3222 | const events = []; |
| 3223 | if (result.transferRequest) |
| 3224 | { events.push(...this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }])); } |
| 3225 | else if (result.event) |
| 3226 | { |
| 3227 | this.#applyMoveToDirectory(result.event); |
| 3228 | events.push(result.event); |
| 3229 | const view = this.workers[record.workerId].call({ |
| 3230 | type: WorkerMessage.inspect, |
| 3231 | entityId |
| 3232 | }); |
| 3233 | if (view) |
| 3234 | { this.#remember(view, record.workerId); } |
| 3235 | } |
| 3236 | return events; |
| 3237 | } |
| 3238 | |
| 3239 | #findJewelryTeleportDestination (originX, originY, entityId, destination) |
| 3240 | { |
| 3241 | if (destination === "church") |
| 3242 | { return this.#findRespawnDestination(originX, originY, entityId); } |
| 3243 | if (destination !== "bank") |
| 3244 | { return null; } |
| 3245 | const record = this.directory.get(entityId); |
| 3246 | const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID); |
| 3247 | const bank = this.courier?.nearestBank(originX, originY); |
| 3248 | if (!bank) |
| 3249 | { return null; } |
| 3250 | const adjacent = []; |
| 3251 | for (let dy = -1; dy <= 1; dy++) |
| 3252 | { |
| 3253 | for (let dx = -1; dx <= 1; dx++) |
| 3254 | { |
| 3255 | if (dx === 0 && dy === 0) |
| 3256 | { continue; } |
| 3257 | adjacent.push({ |
| 3258 | tileX: bank.tileX + dx, |
| 3259 | tileY: bank.tileY + dy, |
| 3260 | dimensionId |
| 3261 | }); |
| 3262 | } |
| 3263 | } |
| 3264 | adjacent.sort((left, right) => |
| 3265 | Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY)) |
| 3266 | - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY)) |
| 3267 | ); |
| 3268 | const tile = adjacent.find((entry) => |
| 3269 | this.isEnterable(entry.tileX, entry.tileY, dimensionId) |
| 3270 | && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId) |
| 3271 | ); |
| 3272 | return tile ?? null; |
| 3273 | } |
| 3274 | |
| 3275 | #skillLevelUpEvents (event) |
| 3276 | { |
| 3277 | const levelUps = event?.levelUps ?? []; |
| 3278 | if (!levelUps.length) |
| 3279 | { return []; } |
| 3280 | const entityId = event.entityId ?? this.characterEntities.get(event.characterId); |
| 3281 | if (entityId == null) |
| 3282 | { return []; } |
| 3283 | const record = this.directory.get(entityId); |
| 3284 | const tileX = record?.tileX ?? 0; |
| 3285 | const tileY = record?.tileY ?? 0; |
| 3286 | return levelUps.map((levelUp) => ({ |
| 3287 | type: "skill-level-up", |
| 3288 | entityId, |
| 3289 | characterId: event.characterId, |
| 3290 | tileX, |
| 3291 | tileY, |
| 3292 | skillId: levelUp.skillId, |
| 3293 | level: levelUp.level, |
| 3294 | previousLevel: levelUp.previousLevel, |
| 3295 | displayName: levelUp.displayName, |
| 3296 | icon: levelUp.icon |
| 3297 | })); |
| 3298 | } |
| 3299 | |
| 3300 | #saveBagFromView (characterId, bag) |
| 3301 | { |
| 3302 | this.stateDb.saveBag(characterId, { |
| 3303 | inventory: bag.inventory, |
| 3304 | equipment: bag.equipment, |
| 3305 | vault: bag.vault, |
| 3306 | vaultReserved: bag.vaultReserved |
| 3307 | }); |
| 3308 | } |
| 3309 | |
| 3310 | releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null) |
| 3311 | { |
| 3312 | const onlineId = this.characterEntities.get(issuerCharacterId); |
| 3313 | const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId); |
| 3314 | if (!bag) |
| 3315 | { return { ok: false, error: "Issuer vault not found." }; } |
| 3316 | const reserved = [...(bag.vaultReserved ?? [])]; |
| 3317 | const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId }); |
| 3318 | if (index < 0) |
| 3319 | { return { ok: false, error: "That cheque cannot be redeemed." }; } |
| 3320 | const [stack] = reserved.splice(index, 1); |
| 3321 | bag.vaultReserved = reserved; |
| 3322 | this.stateDb.saveBag(issuerCharacterId, bag); |
| 3323 | if (onlineId) |
| 3324 | { |
| 3325 | this.applyBag(onlineId, bag); |
| 3326 | this.pushInventory(issuerCharacterId, bag); |
| 3327 | } |
| 3328 | return { ok: true, stack }; |
| 3329 | } |
| 3330 | |
| 3331 | restoreChequeReservation (issuerCharacterId, stack) |
| 3332 | { |
| 3333 | const onlineId = this.characterEntities.get(issuerCharacterId); |
| 3334 | const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId); |
| 3335 | if (!bag) |
| 3336 | { return; } |
| 3337 | bag.vaultReserved = [...(bag.vaultReserved ?? []), stack]; |
| 3338 | this.stateDb.saveBag(issuerCharacterId, bag); |
| 3339 | if (onlineId) |
| 3340 | { |
| 3341 | this.applyBag(onlineId, bag); |
| 3342 | this.pushInventory(issuerCharacterId, bag); |
| 3343 | } |
| 3344 | } |
| 3345 | |
| 3346 | #remember (view, workerId) |
| 3347 | { |
| 3348 | if (!view) |
| 3349 | { return; } |
| 3350 | const previous = this.directory.get(view.entityId); |
| 3351 | this.directory.set(view.entityId, { |
| 3352 | ...view, |
| 3353 | workerId, |
| 3354 | // Keep simulation-only fields that publicEntityView does not carry. |
| 3355 | skullValue: previous?.skullValue ?? view.skullValue ?? 0 |
| 3356 | }); |
| 3357 | if (view.characterId) |
| 3358 | { this.characterEntities.set(view.characterId, view.entityId); } |
| 3359 | } |
| 3360 | |
| 3361 | #applyMoveToDirectory (event) |
| 3362 | { |
| 3363 | const record = this.directory.get(event.entityId); |
| 3364 | if (!record) |
| 3365 | { return; } |
| 3366 | record.tileX = event.tileX; |
| 3367 | record.tileY = event.tileY; |
| 3368 | record.gait = event.gait; |
| 3369 | if (event.dimensionId != null) |
| 3370 | { record.dimensionId = normalizeDimensionId(event.dimensionId); } |
| 3371 | if (event.worldX != null) |
| 3372 | { record.worldX = event.worldX; } |
| 3373 | if (event.worldY != null) |
| 3374 | { record.worldY = event.worldY; } |
| 3375 | if (event.freeFlight != null) |
| 3376 | { record.freeFlight = !!event.freeFlight; } |
| 3377 | } |
| 3378 | |
| 3379 | #forget (entityId) |
| 3380 | { |
| 3381 | const record = this.directory.get(entityId); |
| 3382 | if (record?.characterId) |
| 3383 | { this.characterEntities.delete(record.characterId); } |
| 3384 | this.directory.delete(entityId); |
| 3385 | } |
| 3386 | } |