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