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