| 1 | import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } 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 { bakeChunkAtlases } from "./chunkBake.js"; |
| 6 | import { |
| 7 | frameworkImageFromCanvas, |
| 8 | invalidateCanvasTexture |
| 9 | } from "./canvasSprite.js"; |
| 10 | |
| 11 | const LAYER_GROUND = 0; |
| 12 | const LAYER_EDGE = 900000; |
| 13 | const SORT_BLOCK = 2; |
| 14 | const SORT_ENTITY = 3; |
| 15 | const SORT_HP_BAR = 4; |
| 16 | const SORT_FX = 5; |
| 17 | const RENDER_LAYER_BLOOM = "bloom"; |
| 18 | |
| 19 | const HP_BAR_W = 14; |
| 20 | const HP_BAR_H = 4; |
| 21 | const WALK_TILT_DEG = 6; |
| 22 | const RUN_TILT_DEG = 8; |
| 23 | const SHOVE_TILE_FRACTION = 0.25; |
| 24 | const SHOVE_MS = 280; |
| 25 | const DAMAGE_FLASH_MS = 180; |
| 26 | const DAMAGE_FLOAT_MS = 900; |
| 27 | |
| 28 | const SPRITE_LIGHTING_FRAG = [ |
| 29 | "precision mediump float;", |
| 30 | "varying vec2 v_texCoord;", |
| 31 | "uniform sampler2D u_texture;", |
| 32 | "uniform float u_darkness;", |
| 33 | "uniform float u_strength;", |
| 34 | "void main() {", |
| 35 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 36 | " if (color.a <= 0.0) { discard; }", |
| 37 | " vec3 rgb = mix(color.rgb, vec3(0.0), u_darkness);", |
| 38 | " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);", |
| 39 | " gl_FragColor = vec4(rgb, color.a);", |
| 40 | "}" |
| 41 | ].join("\n"); |
| 42 | |
| 43 | const ATLAS_LIGHTING_FRAG = [ |
| 44 | "precision mediump float;", |
| 45 | "varying vec2 v_texCoord;", |
| 46 | "uniform sampler2D u_texture;", |
| 47 | "uniform sampler2D u_secondary;", |
| 48 | "uniform float u_ambientDark;", |
| 49 | "uniform float u_lightRow;", |
| 50 | "void main() {", |
| 51 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 52 | " if (color.a <= 0.0) { discard; }", |
| 53 | " vec2 lightUV = v_texCoord;", |
| 54 | " if (u_lightRow >= 0.0) {", |
| 55 | " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;", |
| 56 | " }", |
| 57 | " float lit = texture2D(u_secondary, lightUV).r;", |
| 58 | " float darkness = u_ambientDark * (1.0 - lit);", |
| 59 | " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);", |
| 60 | " gl_FragColor = vec4(rgb, color.a);", |
| 61 | "}" |
| 62 | ].join("\n"); |
| 63 | |
| 64 | let spriteLightingShader = null; |
| 65 | let atlasLightingShader = null; |
| 66 | |
| 67 | function getSpriteLightingShader () |
| 68 | { |
| 69 | if (!spriteLightingShader) |
| 70 | { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); } |
| 71 | return spriteLightingShader; |
| 72 | } |
| 73 | |
| 74 | function getAtlasLightingShader () |
| 75 | { |
| 76 | if (!atlasLightingShader) |
| 77 | { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); } |
| 78 | return atlasLightingShader; |
| 79 | } |
| 80 | |
| 81 | export class WorldView |
| 82 | { |
| 83 | constructor (game, scene, catalog = { grounds: {}, blocks: {} }) |
| 84 | { |
| 85 | this.game = game; |
| 86 | this.scene = scene; |
| 87 | this.catalog = catalog; |
| 88 | this.preview = null; |
| 89 | this.zoom = 2; |
| 90 | this.chunks = new Map(); |
| 91 | this.bakedChunks = new Map(); |
| 92 | this.tiles = new Map(); |
| 93 | this.entities = new Map(); |
| 94 | this.groundItems = new Map(); |
| 95 | this.edges = new Map(); |
| 96 | this.localEntityId = null; |
| 97 | this.settings = { ...DEFAULT_WORLD_SETTINGS }; |
| 98 | this.worldHour = 12; |
| 99 | this.nightPreview = null; |
| 100 | this.followPlayer = true; |
| 101 | this.dynamicLights = []; |
| 102 | this.swipes = []; |
| 103 | this.damageFloats = []; |
| 104 | this.damageNumbersEl = document.getElementById("damage-numbers"); |
| 105 | this.#syncBloomLayer(); |
| 106 | } |
| 107 | |
| 108 | setSettings (settings) |
| 109 | { |
| 110 | this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings }; |
| 111 | this.#syncBloomLayer(); |
| 112 | } |
| 113 | |
| 114 | setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null) |
| 115 | { |
| 116 | this.localEntityId = entityId; |
| 117 | this.#upsertEntity({ |
| 118 | entityId, |
| 119 | characterId, |
| 120 | tileX, |
| 121 | tileY, |
| 122 | gait, |
| 123 | sex, |
| 124 | firstName, |
| 125 | lastName, |
| 126 | layers: layers ?? undefined |
| 127 | }); |
| 128 | } |
| 129 | |
| 130 | applySnapshot (snapshot) |
| 131 | { |
| 132 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 133 | this.chunks.set(key, snapshot); |
| 134 | this.#rebuildChunk(snapshot); |
| 135 | this.#redrawPreview(); |
| 136 | for (const entity of snapshot.entities ?? []) |
| 137 | { this.#upsertEntity(entity); } |
| 138 | const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 139 | for (const [id, item] of [...this.groundItems.entries()]) |
| 140 | { |
| 141 | if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY) |
| 142 | { this.despawnGroundItem(id); } |
| 143 | } |
| 144 | for (const item of snapshot.groundItems ?? []) |
| 145 | { this.upsertGroundItem(item); } |
| 146 | this.#rebuildAllEdges(); |
| 147 | } |
| 148 | |
| 149 | removeChunk (chunkX, chunkY) |
| 150 | { |
| 151 | const key = `${chunkX},${chunkY}`; |
| 152 | this.chunks.delete(key); |
| 153 | this.#destroyBakedChunk(key); |
| 154 | this.#destroyEdges(key); |
| 155 | for (const [tileKey, objects] of [...this.tiles.entries()]) |
| 156 | { |
| 157 | if (objects.chunkX === chunkX && objects.chunkY === chunkY) |
| 158 | { |
| 159 | objects.ground?.destroy(); |
| 160 | objects.groundBloom?.destroy(); |
| 161 | objects.block?.destroy(); |
| 162 | objects.blockBloom?.destroy(); |
| 163 | this.tiles.delete(tileKey); |
| 164 | } |
| 165 | } |
| 166 | for (const [id, item] of [...this.groundItems.entries()]) |
| 167 | { |
| 168 | if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) |
| 169 | { this.despawnGroundItem(id); } |
| 170 | } |
| 171 | this.#rebuildAllEdges(); |
| 172 | } |
| 173 | |
| 174 | setChunkOpen (chunkX, chunkY, open) |
| 175 | { |
| 176 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 177 | if (!snapshot) |
| 178 | { return; } |
| 179 | snapshot.open = !!open; |
| 180 | this.#rebuildAllEdges(); |
| 181 | } |
| 182 | |
| 183 | spawnEntity (payload) |
| 184 | { |
| 185 | this.#upsertEntity(payload); |
| 186 | } |
| 187 | |
| 188 | moveEntity (payload) |
| 189 | { |
| 190 | const existing = this.entities.get(payload.entityId); |
| 191 | if (!existing) |
| 192 | { |
| 193 | this.#upsertEntity(payload); |
| 194 | return; |
| 195 | } |
| 196 | const size = this.tileSize(); |
| 197 | existing.fromX = existing.visualX; |
| 198 | existing.fromY = existing.visualY; |
| 199 | existing.shadeFromTileX = existing.tileX; |
| 200 | existing.shadeFromTileY = existing.tileY; |
| 201 | existing.tileX = payload.tileX; |
| 202 | existing.tileY = payload.tileY; |
| 203 | existing.gait = payload.gait; |
| 204 | existing.freeFlight = !!payload.freeFlight || existing.freeFlight; |
| 205 | if (payload.worldX != null && payload.worldY != null) |
| 206 | { |
| 207 | existing.worldX = payload.worldX; |
| 208 | existing.worldY = payload.worldY; |
| 209 | existing.targetX = payload.worldX * size; |
| 210 | existing.targetY = payload.worldY * size; |
| 211 | } |
| 212 | else |
| 213 | { |
| 214 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 215 | existing.targetX = pivot.x; |
| 216 | existing.targetY = pivot.y; |
| 217 | } |
| 218 | existing.lerpStarted = performance.now(); |
| 219 | existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait); |
| 220 | } |
| 221 | |
| 222 | despawnEntity (entityId) |
| 223 | { |
| 224 | const existing = this.entities.get(entityId); |
| 225 | if (!existing) |
| 226 | { return; } |
| 227 | existing.object?.destroy(); |
| 228 | existing.hpBar?.destroy(); |
| 229 | for (const overlay of existing.overlays ?? []) |
| 230 | { overlay.destroy(); } |
| 231 | for (const overlay of existing.bloomOverlays ?? []) |
| 232 | { overlay.destroy(); } |
| 233 | this.entities.delete(entityId); |
| 234 | } |
| 235 | |
| 236 | updateEntityHealth (entityId, health, maxHealth) |
| 237 | { |
| 238 | const entity = this.entities.get(entityId); |
| 239 | if (!entity) |
| 240 | { return; } |
| 241 | entity.health = health; |
| 242 | entity.maxHealth = maxHealth; |
| 243 | this.#syncHpBar(entity); |
| 244 | } |
| 245 | |
| 246 | flashDamage (entityId) |
| 247 | { |
| 248 | const entity = this.entities.get(entityId); |
| 249 | if (!entity) |
| 250 | { return; } |
| 251 | entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS; |
| 252 | } |
| 253 | |
| 254 | spawnDamageNumber (entityId, damage) |
| 255 | { |
| 256 | const amount = damage | 0; |
| 257 | if (amount <= 0) |
| 258 | { return; } |
| 259 | this.damageFloats.push({ |
| 260 | entityId, |
| 261 | damage: amount, |
| 262 | started: performance.now() |
| 263 | }); |
| 264 | } |
| 265 | |
| 266 | setAppearance (payload) |
| 267 | { |
| 268 | const existing = this.entities.get(payload.entityId); |
| 269 | if (!existing) |
| 270 | { return; } |
| 271 | existing.lightRadiusTiles = payload.lightRadiusTiles ?? existing.lightRadiusTiles ?? 0; |
| 272 | this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]); |
| 273 | this.#placeEntity(existing); |
| 274 | } |
| 275 | |
| 276 | upsertGroundItem (payload) |
| 277 | { |
| 278 | const size = this.tileSize(); |
| 279 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 280 | let item = this.groundItems.get(payload.groundItemId); |
| 281 | if (!item) |
| 282 | { |
| 283 | const object = new GameObject(0, 0, this.game.images[payload.sprite] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK); |
| 284 | this.scene.addObject(object); |
| 285 | item = { object }; |
| 286 | this.groundItems.set(payload.groundItemId, item); |
| 287 | } |
| 288 | item.groundItemId = payload.groundItemId; |
| 289 | item.tileX = payload.tileX; |
| 290 | item.tileY = payload.tileY; |
| 291 | item.itemId = payload.itemId; |
| 292 | item.quantity = payload.quantity; |
| 293 | item.displayName = payload.displayName; |
| 294 | item.sprite = payload.sprite; |
| 295 | this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); |
| 296 | this.#syncLitSprite(item.object, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0); |
| 297 | } |
| 298 | |
| 299 | despawnGroundItem (groundItemId) |
| 300 | { |
| 301 | const item = this.groundItems.get(groundItemId); |
| 302 | if (!item) |
| 303 | { return; } |
| 304 | item.object?.destroy(); |
| 305 | this.groundItems.delete(groundItemId); |
| 306 | } |
| 307 | |
| 308 | groundItemAtTile (tileX, tileY) |
| 309 | { |
| 310 | return this.groundItemsAtTile(tileX, tileY)[0] ?? null; |
| 311 | } |
| 312 | |
| 313 | groundItemsAtTile (tileX, tileY) |
| 314 | { |
| 315 | const items = []; |
| 316 | for (const item of this.groundItems.values()) |
| 317 | { |
| 318 | if (item.tileX === tileX && item.tileY === tileY) |
| 319 | { items.push(item); } |
| 320 | } |
| 321 | return items; |
| 322 | } |
| 323 | |
| 324 | entitiesAtTile (tileX, tileY) |
| 325 | { |
| 326 | const matches = []; |
| 327 | for (const entity of this.entities.values()) |
| 328 | { |
| 329 | if (entity.tileX === tileX && entity.tileY === tileY) |
| 330 | { matches.push(entity); } |
| 331 | } |
| 332 | matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0)); |
| 333 | return matches; |
| 334 | } |
| 335 | |
| 336 | setZoom (zoom, limits = { min: 1, max: 4 }) |
| 337 | { |
| 338 | const min = limits.min ?? 1; |
| 339 | const max = limits.max ?? 4; |
| 340 | this.zoom = Math.min(max, Math.max(min, zoom)); |
| 341 | for (const snapshot of this.chunks.values()) |
| 342 | { |
| 343 | this.#layoutBakedChunk(snapshot); |
| 344 | this.#rebuildChunk(snapshot); |
| 345 | } |
| 346 | const size = this.tileSize(); |
| 347 | for (const entity of this.entities.values()) |
| 348 | { |
| 349 | entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x; |
| 350 | entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y; |
| 351 | entity.fromX = entity.visualX; |
| 352 | entity.fromY = entity.visualY; |
| 353 | entity.targetX = entity.visualX; |
| 354 | entity.targetY = entity.visualY; |
| 355 | entity.lerpStarted = null; |
| 356 | this.#placeEntity(entity); |
| 357 | } |
| 358 | for (const item of this.groundItems.values()) |
| 359 | { |
| 360 | const pivot = tilePivot(item.tileX, item.tileY, size); |
| 361 | this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); |
| 362 | } |
| 363 | this.#rebuildAllEdges(); |
| 364 | this.#redrawPreview(); |
| 365 | } |
| 366 | |
| 367 | tileSize () |
| 368 | { |
| 369 | return SPRITE_SIZE_PX * this.zoom; |
| 370 | } |
| 371 | |
| 372 | screenToTile (mouseX, mouseY) |
| 373 | { |
| 374 | const size = this.tileSize(); |
| 375 | const worldX = mouseX - this.scene.cameraPosition.x; |
| 376 | const worldY = mouseY - this.scene.cameraPosition.y; |
| 377 | return { |
| 378 | tileX: Math.floor(worldX / size), |
| 379 | tileY: Math.floor(worldY / size) |
| 380 | }; |
| 381 | } |
| 382 | |
| 383 | entityAtScreen (mouseX, mouseY) |
| 384 | { |
| 385 | let best = null; |
| 386 | let bestLayer = -Infinity; |
| 387 | for (const entity of this.entities.values()) |
| 388 | { |
| 389 | const box = this.#entityScreenBox(entity); |
| 390 | if (!box) |
| 391 | { continue; } |
| 392 | if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom) |
| 393 | { |
| 394 | const layer = entity.object?.layer ?? 0; |
| 395 | if (layer >= bestLayer) |
| 396 | { |
| 397 | best = entity; |
| 398 | bestLayer = layer; |
| 399 | } |
| 400 | } |
| 401 | } |
| 402 | return best; |
| 403 | } |
| 404 | |
| 405 | nametagAnchor (entity) |
| 406 | { |
| 407 | const box = this.#entityScreenBox(entity); |
| 408 | if (!box) |
| 409 | { return null; } |
| 410 | return { x: (box.left + box.right) / 2, y: box.top }; |
| 411 | } |
| 412 | |
| 413 | #entityScreenBox (entity) |
| 414 | { |
| 415 | const object = entity?.object; |
| 416 | if (!object) |
| 417 | { return null; } |
| 418 | const size = object.transform.size; |
| 419 | const x = object.transform.position.x + this.scene.cameraPosition.x; |
| 420 | const y = object.transform.position.y + this.scene.cameraPosition.y; |
| 421 | return { |
| 422 | left: x - size.x / 2, |
| 423 | right: x + size.x / 2, |
| 424 | top: y - size.y / 2, |
| 425 | bottom: y + size.y / 2 |
| 426 | }; |
| 427 | } |
| 428 | |
| 429 | update (deltaTime) |
| 430 | { |
| 431 | const now = performance.now(); |
| 432 | const size = this.tileSize(); |
| 433 | for (const entity of this.entities.values()) |
| 434 | { |
| 435 | const target = entity.targetX != null && entity.targetY != null |
| 436 | ? { x: entity.targetX, y: entity.targetY } |
| 437 | : tilePivot(entity.tileX, entity.tileY, size); |
| 438 | if (entity.lerpStarted != null) |
| 439 | { |
| 440 | const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs)); |
| 441 | entity.visualX = entity.fromX + (target.x - entity.fromX) * t; |
| 442 | entity.visualY = entity.fromY + (target.y - entity.fromY) * t; |
| 443 | if (t >= 1) |
| 444 | { entity.lerpStarted = null; } |
| 445 | } |
| 446 | else |
| 447 | { |
| 448 | entity.visualX = target.x; |
| 449 | entity.visualY = target.y; |
| 450 | } |
| 451 | this.#updateShove(entity, now, size); |
| 452 | this.#placeEntity(entity, now); |
| 453 | } |
| 454 | |
| 455 | this.#updateSwipes(now); |
| 456 | this.#updateDamageNumbers(now); |
| 457 | this.#centerCamera(); |
| 458 | this.#updateShade(deltaTime); |
| 459 | } |
| 460 | |
| 461 | #updateShove (entity, now, tileSize) |
| 462 | { |
| 463 | if (!entity.shove) |
| 464 | { |
| 465 | entity.shoveOffsetX = 0; |
| 466 | entity.shoveOffsetY = 0; |
| 467 | return; |
| 468 | } |
| 469 | const elapsed = now - entity.shove.started; |
| 470 | const t = Math.min(1, elapsed / entity.shove.durationMs); |
| 471 | const maxDist = tileSize * SHOVE_TILE_FRACTION; |
| 472 | const dx = entity.shove.targetVisualX - entity.shove.startVisualX; |
| 473 | const dy = entity.shove.targetVisualY - entity.shove.startVisualY; |
| 474 | const dist = Math.hypot(dx, dy) || 1; |
| 475 | const ux = dx / dist; |
| 476 | const uy = dy / dist; |
| 477 | let phase; |
| 478 | if (t < 0.45) |
| 479 | { phase = t / 0.45; } |
| 480 | else |
| 481 | { phase = 1 - (t - 0.45) / 0.55; } |
| 482 | entity.shoveOffsetX = ux * maxDist * phase; |
| 483 | entity.shoveOffsetY = uy * maxDist * phase; |
| 484 | if (t >= 1) |
| 485 | { entity.shove = null; } |
| 486 | } |
| 487 | |
| 488 | spawnCombatSwing (payload) |
| 489 | { |
| 490 | const attacker = this.entities.get(payload.attackerId); |
| 491 | const target = this.entities.get(payload.targetId); |
| 492 | if (!attacker || !target) |
| 493 | { return; } |
| 494 | attacker.shove = { |
| 495 | startVisualX: attacker.visualX, |
| 496 | startVisualY: attacker.visualY, |
| 497 | targetVisualX: target.visualX, |
| 498 | targetVisualY: target.visualY, |
| 499 | started: performance.now(), |
| 500 | durationMs: SHOVE_MS |
| 501 | }; |
| 502 | const midX = (attacker.visualX + target.visualX) / 2; |
| 503 | const midY = (attacker.visualY + target.visualY) / 2; |
| 504 | const sortY = Math.max(attacker.visualY, target.visualY) + 0.02; |
| 505 | const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI); |
| 506 | const spriteName = "fx:melee-swipe:melee-swipe"; |
| 507 | const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX); |
| 508 | if (object.transform) |
| 509 | { object.transform.rotation = angle; } |
| 510 | this.scene.addObject(object); |
| 511 | this.#placePivoted(object, midX, midY, sortY, SORT_FX); |
| 512 | this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY); |
| 513 | this.swipes.push({ |
| 514 | object, |
| 515 | until: performance.now() + 500, |
| 516 | fromTileX: payload.fromTileX, |
| 517 | fromTileY: payload.fromTileY, |
| 518 | tileX: payload.tileX, |
| 519 | tileY: payload.tileY |
| 520 | }); |
| 521 | } |
| 522 | |
| 523 | /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */ |
| 524 | spawnPhysicalProjectileFx (payload) |
| 525 | { |
| 526 | const spriteName = payload.sprite ?? "fx:projectile:projectile"; |
| 527 | const image = this.game.images[spriteName]; |
| 528 | if (!image) |
| 529 | { return; } |
| 530 | const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize()); |
| 531 | const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize()); |
| 532 | const midX = (fromPivot.x + toPivot.x) / 2; |
| 533 | const midY = (fromPivot.y + toPivot.y) / 2; |
| 534 | const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02; |
| 535 | const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI); |
| 536 | const object = new GameObject(0, 0, image, SORT_FX); |
| 537 | if (object.transform) |
| 538 | { object.transform.rotation = angle; } |
| 539 | this.scene.addObject(object); |
| 540 | this.#placePivoted(object, midX, midY, sortY, SORT_FX); |
| 541 | this.#applyPhysicalCombatFxDarkness( |
| 542 | object, |
| 543 | payload.fromTileX, |
| 544 | payload.fromTileY, |
| 545 | payload.tileX, |
| 546 | payload.tileY |
| 547 | ); |
| 548 | this.swipes.push({ |
| 549 | object, |
| 550 | until: performance.now() + (payload.durationMs ?? 500), |
| 551 | fromTileX: payload.fromTileX, |
| 552 | fromTileY: payload.fromTileY, |
| 553 | tileX: payload.tileX, |
| 554 | tileY: payload.tileY |
| 555 | }); |
| 556 | } |
| 557 | |
| 558 | addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 }) |
| 559 | { |
| 560 | this.dynamicLights.push({ |
| 561 | worldX, |
| 562 | worldY, |
| 563 | radiusTiles, |
| 564 | intensity, |
| 565 | until: performance.now() + durationMs |
| 566 | }); |
| 567 | } |
| 568 | |
| 569 | updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {}) |
| 570 | { |
| 571 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 572 | if (!snapshot) |
| 573 | { return; } |
| 574 | const index = localY * CHUNK_SIZE + localX; |
| 575 | if (ground !== undefined) |
| 576 | { snapshot.grounds[index] = ground; } |
| 577 | if (block !== undefined) |
| 578 | { snapshot.blocks[index] = block; } |
| 579 | if (light !== undefined) |
| 580 | { snapshot.light[index] = light; } |
| 581 | this.#rebuildChunk(snapshot); |
| 582 | } |
| 583 | |
| 584 | setTilePreview (tileX, tileY, override) |
| 585 | { |
| 586 | const previous = this.preview; |
| 587 | this.preview = { tileX, tileY, ...override }; |
| 588 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 589 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 590 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 591 | if (snapshot) |
| 592 | { this.#rebuildChunk(snapshot); } |
| 593 | if (previous && (previous.tileX !== tileX || previous.tileY !== tileY)) |
| 594 | { |
| 595 | const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`); |
| 596 | if (prevSnapshot && prevSnapshot !== snapshot) |
| 597 | { this.#rebuildChunk(prevSnapshot); } |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | clearTilePreview () |
| 602 | { |
| 603 | const previous = this.preview; |
| 604 | this.preview = null; |
| 605 | if (previous) |
| 606 | { |
| 607 | const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`); |
| 608 | if (snapshot) |
| 609 | { this.#rebuildChunk(snapshot); } |
| 610 | } |
| 611 | } |
| 612 | |
| 613 | #lerpMs (gait) |
| 614 | { |
| 615 | const walk = this.settings.walkTilesPerSecond || 2; |
| 616 | const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk; |
| 617 | return seconds * 1000; |
| 618 | } |
| 619 | |
| 620 | #centerCamera () |
| 621 | { |
| 622 | if (!this.followPlayer) |
| 623 | { return; } |
| 624 | const local = this.entities.get(this.localEntityId); |
| 625 | if (!local) |
| 626 | { return; } |
| 627 | this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX; |
| 628 | this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY; |
| 629 | } |
| 630 | |
| 631 | #upsertEntity (payload) |
| 632 | { |
| 633 | const size = this.tileSize(); |
| 634 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 635 | let entity = this.entities.get(payload.entityId); |
| 636 | if (!entity) |
| 637 | { |
| 638 | const spriteName = payload.layers?.[0]?.sprite |
| 639 | ?? payload.sprite |
| 640 | ?? bodySpriteName(payload.sex); |
| 641 | const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY); |
| 642 | this.scene.addObject(object); |
| 643 | this.#startIdleAnimation(object); |
| 644 | entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y }; |
| 645 | this.entities.set(payload.entityId, entity); |
| 646 | } |
| 647 | entity.entityId = payload.entityId; |
| 648 | entity.tileX = payload.tileX; |
| 649 | entity.tileY = payload.tileY; |
| 650 | entity.gait = payload.gait; |
| 651 | entity.sex = payload.sex ?? entity.sex; |
| 652 | entity.characterId = payload.characterId ?? entity.characterId ?? null; |
| 653 | entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null; |
| 654 | entity.hostile = !!payload.hostile; |
| 655 | entity.canFight = !!payload.canFight; |
| 656 | entity.talkable = !!payload.talkable; |
| 657 | entity.untargetable = !!payload.untargetable; |
| 658 | entity.freeFlight = !!payload.freeFlight; |
| 659 | entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0; |
| 660 | if (payload.health != null) |
| 661 | { entity.health = payload.health; } |
| 662 | if (payload.maxHealth != null) |
| 663 | { entity.maxHealth = payload.maxHealth; } |
| 664 | if (payload.firstName) |
| 665 | { entity.firstName = payload.firstName; } |
| 666 | if (payload.lastName) |
| 667 | { entity.lastName = payload.lastName; } |
| 668 | entity.firstName = entity.firstName ?? ""; |
| 669 | entity.lastName = entity.lastName ?? ""; |
| 670 | if (payload.worldX != null && payload.worldY != null) |
| 671 | { |
| 672 | entity.worldX = payload.worldX; |
| 673 | entity.worldY = payload.worldY; |
| 674 | entity.visualX = payload.worldX * size; |
| 675 | entity.visualY = payload.worldY * size; |
| 676 | entity.targetX = entity.visualX; |
| 677 | entity.targetY = entity.visualY; |
| 678 | } |
| 679 | else |
| 680 | { |
| 681 | entity.visualX = pivot.x; |
| 682 | entity.visualY = pivot.y; |
| 683 | entity.targetX = pivot.x; |
| 684 | entity.targetY = pivot.y; |
| 685 | } |
| 686 | entity.fromX = entity.visualX; |
| 687 | entity.fromY = entity.visualY; |
| 688 | if (payload.layers) |
| 689 | { this.#applyLayers(entity, payload.layers); } |
| 690 | this.#syncHpBar(entity); |
| 691 | this.#placeEntity(entity, performance.now()); |
| 692 | } |
| 693 | |
| 694 | #applyLayers (entity, layers) |
| 695 | { |
| 696 | const base = layers[0]?.sprite |
| 697 | ?? bodySpriteName(entity.sex); |
| 698 | if (this.game.images[base]) |
| 699 | { |
| 700 | entity.object.renderer.sprite = this.game.images[base]; |
| 701 | this.#startIdleAnimation(entity.object); |
| 702 | } |
| 703 | for (const overlay of entity.overlays ?? []) |
| 704 | { overlay.destroy(); } |
| 705 | for (const overlay of entity.bloomOverlays ?? []) |
| 706 | { overlay.destroy(); } |
| 707 | entity.overlays = []; |
| 708 | entity.bloomOverlays = []; |
| 709 | for (const layer of layers.slice(1)) |
| 710 | { |
| 711 | const image = this.game.images[layer.sprite]; |
| 712 | if (!image) |
| 713 | { continue; } |
| 714 | const object = new GameObject(0, 0, image, SORT_ENTITY); |
| 715 | this.scene.addObject(object); |
| 716 | entity.overlays.push(object); |
| 717 | const bloomName = bloomCompanionName(layer.sprite); |
| 718 | const bloomImage = this.game.images[bloomName]; |
| 719 | if (!bloomImage) |
| 720 | { continue; } |
| 721 | const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY); |
| 722 | bloom.renderer.layer = RENDER_LAYER_BLOOM; |
| 723 | this.#markUnlit(bloom); |
| 724 | this.scene.addObject(bloom); |
| 725 | entity.bloomOverlays.push(bloom); |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | #placeEntity (entity, now = performance.now()) |
| 730 | { |
| 731 | const zoom = this.zoom; |
| 732 | const offsetX = entity.shoveOffsetX ?? 0; |
| 733 | const offsetY = entity.shoveOffsetY ?? 0; |
| 734 | const pivotX = entity.visualX + offsetX; |
| 735 | const pivotY = entity.visualY + offsetY; |
| 736 | let walkTilt = 0; |
| 737 | if (entity.lerpStarted != null) |
| 738 | { |
| 739 | const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait)); |
| 740 | const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2; |
| 741 | const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG; |
| 742 | walkTilt = Math.sin(cycles) * tilt; |
| 743 | } |
| 744 | const flashStrength = (entity.damageFlashUntil ?? 0) > now |
| 745 | ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS |
| 746 | : 0; |
| 747 | const tileShade = this.#entityShadeAlpha(entity, now); |
| 748 | |
| 749 | entity.object.transform.rotation = walkTilt; |
| 750 | this.#syncLitSprite(entity.object, tileShade, flashStrength); |
| 751 | this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY); |
| 752 | for (let index = 0; index < (entity.overlays ?? []).length; index++) |
| 753 | { |
| 754 | const overlay = entity.overlays[index]; |
| 755 | const overlaySortY = entity.visualY + 0.5 * (index + 1); |
| 756 | overlay.transform.rotation = walkTilt; |
| 757 | this.#syncLitSprite(overlay, tileShade, flashStrength); |
| 758 | this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY); |
| 759 | } |
| 760 | for (const overlay of entity.bloomOverlays ?? []) |
| 761 | { |
| 762 | overlay.transform.rotation = walkTilt; |
| 763 | this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY); |
| 764 | } |
| 765 | this.#placeHpBar(entity, pivotX, pivotY); |
| 766 | } |
| 767 | |
| 768 | #markUnlit (object) |
| 769 | { |
| 770 | if (!object?.renderer) |
| 771 | { return; } |
| 772 | object._lit = false; |
| 773 | object.renderer.shader = null; |
| 774 | object.renderer.shaderUniforms = null; |
| 775 | object.renderer.secondaryMap = null; |
| 776 | } |
| 777 | |
| 778 | #syncLitSprite (object, darkness, flashStrength = 0) |
| 779 | { |
| 780 | if (!object?.renderer || object._lit === false) |
| 781 | { return; } |
| 782 | object._lit = true; |
| 783 | const dark = Math.min(1, Math.max(0, darkness ?? 0)); |
| 784 | const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); |
| 785 | object.renderer.shader = getSpriteLightingShader(); |
| 786 | object.renderer.shaderUniforms = { u_darkness: dark, u_strength: flash }; |
| 787 | object.renderer.secondaryMap = null; |
| 788 | } |
| 789 | |
| 790 | #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY) |
| 791 | { |
| 792 | const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0; |
| 793 | const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0; |
| 794 | this.#syncLitSprite(object, (fromAlpha + toAlpha) / 2); |
| 795 | } |
| 796 | |
| 797 | #syncHpBar (entity) |
| 798 | { |
| 799 | const current = entity.health; |
| 800 | const max = entity.maxHealth; |
| 801 | const show = entity.mobTypeId != null |
| 802 | && current != null |
| 803 | && max != null |
| 804 | && max > 0 |
| 805 | && current < max; |
| 806 | if (!show) |
| 807 | { |
| 808 | entity.hpBar?.destroy(); |
| 809 | entity.hpBar = null; |
| 810 | entity.hpBarCanvas = null; |
| 811 | return; |
| 812 | } |
| 813 | if (!entity.hpBarCanvas) |
| 814 | { |
| 815 | entity.hpBarCanvas = document.createElement("canvas"); |
| 816 | entity.hpBarCanvas.width = HP_BAR_W; |
| 817 | entity.hpBarCanvas.height = HP_BAR_H; |
| 818 | const image = frameworkImageFromCanvas(entity.hpBarCanvas); |
| 819 | entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR); |
| 820 | this.#markUnlit(entity.hpBar); |
| 821 | this.scene.addObject(entity.hpBar); |
| 822 | } |
| 823 | drawHpBar(entity.hpBarCanvas, current, max); |
| 824 | invalidateCanvasTexture(this.scene, entity.hpBarCanvas); |
| 825 | } |
| 826 | |
| 827 | #placeHpBar (entity, pivotX, pivotY) |
| 828 | { |
| 829 | if (!entity.hpBar) |
| 830 | { return; } |
| 831 | const sprite = entity.object?.renderer?.sprite; |
| 832 | if (!sprite) |
| 833 | { return; } |
| 834 | const zoom = this.zoom; |
| 835 | const drawH = sprite.height * zoom; |
| 836 | const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom); |
| 837 | const spriteTop = centerY - drawH / 2; |
| 838 | const barW = HP_BAR_W * zoom; |
| 839 | const barH = HP_BAR_H * zoom; |
| 840 | entity.hpBar.transform.position.x = pivotX; |
| 841 | entity.hpBar.transform.position.y = spriteTop - barH / 2; |
| 842 | entity.hpBar.transform.size = new vector(barW, barH); |
| 843 | entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR); |
| 844 | this.#markSortDirty(); |
| 845 | } |
| 846 | |
| 847 | #rebuildChunk (snapshot) |
| 848 | { |
| 849 | this.#bakeAndPlaceChunk(snapshot); |
| 850 | const tall = new Set( |
| 851 | (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? []) |
| 852 | .map((entry) => `${entry.tileX},${entry.tileY}`) |
| 853 | ); |
| 854 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 855 | { |
| 856 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 857 | { |
| 858 | const tileX = snapshot.chunkX * CHUNK_SIZE + localX; |
| 859 | const tileY = snapshot.chunkY * CHUNK_SIZE + localY; |
| 860 | this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`)); |
| 861 | } |
| 862 | } |
| 863 | } |
| 864 | |
| 865 | #bakeAndPlaceChunk (snapshot) |
| 866 | { |
| 867 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 868 | const atlases = bakeChunkAtlases({ |
| 869 | snapshot, |
| 870 | catalog: this.catalog, |
| 871 | images: this.game.images, |
| 872 | preview: this.preview |
| 873 | }); |
| 874 | const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX; |
| 875 | let baked = this.bakedChunks.get(key); |
| 876 | if (!baked) |
| 877 | { |
| 878 | const lightmapCanvas = makeLightmapCanvas(atlasPx); |
| 879 | baked = { |
| 880 | groundCanvas: atlases.ground, |
| 881 | blockCanvases: atlases.blockRows, |
| 882 | bloomCanvas: atlases.bloom, |
| 883 | lightmapCanvas, |
| 884 | groundImage: frameworkImageFromCanvas(atlases.ground), |
| 885 | blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)), |
| 886 | bloomImage: frameworkImageFromCanvas(atlases.bloom), |
| 887 | lightmapImage: frameworkImageFromCanvas(lightmapCanvas), |
| 888 | groundObject: null, |
| 889 | blockObjects: [], |
| 890 | bloomObject: null, |
| 891 | tallBlocks: atlases.tallBlocks, |
| 892 | lightmapPixels: null |
| 893 | }; |
| 894 | baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND); |
| 895 | this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1); |
| 896 | this.scene.addObject(baked.groundObject); |
| 897 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 898 | { |
| 899 | const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK); |
| 900 | this.#applyAtlasLighting(object, baked.lightmapImage, row); |
| 901 | this.scene.addObject(object); |
| 902 | baked.blockObjects.push(object); |
| 903 | } |
| 904 | baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK); |
| 905 | baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; |
| 906 | this.#markUnlit(baked.bloomObject); |
| 907 | this.scene.addObject(baked.bloomObject); |
| 908 | this.bakedChunks.set(key, baked); |
| 909 | } |
| 910 | else |
| 911 | { |
| 912 | copyCanvas(atlases.ground, baked.groundCanvas); |
| 913 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 914 | { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); } |
| 915 | copyCanvas(atlases.bloom, baked.bloomCanvas); |
| 916 | invalidateCanvasTexture(this.scene, baked.groundCanvas); |
| 917 | for (const canvas of baked.blockCanvases) |
| 918 | { invalidateCanvasTexture(this.scene, canvas); } |
| 919 | invalidateCanvasTexture(this.scene, baked.bloomCanvas); |
| 920 | baked.tallBlocks = atlases.tallBlocks; |
| 921 | } |
| 922 | baked.chunkX = snapshot.chunkX; |
| 923 | baked.chunkY = snapshot.chunkY; |
| 924 | this.#layoutBakedChunk(snapshot); |
| 925 | } |
| 926 | |
| 927 | #applyAtlasLighting (object, lightmapImage, lightRow) |
| 928 | { |
| 929 | if (!object?.renderer) |
| 930 | { return; } |
| 931 | object._lit = true; |
| 932 | object.renderer.shader = getAtlasLightingShader(); |
| 933 | object.renderer.secondaryMap = lightmapImage; |
| 934 | object.renderer.shaderUniforms = { |
| 935 | u_ambientDark: 0, |
| 936 | u_lightRow: lightRow |
| 937 | }; |
| 938 | } |
| 939 | |
| 940 | #layoutBakedChunk (snapshot) |
| 941 | { |
| 942 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 943 | const baked = this.bakedChunks.get(key); |
| 944 | if (!baked) |
| 945 | { return; } |
| 946 | const size = this.tileSize(); |
| 947 | const left = snapshot.chunkX * CHUNK_SIZE * size; |
| 948 | const top = snapshot.chunkY * CHUNK_SIZE * size; |
| 949 | const chunkPx = CHUNK_SIZE * size; |
| 950 | baked.groundObject.transform.position.x = left + chunkPx / 2; |
| 951 | baked.groundObject.transform.position.y = top + chunkPx / 2; |
| 952 | baked.groundObject.transform.size = new vector(chunkPx, chunkPx); |
| 953 | baked.groundObject.layer = LAYER_GROUND; |
| 954 | |
| 955 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 956 | { |
| 957 | const object = baked.blockObjects[row]; |
| 958 | const rowY = top + row * size + size / 2; |
| 959 | object.transform.position.x = left + chunkPx / 2; |
| 960 | object.transform.position.y = rowY; |
| 961 | object.transform.size = new vector(chunkPx, size); |
| 962 | object.layer = ySortLayer(rowY, SORT_BLOCK); |
| 963 | } |
| 964 | |
| 965 | baked.bloomObject.transform.position.x = left + chunkPx / 2; |
| 966 | baked.bloomObject.transform.position.y = top + chunkPx / 2; |
| 967 | baked.bloomObject.transform.size = new vector(chunkPx, chunkPx); |
| 968 | baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK); |
| 969 | baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; |
| 970 | this.#markSortDirty(); |
| 971 | setNearestFilter(this.scene, baked.groundCanvas); |
| 972 | for (const canvas of baked.blockCanvases) |
| 973 | { setNearestFilter(this.scene, canvas); } |
| 974 | setNearestFilter(this.scene, baked.bloomCanvas); |
| 975 | setNearestFilter(this.scene, baked.lightmapCanvas); |
| 976 | } |
| 977 | |
| 978 | #destroyBakedChunk (key) |
| 979 | { |
| 980 | const baked = this.bakedChunks.get(key); |
| 981 | if (!baked) |
| 982 | { return; } |
| 983 | baked.groundObject?.destroy(); |
| 984 | for (const object of baked.blockObjects ?? []) |
| 985 | { object.destroy(); } |
| 986 | baked.bloomObject?.destroy(); |
| 987 | invalidateCanvasTexture(this.scene, baked.groundCanvas); |
| 988 | for (const canvas of baked.blockCanvases ?? []) |
| 989 | { invalidateCanvasTexture(this.scene, canvas); } |
| 990 | invalidateCanvasTexture(this.scene, baked.bloomCanvas); |
| 991 | invalidateCanvasTexture(this.scene, baked.lightmapCanvas); |
| 992 | this.bakedChunks.delete(key); |
| 993 | } |
| 994 | |
| 995 | #redrawPreview () |
| 996 | { |
| 997 | if (!this.preview) |
| 998 | { return; } |
| 999 | const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`); |
| 1000 | if (snapshot) |
| 1001 | { this.#rebuildChunk(snapshot); } |
| 1002 | } |
| 1003 | |
| 1004 | #drawTile (tileX, tileY, forceTall = null) |
| 1005 | { |
| 1006 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 1007 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 1008 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 1009 | if (!snapshot) |
| 1010 | { return; } |
| 1011 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 1012 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 1013 | const index = localY * CHUNK_SIZE + localX; |
| 1014 | const key = `${tileX},${tileY}`; |
| 1015 | let objects = this.tiles.get(key); |
| 1016 | if (!objects) |
| 1017 | { |
| 1018 | objects = { chunkX, chunkY, tileX, tileY }; |
| 1019 | this.tiles.set(key, objects); |
| 1020 | } |
| 1021 | objects.tileX = tileX; |
| 1022 | objects.tileY = tileY; |
| 1023 | objects.chunkX = chunkX; |
| 1024 | objects.chunkY = chunkY; |
| 1025 | objects.light = snapshot.light[index] ?? 0; |
| 1026 | |
| 1027 | if (objects.ground) |
| 1028 | { |
| 1029 | objects.ground.destroy(); |
| 1030 | objects.ground = null; |
| 1031 | } |
| 1032 | if (objects.groundBloom) |
| 1033 | { |
| 1034 | objects.groundBloom.destroy(); |
| 1035 | objects.groundBloom = null; |
| 1036 | } |
| 1037 | |
| 1038 | const baked = this.bakedChunks.get(`${chunkX},${chunkY}`); |
| 1039 | const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY); |
| 1040 | const isTall = forceTall === true || !!tallEntry; |
| 1041 | if (isTall && tallEntry) |
| 1042 | { |
| 1043 | const pivot = tilePivot(tileX, tileY, this.tileSize()); |
| 1044 | objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY); |
| 1045 | if (objects.block) |
| 1046 | { |
| 1047 | this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY); |
| 1048 | this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0); |
| 1049 | } |
| 1050 | objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY); |
| 1051 | } |
| 1052 | else |
| 1053 | { |
| 1054 | objects.block?.destroy(); |
| 1055 | objects.block = null; |
| 1056 | objects.blockBloom?.destroy(); |
| 1057 | objects.blockBloom = null; |
| 1058 | } |
| 1059 | } |
| 1060 | |
| 1061 | #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK) |
| 1062 | { |
| 1063 | if (!name) |
| 1064 | { |
| 1065 | existing?.destroy(); |
| 1066 | return null; |
| 1067 | } |
| 1068 | const object = this.#ensureSprite(existing, name, sortOrder); |
| 1069 | if (!object) |
| 1070 | { return null; } |
| 1071 | object.renderer.layer = RENDER_LAYER_BLOOM; |
| 1072 | this.#markUnlit(object); |
| 1073 | this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder); |
| 1074 | return object; |
| 1075 | } |
| 1076 | |
| 1077 | #placePivoted (object, pivotX, pivotY, sortY, subOrder) |
| 1078 | { |
| 1079 | const sprite = object?.renderer?.sprite; |
| 1080 | if (!sprite) |
| 1081 | { return; } |
| 1082 | const zoom = this.zoom; |
| 1083 | const draw = spriteDrawSize(sprite.width, sprite.height, zoom); |
| 1084 | const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom); |
| 1085 | object.transform.position.x = center.x; |
| 1086 | object.transform.position.y = center.y; |
| 1087 | object.transform.size = new vector(draw.w, draw.h); |
| 1088 | object.layer = ySortLayer(sortY, subOrder); |
| 1089 | this.#markSortDirty(); |
| 1090 | } |
| 1091 | |
| 1092 | #ensureSprite (existing, name, layer) |
| 1093 | { |
| 1094 | const sprite = this.game.images[name]; |
| 1095 | if (!sprite) |
| 1096 | { |
| 1097 | existing?.destroy(); |
| 1098 | return null; |
| 1099 | } |
| 1100 | if (!existing || existing.renderer.sprite !== sprite) |
| 1101 | { |
| 1102 | existing?.destroy(); |
| 1103 | existing = new GameObject(0, 0, sprite, layer); |
| 1104 | this.#syncLitSprite(existing, 0); |
| 1105 | this.scene.addObject(existing); |
| 1106 | this.#startIdleAnimation(existing); |
| 1107 | } |
| 1108 | return existing; |
| 1109 | } |
| 1110 | |
| 1111 | #startIdleAnimation (object) |
| 1112 | { |
| 1113 | const sprite = object?.renderer?.sprite; |
| 1114 | if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0) |
| 1115 | { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); } |
| 1116 | } |
| 1117 | |
| 1118 | #neighborClosed (snapshot, dir, dx, dy) |
| 1119 | { |
| 1120 | const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`); |
| 1121 | if (other) |
| 1122 | { return !other.open; } |
| 1123 | return !!snapshot.closedEdges?.[dir]; |
| 1124 | } |
| 1125 | |
| 1126 | #rebuildAllEdges () |
| 1127 | { |
| 1128 | const seen = new Set(); |
| 1129 | for (const snapshot of this.chunks.values()) |
| 1130 | { |
| 1131 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 1132 | seen.add(key); |
| 1133 | this.#rebuildChunkEdges(snapshot); |
| 1134 | } |
| 1135 | for (const key of [...this.edges.keys()]) |
| 1136 | { |
| 1137 | if (!seen.has(key)) |
| 1138 | { this.#destroyEdges(key); } |
| 1139 | } |
| 1140 | } |
| 1141 | |
| 1142 | #rebuildChunkEdges (snapshot) |
| 1143 | { |
| 1144 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 1145 | let bars = this.edges.get(key); |
| 1146 | if (!bars) |
| 1147 | { |
| 1148 | bars = {}; |
| 1149 | this.edges.set(key, bars); |
| 1150 | } |
| 1151 | |
| 1152 | const size = this.tileSize(); |
| 1153 | const chunkPx = CHUNK_SIZE * size; |
| 1154 | const left = snapshot.chunkX * CHUNK_SIZE * size; |
| 1155 | const top = snapshot.chunkY * CHUNK_SIZE * size; |
| 1156 | const centerX = left + chunkPx / 2; |
| 1157 | const centerY = top + chunkPx / 2; |
| 1158 | const thickness = Math.max(2, Math.round(2 * this.zoom)); |
| 1159 | const draw = snapshot.open === true; |
| 1160 | |
| 1161 | bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1), |
| 1162 | centerX, top, chunkPx, thickness, true); |
| 1163 | bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1), |
| 1164 | centerX, top + chunkPx, chunkPx, thickness, true); |
| 1165 | bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0), |
| 1166 | left, centerY, chunkPx, thickness, false); |
| 1167 | bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0), |
| 1168 | left + chunkPx, centerY, chunkPx, thickness, false); |
| 1169 | } |
| 1170 | |
| 1171 | #edgeBar (existing, visible, x, y, length, thickness, horizontal) |
| 1172 | { |
| 1173 | if (!visible) |
| 1174 | { |
| 1175 | if (existing) |
| 1176 | { existing.renderer.visible = false; } |
| 1177 | return existing; |
| 1178 | } |
| 1179 | |
| 1180 | existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE); |
| 1181 | this.#markUnlit(existing); |
| 1182 | existing.renderer.visible = true; |
| 1183 | existing.transform.position.x = x; |
| 1184 | existing.transform.position.y = y; |
| 1185 | existing.transform.size = horizontal |
| 1186 | ? new vector(length, thickness) |
| 1187 | : new vector(thickness, length); |
| 1188 | existing.layer = LAYER_EDGE; |
| 1189 | this.#markSortDirty(); |
| 1190 | return existing; |
| 1191 | } |
| 1192 | |
| 1193 | #destroyEdges (key) |
| 1194 | { |
| 1195 | const bars = this.edges.get(key); |
| 1196 | if (!bars) |
| 1197 | { return; } |
| 1198 | bars.north?.destroy(); |
| 1199 | bars.east?.destroy(); |
| 1200 | bars.south?.destroy(); |
| 1201 | bars.west?.destroy(); |
| 1202 | this.edges.delete(key); |
| 1203 | } |
| 1204 | |
| 1205 | #entityShadeAlpha (entity, now) |
| 1206 | { |
| 1207 | const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0; |
| 1208 | if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null) |
| 1209 | { return toAlpha; } |
| 1210 | const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0; |
| 1211 | const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1)); |
| 1212 | return fromAlpha + (toAlpha - fromAlpha) * t; |
| 1213 | } |
| 1214 | |
| 1215 | #markSortDirty () |
| 1216 | { |
| 1217 | this.scene._sortDirty = true; |
| 1218 | } |
| 1219 | |
| 1220 | #updateShade () |
| 1221 | { |
| 1222 | const hour = this.nightPreview ?? this.worldHour; |
| 1223 | const ambientDark = nightFactor(hour, this.settings.nightDarkness); |
| 1224 | const now = performance.now(); |
| 1225 | this.dynamicLights = this.dynamicLights.filter((light) => light.until > now); |
| 1226 | |
| 1227 | const activeLights = [...this.dynamicLights]; |
| 1228 | const tileSize = this.tileSize(); |
| 1229 | for (const entity of this.entities.values()) |
| 1230 | { |
| 1231 | const radius = entity.lightRadiusTiles ?? 0; |
| 1232 | if (radius <= 0) |
| 1233 | { continue; } |
| 1234 | activeLights.push({ |
| 1235 | worldX: entity.visualX / tileSize, |
| 1236 | worldY: entity.visualY / tileSize, |
| 1237 | radiusTiles: radius, |
| 1238 | intensity: 0.85 |
| 1239 | }); |
| 1240 | } |
| 1241 | |
| 1242 | for (const objects of this.tiles.values()) |
| 1243 | { |
| 1244 | const intensity = this.#tileLightIntensity(objects, activeLights); |
| 1245 | objects.shadeAlpha = ambientDark * (1 - intensity); |
| 1246 | if (objects.block) |
| 1247 | { this.#syncLitSprite(objects.block, objects.shadeAlpha); } |
| 1248 | } |
| 1249 | |
| 1250 | for (const baked of this.bakedChunks.values()) |
| 1251 | { |
| 1252 | this.#writeChunkLightmap(baked, activeLights); |
| 1253 | if (baked.groundObject?.renderer?.shaderUniforms) |
| 1254 | { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; } |
| 1255 | for (const object of baked.blockObjects ?? []) |
| 1256 | { |
| 1257 | if (object?.renderer?.shaderUniforms) |
| 1258 | { object.renderer.shaderUniforms.u_ambientDark = ambientDark; } |
| 1259 | } |
| 1260 | } |
| 1261 | |
| 1262 | for (const item of this.groundItems.values()) |
| 1263 | { |
| 1264 | const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0; |
| 1265 | this.#syncLitSprite(item.object, alpha); |
| 1266 | } |
| 1267 | } |
| 1268 | |
| 1269 | #tileLightIntensity (objects, activeLights) |
| 1270 | { |
| 1271 | const baked = Math.min(1, Math.max(0, (objects.light ?? 0) / 255)); |
| 1272 | let dynamic = 0; |
| 1273 | for (const light of activeLights) |
| 1274 | { |
| 1275 | const dx = (objects.tileX + 0.5) - light.worldX; |
| 1276 | const dy = (objects.tileY + 0.5) - light.worldY; |
| 1277 | const dist = Math.hypot(dx, dy); |
| 1278 | if (dist >= light.radiusTiles) |
| 1279 | { continue; } |
| 1280 | const falloff = 1 - dist / light.radiusTiles; |
| 1281 | dynamic = Math.max(dynamic, falloff * light.intensity); |
| 1282 | } |
| 1283 | return Math.max(baked, dynamic); |
| 1284 | } |
| 1285 | |
| 1286 | #writeChunkLightmap (baked, activeLights) |
| 1287 | { |
| 1288 | const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`); |
| 1289 | if (!snapshot) |
| 1290 | { return; } |
| 1291 | const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX; |
| 1292 | const pixelCount = atlasPx * atlasPx * 4; |
| 1293 | if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount) |
| 1294 | { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); } |
| 1295 | const pixels = baked.lightmapPixels; |
| 1296 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 1297 | { |
| 1298 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 1299 | { |
| 1300 | const tileX = baked.chunkX * CHUNK_SIZE + localX; |
| 1301 | const tileY = baked.chunkY * CHUNK_SIZE + localY; |
| 1302 | const index = localY * CHUNK_SIZE + localX; |
| 1303 | const tileObjects = this.tiles.get(`${tileX},${tileY}`); |
| 1304 | let intensity; |
| 1305 | if (tileObjects) |
| 1306 | { |
| 1307 | intensity = this.#tileLightIntensity(tileObjects, activeLights); |
| 1308 | } |
| 1309 | else |
| 1310 | { |
| 1311 | intensity = Math.min(1, Math.max(0, (snapshot.light[index] ?? 0) / 255)); |
| 1312 | } |
| 1313 | const value = Math.round(Math.min(1, intensity) * 255); |
| 1314 | const baseX = localX * SPRITE_SIZE_PX; |
| 1315 | const baseY = localY * SPRITE_SIZE_PX; |
| 1316 | for (let py = 0; py < SPRITE_SIZE_PX; py++) |
| 1317 | { |
| 1318 | for (let px = 0; px < SPRITE_SIZE_PX; px++) |
| 1319 | { |
| 1320 | const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4; |
| 1321 | pixels[offset] = value; |
| 1322 | pixels[offset + 1] = value; |
| 1323 | pixels[offset + 2] = value; |
| 1324 | pixels[offset + 3] = 255; |
| 1325 | } |
| 1326 | } |
| 1327 | } |
| 1328 | } |
| 1329 | const ctx = baked.lightmapCanvas.getContext("2d"); |
| 1330 | ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0); |
| 1331 | invalidateCanvasTexture(this.scene, baked.lightmapCanvas); |
| 1332 | } |
| 1333 | |
| 1334 | #updateSwipes (now) |
| 1335 | { |
| 1336 | this.swipes = this.swipes.filter((swipe) => |
| 1337 | { |
| 1338 | if (swipe.until > now) |
| 1339 | { |
| 1340 | if (swipe.fromTileX != null) |
| 1341 | { |
| 1342 | this.#applyPhysicalCombatFxDarkness( |
| 1343 | swipe.object, |
| 1344 | swipe.fromTileX, |
| 1345 | swipe.fromTileY, |
| 1346 | swipe.tileX, |
| 1347 | swipe.tileY |
| 1348 | ); |
| 1349 | } |
| 1350 | return true; |
| 1351 | } |
| 1352 | swipe.object?.destroy(); |
| 1353 | return false; |
| 1354 | }); |
| 1355 | } |
| 1356 | |
| 1357 | #updateDamageNumbers (now) |
| 1358 | { |
| 1359 | const layer = this.damageNumbersEl; |
| 1360 | if (!layer) |
| 1361 | { return; } |
| 1362 | this.damageFloats = this.damageFloats.filter((entry) => |
| 1363 | { |
| 1364 | const elapsed = now - entry.started; |
| 1365 | if (elapsed >= DAMAGE_FLOAT_MS) |
| 1366 | { |
| 1367 | entry.element?.remove(); |
| 1368 | return false; |
| 1369 | } |
| 1370 | const entity = this.entities.get(entry.entityId); |
| 1371 | if (!entity) |
| 1372 | { |
| 1373 | entry.element?.remove(); |
| 1374 | return false; |
| 1375 | } |
| 1376 | if (!entry.element) |
| 1377 | { |
| 1378 | entry.element = document.createElement("span"); |
| 1379 | entry.element.className = "damage-number"; |
| 1380 | entry.element.textContent = String(entry.damage); |
| 1381 | layer.append(entry.element); |
| 1382 | } |
| 1383 | const anchor = this.nametagAnchor(entity); |
| 1384 | if (!anchor) |
| 1385 | { return true; } |
| 1386 | const t = elapsed / DAMAGE_FLOAT_MS; |
| 1387 | entry.element.style.left = `${anchor.x}px`; |
| 1388 | entry.element.style.top = `${anchor.y - 6 - t * 28}px`; |
| 1389 | entry.element.style.opacity = String(1 - t); |
| 1390 | return true; |
| 1391 | }); |
| 1392 | } |
| 1393 | |
| 1394 | #syncBloomLayer () |
| 1395 | { |
| 1396 | const settings = this.settings ?? DEFAULT_WORLD_SETTINGS; |
| 1397 | this.scene.setLayers([ |
| 1398 | { name: "default" }, |
| 1399 | { |
| 1400 | name: RENDER_LAYER_BLOOM, |
| 1401 | composite: "add", |
| 1402 | postShaders: Shader.getBloomPostChain({ |
| 1403 | threshold: settings.bloomThreshold, |
| 1404 | softKnee: settings.bloomSoftKnee, |
| 1405 | intensity: settings.bloomIntensity, |
| 1406 | blurSize: settings.bloomBlurSize, |
| 1407 | saturation: settings.bloomSaturation, |
| 1408 | colorPreserve: settings.bloomColorPreserve, |
| 1409 | dilate: settings.bloomDilate, |
| 1410 | scales: Math.max(1, Math.round(settings.bloomScales ?? 1)), |
| 1411 | halfRes: (settings.bloomHalfRes ?? 1) >= 0.5 |
| 1412 | }) |
| 1413 | } |
| 1414 | ]); |
| 1415 | } |
| 1416 | } |
| 1417 | |
| 1418 | export function nightFactor (hour, nightDarkness = 0.72) |
| 1419 | { |
| 1420 | const peak = Math.min(1, Math.max(0, nightDarkness)); |
| 1421 | if (hour >= 8 && hour <= 16) |
| 1422 | { return 0; } |
| 1423 | if (hour >= 22 || hour <= 5) |
| 1424 | { return peak; } |
| 1425 | if (hour < 8) |
| 1426 | { return lerp(peak, 0, (hour - 5) / 3); } |
| 1427 | return lerp(0, peak, (hour - 16) / 6); |
| 1428 | } |
| 1429 | |
| 1430 | function bodySpriteName (sex) |
| 1431 | { |
| 1432 | const key = sex === "female" ? "player-body-female" : "player-body-male"; |
| 1433 | return spriteImageName("character", key, key); |
| 1434 | } |
| 1435 | |
| 1436 | function lerp (a, b, t) |
| 1437 | { |
| 1438 | return a + (b - a) * Math.min(1, Math.max(0, t)); |
| 1439 | } |
| 1440 | |
| 1441 | function makeLightmapCanvas (size) |
| 1442 | { |
| 1443 | const canvas = document.createElement("canvas"); |
| 1444 | canvas.width = size; |
| 1445 | canvas.height = size; |
| 1446 | return canvas; |
| 1447 | } |
| 1448 | |
| 1449 | function copyCanvas (source, dest) |
| 1450 | { |
| 1451 | const ctx = dest.getContext("2d"); |
| 1452 | ctx.imageSmoothingEnabled = false; |
| 1453 | ctx.clearRect(0, 0, dest.width, dest.height); |
| 1454 | ctx.drawImage(source, 0, 0); |
| 1455 | } |
| 1456 | |
| 1457 | function setNearestFilter (scene, canvas) |
| 1458 | { |
| 1459 | const glContext = scene?.glContext; |
| 1460 | if (!glContext || !canvas) |
| 1461 | { return; } |
| 1462 | const texture = glContext.getTexture(canvas); |
| 1463 | if (!texture) |
| 1464 | { return; } |
| 1465 | const gl = glContext.gl; |
| 1466 | gl.bindTexture(gl.TEXTURE_2D, texture); |
| 1467 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); |
| 1468 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); |
| 1469 | } |
| 1470 | |
| 1471 | function drawHpBar (canvas, current, max) |
| 1472 | { |
| 1473 | const ctx = canvas.getContext("2d"); |
| 1474 | ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H); |
| 1475 | ctx.fillStyle = "#000000"; |
| 1476 | ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H); |
| 1477 | const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0; |
| 1478 | const fillW = Math.round(12 * ratio); |
| 1479 | if (fillW > 0) |
| 1480 | { |
| 1481 | ctx.fillStyle = "#ff0000"; |
| 1482 | ctx.fillRect(1, 1, fillW, 2); |
| 1483 | } |
| 1484 | } |