| 1 | import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js"; |
| 2 | import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js"; |
| 3 | import { itemSpriteName } from "/shared/definitions/items.js"; |
| 4 | import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js"; |
| 5 | import { |
| 6 | bakeChunkAtlases, |
| 7 | frameworkImageFromCanvas, |
| 8 | invalidateCanvasTexture |
| 9 | } from "./chunkBake.js"; |
| 10 | |
| 11 | const LAYER_GROUND = 0; |
| 12 | const LAYER_EDGE = 900000; |
| 13 | const SORT_BLOCK = 1; |
| 14 | const SORT_SHADE = 2; |
| 15 | const SORT_ENTITY = 3; |
| 16 | const SORT_SPRITE_SHADE = 4; |
| 17 | const RENDER_LAYER_BLOOM = "bloom"; |
| 18 | |
| 19 | export class WorldView |
| 20 | { |
| 21 | constructor (game, scene, catalog = { grounds: {}, blocks: {} }) |
| 22 | { |
| 23 | this.game = game; |
| 24 | this.scene = scene; |
| 25 | this.catalog = catalog; |
| 26 | this.preview = null; |
| 27 | this.zoom = 2; |
| 28 | this.chunks = new Map(); |
| 29 | this.bakedChunks = new Map(); |
| 30 | this.tiles = new Map(); |
| 31 | this.entities = new Map(); |
| 32 | this.groundItems = new Map(); |
| 33 | this.edges = new Map(); |
| 34 | this.localEntityId = null; |
| 35 | this.settings = { ...DEFAULT_WORLD_SETTINGS }; |
| 36 | this.worldHour = 12; |
| 37 | this.nightPreview = null; |
| 38 | this.followPlayer = true; |
| 39 | this.dynamicLights = []; |
| 40 | this.swipes = []; |
| 41 | this.#syncBloomLayer(); |
| 42 | } |
| 43 | |
| 44 | setSettings (settings) |
| 45 | { |
| 46 | this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings }; |
| 47 | this.#syncBloomLayer(); |
| 48 | } |
| 49 | |
| 50 | setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null) |
| 51 | { |
| 52 | this.localEntityId = entityId; |
| 53 | this.#upsertEntity({ |
| 54 | entityId, |
| 55 | characterId, |
| 56 | tileX, |
| 57 | tileY, |
| 58 | gait, |
| 59 | sex, |
| 60 | firstName, |
| 61 | lastName, |
| 62 | layers: layers ?? undefined |
| 63 | }); |
| 64 | } |
| 65 | |
| 66 | applySnapshot (snapshot) |
| 67 | { |
| 68 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 69 | this.chunks.set(key, snapshot); |
| 70 | this.#rebuildChunk(snapshot); |
| 71 | this.#redrawPreview(); |
| 72 | for (const entity of snapshot.entities ?? []) |
| 73 | { this.#upsertEntity(entity); } |
| 74 | const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 75 | for (const [id, item] of [...this.groundItems.entries()]) |
| 76 | { |
| 77 | if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY) |
| 78 | { this.despawnGroundItem(id); } |
| 79 | } |
| 80 | for (const item of snapshot.groundItems ?? []) |
| 81 | { this.upsertGroundItem(item); } |
| 82 | this.#rebuildAllEdges(); |
| 83 | } |
| 84 | |
| 85 | removeChunk (chunkX, chunkY) |
| 86 | { |
| 87 | const key = `${chunkX},${chunkY}`; |
| 88 | this.chunks.delete(key); |
| 89 | this.#destroyBakedChunk(key); |
| 90 | this.#destroyEdges(key); |
| 91 | for (const [tileKey, objects] of [...this.tiles.entries()]) |
| 92 | { |
| 93 | if (objects.chunkX === chunkX && objects.chunkY === chunkY) |
| 94 | { |
| 95 | objects.block?.destroy(); |
| 96 | objects.blockBloom?.destroy(); |
| 97 | objects.spriteShade?.destroy(); |
| 98 | objects.shade?.destroy(); |
| 99 | this.tiles.delete(tileKey); |
| 100 | } |
| 101 | } |
| 102 | for (const [id, item] of [...this.groundItems.entries()]) |
| 103 | { |
| 104 | if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) |
| 105 | { this.despawnGroundItem(id); } |
| 106 | } |
| 107 | this.#rebuildAllEdges(); |
| 108 | } |
| 109 | |
| 110 | setChunkOpen (chunkX, chunkY, open) |
| 111 | { |
| 112 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 113 | if (!snapshot) |
| 114 | { return; } |
| 115 | snapshot.open = !!open; |
| 116 | this.#rebuildAllEdges(); |
| 117 | } |
| 118 | |
| 119 | spawnEntity (payload) |
| 120 | { |
| 121 | this.#upsertEntity(payload); |
| 122 | } |
| 123 | |
| 124 | moveEntity (payload) |
| 125 | { |
| 126 | const existing = this.entities.get(payload.entityId); |
| 127 | if (!existing) |
| 128 | { |
| 129 | this.#upsertEntity(payload); |
| 130 | return; |
| 131 | } |
| 132 | const size = this.tileSize(); |
| 133 | existing.fromX = existing.visualX; |
| 134 | existing.fromY = existing.visualY; |
| 135 | existing.tileX = payload.tileX; |
| 136 | existing.tileY = payload.tileY; |
| 137 | existing.gait = payload.gait; |
| 138 | existing.freeFlight = !!payload.freeFlight || existing.freeFlight; |
| 139 | if (payload.worldX != null && payload.worldY != null) |
| 140 | { |
| 141 | existing.worldX = payload.worldX; |
| 142 | existing.worldY = payload.worldY; |
| 143 | existing.targetX = payload.worldX * size; |
| 144 | existing.targetY = payload.worldY * size; |
| 145 | } |
| 146 | else |
| 147 | { |
| 148 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 149 | existing.targetX = pivot.x; |
| 150 | existing.targetY = pivot.y; |
| 151 | } |
| 152 | existing.lerpStarted = performance.now(); |
| 153 | existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait); |
| 154 | } |
| 155 | |
| 156 | despawnEntity (entityId) |
| 157 | { |
| 158 | const existing = this.entities.get(entityId); |
| 159 | if (!existing) |
| 160 | { return; } |
| 161 | existing.object?.destroy(); |
| 162 | existing.spriteShade?.destroy(); |
| 163 | for (const overlay of existing.overlays ?? []) |
| 164 | { overlay.destroy(); } |
| 165 | for (const overlay of existing.bloomOverlays ?? []) |
| 166 | { overlay.destroy(); } |
| 167 | this.entities.delete(entityId); |
| 168 | } |
| 169 | |
| 170 | setAppearance (payload) |
| 171 | { |
| 172 | const existing = this.entities.get(payload.entityId); |
| 173 | if (!existing) |
| 174 | { return; } |
| 175 | this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]); |
| 176 | this.#placeEntity(existing); |
| 177 | } |
| 178 | |
| 179 | upsertGroundItem (payload) |
| 180 | { |
| 181 | const size = this.tileSize(); |
| 182 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 183 | let item = this.groundItems.get(payload.groundItemId); |
| 184 | if (!item) |
| 185 | { |
| 186 | const object = new GameObject(0, 0, this.game.images[payload.sprite] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK); |
| 187 | this.scene.addObject(object); |
| 188 | item = { object }; |
| 189 | this.groundItems.set(payload.groundItemId, item); |
| 190 | } |
| 191 | item.groundItemId = payload.groundItemId; |
| 192 | item.tileX = payload.tileX; |
| 193 | item.tileY = payload.tileY; |
| 194 | item.itemId = payload.itemId; |
| 195 | item.quantity = payload.quantity; |
| 196 | item.displayName = payload.displayName; |
| 197 | item.sprite = payload.sprite; |
| 198 | this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); |
| 199 | } |
| 200 | |
| 201 | despawnGroundItem (groundItemId) |
| 202 | { |
| 203 | const item = this.groundItems.get(groundItemId); |
| 204 | if (!item) |
| 205 | { return; } |
| 206 | item.object?.destroy(); |
| 207 | this.groundItems.delete(groundItemId); |
| 208 | } |
| 209 | |
| 210 | groundItemAtTile (tileX, tileY) |
| 211 | { |
| 212 | for (const item of this.groundItems.values()) |
| 213 | { |
| 214 | if (item.tileX === tileX && item.tileY === tileY) |
| 215 | { return item; } |
| 216 | } |
| 217 | return null; |
| 218 | } |
| 219 | |
| 220 | setZoom (zoom, limits = { min: 1, max: 4 }) |
| 221 | { |
| 222 | const min = limits.min ?? 1; |
| 223 | const max = limits.max ?? 4; |
| 224 | this.zoom = Math.min(max, Math.max(min, zoom)); |
| 225 | for (const snapshot of this.chunks.values()) |
| 226 | { |
| 227 | this.#layoutBakedChunk(snapshot); |
| 228 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 229 | { |
| 230 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 231 | { this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); } |
| 232 | } |
| 233 | } |
| 234 | const size = this.tileSize(); |
| 235 | for (const entity of this.entities.values()) |
| 236 | { |
| 237 | entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x; |
| 238 | entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y; |
| 239 | entity.fromX = entity.visualX; |
| 240 | entity.fromY = entity.visualY; |
| 241 | entity.targetX = entity.visualX; |
| 242 | entity.targetY = entity.visualY; |
| 243 | entity.lerpStarted = null; |
| 244 | this.#placeEntity(entity); |
| 245 | } |
| 246 | for (const item of this.groundItems.values()) |
| 247 | { |
| 248 | const pivot = tilePivot(item.tileX, item.tileY, size); |
| 249 | this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); |
| 250 | } |
| 251 | this.#rebuildAllEdges(); |
| 252 | this.#redrawPreview(); |
| 253 | } |
| 254 | |
| 255 | tileSize () |
| 256 | { |
| 257 | return SPRITE_SIZE_PX * this.zoom; |
| 258 | } |
| 259 | |
| 260 | screenToTile (mouseX, mouseY) |
| 261 | { |
| 262 | const size = this.tileSize(); |
| 263 | const worldX = mouseX - this.scene.cameraPosition.x; |
| 264 | const worldY = mouseY - this.scene.cameraPosition.y; |
| 265 | return { |
| 266 | tileX: Math.floor(worldX / size), |
| 267 | tileY: Math.floor(worldY / size) |
| 268 | }; |
| 269 | } |
| 270 | |
| 271 | entityAtScreen (mouseX, mouseY) |
| 272 | { |
| 273 | let best = null; |
| 274 | let bestLayer = -Infinity; |
| 275 | for (const entity of this.entities.values()) |
| 276 | { |
| 277 | const box = this.#entityScreenBox(entity); |
| 278 | if (!box) |
| 279 | { continue; } |
| 280 | if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom) |
| 281 | { |
| 282 | const layer = entity.object?.layer ?? 0; |
| 283 | if (layer >= bestLayer) |
| 284 | { |
| 285 | best = entity; |
| 286 | bestLayer = layer; |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | return best; |
| 291 | } |
| 292 | |
| 293 | nametagAnchor (entity) |
| 294 | { |
| 295 | const box = this.#entityScreenBox(entity); |
| 296 | if (!box) |
| 297 | { return null; } |
| 298 | return { x: (box.left + box.right) / 2, y: box.top }; |
| 299 | } |
| 300 | |
| 301 | #entityScreenBox (entity) |
| 302 | { |
| 303 | const object = entity?.object; |
| 304 | if (!object) |
| 305 | { return null; } |
| 306 | const size = object.transform.size; |
| 307 | const x = object.transform.position.x + this.scene.cameraPosition.x; |
| 308 | const y = object.transform.position.y + this.scene.cameraPosition.y; |
| 309 | return { |
| 310 | left: x - size.x / 2, |
| 311 | right: x + size.x / 2, |
| 312 | top: y - size.y / 2, |
| 313 | bottom: y + size.y / 2 |
| 314 | }; |
| 315 | } |
| 316 | |
| 317 | update (deltaTime) |
| 318 | { |
| 319 | const now = performance.now(); |
| 320 | const size = this.tileSize(); |
| 321 | for (const entity of this.entities.values()) |
| 322 | { |
| 323 | const target = entity.targetX != null && entity.targetY != null |
| 324 | ? { x: entity.targetX, y: entity.targetY } |
| 325 | : tilePivot(entity.tileX, entity.tileY, size); |
| 326 | if (entity.lerpStarted != null) |
| 327 | { |
| 328 | const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs)); |
| 329 | entity.visualX = entity.fromX + (target.x - entity.fromX) * t; |
| 330 | entity.visualY = entity.fromY + (target.y - entity.fromY) * t; |
| 331 | if (t >= 1) |
| 332 | { entity.lerpStarted = null; } |
| 333 | } |
| 334 | else |
| 335 | { |
| 336 | entity.visualX = target.x; |
| 337 | entity.visualY = target.y; |
| 338 | } |
| 339 | this.#placeEntity(entity); |
| 340 | } |
| 341 | |
| 342 | this.#updateSwipes(now); |
| 343 | this.#centerCamera(); |
| 344 | this.#updateShade(deltaTime); |
| 345 | } |
| 346 | |
| 347 | spawnCombatSwing (payload) |
| 348 | { |
| 349 | const attacker = this.entities.get(payload.attackerId); |
| 350 | const target = this.entities.get(payload.targetId); |
| 351 | if (!attacker || !target) |
| 352 | { return; } |
| 353 | const midX = (attacker.visualX + target.visualX) / 2; |
| 354 | const midY = (attacker.visualY + target.visualY) / 2; |
| 355 | const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI); |
| 356 | const spriteName = "fx:melee-swipe:melee-swipe"; |
| 357 | const object = new GameObject(midX, midY, this.game.images[spriteName], SORT_ENTITY + 1); |
| 358 | if (object.transform) |
| 359 | { object.transform.rotation = angle; } |
| 360 | this.scene.addObject(object); |
| 361 | this.swipes.push({ object, until: performance.now() + 500 }); |
| 362 | this.addDynamicLight({ |
| 363 | worldX: (attacker.tileX + target.tileX) / 2 + 0.5, |
| 364 | worldY: (attacker.tileY + target.tileY) / 2 + 0.5, |
| 365 | radiusTiles: 2.5, |
| 366 | intensity: 0.55, |
| 367 | durationMs: 220 |
| 368 | }); |
| 369 | } |
| 370 | |
| 371 | addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 }) |
| 372 | { |
| 373 | this.dynamicLights.push({ |
| 374 | worldX, |
| 375 | worldY, |
| 376 | radiusTiles, |
| 377 | intensity, |
| 378 | until: performance.now() + durationMs |
| 379 | }); |
| 380 | } |
| 381 | |
| 382 | updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {}) |
| 383 | { |
| 384 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 385 | if (!snapshot) |
| 386 | { return; } |
| 387 | const index = localY * CHUNK_SIZE + localX; |
| 388 | if (ground !== undefined) |
| 389 | { snapshot.grounds[index] = ground; } |
| 390 | if (block !== undefined) |
| 391 | { snapshot.blocks[index] = block; } |
| 392 | if (light !== undefined) |
| 393 | { snapshot.light[index] = light; } |
| 394 | this.#rebuildChunk(snapshot); |
| 395 | } |
| 396 | |
| 397 | setTilePreview (tileX, tileY, override) |
| 398 | { |
| 399 | const previous = this.preview; |
| 400 | this.preview = { tileX, tileY, ...override }; |
| 401 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 402 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 403 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 404 | if (snapshot) |
| 405 | { this.#rebuildChunk(snapshot); } |
| 406 | if (previous && (previous.tileX !== tileX || previous.tileY !== tileY)) |
| 407 | { |
| 408 | const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`); |
| 409 | if (prevSnapshot && prevSnapshot !== snapshot) |
| 410 | { this.#rebuildChunk(prevSnapshot); } |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | clearTilePreview () |
| 415 | { |
| 416 | const previous = this.preview; |
| 417 | this.preview = null; |
| 418 | if (previous) |
| 419 | { |
| 420 | const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`); |
| 421 | if (snapshot) |
| 422 | { this.#rebuildChunk(snapshot); } |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | #lerpMs (gait) |
| 427 | { |
| 428 | const walk = this.settings.walkTilesPerSecond || 2; |
| 429 | const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk; |
| 430 | return seconds * 1000; |
| 431 | } |
| 432 | |
| 433 | #centerCamera () |
| 434 | { |
| 435 | if (!this.followPlayer) |
| 436 | { return; } |
| 437 | const local = this.entities.get(this.localEntityId); |
| 438 | if (!local) |
| 439 | { return; } |
| 440 | this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX; |
| 441 | this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY; |
| 442 | } |
| 443 | |
| 444 | #upsertEntity (payload) |
| 445 | { |
| 446 | const size = this.tileSize(); |
| 447 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 448 | let entity = this.entities.get(payload.entityId); |
| 449 | if (!entity) |
| 450 | { |
| 451 | const spriteName = payload.layers?.[0]?.sprite |
| 452 | ?? payload.sprite |
| 453 | ?? bodySpriteName(payload.sex); |
| 454 | const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY); |
| 455 | this.scene.addObject(object); |
| 456 | this.#startIdleAnimation(object); |
| 457 | entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y }; |
| 458 | this.entities.set(payload.entityId, entity); |
| 459 | } |
| 460 | entity.entityId = payload.entityId; |
| 461 | entity.tileX = payload.tileX; |
| 462 | entity.tileY = payload.tileY; |
| 463 | entity.gait = payload.gait; |
| 464 | entity.sex = payload.sex ?? entity.sex; |
| 465 | entity.characterId = payload.characterId ?? entity.characterId ?? null; |
| 466 | entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null; |
| 467 | entity.hostile = !!payload.hostile; |
| 468 | entity.talkable = !!payload.talkable; |
| 469 | entity.untargetable = !!payload.untargetable; |
| 470 | entity.freeFlight = !!payload.freeFlight; |
| 471 | if (payload.firstName) |
| 472 | { entity.firstName = payload.firstName; } |
| 473 | if (payload.lastName) |
| 474 | { entity.lastName = payload.lastName; } |
| 475 | entity.firstName = entity.firstName ?? ""; |
| 476 | entity.lastName = entity.lastName ?? ""; |
| 477 | if (payload.worldX != null && payload.worldY != null) |
| 478 | { |
| 479 | entity.worldX = payload.worldX; |
| 480 | entity.worldY = payload.worldY; |
| 481 | entity.visualX = payload.worldX * size; |
| 482 | entity.visualY = payload.worldY * size; |
| 483 | entity.targetX = entity.visualX; |
| 484 | entity.targetY = entity.visualY; |
| 485 | } |
| 486 | else |
| 487 | { |
| 488 | entity.visualX = pivot.x; |
| 489 | entity.visualY = pivot.y; |
| 490 | entity.targetX = pivot.x; |
| 491 | entity.targetY = pivot.y; |
| 492 | } |
| 493 | entity.fromX = entity.visualX; |
| 494 | entity.fromY = entity.visualY; |
| 495 | if (payload.layers) |
| 496 | { this.#applyLayers(entity, payload.layers); } |
| 497 | this.#placeEntity(entity); |
| 498 | } |
| 499 | |
| 500 | #applyLayers (entity, layers) |
| 501 | { |
| 502 | const base = layers[0]?.sprite |
| 503 | ?? bodySpriteName(entity.sex); |
| 504 | if (this.game.images[base]) |
| 505 | { |
| 506 | entity.object.renderer.sprite = this.game.images[base]; |
| 507 | this.#startIdleAnimation(entity.object); |
| 508 | } |
| 509 | for (const overlay of entity.overlays ?? []) |
| 510 | { overlay.destroy(); } |
| 511 | for (const overlay of entity.bloomOverlays ?? []) |
| 512 | { overlay.destroy(); } |
| 513 | entity.overlays = []; |
| 514 | entity.bloomOverlays = []; |
| 515 | for (const layer of layers.slice(1)) |
| 516 | { |
| 517 | const image = this.game.images[layer.sprite]; |
| 518 | if (!image) |
| 519 | { continue; } |
| 520 | const object = new GameObject(0, 0, image, SORT_ENTITY); |
| 521 | this.scene.addObject(object); |
| 522 | entity.overlays.push(object); |
| 523 | const bloomName = bloomCompanionName(layer.sprite); |
| 524 | const bloomImage = this.game.images[bloomName]; |
| 525 | if (!bloomImage) |
| 526 | { continue; } |
| 527 | const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY); |
| 528 | bloom.renderer.layer = RENDER_LAYER_BLOOM; |
| 529 | this.scene.addObject(bloom); |
| 530 | entity.bloomOverlays.push(bloom); |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | #placeEntity (entity) |
| 535 | { |
| 536 | this.#placePivoted(entity.object, entity.visualX, entity.visualY, entity.visualY, SORT_ENTITY); |
| 537 | for (const overlay of entity.overlays ?? []) |
| 538 | { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.001, SORT_ENTITY); } |
| 539 | for (const overlay of entity.bloomOverlays ?? []) |
| 540 | { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); } |
| 541 | entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, entity.visualX, entity.visualY); |
| 542 | } |
| 543 | |
| 544 | #rebuildChunk (snapshot) |
| 545 | { |
| 546 | this.#bakeAndPlaceChunk(snapshot); |
| 547 | const tall = new Set( |
| 548 | (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? []) |
| 549 | .map((entry) => `${entry.tileX},${entry.tileY}`) |
| 550 | ); |
| 551 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 552 | { |
| 553 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 554 | { |
| 555 | const tileX = snapshot.chunkX * CHUNK_SIZE + localX; |
| 556 | const tileY = snapshot.chunkY * CHUNK_SIZE + localY; |
| 557 | this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`)); |
| 558 | } |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | #redrawPreview () |
| 563 | { |
| 564 | if (!this.preview) |
| 565 | { return; } |
| 566 | const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`); |
| 567 | if (snapshot) |
| 568 | { this.#rebuildChunk(snapshot); } |
| 569 | } |
| 570 | |
| 571 | #bakeAndPlaceChunk (snapshot) |
| 572 | { |
| 573 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 574 | const atlases = bakeChunkAtlases({ |
| 575 | snapshot, |
| 576 | catalog: this.catalog, |
| 577 | images: this.game.images, |
| 578 | preview: this.preview |
| 579 | }); |
| 580 | let baked = this.bakedChunks.get(key); |
| 581 | if (!baked) |
| 582 | { |
| 583 | baked = { |
| 584 | groundCanvas: atlases.ground, |
| 585 | blockCanvases: atlases.blockRows, |
| 586 | bloomCanvas: atlases.bloom, |
| 587 | groundImage: frameworkImageFromCanvas(atlases.ground), |
| 588 | blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)), |
| 589 | bloomImage: frameworkImageFromCanvas(atlases.bloom), |
| 590 | groundObject: null, |
| 591 | blockObjects: [], |
| 592 | bloomObject: null, |
| 593 | tallBlocks: atlases.tallBlocks |
| 594 | }; |
| 595 | baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND); |
| 596 | this.scene.addObject(baked.groundObject); |
| 597 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 598 | { |
| 599 | const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK); |
| 600 | this.scene.addObject(object); |
| 601 | baked.blockObjects.push(object); |
| 602 | } |
| 603 | baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK); |
| 604 | baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; |
| 605 | this.scene.addObject(baked.bloomObject); |
| 606 | this.bakedChunks.set(key, baked); |
| 607 | } |
| 608 | else |
| 609 | { |
| 610 | copyCanvas(atlases.ground, baked.groundCanvas); |
| 611 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 612 | { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); } |
| 613 | copyCanvas(atlases.bloom, baked.bloomCanvas); |
| 614 | invalidateCanvasTexture(this.scene, baked.groundCanvas); |
| 615 | for (const canvas of baked.blockCanvases) |
| 616 | { invalidateCanvasTexture(this.scene, canvas); } |
| 617 | invalidateCanvasTexture(this.scene, baked.bloomCanvas); |
| 618 | baked.tallBlocks = atlases.tallBlocks; |
| 619 | } |
| 620 | this.#layoutBakedChunk(snapshot); |
| 621 | } |
| 622 | |
| 623 | #layoutBakedChunk (snapshot) |
| 624 | { |
| 625 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 626 | const baked = this.bakedChunks.get(key); |
| 627 | if (!baked) |
| 628 | { return; } |
| 629 | const size = this.tileSize(); |
| 630 | const left = snapshot.chunkX * CHUNK_SIZE * size; |
| 631 | const top = snapshot.chunkY * CHUNK_SIZE * size; |
| 632 | const chunkPx = CHUNK_SIZE * size; |
| 633 | baked.groundObject.transform.position.x = left + chunkPx / 2; |
| 634 | baked.groundObject.transform.position.y = top + chunkPx / 2; |
| 635 | baked.groundObject.transform.size = new vector(chunkPx, chunkPx); |
| 636 | baked.groundObject.layer = LAYER_GROUND; |
| 637 | |
| 638 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 639 | { |
| 640 | const object = baked.blockObjects[row]; |
| 641 | const rowY = top + row * size + size / 2; |
| 642 | object.transform.position.x = left + chunkPx / 2; |
| 643 | object.transform.position.y = rowY; |
| 644 | object.transform.size = new vector(chunkPx, size); |
| 645 | object.layer = ySortLayer(rowY, SORT_BLOCK); |
| 646 | } |
| 647 | |
| 648 | baked.bloomObject.transform.position.x = left + chunkPx / 2; |
| 649 | baked.bloomObject.transform.position.y = top + chunkPx / 2; |
| 650 | baked.bloomObject.transform.size = new vector(chunkPx, chunkPx); |
| 651 | baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK); |
| 652 | baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; |
| 653 | this.#markSortDirty(); |
| 654 | setNearestFilter(this.scene, baked.groundCanvas); |
| 655 | for (const canvas of baked.blockCanvases) |
| 656 | { setNearestFilter(this.scene, canvas); } |
| 657 | setNearestFilter(this.scene, baked.bloomCanvas); |
| 658 | } |
| 659 | |
| 660 | #destroyBakedChunk (key) |
| 661 | { |
| 662 | const baked = this.bakedChunks.get(key); |
| 663 | if (!baked) |
| 664 | { return; } |
| 665 | baked.groundObject?.destroy(); |
| 666 | for (const object of baked.blockObjects ?? []) |
| 667 | { object.destroy(); } |
| 668 | baked.bloomObject?.destroy(); |
| 669 | invalidateCanvasTexture(this.scene, baked.groundCanvas); |
| 670 | for (const canvas of baked.blockCanvases ?? []) |
| 671 | { invalidateCanvasTexture(this.scene, canvas); } |
| 672 | invalidateCanvasTexture(this.scene, baked.bloomCanvas); |
| 673 | this.bakedChunks.delete(key); |
| 674 | } |
| 675 | |
| 676 | #drawTile (tileX, tileY, forceTall = null) |
| 677 | { |
| 678 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 679 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 680 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 681 | if (!snapshot) |
| 682 | { return; } |
| 683 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 684 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 685 | const index = localY * CHUNK_SIZE + localX; |
| 686 | const key = `${tileX},${tileY}`; |
| 687 | let objects = this.tiles.get(key); |
| 688 | if (!objects) |
| 689 | { |
| 690 | objects = { chunkX, chunkY, tileX, tileY }; |
| 691 | this.tiles.set(key, objects); |
| 692 | } |
| 693 | objects.tileX = tileX; |
| 694 | objects.tileY = tileY; |
| 695 | objects.chunkX = chunkX; |
| 696 | objects.chunkY = chunkY; |
| 697 | |
| 698 | const size = this.tileSize(); |
| 699 | const pivot = tilePivot(tileX, tileY, size); |
| 700 | objects.light = snapshot.light[index] ?? 0; |
| 701 | const previousShade = objects.shade; |
| 702 | objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, ySortLayer(pivot.y, SORT_SHADE)); |
| 703 | if (objects.shade && objects.shade !== previousShade) |
| 704 | { objects.shade.renderer.alpha = 0; } |
| 705 | |
| 706 | const baked = this.bakedChunks.get(`${chunkX},${chunkY}`); |
| 707 | const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY); |
| 708 | const isTall = forceTall === true || !!tallEntry; |
| 709 | if (isTall && tallEntry) |
| 710 | { |
| 711 | objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY); |
| 712 | if (objects.block) |
| 713 | { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY); } |
| 714 | objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY); |
| 715 | objects.spriteShade = this.#placeSpriteShade(objects.spriteShade, objects.block, pivot.x, pivot.y); |
| 716 | } |
| 717 | else |
| 718 | { |
| 719 | if (objects.block) |
| 720 | { |
| 721 | objects.block.destroy(); |
| 722 | objects.block = null; |
| 723 | } |
| 724 | if (objects.blockBloom) |
| 725 | { |
| 726 | objects.blockBloom.destroy(); |
| 727 | objects.blockBloom = null; |
| 728 | } |
| 729 | if (objects.spriteShade) |
| 730 | { |
| 731 | objects.spriteShade.destroy(); |
| 732 | objects.spriteShade = null; |
| 733 | } |
| 734 | } |
| 735 | } |
| 736 | |
| 737 | #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK) |
| 738 | { |
| 739 | if (!name) |
| 740 | { |
| 741 | existing?.destroy(); |
| 742 | return null; |
| 743 | } |
| 744 | const object = this.#ensureSprite(existing, name, sortOrder); |
| 745 | if (!object) |
| 746 | { return null; } |
| 747 | object.renderer.layer = RENDER_LAYER_BLOOM; |
| 748 | this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder); |
| 749 | return object; |
| 750 | } |
| 751 | |
| 752 | #placeSpriteShade (existing, targetObject, pivotX, pivotY) |
| 753 | { |
| 754 | if (!targetObject?.renderer?.sprite) |
| 755 | { |
| 756 | existing?.destroy(); |
| 757 | return null; |
| 758 | } |
| 759 | const shade = this.#ensureSprite(existing, "night-shade", SORT_SPRITE_SHADE); |
| 760 | if (!shade) |
| 761 | { return null; } |
| 762 | const sprite = targetObject.renderer.sprite; |
| 763 | const zoom = this.zoom; |
| 764 | const draw = spriteDrawSize(sprite.width, sprite.height, zoom); |
| 765 | const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom); |
| 766 | shade.transform.position.x = center.x; |
| 767 | shade.transform.position.y = center.y; |
| 768 | shade.transform.size = new vector(draw.w, draw.h); |
| 769 | shade.layer = ySortLayer(pivotY, SORT_SPRITE_SHADE); |
| 770 | this.#markSortDirty(); |
| 771 | return shade; |
| 772 | } |
| 773 | |
| 774 | #tileFill (existing, name, x, y, layer) |
| 775 | { |
| 776 | existing = this.#ensureSprite(existing, name, layer); |
| 777 | if (!existing) |
| 778 | { return null; } |
| 779 | const size = this.tileSize(); |
| 780 | existing.transform.position.x = x; |
| 781 | existing.transform.position.y = y; |
| 782 | existing.transform.size = new vector(size, size); |
| 783 | existing.layer = layer; |
| 784 | this.#markSortDirty(); |
| 785 | return existing; |
| 786 | } |
| 787 | |
| 788 | #placePivoted (object, pivotX, pivotY, sortY, subOrder) |
| 789 | { |
| 790 | const sprite = object?.renderer?.sprite; |
| 791 | if (!sprite) |
| 792 | { return; } |
| 793 | const zoom = this.zoom; |
| 794 | const draw = spriteDrawSize(sprite.width, sprite.height, zoom); |
| 795 | const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom); |
| 796 | object.transform.position.x = center.x; |
| 797 | object.transform.position.y = center.y; |
| 798 | object.transform.size = new vector(draw.w, draw.h); |
| 799 | object.layer = ySortLayer(sortY, subOrder); |
| 800 | this.#markSortDirty(); |
| 801 | } |
| 802 | |
| 803 | #ensureSprite (existing, name, layer) |
| 804 | { |
| 805 | const sprite = this.game.images[name]; |
| 806 | if (!sprite) |
| 807 | { |
| 808 | existing?.destroy(); |
| 809 | return null; |
| 810 | } |
| 811 | if (!existing || existing.renderer.sprite !== sprite) |
| 812 | { |
| 813 | existing?.destroy(); |
| 814 | existing = new GameObject(0, 0, sprite, layer); |
| 815 | this.scene.addObject(existing); |
| 816 | this.#startIdleAnimation(existing); |
| 817 | } |
| 818 | return existing; |
| 819 | } |
| 820 | |
| 821 | #startIdleAnimation (object) |
| 822 | { |
| 823 | const sprite = object?.renderer?.sprite; |
| 824 | if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0) |
| 825 | { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); } |
| 826 | } |
| 827 | |
| 828 | #neighborClosed (snapshot, dir, dx, dy) |
| 829 | { |
| 830 | const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`); |
| 831 | if (other) |
| 832 | { return !other.open; } |
| 833 | return !!snapshot.closedEdges?.[dir]; |
| 834 | } |
| 835 | |
| 836 | #rebuildAllEdges () |
| 837 | { |
| 838 | const seen = new Set(); |
| 839 | for (const snapshot of this.chunks.values()) |
| 840 | { |
| 841 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 842 | seen.add(key); |
| 843 | this.#rebuildChunkEdges(snapshot); |
| 844 | } |
| 845 | for (const key of [...this.edges.keys()]) |
| 846 | { |
| 847 | if (!seen.has(key)) |
| 848 | { this.#destroyEdges(key); } |
| 849 | } |
| 850 | } |
| 851 | |
| 852 | #rebuildChunkEdges (snapshot) |
| 853 | { |
| 854 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 855 | let bars = this.edges.get(key); |
| 856 | if (!bars) |
| 857 | { |
| 858 | bars = {}; |
| 859 | this.edges.set(key, bars); |
| 860 | } |
| 861 | |
| 862 | const size = this.tileSize(); |
| 863 | const chunkPx = CHUNK_SIZE * size; |
| 864 | const left = snapshot.chunkX * CHUNK_SIZE * size; |
| 865 | const top = snapshot.chunkY * CHUNK_SIZE * size; |
| 866 | const centerX = left + chunkPx / 2; |
| 867 | const centerY = top + chunkPx / 2; |
| 868 | const thickness = Math.max(2, Math.round(2 * this.zoom)); |
| 869 | const draw = snapshot.open === true; |
| 870 | |
| 871 | bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1), |
| 872 | centerX, top, chunkPx, thickness, true); |
| 873 | bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1), |
| 874 | centerX, top + chunkPx, chunkPx, thickness, true); |
| 875 | bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0), |
| 876 | left, centerY, chunkPx, thickness, false); |
| 877 | bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0), |
| 878 | left + chunkPx, centerY, chunkPx, thickness, false); |
| 879 | } |
| 880 | |
| 881 | #edgeBar (existing, visible, x, y, length, thickness, horizontal) |
| 882 | { |
| 883 | if (!visible) |
| 884 | { |
| 885 | if (existing) |
| 886 | { existing.renderer.visible = false; } |
| 887 | return existing; |
| 888 | } |
| 889 | |
| 890 | existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE); |
| 891 | existing.renderer.visible = true; |
| 892 | existing.transform.position.x = x; |
| 893 | existing.transform.position.y = y; |
| 894 | existing.transform.size = horizontal |
| 895 | ? new vector(length, thickness) |
| 896 | : new vector(thickness, length); |
| 897 | existing.layer = LAYER_EDGE; |
| 898 | this.#markSortDirty(); |
| 899 | return existing; |
| 900 | } |
| 901 | |
| 902 | #destroyEdges (key) |
| 903 | { |
| 904 | const bars = this.edges.get(key); |
| 905 | if (!bars) |
| 906 | { return; } |
| 907 | bars.north?.destroy(); |
| 908 | bars.east?.destroy(); |
| 909 | bars.south?.destroy(); |
| 910 | bars.west?.destroy(); |
| 911 | this.edges.delete(key); |
| 912 | } |
| 913 | |
| 914 | #markSortDirty () |
| 915 | { |
| 916 | this.scene._sortDirty = true; |
| 917 | } |
| 918 | |
| 919 | #updateShade () |
| 920 | { |
| 921 | const hour = this.nightPreview ?? this.worldHour; |
| 922 | const ambientDark = nightFactor(hour, this.settings.nightDarkness); |
| 923 | const now = performance.now(); |
| 924 | this.dynamicLights = this.dynamicLights.filter((light) => light.until > now); |
| 925 | for (const objects of this.tiles.values()) |
| 926 | { |
| 927 | const baked = Math.min(1, Math.max(0, (objects.light ?? 0) / 255)); |
| 928 | let dynamic = 0; |
| 929 | for (const light of this.dynamicLights) |
| 930 | { |
| 931 | const dx = (objects.tileX + 0.5) - light.worldX; |
| 932 | const dy = (objects.tileY + 0.5) - light.worldY; |
| 933 | const dist = Math.hypot(dx, dy); |
| 934 | if (dist >= light.radiusTiles) |
| 935 | { continue; } |
| 936 | const falloff = 1 - dist / light.radiusTiles; |
| 937 | dynamic = Math.max(dynamic, falloff * light.intensity); |
| 938 | } |
| 939 | const intensity = Math.max(baked, dynamic); |
| 940 | const alpha = ambientDark * (1 - intensity); |
| 941 | objects.shadeAlpha = alpha; |
| 942 | if (objects.shade) |
| 943 | { objects.shade.renderer.alpha = alpha; } |
| 944 | if (objects.spriteShade) |
| 945 | { objects.spriteShade.renderer.alpha = alpha; } |
| 946 | } |
| 947 | for (const entity of this.entities.values()) |
| 948 | { |
| 949 | if (!entity.spriteShade) |
| 950 | { continue; } |
| 951 | const tile = this.tiles.get(`${entity.tileX},${entity.tileY}`); |
| 952 | entity.spriteShade.renderer.alpha = tile?.shadeAlpha ?? 0; |
| 953 | } |
| 954 | } |
| 955 | |
| 956 | #updateSwipes (now) |
| 957 | { |
| 958 | this.swipes = this.swipes.filter((swipe) => |
| 959 | { |
| 960 | if (swipe.until > now) |
| 961 | { return true; } |
| 962 | swipe.object?.destroy(); |
| 963 | return false; |
| 964 | }); |
| 965 | } |
| 966 | |
| 967 | #syncBloomLayer () |
| 968 | { |
| 969 | const settings = this.settings ?? DEFAULT_WORLD_SETTINGS; |
| 970 | this.scene.setLayers([ |
| 971 | { name: "default" }, |
| 972 | { |
| 973 | name: RENDER_LAYER_BLOOM, |
| 974 | composite: "add", |
| 975 | postShaders: Shader.getBloomPostChain({ |
| 976 | threshold: settings.bloomThreshold, |
| 977 | softKnee: settings.bloomSoftKnee, |
| 978 | intensity: settings.bloomIntensity, |
| 979 | blurSize: settings.bloomBlurSize, |
| 980 | saturation: settings.bloomSaturation, |
| 981 | colorPreserve: settings.bloomColorPreserve, |
| 982 | dilate: settings.bloomDilate, |
| 983 | scales: Math.max(1, Math.round(settings.bloomScales ?? 1)), |
| 984 | halfRes: (settings.bloomHalfRes ?? 1) >= 0.5 |
| 985 | }) |
| 986 | } |
| 987 | ]); |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | export function nightFactor (hour, nightDarkness = 0.72) |
| 992 | { |
| 993 | const peak = Math.min(1, Math.max(0, nightDarkness)); |
| 994 | if (hour >= 8 && hour <= 16) |
| 995 | { return 0; } |
| 996 | if (hour >= 22 || hour <= 5) |
| 997 | { return peak; } |
| 998 | if (hour < 8) |
| 999 | { return lerp(peak, 0, (hour - 5) / 3); } |
| 1000 | return lerp(0, peak, (hour - 16) / 6); |
| 1001 | } |
| 1002 | |
| 1003 | function bodySpriteName (sex) |
| 1004 | { |
| 1005 | const key = sex === "female" ? "player-body-female" : "player-body-male"; |
| 1006 | return spriteImageName("character", key, key); |
| 1007 | } |
| 1008 | |
| 1009 | function lerp (a, b, t) |
| 1010 | { |
| 1011 | return a + (b - a) * Math.min(1, Math.max(0, t)); |
| 1012 | } |
| 1013 | |
| 1014 | function copyCanvas (source, dest) |
| 1015 | { |
| 1016 | const ctx = dest.getContext("2d"); |
| 1017 | ctx.imageSmoothingEnabled = false; |
| 1018 | ctx.clearRect(0, 0, dest.width, dest.height); |
| 1019 | ctx.drawImage(source, 0, 0); |
| 1020 | } |
| 1021 | |
| 1022 | function setNearestFilter (scene, canvas) |
| 1023 | { |
| 1024 | const glContext = scene?.glContext; |
| 1025 | if (!glContext || !canvas) |
| 1026 | { return; } |
| 1027 | const texture = glContext.getTexture(canvas); |
| 1028 | if (!texture) |
| 1029 | { return; } |
| 1030 | const gl = glContext.gl; |
| 1031 | gl.bindTexture(gl.TEXTURE_2D, texture); |
| 1032 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); |
| 1033 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); |
| 1034 | } |