| 1 | import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } from "/shared/protocol/constants.js"; |
| 2 | import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js"; |
| 3 | import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js"; |
| 4 | import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js"; |
| 5 | import { itemSpriteName, itemDefinition } from "/shared/definitions/items.js"; |
| 6 | import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js"; |
| 7 | import { normalizeGround, isWadeGround, isWaterGround } from "/shared/definitions/tiles.js"; |
| 8 | import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js"; |
| 9 | import { bakeChunkAtlases } from "./chunkBake.js"; |
| 10 | import { |
| 11 | frameworkImageFromCanvas, |
| 12 | invalidateCanvasTexture |
| 13 | } from "./canvasSprite.js"; |
| 14 | import { applyNearestToAllTextures, setNearestFilter } from "./sprites.js"; |
| 15 | |
| 16 | const LAYER_GROUND = 0; |
| 17 | const LAYER_EDGE = 900000; |
| 18 | const SORT_BLOCK = 2; |
| 19 | const SORT_ENTITY = 3; |
| 20 | const SORT_HP_BAR = 4; |
| 21 | const SORT_FX = 5; |
| 22 | const RENDER_LAYER_BLOOM = "bloom"; |
| 23 | |
| 24 | const HP_BAR_W = 14; |
| 25 | const HP_BAR_H = 4; |
| 26 | const WALK_TILT_DEG = 6; |
| 27 | const RUN_TILT_DEG = 8; |
| 28 | const SHOVE_TILE_FRACTION = 0.25; |
| 29 | const SHOVE_MS = 280; |
| 30 | const DAMAGE_FLASH_MS = 180; |
| 31 | const DAMAGE_FLOAT_MS = 900; |
| 32 | |
| 33 | const SPRITE_LIGHTING_FRAG = [ |
| 34 | "precision mediump float;", |
| 35 | "varying vec2 v_texCoord;", |
| 36 | "uniform sampler2D u_texture;", |
| 37 | "uniform float u_darkness;", |
| 38 | "uniform float u_strength;", |
| 39 | "uniform float u_wade;", |
| 40 | "uniform float u_spriteHeight;", |
| 41 | "void main() {", |
| 42 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 43 | " if (color.a <= 0.0) { discard; }", |
| 44 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 45 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 46 | " vec3 rgb = color.rgb;", |
| 47 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 48 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 49 | " }", |
| 50 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 51 | " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);", |
| 52 | " gl_FragColor = vec4(rgb, color.a);", |
| 53 | "}" |
| 54 | ].join("\n"); |
| 55 | |
| 56 | const WATER_GROUND_FRAG = [ |
| 57 | "precision mediump float;", |
| 58 | "varying vec2 v_texCoord;", |
| 59 | "uniform sampler2D u_texture;", |
| 60 | "uniform float u_darkness;", |
| 61 | "uniform float u_time;", |
| 62 | "uniform float u_edgeN;", |
| 63 | "uniform float u_edgeE;", |
| 64 | "uniform float u_edgeS;", |
| 65 | "uniform float u_edgeW;", |
| 66 | "void main() {", |
| 67 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 68 | " if (color.a <= 0.0) { discard; }", |
| 69 | " vec3 rgb = color.rgb;", |
| 70 | " float foam = 0.0;", |
| 71 | " float pulse = 0.55 + 0.45 * sin(u_time * 3.2 + v_texCoord.x * 18.0 + v_texCoord.y * 10.0);", |
| 72 | " if (u_edgeN > 0.5 && v_texCoord.y < 0.22) {", |
| 73 | " foam = max(foam, (1.0 - v_texCoord.y / 0.22) * pulse);", |
| 74 | " }", |
| 75 | " if (u_edgeS > 0.5 && v_texCoord.y > 0.78) {", |
| 76 | " foam = max(foam, ((v_texCoord.y - 0.78) / 0.22) * pulse);", |
| 77 | " }", |
| 78 | " if (u_edgeW > 0.5 && v_texCoord.x < 0.22) {", |
| 79 | " foam = max(foam, (1.0 - v_texCoord.x / 0.22) * pulse);", |
| 80 | " }", |
| 81 | " if (u_edgeE > 0.5 && v_texCoord.x > 0.78) {", |
| 82 | " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);", |
| 83 | " }", |
| 84 | " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));", |
| 85 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 86 | " gl_FragColor = vec4(rgb, color.a);", |
| 87 | "}" |
| 88 | ].join("\n"); |
| 89 | |
| 90 | /** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */ |
| 91 | const TINT_LIT_SPRITE_FRAG = [ |
| 92 | "precision mediump float;", |
| 93 | "varying vec2 v_texCoord;", |
| 94 | "uniform sampler2D u_texture;", |
| 95 | "uniform float u_darkness;", |
| 96 | "uniform float u_strength;", |
| 97 | "uniform float u_wade;", |
| 98 | "uniform float u_spriteHeight;", |
| 99 | "uniform float u_useTint;", |
| 100 | "uniform vec3 u_tintColor;", |
| 101 | "void main() {", |
| 102 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 103 | " if (color.a <= 0.0) { discard; }", |
| 104 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 105 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 106 | " vec3 rgb = color.rgb;", |
| 107 | " if (u_useTint > 0.5) {", |
| 108 | " float eps = 1.0 / 255.0;", |
| 109 | " if (abs(color.r - color.b) <= eps && color.g < color.r - eps) {", |
| 110 | " float L = color.r;", |
| 111 | " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;", |
| 112 | " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;", |
| 113 | " }", |
| 114 | " }", |
| 115 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 116 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 117 | " }", |
| 118 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 119 | " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);", |
| 120 | " gl_FragColor = vec4(rgb, color.a);", |
| 121 | "}" |
| 122 | ].join("\n"); |
| 123 | |
| 124 | const ATLAS_LIGHTING_FRAG = [ |
| 125 | "precision mediump float;", |
| 126 | "varying vec2 v_texCoord;", |
| 127 | "uniform sampler2D u_texture;", |
| 128 | "uniform sampler2D u_secondary;", |
| 129 | "uniform float u_ambientDark;", |
| 130 | "uniform float u_lightRow;", |
| 131 | "void main() {", |
| 132 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 133 | " if (color.a <= 0.0) { discard; }", |
| 134 | " vec2 lightUV = v_texCoord;", |
| 135 | " if (u_lightRow >= 0.0) {", |
| 136 | " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;", |
| 137 | " }", |
| 138 | " float lit = texture2D(u_secondary, lightUV).r;", |
| 139 | " float darkness = u_ambientDark * (1.0 - lit);", |
| 140 | " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);", |
| 141 | " gl_FragColor = vec4(rgb, color.a);", |
| 142 | "}" |
| 143 | ].join("\n"); |
| 144 | |
| 145 | let spriteLightingShader = null; |
| 146 | let atlasLightingShader = null; |
| 147 | let waterGroundShader = null; |
| 148 | let tintLitSpriteShader = null; |
| 149 | |
| 150 | function getSpriteLightingShader () |
| 151 | { |
| 152 | if (!spriteLightingShader) |
| 153 | { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); } |
| 154 | return spriteLightingShader; |
| 155 | } |
| 156 | |
| 157 | function getAtlasLightingShader () |
| 158 | { |
| 159 | if (!atlasLightingShader) |
| 160 | { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); } |
| 161 | return atlasLightingShader; |
| 162 | } |
| 163 | |
| 164 | function getWaterGroundShader () |
| 165 | { |
| 166 | if (!waterGroundShader) |
| 167 | { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); } |
| 168 | return waterGroundShader; |
| 169 | } |
| 170 | |
| 171 | function getTintLitSpriteShader () |
| 172 | { |
| 173 | if (!tintLitSpriteShader) |
| 174 | { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); } |
| 175 | return tintLitSpriteShader; |
| 176 | } |
| 177 | |
| 178 | export class WorldView |
| 179 | { |
| 180 | constructor (game, scene, catalog = { grounds: {}, blocks: {} }) |
| 181 | { |
| 182 | this.game = game; |
| 183 | this.scene = scene; |
| 184 | this.catalog = catalog; |
| 185 | this.preview = null; |
| 186 | this.zoom = 2; |
| 187 | this.chunks = new Map(); |
| 188 | this.bakedChunks = new Map(); |
| 189 | this.tiles = new Map(); |
| 190 | this.entities = new Map(); |
| 191 | this.groundItems = new Map(); |
| 192 | this.edges = new Map(); |
| 193 | this.localEntityId = null; |
| 194 | this.settings = { ...DEFAULT_WORLD_SETTINGS }; |
| 195 | this.worldHour = 12; |
| 196 | this.nightPreview = null; |
| 197 | this.followPlayer = true; |
| 198 | this.dynamicLights = []; |
| 199 | this.swipes = []; |
| 200 | this.damageFloats = []; |
| 201 | this.damageNumbersEl = document.getElementById("damage-numbers"); |
| 202 | /** @type {Map<string, { object: object, tileX: number, tileY: number, spriteName: string }>} */ |
| 203 | this.editorSpawners = new Map(); |
| 204 | this.spawnRangeHighlight = null; |
| 205 | this.wanderRangeHighlight = null; |
| 206 | this.#syncBloomLayer(); |
| 207 | } |
| 208 | |
| 209 | setSettings (settings) |
| 210 | { |
| 211 | this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings }; |
| 212 | this.#syncBloomLayer(); |
| 213 | } |
| 214 | |
| 215 | setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null) |
| 216 | { |
| 217 | this.localEntityId = entityId; |
| 218 | this.#upsertEntity({ |
| 219 | entityId, |
| 220 | characterId, |
| 221 | tileX, |
| 222 | tileY, |
| 223 | gait, |
| 224 | sex, |
| 225 | firstName, |
| 226 | lastName, |
| 227 | layers: layers ?? undefined |
| 228 | }); |
| 229 | } |
| 230 | |
| 231 | applySnapshot (snapshot) |
| 232 | { |
| 233 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 234 | this.chunks.set(key, snapshot); |
| 235 | this.#rebuildChunk(snapshot); |
| 236 | this.#redrawPreview(); |
| 237 | this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY); |
| 238 | for (const entity of snapshot.entities ?? []) |
| 239 | { this.#upsertEntity(entity); } |
| 240 | const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 241 | for (const [id, item] of [...this.groundItems.entries()]) |
| 242 | { |
| 243 | if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY) |
| 244 | { this.despawnGroundItem(id); } |
| 245 | } |
| 246 | for (const item of snapshot.groundItems ?? []) |
| 247 | { this.upsertGroundItem(item); } |
| 248 | this.#rebuildAllEdges(); |
| 249 | } |
| 250 | |
| 251 | removeChunk (chunkX, chunkY) |
| 252 | { |
| 253 | const key = `${chunkX},${chunkY}`; |
| 254 | this.chunks.delete(key); |
| 255 | this.#destroyBakedChunk(key); |
| 256 | this.#destroyEdges(key); |
| 257 | const prefix = `${chunkX},${chunkY}:`; |
| 258 | for (const [spawnerKey, entry] of [...this.editorSpawners.entries()]) |
| 259 | { |
| 260 | if (!spawnerKey.startsWith(prefix)) |
| 261 | { continue; } |
| 262 | entry.object?.destroy(); |
| 263 | this.editorSpawners.delete(spawnerKey); |
| 264 | } |
| 265 | for (const [tileKey, objects] of [...this.tiles.entries()]) |
| 266 | { |
| 267 | if (objects.chunkX === chunkX && objects.chunkY === chunkY) |
| 268 | { |
| 269 | objects.ground?.destroy(); |
| 270 | objects.groundBloom?.destroy(); |
| 271 | objects.block?.destroy(); |
| 272 | objects.blockBloom?.destroy(); |
| 273 | this.tiles.delete(tileKey); |
| 274 | } |
| 275 | } |
| 276 | for (const [id, item] of [...this.groundItems.entries()]) |
| 277 | { |
| 278 | if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) |
| 279 | { this.despawnGroundItem(id); } |
| 280 | } |
| 281 | this.#rebuildAllEdges(); |
| 282 | } |
| 283 | |
| 284 | setChunkOpen (chunkX, chunkY, open) |
| 285 | { |
| 286 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 287 | if (!snapshot) |
| 288 | { return; } |
| 289 | snapshot.open = !!open; |
| 290 | this.#rebuildAllEdges(); |
| 291 | } |
| 292 | |
| 293 | spawnEntity (payload) |
| 294 | { |
| 295 | this.#upsertEntity(payload); |
| 296 | } |
| 297 | |
| 298 | moveEntity (payload) |
| 299 | { |
| 300 | const existing = this.entities.get(payload.entityId); |
| 301 | if (!existing) |
| 302 | { |
| 303 | this.#upsertEntity(payload); |
| 304 | return; |
| 305 | } |
| 306 | const size = this.tileSize(); |
| 307 | existing.fromX = existing.visualX; |
| 308 | existing.fromY = existing.visualY; |
| 309 | existing.shadeFromTileX = existing.tileX; |
| 310 | existing.shadeFromTileY = existing.tileY; |
| 311 | existing.tileX = payload.tileX; |
| 312 | existing.tileY = payload.tileY; |
| 313 | existing.gait = payload.gait; |
| 314 | existing.freeFlight = !!payload.freeFlight || existing.freeFlight; |
| 315 | if (payload.worldX != null && payload.worldY != null) |
| 316 | { |
| 317 | existing.worldX = payload.worldX; |
| 318 | existing.worldY = payload.worldY; |
| 319 | existing.targetX = payload.worldX * size; |
| 320 | existing.targetY = payload.worldY * size; |
| 321 | } |
| 322 | else |
| 323 | { |
| 324 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 325 | existing.targetX = pivot.x; |
| 326 | existing.targetY = pivot.y; |
| 327 | } |
| 328 | existing.lerpStarted = performance.now(); |
| 329 | existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait); |
| 330 | } |
| 331 | |
| 332 | despawnEntity (entityId) |
| 333 | { |
| 334 | const existing = this.entities.get(entityId); |
| 335 | if (!existing) |
| 336 | { return; } |
| 337 | existing.object?.destroy(); |
| 338 | existing.hpBar?.destroy(); |
| 339 | for (const overlay of existing.overlays ?? []) |
| 340 | { overlay.destroy(); } |
| 341 | for (const overlay of existing.bloomOverlays ?? []) |
| 342 | { overlay.destroy(); } |
| 343 | this.entities.delete(entityId); |
| 344 | } |
| 345 | |
| 346 | updateEntityHealth (entityId, health, maxHealth) |
| 347 | { |
| 348 | const entity = this.entities.get(entityId); |
| 349 | if (!entity) |
| 350 | { return; } |
| 351 | entity.health = health; |
| 352 | entity.maxHealth = maxHealth; |
| 353 | this.#syncHpBar(entity); |
| 354 | } |
| 355 | |
| 356 | flashDamage (entityId) |
| 357 | { |
| 358 | const entity = this.entities.get(entityId); |
| 359 | if (!entity) |
| 360 | { return; } |
| 361 | entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS; |
| 362 | } |
| 363 | |
| 364 | spawnDamageNumber (entityId, damage) |
| 365 | { |
| 366 | const amount = damage | 0; |
| 367 | if (amount <= 0) |
| 368 | { return; } |
| 369 | this.damageFloats.push({ |
| 370 | entityId, |
| 371 | damage: amount, |
| 372 | started: performance.now() |
| 373 | }); |
| 374 | } |
| 375 | |
| 376 | setAppearance (payload) |
| 377 | { |
| 378 | const existing = this.entities.get(payload.entityId); |
| 379 | if (!existing) |
| 380 | { return; } |
| 381 | existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0; |
| 382 | this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]); |
| 383 | this.#placeEntity(existing); |
| 384 | } |
| 385 | |
| 386 | upsertGroundItem (payload) |
| 387 | { |
| 388 | const size = this.tileSize(); |
| 389 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 390 | const potion = payload.instance?.kind === "potion" ? payload.instance : null; |
| 391 | const spriteName = potion |
| 392 | ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`) |
| 393 | : (payload.sprite ?? itemSpriteName(payload.itemId, payload.instance)); |
| 394 | let item = this.groundItems.get(payload.groundItemId); |
| 395 | if (!item) |
| 396 | { |
| 397 | const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK); |
| 398 | this.scene.addObject(object); |
| 399 | item = { object }; |
| 400 | this.groundItems.set(payload.groundItemId, item); |
| 401 | } |
| 402 | else if (item.object && this.game.images[spriteName]) |
| 403 | { item.object.image = this.game.images[spriteName]; } |
| 404 | item.groundItemId = payload.groundItemId; |
| 405 | item.tileX = payload.tileX; |
| 406 | item.tileY = payload.tileY; |
| 407 | item.itemId = payload.itemId; |
| 408 | item.quantity = payload.quantity; |
| 409 | item.displayName = payload.displayName; |
| 410 | item.sprite = spriteName; |
| 411 | item.instance = payload.instance ?? null; |
| 412 | const stack = { itemId: payload.itemId, instance: payload.instance ?? null }; |
| 413 | item.tintColor = resolveItemTint(stack, itemDefinition(payload.itemId)); |
| 414 | this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); |
| 415 | this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0); |
| 416 | } |
| 417 | |
| 418 | despawnGroundItem (groundItemId) |
| 419 | { |
| 420 | const item = this.groundItems.get(groundItemId); |
| 421 | if (!item) |
| 422 | { return; } |
| 423 | item.object?.destroy(); |
| 424 | this.groundItems.delete(groundItemId); |
| 425 | } |
| 426 | |
| 427 | groundItemAtTile (tileX, tileY) |
| 428 | { |
| 429 | return this.groundItemsAtTile(tileX, tileY)[0] ?? null; |
| 430 | } |
| 431 | |
| 432 | groundItemsAtTile (tileX, tileY) |
| 433 | { |
| 434 | const items = []; |
| 435 | for (const item of this.groundItems.values()) |
| 436 | { |
| 437 | if (item.tileX === tileX && item.tileY === tileY) |
| 438 | { items.push(item); } |
| 439 | } |
| 440 | return items; |
| 441 | } |
| 442 | |
| 443 | entitiesAtTile (tileX, tileY) |
| 444 | { |
| 445 | const matches = []; |
| 446 | for (const entity of this.entities.values()) |
| 447 | { |
| 448 | if (entity.tileX === tileX && entity.tileY === tileY) |
| 449 | { matches.push(entity); } |
| 450 | } |
| 451 | matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0)); |
| 452 | return matches; |
| 453 | } |
| 454 | |
| 455 | setZoom (zoom, limits = { min: 1, max: 4 }) |
| 456 | { |
| 457 | const min = limits.min ?? 1; |
| 458 | const max = limits.max ?? 4; |
| 459 | this.zoom = Math.min(max, Math.max(min, zoom)); |
| 460 | for (const snapshot of this.chunks.values()) |
| 461 | { |
| 462 | this.#layoutBakedChunk(snapshot); |
| 463 | this.#rebuildChunk(snapshot); |
| 464 | } |
| 465 | const size = this.tileSize(); |
| 466 | for (const entity of this.entities.values()) |
| 467 | { |
| 468 | entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x; |
| 469 | entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y; |
| 470 | entity.fromX = entity.visualX; |
| 471 | entity.fromY = entity.visualY; |
| 472 | entity.targetX = entity.visualX; |
| 473 | entity.targetY = entity.visualY; |
| 474 | entity.lerpStarted = null; |
| 475 | this.#placeEntity(entity); |
| 476 | } |
| 477 | for (const item of this.groundItems.values()) |
| 478 | { |
| 479 | const pivot = tilePivot(item.tileX, item.tileY, size); |
| 480 | this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); |
| 481 | } |
| 482 | this.#rebuildAllEdges(); |
| 483 | this.#redrawPreview(); |
| 484 | this.#relayoutEditorSpawners(); |
| 485 | this.#relayoutSpawnRangeHighlight(); |
| 486 | applyNearestToAllTextures(this.scene, this.game.images); |
| 487 | } |
| 488 | |
| 489 | tileSize () |
| 490 | { |
| 491 | return SPRITE_SIZE_PX * this.zoom; |
| 492 | } |
| 493 | |
| 494 | screenToTile (mouseX, mouseY) |
| 495 | { |
| 496 | const size = this.tileSize(); |
| 497 | const worldX = mouseX - this.scene.cameraPosition.x; |
| 498 | const worldY = mouseY - this.scene.cameraPosition.y; |
| 499 | return { |
| 500 | tileX: Math.floor(worldX / size), |
| 501 | tileY: Math.floor(worldY / size) |
| 502 | }; |
| 503 | } |
| 504 | |
| 505 | entityAtScreen (mouseX, mouseY) |
| 506 | { |
| 507 | let best = null; |
| 508 | let bestLayer = -Infinity; |
| 509 | for (const entity of this.entities.values()) |
| 510 | { |
| 511 | const box = this.#entityScreenBox(entity); |
| 512 | if (!box) |
| 513 | { continue; } |
| 514 | if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom) |
| 515 | { |
| 516 | const layer = entity.object?.layer ?? 0; |
| 517 | if (layer >= bestLayer) |
| 518 | { |
| 519 | best = entity; |
| 520 | bestLayer = layer; |
| 521 | } |
| 522 | } |
| 523 | } |
| 524 | return best; |
| 525 | } |
| 526 | |
| 527 | nametagAnchor (entity) |
| 528 | { |
| 529 | const box = this.#entityScreenBox(entity); |
| 530 | if (!box) |
| 531 | { return null; } |
| 532 | return { x: (box.left + box.right) / 2, y: box.top }; |
| 533 | } |
| 534 | |
| 535 | #entityScreenBox (entity) |
| 536 | { |
| 537 | const object = entity?.object; |
| 538 | if (!object) |
| 539 | { return null; } |
| 540 | const size = object.transform.size; |
| 541 | const x = object.transform.position.x + this.scene.cameraPosition.x; |
| 542 | const y = object.transform.position.y + this.scene.cameraPosition.y; |
| 543 | return { |
| 544 | left: x - size.x / 2, |
| 545 | right: x + size.x / 2, |
| 546 | top: y - size.y / 2, |
| 547 | bottom: y + size.y / 2 |
| 548 | }; |
| 549 | } |
| 550 | |
| 551 | update (deltaTime) |
| 552 | { |
| 553 | const now = performance.now(); |
| 554 | const size = this.tileSize(); |
| 555 | for (const entity of this.entities.values()) |
| 556 | { |
| 557 | const target = entity.targetX != null && entity.targetY != null |
| 558 | ? { x: entity.targetX, y: entity.targetY } |
| 559 | : tilePivot(entity.tileX, entity.tileY, size); |
| 560 | if (entity.lerpStarted != null) |
| 561 | { |
| 562 | const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs)); |
| 563 | entity.visualX = entity.fromX + (target.x - entity.fromX) * t; |
| 564 | entity.visualY = entity.fromY + (target.y - entity.fromY) * t; |
| 565 | if (t >= 1) |
| 566 | { entity.lerpStarted = null; } |
| 567 | } |
| 568 | else |
| 569 | { |
| 570 | entity.visualX = target.x; |
| 571 | entity.visualY = target.y; |
| 572 | } |
| 573 | this.#updateShove(entity, now, size); |
| 574 | this.#placeEntity(entity, now); |
| 575 | } |
| 576 | |
| 577 | this.#updateSwipes(now); |
| 578 | this.#updateDamageNumbers(now); |
| 579 | this.#centerCamera(); |
| 580 | this.#updateShade(deltaTime); |
| 581 | } |
| 582 | |
| 583 | #updateShove (entity, now, tileSize) |
| 584 | { |
| 585 | if (!entity.shove) |
| 586 | { |
| 587 | entity.shoveOffsetX = 0; |
| 588 | entity.shoveOffsetY = 0; |
| 589 | return; |
| 590 | } |
| 591 | const elapsed = now - entity.shove.started; |
| 592 | const t = Math.min(1, elapsed / entity.shove.durationMs); |
| 593 | const maxDist = tileSize * SHOVE_TILE_FRACTION; |
| 594 | const dx = entity.shove.targetVisualX - entity.shove.startVisualX; |
| 595 | const dy = entity.shove.targetVisualY - entity.shove.startVisualY; |
| 596 | const dist = Math.hypot(dx, dy) || 1; |
| 597 | const ux = dx / dist; |
| 598 | const uy = dy / dist; |
| 599 | let phase; |
| 600 | if (t < 0.45) |
| 601 | { phase = t / 0.45; } |
| 602 | else |
| 603 | { phase = 1 - (t - 0.45) / 0.55; } |
| 604 | entity.shoveOffsetX = ux * maxDist * phase; |
| 605 | entity.shoveOffsetY = uy * maxDist * phase; |
| 606 | if (t >= 1) |
| 607 | { entity.shove = null; } |
| 608 | } |
| 609 | |
| 610 | spawnCombatSwing (payload) |
| 611 | { |
| 612 | const attacker = this.entities.get(payload.attackerId); |
| 613 | const target = this.entities.get(payload.targetId); |
| 614 | if (!attacker || !target) |
| 615 | { return; } |
| 616 | this.#applyShove(attacker, target.visualX, target.visualY); |
| 617 | const midX = (attacker.visualX + target.visualX) / 2; |
| 618 | const midY = (attacker.visualY + target.visualY) / 2; |
| 619 | const sortY = Math.max(attacker.visualY, target.visualY) + 0.02; |
| 620 | const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI); |
| 621 | const spriteName = "fx:melee-swipe:melee-swipe"; |
| 622 | const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX); |
| 623 | if (object.transform) |
| 624 | { object.transform.rotation = angle; } |
| 625 | this.scene.addObject(object); |
| 626 | this.#placePivoted(object, midX, midY, sortY, SORT_FX); |
| 627 | this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY); |
| 628 | this.swipes.push({ |
| 629 | object, |
| 630 | until: performance.now() + 500, |
| 631 | fromTileX: payload.fromTileX, |
| 632 | fromTileY: payload.fromTileY, |
| 633 | tileX: payload.tileX, |
| 634 | tileY: payload.tileY |
| 635 | }); |
| 636 | } |
| 637 | |
| 638 | /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */ |
| 639 | spawnGatherSwing (payload) |
| 640 | { |
| 641 | const attacker = this.entities.get(payload.attackerId); |
| 642 | if (!attacker) |
| 643 | { return; } |
| 644 | const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize()); |
| 645 | this.#applyShove(attacker, pivot.x, pivot.y); |
| 646 | } |
| 647 | |
| 648 | #applyShove (entity, targetVisualX, targetVisualY) |
| 649 | { |
| 650 | entity.shove = { |
| 651 | startVisualX: entity.visualX, |
| 652 | startVisualY: entity.visualY, |
| 653 | targetVisualX, |
| 654 | targetVisualY, |
| 655 | started: performance.now(), |
| 656 | durationMs: SHOVE_MS |
| 657 | }; |
| 658 | } |
| 659 | |
| 660 | /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */ |
| 661 | spawnPhysicalProjectileFx (payload) |
| 662 | { |
| 663 | const spriteName = payload.sprite ?? "fx:projectile:projectile"; |
| 664 | const image = this.game.images[spriteName]; |
| 665 | if (!image) |
| 666 | { return; } |
| 667 | const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize()); |
| 668 | const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize()); |
| 669 | const midX = (fromPivot.x + toPivot.x) / 2; |
| 670 | const midY = (fromPivot.y + toPivot.y) / 2; |
| 671 | const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02; |
| 672 | const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI); |
| 673 | const object = new GameObject(0, 0, image, SORT_FX); |
| 674 | if (object.transform) |
| 675 | { object.transform.rotation = angle; } |
| 676 | this.scene.addObject(object); |
| 677 | this.#placePivoted(object, midX, midY, sortY, SORT_FX); |
| 678 | this.#applyPhysicalCombatFxDarkness( |
| 679 | object, |
| 680 | payload.fromTileX, |
| 681 | payload.fromTileY, |
| 682 | payload.tileX, |
| 683 | payload.tileY |
| 684 | ); |
| 685 | this.swipes.push({ |
| 686 | object, |
| 687 | until: performance.now() + (payload.durationMs ?? 500), |
| 688 | fromTileX: payload.fromTileX, |
| 689 | fromTileY: payload.fromTileY, |
| 690 | tileX: payload.tileX, |
| 691 | tileY: payload.tileY |
| 692 | }); |
| 693 | } |
| 694 | |
| 695 | addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 }) |
| 696 | { |
| 697 | this.dynamicLights.push({ |
| 698 | tileX: Math.floor(worldX), |
| 699 | tileY: Math.floor(worldY), |
| 700 | range: radiusTiles, |
| 701 | intensity, |
| 702 | until: performance.now() + durationMs |
| 703 | }); |
| 704 | } |
| 705 | |
| 706 | updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {}) |
| 707 | { |
| 708 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 709 | if (!snapshot) |
| 710 | { return; } |
| 711 | const index = localY * CHUNK_SIZE + localX; |
| 712 | if (ground !== undefined) |
| 713 | { snapshot.grounds[index] = ground; } |
| 714 | if (block !== undefined) |
| 715 | { snapshot.blocks[index] = block; } |
| 716 | if (light !== undefined) |
| 717 | { snapshot.light[index] = light; } |
| 718 | this.#rebuildChunk(snapshot); |
| 719 | } |
| 720 | |
| 721 | /** |
| 722 | * Editor-only mob markers for authored spawners (invisible during play). |
| 723 | * @param {number} chunkX |
| 724 | * @param {number} chunkY |
| 725 | * @param {Array<{ localX: number, localY: number, config?: { mobTypeId?: string } }>} spawners |
| 726 | * @param {(mobTypeId: string) => string} resolveSprite |
| 727 | */ |
| 728 | setEditorSpawners (chunkX, chunkY, spawners, resolveSprite) |
| 729 | { |
| 730 | const prefix = `${chunkX},${chunkY}:`; |
| 731 | for (const [key, entry] of [...this.editorSpawners.entries()]) |
| 732 | { |
| 733 | if (!key.startsWith(prefix)) |
| 734 | { continue; } |
| 735 | entry.object?.destroy(); |
| 736 | this.editorSpawners.delete(key); |
| 737 | } |
| 738 | for (const spawner of spawners ?? []) |
| 739 | { |
| 740 | const tileX = chunkX * CHUNK_SIZE + spawner.localX; |
| 741 | const tileY = chunkY * CHUNK_SIZE + spawner.localY; |
| 742 | const spriteName = resolveSprite?.(spawner.config?.mobTypeId) ?? null; |
| 743 | if (!spriteName) |
| 744 | { continue; } |
| 745 | const key = `${prefix}${spawner.localX},${spawner.localY}`; |
| 746 | const object = this.#ensureSprite(null, spriteName, SORT_ENTITY); |
| 747 | if (!object) |
| 748 | { continue; } |
| 749 | object.renderer.alpha = 0.85; |
| 750 | const pivot = tilePivot(tileX, tileY, this.tileSize()); |
| 751 | this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY); |
| 752 | this.#markUnlit(object); |
| 753 | this.editorSpawners.set(key, { object, tileX, tileY, spriteName }); |
| 754 | } |
| 755 | } |
| 756 | |
| 757 | clearEditorSpawners () |
| 758 | { |
| 759 | for (const entry of this.editorSpawners.values()) |
| 760 | { entry.object?.destroy(); } |
| 761 | this.editorSpawners.clear(); |
| 762 | } |
| 763 | |
| 764 | #relayoutEditorSpawners () |
| 765 | { |
| 766 | const size = this.tileSize(); |
| 767 | for (const entry of this.editorSpawners.values()) |
| 768 | { |
| 769 | if (!entry.object) |
| 770 | { continue; } |
| 771 | const pivot = tilePivot(entry.tileX, entry.tileY, size); |
| 772 | this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY); |
| 773 | } |
| 774 | } |
| 775 | |
| 776 | /** |
| 777 | * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares). |
| 778 | */ |
| 779 | setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null) |
| 780 | { |
| 781 | const spawnRadius = Math.max(0, spawnRange | 0); |
| 782 | const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0)); |
| 783 | if (this.spawnRangeHighlight |
| 784 | && this.wanderRangeHighlight |
| 785 | && this.spawnRangeHighlight.tileX === tileX |
| 786 | && this.spawnRangeHighlight.tileY === tileY |
| 787 | && this.spawnRangeHighlight.range === spawnRadius |
| 788 | && this.wanderRangeHighlight.range === wanderRadius) |
| 789 | { |
| 790 | this.#relayoutSpawnRangeHighlight(); |
| 791 | return; |
| 792 | } |
| 793 | this.clearSpawnRangeHighlight(); |
| 794 | const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE); |
| 795 | const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE); |
| 796 | if (wanderObject) |
| 797 | { |
| 798 | this.#markUnlit(wanderObject); |
| 799 | wanderObject.renderer.alpha = 1; |
| 800 | this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius }; |
| 801 | } |
| 802 | if (spawnObject) |
| 803 | { |
| 804 | this.#markUnlit(spawnObject); |
| 805 | spawnObject.renderer.alpha = 1; |
| 806 | this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius }; |
| 807 | } |
| 808 | this.#relayoutSpawnRangeHighlight(); |
| 809 | } |
| 810 | |
| 811 | clearSpawnRangeHighlight () |
| 812 | { |
| 813 | this.spawnRangeHighlight?.object?.destroy(); |
| 814 | this.wanderRangeHighlight?.object?.destroy(); |
| 815 | this.spawnRangeHighlight = null; |
| 816 | this.wanderRangeHighlight = null; |
| 817 | } |
| 818 | |
| 819 | #relayoutSpawnRangeHighlight () |
| 820 | { |
| 821 | this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2); |
| 822 | this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1); |
| 823 | } |
| 824 | |
| 825 | #layoutRangeOverlay (highlight, layer) |
| 826 | { |
| 827 | if (!highlight?.object) |
| 828 | { return; } |
| 829 | const size = this.tileSize(); |
| 830 | const side = (2 * highlight.range + 1) * size; |
| 831 | const left = (highlight.tileX - highlight.range) * size; |
| 832 | const top = (highlight.tileY - highlight.range) * size; |
| 833 | highlight.object.transform.position.x = left + side / 2; |
| 834 | highlight.object.transform.position.y = top + side / 2; |
| 835 | highlight.object.transform.size = new vector(side, side); |
| 836 | highlight.object.layer = layer; |
| 837 | this.#markSortDirty(); |
| 838 | } |
| 839 | |
| 840 | setTilePreview (tileX, tileY, override) |
| 841 | { |
| 842 | const previous = this.preview; |
| 843 | this.preview = { tileX, tileY, ...override }; |
| 844 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 845 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 846 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 847 | if (snapshot) |
| 848 | { this.#rebuildChunk(snapshot); } |
| 849 | if (previous && (previous.tileX !== tileX || previous.tileY !== tileY)) |
| 850 | { |
| 851 | const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`); |
| 852 | if (prevSnapshot && prevSnapshot !== snapshot) |
| 853 | { this.#rebuildChunk(prevSnapshot); } |
| 854 | } |
| 855 | } |
| 856 | |
| 857 | clearTilePreview () |
| 858 | { |
| 859 | const previous = this.preview; |
| 860 | this.preview = null; |
| 861 | if (previous) |
| 862 | { |
| 863 | const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`); |
| 864 | if (snapshot) |
| 865 | { this.#rebuildChunk(snapshot); } |
| 866 | } |
| 867 | } |
| 868 | |
| 869 | #lerpMs (gait) |
| 870 | { |
| 871 | const walk = this.settings.walkTilesPerSecond || 2; |
| 872 | const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk; |
| 873 | return seconds * 1000; |
| 874 | } |
| 875 | |
| 876 | #centerCamera () |
| 877 | { |
| 878 | if (!this.followPlayer) |
| 879 | { return; } |
| 880 | const local = this.entities.get(this.localEntityId); |
| 881 | if (!local) |
| 882 | { return; } |
| 883 | this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX; |
| 884 | this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY; |
| 885 | } |
| 886 | |
| 887 | #upsertEntity (payload) |
| 888 | { |
| 889 | const size = this.tileSize(); |
| 890 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 891 | let entity = this.entities.get(payload.entityId); |
| 892 | if (!entity) |
| 893 | { |
| 894 | const spriteName = payload.layers?.[0]?.sprite |
| 895 | ?? payload.sprite |
| 896 | ?? bodySpriteName(payload.sex); |
| 897 | const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY); |
| 898 | this.scene.addObject(object); |
| 899 | this.#startIdleAnimation(object); |
| 900 | entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y }; |
| 901 | this.entities.set(payload.entityId, entity); |
| 902 | } |
| 903 | entity.entityId = payload.entityId; |
| 904 | entity.tileX = payload.tileX; |
| 905 | entity.tileY = payload.tileY; |
| 906 | entity.gait = payload.gait; |
| 907 | entity.sex = payload.sex ?? entity.sex; |
| 908 | entity.characterId = payload.characterId ?? entity.characterId ?? null; |
| 909 | entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null; |
| 910 | entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile; |
| 911 | entity.canFight = payload.canFight != null |
| 912 | ? !!payload.canFight |
| 913 | : !!(entity.canFight || (payload.mobTypeId && !payload.talkable)); |
| 914 | entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable; |
| 915 | entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable; |
| 916 | entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight; |
| 917 | entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0; |
| 918 | if (payload.health != null) |
| 919 | { entity.health = payload.health; } |
| 920 | if (payload.maxHealth != null) |
| 921 | { entity.maxHealth = payload.maxHealth; } |
| 922 | if (payload.firstName) |
| 923 | { entity.firstName = payload.firstName; } |
| 924 | if (payload.lastName) |
| 925 | { entity.lastName = payload.lastName; } |
| 926 | entity.firstName = entity.firstName ?? ""; |
| 927 | entity.lastName = entity.lastName ?? ""; |
| 928 | if (payload.worldX != null && payload.worldY != null) |
| 929 | { |
| 930 | entity.worldX = payload.worldX; |
| 931 | entity.worldY = payload.worldY; |
| 932 | entity.visualX = payload.worldX * size; |
| 933 | entity.visualY = payload.worldY * size; |
| 934 | entity.targetX = entity.visualX; |
| 935 | entity.targetY = entity.visualY; |
| 936 | } |
| 937 | else |
| 938 | { |
| 939 | entity.visualX = pivot.x; |
| 940 | entity.visualY = pivot.y; |
| 941 | entity.targetX = pivot.x; |
| 942 | entity.targetY = pivot.y; |
| 943 | } |
| 944 | entity.fromX = entity.visualX; |
| 945 | entity.fromY = entity.visualY; |
| 946 | if (payload.layers) |
| 947 | { this.#applyLayers(entity, payload.layers); } |
| 948 | this.#syncHpBar(entity); |
| 949 | this.#placeEntity(entity, performance.now()); |
| 950 | } |
| 951 | |
| 952 | #applyLayers (entity, layers) |
| 953 | { |
| 954 | const base = layers[0]?.sprite |
| 955 | ?? bodySpriteName(entity.sex); |
| 956 | if (this.game.images[base]) |
| 957 | { |
| 958 | entity.object.renderer.sprite = this.game.images[base]; |
| 959 | this.#startIdleAnimation(entity.object); |
| 960 | } |
| 961 | for (const overlay of entity.overlays ?? []) |
| 962 | { overlay.destroy(); } |
| 963 | for (const overlay of entity.bloomOverlays ?? []) |
| 964 | { overlay.destroy(); } |
| 965 | entity.overlays = []; |
| 966 | entity.overlayTints = []; |
| 967 | entity.bloomOverlays = []; |
| 968 | for (const layer of layers.slice(1)) |
| 969 | { |
| 970 | const image = this.game.images[layer.sprite]; |
| 971 | if (!image) |
| 972 | { continue; } |
| 973 | const object = new GameObject(0, 0, image, SORT_ENTITY); |
| 974 | this.scene.addObject(object); |
| 975 | entity.overlays.push(object); |
| 976 | entity.overlayTints.push( |
| 977 | layer.tint |
| 978 | ? normalizeRgb(layer.tint) |
| 979 | : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null) |
| 980 | ); |
| 981 | const bloomName = bloomCompanionName(layer.sprite); |
| 982 | const bloomImage = this.game.images[bloomName]; |
| 983 | if (!bloomImage) |
| 984 | { continue; } |
| 985 | const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY); |
| 986 | bloom.renderer.layer = RENDER_LAYER_BLOOM; |
| 987 | this.#markUnlit(bloom); |
| 988 | this.scene.addObject(bloom); |
| 989 | entity.bloomOverlays.push(bloom); |
| 990 | } |
| 991 | } |
| 992 | |
| 993 | #placeEntity (entity, now = performance.now()) |
| 994 | { |
| 995 | const zoom = this.zoom; |
| 996 | const offsetX = entity.shoveOffsetX ?? 0; |
| 997 | const offsetY = entity.shoveOffsetY ?? 0; |
| 998 | const pivotX = entity.visualX + offsetX; |
| 999 | const pivotY = entity.visualY + offsetY; |
| 1000 | let walkTilt = 0; |
| 1001 | if (entity.lerpStarted != null) |
| 1002 | { |
| 1003 | const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait)); |
| 1004 | const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2; |
| 1005 | const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG; |
| 1006 | walkTilt = Math.sin(cycles) * tilt; |
| 1007 | } |
| 1008 | const flashStrength = (entity.damageFlashUntil ?? 0) > now |
| 1009 | ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS |
| 1010 | : 0; |
| 1011 | const tileShade = this.#entityShadeAlpha(entity, now); |
| 1012 | const wade = isWadeGround(this.#groundTypeAt(entity.tileX, entity.tileY)); |
| 1013 | |
| 1014 | entity.object.transform.rotation = walkTilt; |
| 1015 | this.#syncLitSprite(entity.object, tileShade, flashStrength, wade); |
| 1016 | this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY); |
| 1017 | for (let index = 0; index < (entity.overlays ?? []).length; index++) |
| 1018 | { |
| 1019 | const overlay = entity.overlays[index]; |
| 1020 | const overlaySortY = entity.visualY + 0.5 * (index + 1); |
| 1021 | overlay.transform.rotation = walkTilt; |
| 1022 | this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null); |
| 1023 | this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY); |
| 1024 | } |
| 1025 | for (const overlay of entity.bloomOverlays ?? []) |
| 1026 | { |
| 1027 | overlay.transform.rotation = walkTilt; |
| 1028 | this.#syncLitSprite(overlay, tileShade, flashStrength, wade); |
| 1029 | this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY); |
| 1030 | } |
| 1031 | this.#placeHpBar(entity, pivotX, pivotY); |
| 1032 | } |
| 1033 | |
| 1034 | #markUnlit (object) |
| 1035 | { |
| 1036 | if (!object?.renderer) |
| 1037 | { return; } |
| 1038 | object._lit = false; |
| 1039 | object.renderer.shader = null; |
| 1040 | object.renderer.shaderUniforms = null; |
| 1041 | object.renderer.secondaryMap = null; |
| 1042 | } |
| 1043 | |
| 1044 | #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null) |
| 1045 | { |
| 1046 | if (!object?.renderer || object._lit === false) |
| 1047 | { return; } |
| 1048 | object._lit = true; |
| 1049 | const dark = Math.min(1, Math.max(0, darkness ?? 0)); |
| 1050 | const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); |
| 1051 | const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX; |
| 1052 | const tint = tintColor ? normalizeRgb(tintColor) : null; |
| 1053 | if (tint) |
| 1054 | { |
| 1055 | object.renderer.shader = getTintLitSpriteShader(); |
| 1056 | object.renderer.shaderUniforms = { |
| 1057 | u_darkness: dark, |
| 1058 | u_strength: flash, |
| 1059 | u_wade: wade ? 1 : 0, |
| 1060 | u_spriteHeight: height, |
| 1061 | u_useTint: 1, |
| 1062 | u_tintColor: [tint.r, tint.g, tint.b] |
| 1063 | }; |
| 1064 | } |
| 1065 | else |
| 1066 | { |
| 1067 | object.renderer.shader = getSpriteLightingShader(); |
| 1068 | object.renderer.shaderUniforms = { |
| 1069 | u_darkness: dark, |
| 1070 | u_strength: flash, |
| 1071 | u_wade: wade ? 1 : 0, |
| 1072 | u_spriteHeight: height |
| 1073 | }; |
| 1074 | } |
| 1075 | object.renderer.secondaryMap = null; |
| 1076 | } |
| 1077 | |
| 1078 | #syncGroundItemSprite (item, darkness) |
| 1079 | { |
| 1080 | this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null); |
| 1081 | } |
| 1082 | |
| 1083 | #groundTypeAt (tileX, tileY) |
| 1084 | { |
| 1085 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 1086 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 1087 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 1088 | if (!snapshot) |
| 1089 | { return null; } |
| 1090 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 1091 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 1092 | const index = localY * CHUNK_SIZE + localX; |
| 1093 | return normalizeGround(snapshot.grounds?.[index]).typeId; |
| 1094 | } |
| 1095 | |
| 1096 | #waterCoastEdges (tileX, tileY) |
| 1097 | { |
| 1098 | return { |
| 1099 | n: !isWaterGround(this.#groundTypeAt(tileX, tileY - 1)) ? 1 : 0, |
| 1100 | e: !isWaterGround(this.#groundTypeAt(tileX + 1, tileY)) ? 1 : 0, |
| 1101 | s: !isWaterGround(this.#groundTypeAt(tileX, tileY + 1)) ? 1 : 0, |
| 1102 | w: !isWaterGround(this.#groundTypeAt(tileX - 1, tileY)) ? 1 : 0 |
| 1103 | }; |
| 1104 | } |
| 1105 | |
| 1106 | #syncWaterGroundSprite (object, darkness, edges, timeSec) |
| 1107 | { |
| 1108 | if (!object?.renderer) |
| 1109 | { return; } |
| 1110 | object._lit = true; |
| 1111 | object.renderer.shader = getWaterGroundShader(); |
| 1112 | object.renderer.secondaryMap = null; |
| 1113 | object.renderer.shaderUniforms = { |
| 1114 | u_darkness: Math.min(1, Math.max(0, darkness ?? 0)), |
| 1115 | u_time: timeSec, |
| 1116 | u_edgeN: edges?.n ?? 0, |
| 1117 | u_edgeE: edges?.e ?? 0, |
| 1118 | u_edgeS: edges?.s ?? 0, |
| 1119 | u_edgeW: edges?.w ?? 0 |
| 1120 | }; |
| 1121 | } |
| 1122 | |
| 1123 | #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY) |
| 1124 | { |
| 1125 | const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0; |
| 1126 | const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0; |
| 1127 | this.#syncLitSprite(object, (fromAlpha + toAlpha) / 2); |
| 1128 | } |
| 1129 | |
| 1130 | #syncHpBar (entity) |
| 1131 | { |
| 1132 | const current = entity.health; |
| 1133 | const max = entity.maxHealth; |
| 1134 | const show = entity.mobTypeId != null |
| 1135 | && current != null |
| 1136 | && max != null |
| 1137 | && max > 0 |
| 1138 | && current < max; |
| 1139 | if (!show) |
| 1140 | { |
| 1141 | entity.hpBar?.destroy(); |
| 1142 | entity.hpBar = null; |
| 1143 | entity.hpBarCanvas = null; |
| 1144 | return; |
| 1145 | } |
| 1146 | if (!entity.hpBarCanvas) |
| 1147 | { |
| 1148 | entity.hpBarCanvas = document.createElement("canvas"); |
| 1149 | entity.hpBarCanvas.width = HP_BAR_W; |
| 1150 | entity.hpBarCanvas.height = HP_BAR_H; |
| 1151 | const image = frameworkImageFromCanvas(entity.hpBarCanvas); |
| 1152 | entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR); |
| 1153 | this.#markUnlit(entity.hpBar); |
| 1154 | this.scene.addObject(entity.hpBar); |
| 1155 | } |
| 1156 | drawHpBar(entity.hpBarCanvas, current, max); |
| 1157 | invalidateCanvasTexture(this.scene, entity.hpBarCanvas); |
| 1158 | } |
| 1159 | |
| 1160 | #placeHpBar (entity, pivotX, pivotY) |
| 1161 | { |
| 1162 | if (!entity.hpBar) |
| 1163 | { return; } |
| 1164 | const sprite = entity.object?.renderer?.sprite; |
| 1165 | if (!sprite) |
| 1166 | { return; } |
| 1167 | const zoom = this.zoom; |
| 1168 | const drawH = sprite.height * zoom; |
| 1169 | const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom); |
| 1170 | const spriteTop = centerY - drawH / 2; |
| 1171 | const barW = HP_BAR_W * zoom; |
| 1172 | const barH = HP_BAR_H * zoom; |
| 1173 | entity.hpBar.transform.position.x = pivotX; |
| 1174 | entity.hpBar.transform.position.y = spriteTop - barH / 2; |
| 1175 | entity.hpBar.transform.size = new vector(barW, barH); |
| 1176 | entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR); |
| 1177 | this.#markSortDirty(); |
| 1178 | } |
| 1179 | |
| 1180 | #rebuildChunk (snapshot) |
| 1181 | { |
| 1182 | this.#bakeAndPlaceChunk(snapshot); |
| 1183 | const tall = new Set( |
| 1184 | (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? []) |
| 1185 | .map((entry) => `${entry.tileX},${entry.tileY}`) |
| 1186 | ); |
| 1187 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 1188 | { |
| 1189 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 1190 | { |
| 1191 | const tileX = snapshot.chunkX * CHUNK_SIZE + localX; |
| 1192 | const tileY = snapshot.chunkY * CHUNK_SIZE + localY; |
| 1193 | this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`)); |
| 1194 | } |
| 1195 | } |
| 1196 | } |
| 1197 | |
| 1198 | #bakeAndPlaceChunk (snapshot) |
| 1199 | { |
| 1200 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 1201 | const atlases = bakeChunkAtlases({ |
| 1202 | snapshot, |
| 1203 | catalog: this.catalog, |
| 1204 | images: this.game.images, |
| 1205 | preview: this.preview |
| 1206 | }); |
| 1207 | const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX; |
| 1208 | let baked = this.bakedChunks.get(key); |
| 1209 | if (!baked) |
| 1210 | { |
| 1211 | const lightmapCanvas = makeLightmapCanvas(atlasPx); |
| 1212 | baked = { |
| 1213 | groundCanvas: atlases.ground, |
| 1214 | blockCanvases: atlases.blockRows, |
| 1215 | bloomCanvas: atlases.bloom, |
| 1216 | lightmapCanvas, |
| 1217 | groundImage: frameworkImageFromCanvas(atlases.ground), |
| 1218 | blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)), |
| 1219 | bloomImage: frameworkImageFromCanvas(atlases.bloom), |
| 1220 | lightmapImage: frameworkImageFromCanvas(lightmapCanvas), |
| 1221 | groundObject: null, |
| 1222 | blockObjects: [], |
| 1223 | bloomObject: null, |
| 1224 | tallBlocks: atlases.tallBlocks, |
| 1225 | animatedGrounds: atlases.animatedGrounds, |
| 1226 | lightmapPixels: null |
| 1227 | }; |
| 1228 | baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND); |
| 1229 | this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1); |
| 1230 | this.scene.addObject(baked.groundObject); |
| 1231 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 1232 | { |
| 1233 | const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK); |
| 1234 | this.#applyAtlasLighting(object, baked.lightmapImage, row); |
| 1235 | this.scene.addObject(object); |
| 1236 | baked.blockObjects.push(object); |
| 1237 | } |
| 1238 | baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK); |
| 1239 | baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; |
| 1240 | this.#markUnlit(baked.bloomObject); |
| 1241 | this.scene.addObject(baked.bloomObject); |
| 1242 | this.bakedChunks.set(key, baked); |
| 1243 | } |
| 1244 | else |
| 1245 | { |
| 1246 | copyCanvas(atlases.ground, baked.groundCanvas); |
| 1247 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 1248 | { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); } |
| 1249 | copyCanvas(atlases.bloom, baked.bloomCanvas); |
| 1250 | invalidateCanvasTexture(this.scene, baked.groundCanvas); |
| 1251 | for (const canvas of baked.blockCanvases) |
| 1252 | { invalidateCanvasTexture(this.scene, canvas); } |
| 1253 | invalidateCanvasTexture(this.scene, baked.bloomCanvas); |
| 1254 | baked.tallBlocks = atlases.tallBlocks; |
| 1255 | baked.animatedGrounds = atlases.animatedGrounds; |
| 1256 | } |
| 1257 | baked.chunkX = snapshot.chunkX; |
| 1258 | baked.chunkY = snapshot.chunkY; |
| 1259 | this.#layoutBakedChunk(snapshot); |
| 1260 | } |
| 1261 | |
| 1262 | #applyAtlasLighting (object, lightmapImage, lightRow) |
| 1263 | { |
| 1264 | if (!object?.renderer) |
| 1265 | { return; } |
| 1266 | object._lit = true; |
| 1267 | object.renderer.shader = getAtlasLightingShader(); |
| 1268 | object.renderer.secondaryMap = lightmapImage; |
| 1269 | object.renderer.shaderUniforms = { |
| 1270 | u_ambientDark: 0, |
| 1271 | u_lightRow: lightRow |
| 1272 | }; |
| 1273 | } |
| 1274 | |
| 1275 | #layoutBakedChunk (snapshot) |
| 1276 | { |
| 1277 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 1278 | const baked = this.bakedChunks.get(key); |
| 1279 | if (!baked) |
| 1280 | { return; } |
| 1281 | const size = this.tileSize(); |
| 1282 | const left = snapshot.chunkX * CHUNK_SIZE * size; |
| 1283 | const top = snapshot.chunkY * CHUNK_SIZE * size; |
| 1284 | const chunkPx = CHUNK_SIZE * size; |
| 1285 | baked.groundObject.transform.position.x = left + chunkPx / 2; |
| 1286 | baked.groundObject.transform.position.y = top + chunkPx / 2; |
| 1287 | baked.groundObject.transform.size = new vector(chunkPx, chunkPx); |
| 1288 | baked.groundObject.layer = LAYER_GROUND; |
| 1289 | |
| 1290 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 1291 | { |
| 1292 | const object = baked.blockObjects[row]; |
| 1293 | const rowY = top + row * size + size / 2; |
| 1294 | object.transform.position.x = left + chunkPx / 2; |
| 1295 | object.transform.position.y = rowY; |
| 1296 | object.transform.size = new vector(chunkPx, size); |
| 1297 | object.layer = ySortLayer(rowY, SORT_BLOCK); |
| 1298 | } |
| 1299 | |
| 1300 | baked.bloomObject.transform.position.x = left + chunkPx / 2; |
| 1301 | baked.bloomObject.transform.position.y = top + chunkPx / 2; |
| 1302 | baked.bloomObject.transform.size = new vector(chunkPx, chunkPx); |
| 1303 | baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK); |
| 1304 | baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; |
| 1305 | this.#markSortDirty(); |
| 1306 | setNearestFilter(this.scene, baked.groundCanvas); |
| 1307 | for (const canvas of baked.blockCanvases) |
| 1308 | { setNearestFilter(this.scene, canvas); } |
| 1309 | setNearestFilter(this.scene, baked.bloomCanvas); |
| 1310 | setNearestFilter(this.scene, baked.lightmapCanvas); |
| 1311 | } |
| 1312 | |
| 1313 | #destroyBakedChunk (key) |
| 1314 | { |
| 1315 | const baked = this.bakedChunks.get(key); |
| 1316 | if (!baked) |
| 1317 | { return; } |
| 1318 | baked.groundObject?.destroy(); |
| 1319 | for (const object of baked.blockObjects ?? []) |
| 1320 | { object.destroy(); } |
| 1321 | baked.bloomObject?.destroy(); |
| 1322 | invalidateCanvasTexture(this.scene, baked.groundCanvas); |
| 1323 | for (const canvas of baked.blockCanvases ?? []) |
| 1324 | { invalidateCanvasTexture(this.scene, canvas); } |
| 1325 | invalidateCanvasTexture(this.scene, baked.bloomCanvas); |
| 1326 | invalidateCanvasTexture(this.scene, baked.lightmapCanvas); |
| 1327 | this.bakedChunks.delete(key); |
| 1328 | } |
| 1329 | |
| 1330 | #redrawPreview () |
| 1331 | { |
| 1332 | if (!this.preview) |
| 1333 | { return; } |
| 1334 | const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`); |
| 1335 | if (snapshot) |
| 1336 | { this.#rebuildChunk(snapshot); } |
| 1337 | } |
| 1338 | |
| 1339 | #refreshWaterCoastsNear (chunkX, chunkY) |
| 1340 | { |
| 1341 | const timeSec = performance.now() / 1000; |
| 1342 | for (const objects of this.tiles.values()) |
| 1343 | { |
| 1344 | if (!objects.ground || !isWaterGround(objects.groundTypeId)) |
| 1345 | { continue; } |
| 1346 | if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1) |
| 1347 | { continue; } |
| 1348 | objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY); |
| 1349 | this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, objects.waterEdges, timeSec); |
| 1350 | } |
| 1351 | } |
| 1352 | |
| 1353 | #drawTile (tileX, tileY, forceTall = null) |
| 1354 | { |
| 1355 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 1356 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 1357 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 1358 | if (!snapshot) |
| 1359 | { return; } |
| 1360 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 1361 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 1362 | const index = localY * CHUNK_SIZE + localX; |
| 1363 | const key = `${tileX},${tileY}`; |
| 1364 | let objects = this.tiles.get(key); |
| 1365 | if (!objects) |
| 1366 | { |
| 1367 | objects = { chunkX, chunkY, tileX, tileY }; |
| 1368 | this.tiles.set(key, objects); |
| 1369 | } |
| 1370 | objects.tileX = tileX; |
| 1371 | objects.tileY = tileY; |
| 1372 | objects.chunkX = chunkX; |
| 1373 | objects.chunkY = chunkY; |
| 1374 | objects.light = snapshot.light[index] ?? 0; |
| 1375 | |
| 1376 | const baked = this.bakedChunks.get(`${chunkX},${chunkY}`); |
| 1377 | const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY); |
| 1378 | if (animatedGround) |
| 1379 | { |
| 1380 | objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND); |
| 1381 | if (objects.ground) |
| 1382 | { |
| 1383 | const size = this.tileSize(); |
| 1384 | objects.ground.transform.position.x = tileX * size + size / 2; |
| 1385 | objects.ground.transform.position.y = tileY * size + size / 2; |
| 1386 | objects.ground.transform.size = new vector(size, size); |
| 1387 | objects.ground.layer = LAYER_GROUND; |
| 1388 | objects.groundTypeId = animatedGround.typeId; |
| 1389 | const edges = isWaterGround(animatedGround.typeId) |
| 1390 | ? this.#waterCoastEdges(tileX, tileY) |
| 1391 | : { n: 0, e: 0, s: 0, w: 0 }; |
| 1392 | objects.waterEdges = edges; |
| 1393 | this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, edges, performance.now() / 1000); |
| 1394 | this.#markSortDirty(); |
| 1395 | } |
| 1396 | if (animatedGround.bloom) |
| 1397 | { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); } |
| 1398 | else |
| 1399 | { |
| 1400 | objects.groundBloom?.destroy(); |
| 1401 | objects.groundBloom = null; |
| 1402 | } |
| 1403 | } |
| 1404 | else |
| 1405 | { |
| 1406 | objects.ground?.destroy(); |
| 1407 | objects.ground = null; |
| 1408 | objects.groundBloom?.destroy(); |
| 1409 | objects.groundBloom = null; |
| 1410 | objects.groundTypeId = null; |
| 1411 | objects.waterEdges = null; |
| 1412 | } |
| 1413 | |
| 1414 | const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY); |
| 1415 | const isTall = forceTall === true || !!tallEntry; |
| 1416 | if (isTall && tallEntry) |
| 1417 | { |
| 1418 | const pivot = tilePivot(tileX, tileY, this.tileSize()); |
| 1419 | objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY); |
| 1420 | if (objects.block) |
| 1421 | { |
| 1422 | this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY); |
| 1423 | this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0); |
| 1424 | } |
| 1425 | objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY); |
| 1426 | } |
| 1427 | else |
| 1428 | { |
| 1429 | objects.block?.destroy(); |
| 1430 | objects.block = null; |
| 1431 | objects.blockBloom?.destroy(); |
| 1432 | objects.blockBloom = null; |
| 1433 | } |
| 1434 | } |
| 1435 | |
| 1436 | #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK) |
| 1437 | { |
| 1438 | if (!name) |
| 1439 | { |
| 1440 | existing?.destroy(); |
| 1441 | return null; |
| 1442 | } |
| 1443 | const object = this.#ensureSprite(existing, name, sortOrder); |
| 1444 | if (!object) |
| 1445 | { return null; } |
| 1446 | object.renderer.layer = RENDER_LAYER_BLOOM; |
| 1447 | this.#markUnlit(object); |
| 1448 | this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder); |
| 1449 | return object; |
| 1450 | } |
| 1451 | |
| 1452 | #placePivoted (object, pivotX, pivotY, sortY, subOrder) |
| 1453 | { |
| 1454 | const sprite = object?.renderer?.sprite; |
| 1455 | if (!sprite) |
| 1456 | { return; } |
| 1457 | const zoom = this.zoom; |
| 1458 | const draw = spriteDrawSize(sprite.width, sprite.height, zoom); |
| 1459 | const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom); |
| 1460 | object.transform.position.x = center.x; |
| 1461 | object.transform.position.y = center.y; |
| 1462 | object.transform.size = new vector(draw.w, draw.h); |
| 1463 | object.layer = ySortLayer(sortY, subOrder); |
| 1464 | this.#markSortDirty(); |
| 1465 | } |
| 1466 | |
| 1467 | #ensureSprite (existing, name, layer) |
| 1468 | { |
| 1469 | const sprite = this.game.images[name]; |
| 1470 | if (!sprite) |
| 1471 | { |
| 1472 | existing?.destroy(); |
| 1473 | return null; |
| 1474 | } |
| 1475 | if (!existing || existing.renderer.sprite !== sprite) |
| 1476 | { |
| 1477 | existing?.destroy(); |
| 1478 | existing = new GameObject(0, 0, sprite, layer); |
| 1479 | this.#syncLitSprite(existing, 0); |
| 1480 | this.scene.addObject(existing); |
| 1481 | this.#startIdleAnimation(existing); |
| 1482 | } |
| 1483 | return existing; |
| 1484 | } |
| 1485 | |
| 1486 | #startIdleAnimation (object) |
| 1487 | { |
| 1488 | const sprite = object?.renderer?.sprite; |
| 1489 | if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0) |
| 1490 | { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); } |
| 1491 | } |
| 1492 | |
| 1493 | #neighborClosed (snapshot, dir, dx, dy) |
| 1494 | { |
| 1495 | const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`); |
| 1496 | if (other) |
| 1497 | { return !other.open; } |
| 1498 | return !!snapshot.closedEdges?.[dir]; |
| 1499 | } |
| 1500 | |
| 1501 | #rebuildAllEdges () |
| 1502 | { |
| 1503 | const seen = new Set(); |
| 1504 | for (const snapshot of this.chunks.values()) |
| 1505 | { |
| 1506 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 1507 | seen.add(key); |
| 1508 | this.#rebuildChunkEdges(snapshot); |
| 1509 | } |
| 1510 | for (const key of [...this.edges.keys()]) |
| 1511 | { |
| 1512 | if (!seen.has(key)) |
| 1513 | { this.#destroyEdges(key); } |
| 1514 | } |
| 1515 | } |
| 1516 | |
| 1517 | #rebuildChunkEdges (snapshot) |
| 1518 | { |
| 1519 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 1520 | let bars = this.edges.get(key); |
| 1521 | if (!bars) |
| 1522 | { |
| 1523 | bars = {}; |
| 1524 | this.edges.set(key, bars); |
| 1525 | } |
| 1526 | |
| 1527 | const size = this.tileSize(); |
| 1528 | const chunkPx = CHUNK_SIZE * size; |
| 1529 | const left = snapshot.chunkX * CHUNK_SIZE * size; |
| 1530 | const top = snapshot.chunkY * CHUNK_SIZE * size; |
| 1531 | const centerX = left + chunkPx / 2; |
| 1532 | const centerY = top + chunkPx / 2; |
| 1533 | const thickness = Math.max(2, Math.round(2 * this.zoom)); |
| 1534 | const draw = snapshot.open === true; |
| 1535 | |
| 1536 | bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1), |
| 1537 | centerX, top, chunkPx, thickness, true); |
| 1538 | bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1), |
| 1539 | centerX, top + chunkPx, chunkPx, thickness, true); |
| 1540 | bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0), |
| 1541 | left, centerY, chunkPx, thickness, false); |
| 1542 | bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0), |
| 1543 | left + chunkPx, centerY, chunkPx, thickness, false); |
| 1544 | } |
| 1545 | |
| 1546 | #edgeBar (existing, visible, x, y, length, thickness, horizontal) |
| 1547 | { |
| 1548 | if (!visible) |
| 1549 | { |
| 1550 | if (existing) |
| 1551 | { existing.renderer.visible = false; } |
| 1552 | return existing; |
| 1553 | } |
| 1554 | |
| 1555 | existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE); |
| 1556 | this.#markUnlit(existing); |
| 1557 | existing.renderer.visible = true; |
| 1558 | existing.transform.position.x = x; |
| 1559 | existing.transform.position.y = y; |
| 1560 | existing.transform.size = horizontal |
| 1561 | ? new vector(length, thickness) |
| 1562 | : new vector(thickness, length); |
| 1563 | existing.layer = LAYER_EDGE; |
| 1564 | this.#markSortDirty(); |
| 1565 | return existing; |
| 1566 | } |
| 1567 | |
| 1568 | #destroyEdges (key) |
| 1569 | { |
| 1570 | const bars = this.edges.get(key); |
| 1571 | if (!bars) |
| 1572 | { return; } |
| 1573 | bars.north?.destroy(); |
| 1574 | bars.east?.destroy(); |
| 1575 | bars.south?.destroy(); |
| 1576 | bars.west?.destroy(); |
| 1577 | this.edges.delete(key); |
| 1578 | } |
| 1579 | |
| 1580 | #entityShadeAlpha (entity, now) |
| 1581 | { |
| 1582 | const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0; |
| 1583 | if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null) |
| 1584 | { return toAlpha; } |
| 1585 | const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0; |
| 1586 | const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1)); |
| 1587 | return fromAlpha + (toAlpha - fromAlpha) * t; |
| 1588 | } |
| 1589 | |
| 1590 | #markSortDirty () |
| 1591 | { |
| 1592 | this.scene._sortDirty = true; |
| 1593 | } |
| 1594 | |
| 1595 | #updateShade () |
| 1596 | { |
| 1597 | const hour = this.nightPreview ?? this.worldHour; |
| 1598 | const ambientDark = nightFactor(hour, this.settings.nightDarkness); |
| 1599 | const now = performance.now(); |
| 1600 | this.dynamicLights = this.dynamicLights.filter((light) => light.until > now); |
| 1601 | |
| 1602 | const activeLights = [...this.dynamicLights]; |
| 1603 | const tileSize = this.tileSize(); |
| 1604 | for (const entity of this.entities.values()) |
| 1605 | { |
| 1606 | const range = entity.lightRadiusTiles ?? 0; |
| 1607 | if (range <= 0) |
| 1608 | { continue; } |
| 1609 | activeLights.push({ |
| 1610 | tileX: Math.floor(entity.visualX / tileSize), |
| 1611 | tileY: Math.floor(entity.visualY / tileSize), |
| 1612 | range, |
| 1613 | intensity: 1 |
| 1614 | }); |
| 1615 | } |
| 1616 | |
| 1617 | const isPassable = makeSnapshotPassable(this.chunks); |
| 1618 | |
| 1619 | for (const objects of this.tiles.values()) |
| 1620 | { |
| 1621 | const intensity = this.#tileLightIntensity(objects, activeLights, isPassable); |
| 1622 | objects.shadeAlpha = ambientDark * (1 - intensity); |
| 1623 | if (objects.block) |
| 1624 | { this.#syncLitSprite(objects.block, objects.shadeAlpha); } |
| 1625 | if (objects.ground && isWaterGround(objects.groundTypeId)) |
| 1626 | { |
| 1627 | this.#syncWaterGroundSprite( |
| 1628 | objects.ground, |
| 1629 | objects.shadeAlpha, |
| 1630 | objects.waterEdges ?? this.#waterCoastEdges(objects.tileX, objects.tileY), |
| 1631 | now / 1000 |
| 1632 | ); |
| 1633 | } |
| 1634 | else if (objects.ground) |
| 1635 | { this.#syncLitSprite(objects.ground, objects.shadeAlpha); } |
| 1636 | } |
| 1637 | |
| 1638 | for (const baked of this.bakedChunks.values()) |
| 1639 | { |
| 1640 | this.#writeChunkLightmap(baked, activeLights, isPassable); |
| 1641 | if (baked.groundObject?.renderer?.shaderUniforms) |
| 1642 | { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; } |
| 1643 | for (const object of baked.blockObjects ?? []) |
| 1644 | { |
| 1645 | if (object?.renderer?.shaderUniforms) |
| 1646 | { object.renderer.shaderUniforms.u_ambientDark = ambientDark; } |
| 1647 | } |
| 1648 | } |
| 1649 | |
| 1650 | for (const item of this.groundItems.values()) |
| 1651 | { |
| 1652 | const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0; |
| 1653 | this.#syncGroundItemSprite(item, alpha); |
| 1654 | } |
| 1655 | } |
| 1656 | |
| 1657 | #tileLightIntensity (objects, activeLights, isPassable) |
| 1658 | { |
| 1659 | const baked = lightIntensity(objects.light ?? 0); |
| 1660 | const dynamic = dynamicLightAtTile( |
| 1661 | objects.tileX, |
| 1662 | objects.tileY, |
| 1663 | activeLights, |
| 1664 | isPassable |
| 1665 | ); |
| 1666 | return Math.max(baked, dynamic); |
| 1667 | } |
| 1668 | |
| 1669 | #writeChunkLightmap (baked, activeLights, isPassable) |
| 1670 | { |
| 1671 | const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`); |
| 1672 | if (!snapshot) |
| 1673 | { return; } |
| 1674 | const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX; |
| 1675 | const pixelCount = atlasPx * atlasPx * 4; |
| 1676 | if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount) |
| 1677 | { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); } |
| 1678 | const pixels = baked.lightmapPixels; |
| 1679 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 1680 | { |
| 1681 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 1682 | { |
| 1683 | const tileX = baked.chunkX * CHUNK_SIZE + localX; |
| 1684 | const tileY = baked.chunkY * CHUNK_SIZE + localY; |
| 1685 | const index = localY * CHUNK_SIZE + localX; |
| 1686 | const tileObjects = this.tiles.get(`${tileX},${tileY}`); |
| 1687 | let intensity; |
| 1688 | if (tileObjects) |
| 1689 | { |
| 1690 | intensity = this.#tileLightIntensity(tileObjects, activeLights, isPassable); |
| 1691 | } |
| 1692 | else |
| 1693 | { |
| 1694 | const baked = lightIntensity(snapshot.light[index] ?? 0); |
| 1695 | const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, isPassable); |
| 1696 | intensity = Math.max(baked, dynamic); |
| 1697 | } |
| 1698 | const value = Math.round(Math.min(1, intensity) * 255); |
| 1699 | const baseX = localX * SPRITE_SIZE_PX; |
| 1700 | const baseY = localY * SPRITE_SIZE_PX; |
| 1701 | for (let py = 0; py < SPRITE_SIZE_PX; py++) |
| 1702 | { |
| 1703 | for (let px = 0; px < SPRITE_SIZE_PX; px++) |
| 1704 | { |
| 1705 | const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4; |
| 1706 | pixels[offset] = value; |
| 1707 | pixels[offset + 1] = value; |
| 1708 | pixels[offset + 2] = value; |
| 1709 | pixels[offset + 3] = 255; |
| 1710 | } |
| 1711 | } |
| 1712 | } |
| 1713 | } |
| 1714 | const ctx = baked.lightmapCanvas.getContext("2d"); |
| 1715 | ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0); |
| 1716 | invalidateCanvasTexture(this.scene, baked.lightmapCanvas); |
| 1717 | } |
| 1718 | |
| 1719 | #updateSwipes (now) |
| 1720 | { |
| 1721 | this.swipes = this.swipes.filter((swipe) => |
| 1722 | { |
| 1723 | if (swipe.until > now) |
| 1724 | { |
| 1725 | if (swipe.fromTileX != null) |
| 1726 | { |
| 1727 | this.#applyPhysicalCombatFxDarkness( |
| 1728 | swipe.object, |
| 1729 | swipe.fromTileX, |
| 1730 | swipe.fromTileY, |
| 1731 | swipe.tileX, |
| 1732 | swipe.tileY |
| 1733 | ); |
| 1734 | } |
| 1735 | return true; |
| 1736 | } |
| 1737 | swipe.object?.destroy(); |
| 1738 | return false; |
| 1739 | }); |
| 1740 | } |
| 1741 | |
| 1742 | #updateDamageNumbers (now) |
| 1743 | { |
| 1744 | const layer = this.damageNumbersEl; |
| 1745 | if (!layer) |
| 1746 | { return; } |
| 1747 | this.damageFloats = this.damageFloats.filter((entry) => |
| 1748 | { |
| 1749 | const elapsed = now - entry.started; |
| 1750 | if (elapsed >= DAMAGE_FLOAT_MS) |
| 1751 | { |
| 1752 | entry.element?.remove(); |
| 1753 | return false; |
| 1754 | } |
| 1755 | const entity = this.entities.get(entry.entityId); |
| 1756 | if (!entity) |
| 1757 | { |
| 1758 | entry.element?.remove(); |
| 1759 | return false; |
| 1760 | } |
| 1761 | if (!entry.element) |
| 1762 | { |
| 1763 | entry.element = document.createElement("span"); |
| 1764 | entry.element.className = "damage-number"; |
| 1765 | entry.element.textContent = String(entry.damage); |
| 1766 | layer.append(entry.element); |
| 1767 | } |
| 1768 | const anchor = this.nametagAnchor(entity); |
| 1769 | if (!anchor) |
| 1770 | { return true; } |
| 1771 | const t = elapsed / DAMAGE_FLOAT_MS; |
| 1772 | entry.element.style.left = `${anchor.x}px`; |
| 1773 | entry.element.style.top = `${anchor.y - 6 - t * 28}px`; |
| 1774 | entry.element.style.opacity = String(1 - t); |
| 1775 | return true; |
| 1776 | }); |
| 1777 | } |
| 1778 | |
| 1779 | #syncBloomLayer () |
| 1780 | { |
| 1781 | const settings = this.settings ?? DEFAULT_WORLD_SETTINGS; |
| 1782 | this.scene.setLayers([ |
| 1783 | { name: "default" }, |
| 1784 | { |
| 1785 | name: RENDER_LAYER_BLOOM, |
| 1786 | composite: "add", |
| 1787 | postShaders: Shader.getBloomPostChain({ |
| 1788 | threshold: settings.bloomThreshold, |
| 1789 | softKnee: settings.bloomSoftKnee, |
| 1790 | intensity: settings.bloomIntensity, |
| 1791 | blurSize: settings.bloomBlurSize, |
| 1792 | saturation: settings.bloomSaturation, |
| 1793 | colorPreserve: settings.bloomColorPreserve, |
| 1794 | dilate: settings.bloomDilate, |
| 1795 | scales: Math.max(1, Math.round(settings.bloomScales ?? 1)), |
| 1796 | halfRes: (settings.bloomHalfRes ?? 1) >= 0.5 |
| 1797 | }) |
| 1798 | } |
| 1799 | ]); |
| 1800 | } |
| 1801 | } |
| 1802 | |
| 1803 | export function nightFactor (hour, nightDarkness = 0.72) |
| 1804 | { |
| 1805 | const peak = Math.min(1, Math.max(0, nightDarkness)); |
| 1806 | if (hour >= 8 && hour <= 16) |
| 1807 | { return 0; } |
| 1808 | if (hour >= 22 || hour <= 5) |
| 1809 | { return peak; } |
| 1810 | if (hour < 8) |
| 1811 | { return lerp(peak, 0, (hour - 5) / 3); } |
| 1812 | return lerp(0, peak, (hour - 16) / 6); |
| 1813 | } |
| 1814 | |
| 1815 | function bodySpriteName (sex) |
| 1816 | { |
| 1817 | const key = sex === "female" ? "player-body-female" : "player-body-male"; |
| 1818 | return spriteImageName("character", key, key); |
| 1819 | } |
| 1820 | |
| 1821 | function lerp (a, b, t) |
| 1822 | { |
| 1823 | return a + (b - a) * Math.min(1, Math.max(0, t)); |
| 1824 | } |
| 1825 | |
| 1826 | function makeLightmapCanvas (size) |
| 1827 | { |
| 1828 | const canvas = document.createElement("canvas"); |
| 1829 | canvas.width = size; |
| 1830 | canvas.height = size; |
| 1831 | return canvas; |
| 1832 | } |
| 1833 | |
| 1834 | function copyCanvas (source, dest) |
| 1835 | { |
| 1836 | const ctx = dest.getContext("2d"); |
| 1837 | ctx.imageSmoothingEnabled = false; |
| 1838 | ctx.clearRect(0, 0, dest.width, dest.height); |
| 1839 | ctx.drawImage(source, 0, 0); |
| 1840 | } |
| 1841 | |
| 1842 | function drawHpBar (canvas, current, max) |
| 1843 | { |
| 1844 | const ctx = canvas.getContext("2d"); |
| 1845 | ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H); |
| 1846 | ctx.fillStyle = "#000000"; |
| 1847 | ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H); |
| 1848 | const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0; |
| 1849 | const fillW = Math.round(12 * ratio); |
| 1850 | if (fillW > 0) |
| 1851 | { |
| 1852 | ctx.fillStyle = "#ff0000"; |
| 1853 | ctx.fillRect(1, 1, fillW, 2); |
| 1854 | } |
| 1855 | } |