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