| 1 | import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js"; |
| 2 | import { dynamicLightAtTile, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js"; |
| 3 | import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js"; |
| 4 | import { bakeChunkOcclusion, tileLightOcclusionAt } from "/shared/lighting/chunkOcclusion.js"; |
| 5 | import { collectBlockLightSources, maxBlockLightRangeTiles } from "/shared/lighting/blockLights.js"; |
| 6 | import { smoothLitCorner } from "/shared/lighting/lightCorners.js"; |
| 7 | import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js"; |
| 8 | import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemSpriteNameForStack, itemDefinition } from "/shared/definitions/items.js"; |
| 9 | import |
| 10 | { |
| 11 | resolveItemTint, |
| 12 | resolveEquipTint, |
| 13 | resolveItemDualTint, |
| 14 | resolveEquipDualTint, |
| 15 | normalizeRgb |
| 16 | } from "/shared/render/tint.js"; |
| 17 | import { layersFromSpawnerConfig } from "/shared/appearance/layers.js"; |
| 18 | import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js"; |
| 19 | import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, LightOcclusion, blockDefinition, blockLightOcclusionForBlock } from "/shared/definitions/tiles.js"; |
| 20 | import { doorSortSubOrder, doorRestingState } from "/shared/world/doors.js"; |
| 21 | import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js"; |
| 22 | import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js"; |
| 23 | import { createChunkAtlasCache } from "./chunkAtlasCache.js"; |
| 24 | import |
| 25 | { |
| 26 | frameworkImageFromCanvas, |
| 27 | invalidateCanvasTexture |
| 28 | } from "./canvasSprite.js"; |
| 29 | import { setNearestFilter } from "./sprites.js"; |
| 30 | import { SeasonId, seasonIdAt } from "/shared/world/season.js"; |
| 31 | import |
| 32 | { |
| 33 | OVERWORLD_ID, |
| 34 | normalizeDimensionId, |
| 35 | normalizeLightingMode, |
| 36 | normalizeSeasonMode, |
| 37 | resolveDimensionDarknessFactor, |
| 38 | resolveDimensionSeasonId |
| 39 | } from "/shared/world/dimensions.js"; |
| 40 | import { spellDefinition, spellProjectileTint } from "/shared/definitions/spells.js"; |
| 41 | import { skullTintColor } from "/shared/combat/skull.js"; |
| 42 | |
| 43 | const LAYER_GROUND = 0; |
| 44 | const LAYER_EDGE = 900000; |
| 45 | const SORT_BLOCK = 2; |
| 46 | const SORT_ENTITY = 3; |
| 47 | /** Equipment overlays use SORT_ENTITY + 1 + index (same sortY band). */ |
| 48 | const SORT_HP_BAR = 14; |
| 49 | const SORT_FX = 5; |
| 50 | const RENDER_LAYER_BLOOM = "bloom"; |
| 51 | const SKULL_SPRITE = "fx:skull:skull"; |
| 52 | |
| 53 | const HP_BAR_W = 14; |
| 54 | const HP_BAR_H = 4; |
| 55 | const WALK_TILT_DEG = 6; |
| 56 | const RUN_TILT_DEG = 8; |
| 57 | const SHOVE_TILE_FRACTION = 0.25; |
| 58 | const SHOVE_MS = 280; |
| 59 | /** Soft reflow when stack circle targets change (join/leave a shared tile). */ |
| 60 | const STACK_SPREAD_LERP_MS = 280; |
| 61 | /** Melee swipe fade: full opacity → transparent over this duration, then remove. */ |
| 62 | const MELEE_SWIPE_MS = 500; |
| 63 | /** Extra random yaw (±deg) on top of aim rotation. */ |
| 64 | const MELEE_SWIPE_JITTER_DEG = 10; |
| 65 | /** Hold gather-tool equip overlay slightly past swing interval so it stays visible between swings. */ |
| 66 | const GATHER_TOOL_HOLD_MS = 1100; |
| 67 | const DAMAGE_FLASH_MS = 180; |
| 68 | const FLASH_COLOR_DAMAGE = Object.freeze([1.0, 0.12, 0.12]); |
| 69 | const FLASH_COLOR_BLOCK = Object.freeze([1.0, 1.0, 1.0]); |
| 70 | /** Combat death: full red silhouette fades to transparent after the killing blow. */ |
| 71 | const DEATH_FADE_MS = 500; |
| 72 | /** Interest leave / non-combat despawn: plain alpha fade (still lit / darkened). */ |
| 73 | const DESPAWN_FADE_MS = 500; |
| 74 | const DAMAGE_FLOAT_MS = 900; |
| 75 | const SKILL_LEVEL_FLOAT_MS = 2800; |
| 76 | /** Projectiles spawn this many sprite-pixels below the caster sprite top. */ |
| 77 | const PROJECTILE_LAUNCH_FROM_TOP_PX = 4; |
| 78 | |
| 79 | const SPRITE_LIGHTING_FRAG = [ |
| 80 | "precision mediump float;", |
| 81 | "varying vec2 v_texCoord;", |
| 82 | "uniform sampler2D u_texture;", |
| 83 | "uniform float u_alpha;", |
| 84 | "uniform float u_darkness;", |
| 85 | "uniform float u_strength;", |
| 86 | "uniform vec3 u_flashColor;", |
| 87 | "uniform float u_wade;", |
| 88 | "uniform float u_spriteHeight;", |
| 89 | "void main() {", |
| 90 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 91 | " if (color.a <= 0.0) { discard; }", |
| 92 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 93 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 94 | " vec3 rgb = color.rgb;", |
| 95 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 96 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 97 | " }", |
| 98 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 99 | " rgb = mix(rgb, u_flashColor, u_strength);", |
| 100 | " gl_FragColor = vec4(rgb, color.a * u_alpha);", |
| 101 | "}" |
| 102 | ].join("\n"); |
| 103 | |
| 104 | const WATER_GROUND_FRAG = [ |
| 105 | "precision mediump float;", |
| 106 | "varying vec2 v_texCoord;", |
| 107 | "uniform sampler2D u_texture;", |
| 108 | "uniform float u_alpha;", |
| 109 | "uniform float u_ambientDark;", |
| 110 | "uniform float u_litNW;", |
| 111 | "uniform float u_litNE;", |
| 112 | "uniform float u_litSW;", |
| 113 | "uniform float u_litSE;", |
| 114 | "uniform float u_time;", |
| 115 | "uniform float u_edgeN;", |
| 116 | "uniform float u_edgeE;", |
| 117 | "uniform float u_edgeS;", |
| 118 | "uniform float u_edgeW;", |
| 119 | "void main() {", |
| 120 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 121 | " if (color.a <= 0.0) { discard; }", |
| 122 | " vec3 rgb = color.rgb;", |
| 123 | " float foam = 0.0;", |
| 124 | " float pulse = 0.55 + 0.45 * sin(u_time * 3.2 + v_texCoord.x * 18.0 + v_texCoord.y * 10.0);", |
| 125 | " if (u_edgeN > 0.5 && v_texCoord.y < 0.22) {", |
| 126 | " foam = max(foam, (1.0 - v_texCoord.y / 0.22) * pulse);", |
| 127 | " }", |
| 128 | " if (u_edgeS > 0.5 && v_texCoord.y > 0.78) {", |
| 129 | " foam = max(foam, ((v_texCoord.y - 0.78) / 0.22) * pulse);", |
| 130 | " }", |
| 131 | " if (u_edgeW > 0.5 && v_texCoord.x < 0.22) {", |
| 132 | " foam = max(foam, (1.0 - v_texCoord.x / 0.22) * pulse);", |
| 133 | " }", |
| 134 | " if (u_edgeE > 0.5 && v_texCoord.x > 0.78) {", |
| 135 | " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);", |
| 136 | " }", |
| 137 | " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));", |
| 138 | " float litTop = mix(u_litNW, u_litNE, v_texCoord.x);", |
| 139 | " float litBottom = mix(u_litSW, u_litSE, v_texCoord.x);", |
| 140 | " float lit = mix(litTop, litBottom, v_texCoord.y);", |
| 141 | " float darkness = u_ambientDark * (1.0 - lit);", |
| 142 | " rgb = mix(rgb, vec3(0.0), darkness);", |
| 143 | " gl_FragColor = vec4(rgb, color.a * u_alpha);", |
| 144 | "}" |
| 145 | ].join("\n"); |
| 146 | |
| 147 | /** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */ |
| 148 | const TINT_LIT_SPRITE_FRAG = [ |
| 149 | "precision mediump float;", |
| 150 | "varying vec2 v_texCoord;", |
| 151 | "uniform sampler2D u_texture;", |
| 152 | "uniform float u_alpha;", |
| 153 | "uniform float u_darkness;", |
| 154 | "uniform float u_strength;", |
| 155 | "uniform vec3 u_flashColor;", |
| 156 | "uniform float u_wade;", |
| 157 | "uniform float u_spriteHeight;", |
| 158 | "uniform float u_useTint;", |
| 159 | "uniform vec3 u_tintColor;", |
| 160 | "void main() {", |
| 161 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 162 | " if (color.a <= 0.0) { discard; }", |
| 163 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 164 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 165 | " vec3 rgb = color.rgb;", |
| 166 | " if (u_useTint > 0.5) {", |
| 167 | " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {", |
| 168 | " float L = color.r;", |
| 169 | " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;", |
| 170 | " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;", |
| 171 | " }", |
| 172 | " }", |
| 173 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 174 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 175 | " }", |
| 176 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 177 | " rgb = mix(rgb, u_flashColor, u_strength);", |
| 178 | " gl_FragColor = vec4(rgb, color.a * u_alpha);", |
| 179 | "}" |
| 180 | ].join("\n"); |
| 181 | |
| 182 | /** Dual/triple-channel tint: red = shaft, blue = tip, green = coat; then darkness. |
| 183 | * Only when the primary channel is highest and the other two are equal; |
| 184 | * equal non-zero secondaries lighten the assigned tint toward white. */ |
| 185 | const DUAL_TINT_LIT_SPRITE_FRAG = [ |
| 186 | "precision mediump float;", |
| 187 | "varying vec2 v_texCoord;", |
| 188 | "uniform sampler2D u_texture;", |
| 189 | "uniform float u_alpha;", |
| 190 | "uniform float u_darkness;", |
| 191 | "uniform float u_strength;", |
| 192 | "uniform vec3 u_flashColor;", |
| 193 | "uniform float u_wade;", |
| 194 | "uniform float u_spriteHeight;", |
| 195 | "uniform vec3 u_shaftTint;", |
| 196 | "uniform vec3 u_tipTint;", |
| 197 | "uniform vec3 u_coatTint;", |
| 198 | "uniform float u_hasCoat;", |
| 199 | "vec3 channelTint(float L, float secondary, vec3 tint) {", |
| 200 | " float blend = L > 0.0 ? clamp(secondary / L, 0.0, 1.0) : 0.0;", |
| 201 | " return mix(tint, vec3(1.0), blend) * L;", |
| 202 | "}", |
| 203 | "float channelMask(float primary, float o1, float o2) {", |
| 204 | " float equal = step(abs(o1 - o2), 0.04);", |
| 205 | " return clamp((primary - max(o1, o2)) * 1.75, 0.0, 1.0) * equal;", |
| 206 | "}", |
| 207 | "void main() {", |
| 208 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 209 | " if (color.a <= 0.0) { discard; }", |
| 210 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 211 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 212 | " vec3 rgb = color.rgb;", |
| 213 | " if (u_hasCoat > 0.5) {", |
| 214 | " float coatMask = channelMask(color.g, color.r, color.b);", |
| 215 | " if (coatMask > 0.0) {", |
| 216 | " vec3 coatCol = channelTint(color.g, color.r, u_coatTint);", |
| 217 | " rgb = mix(rgb, coatCol, coatMask);", |
| 218 | " }", |
| 219 | " }", |
| 220 | " float tipMask = channelMask(color.b, color.r, color.g);", |
| 221 | " if (tipMask > 0.0) {", |
| 222 | " vec3 tipCol = channelTint(color.b, color.r, u_tipTint);", |
| 223 | " rgb = mix(rgb, tipCol, tipMask);", |
| 224 | " }", |
| 225 | " float shaftMask = channelMask(color.r, color.g, color.b);", |
| 226 | " if (shaftMask > 0.0) {", |
| 227 | " vec3 shaftCol = channelTint(color.r, color.g, u_shaftTint);", |
| 228 | " rgb = mix(rgb, shaftCol, shaftMask);", |
| 229 | " }", |
| 230 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 231 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 232 | " }", |
| 233 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 234 | " rgb = mix(rgb, u_flashColor, u_strength);", |
| 235 | " gl_FragColor = vec4(rgb, color.a * u_alpha);", |
| 236 | "}" |
| 237 | ].join("\n"); |
| 238 | |
| 239 | /** Magenta-tint equip overlay that clips alpha to the worn body silhouette. */ |
| 240 | /** |
| 241 | * Tight-fit: clip clothing alpha to the body silhouette in *pivot space* |
| 242 | * (sizes may differ: shirt 20×24 vs body 16×24). Sample body UV remapped from |
| 243 | * clothing frame coords; 1px dilate fills armpit/crotch gaps in the body art. |
| 244 | */ |
| 245 | const TIGHT_FIT_BODY_MASK_GLSL = [ |
| 246 | "uniform vec2 u_clothSize;", |
| 247 | "uniform vec2 u_bodySize;", |
| 248 | "uniform float u_pivotFromBottom;", |
| 249 | "uniform vec4 u_clothUvRect;", |
| 250 | "uniform vec4 u_bodyUvRect;", |
| 251 | "float tightFitBodyAlpha() {", |
| 252 | " vec2 clothSpan = max(u_clothUvRect.zw - u_clothUvRect.xy, vec2(1e-5));", |
| 253 | " vec2 nu = (v_texCoord - u_clothUvRect.xy) / clothSpan;", |
| 254 | " float ox = (nu.x - 0.5) * u_clothSize.x;", |
| 255 | " float oy = nu.y * u_clothSize.y - (u_clothSize.y - u_pivotFromBottom);", |
| 256 | " vec2 bodySize = max(u_bodySize, vec2(1.0));", |
| 257 | " vec2 bodyNu = vec2(0.5 + ox / bodySize.x, ((u_bodySize.y - u_pivotFromBottom) + oy) / bodySize.y);", |
| 258 | " vec2 bodySpan = max(u_bodyUvRect.zw - u_bodyUvRect.xy, vec2(1e-5));", |
| 259 | " vec2 texel = 1.0 / bodySize;", |
| 260 | " float bodyA = 0.0;", |
| 261 | " for (int dy = -1; dy <= 1; dy++) {", |
| 262 | " for (int dx = -1; dx <= 1; dx++) {", |
| 263 | " vec2 sampleNu = bodyNu + vec2(float(dx), float(dy)) * texel;", |
| 264 | " if (sampleNu.x < 0.0 || sampleNu.x > 1.0 || sampleNu.y < 0.0 || sampleNu.y > 1.0) { continue; }", |
| 265 | " vec2 sampleUv = u_bodyUvRect.xy + sampleNu * bodySpan;", |
| 266 | " bodyA = max(bodyA, texture2D(u_secondary, sampleUv).a);", |
| 267 | " }", |
| 268 | " }", |
| 269 | " return bodyA;", |
| 270 | "}" |
| 271 | ].join("\n"); |
| 272 | |
| 273 | const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [ |
| 274 | "precision mediump float;", |
| 275 | "varying vec2 v_texCoord;", |
| 276 | "uniform sampler2D u_texture;", |
| 277 | "uniform sampler2D u_secondary;", |
| 278 | "uniform float u_alpha;", |
| 279 | "uniform float u_darkness;", |
| 280 | "uniform float u_strength;", |
| 281 | "uniform vec3 u_flashColor;", |
| 282 | "uniform float u_wade;", |
| 283 | "uniform float u_spriteHeight;", |
| 284 | "uniform float u_useTint;", |
| 285 | "uniform vec3 u_tintColor;", |
| 286 | TIGHT_FIT_BODY_MASK_GLSL, |
| 287 | "void main() {", |
| 288 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 289 | " if (color.a <= 0.0) { discard; }", |
| 290 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 291 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 292 | " vec3 rgb = color.rgb;", |
| 293 | " if (u_useTint > 0.5) {", |
| 294 | " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {", |
| 295 | " float L = color.r;", |
| 296 | " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;", |
| 297 | " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;", |
| 298 | " }", |
| 299 | " }", |
| 300 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 301 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 302 | " }", |
| 303 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 304 | " rgb = mix(rgb, u_flashColor, u_strength);", |
| 305 | " float alpha = min(tightFitBodyAlpha(), color.a) * u_alpha;", |
| 306 | " if (alpha <= 0.0) { discard; }", |
| 307 | " gl_FragColor = vec4(rgb, alpha);", |
| 308 | "}" |
| 309 | ].join("\n"); |
| 310 | |
| 311 | /** Body-clipped equip overlay without dye recolour. */ |
| 312 | const TIGHT_FIT_LIT_SPRITE_FRAG = [ |
| 313 | "precision mediump float;", |
| 314 | "varying vec2 v_texCoord;", |
| 315 | "uniform sampler2D u_texture;", |
| 316 | "uniform sampler2D u_secondary;", |
| 317 | "uniform float u_alpha;", |
| 318 | "uniform float u_darkness;", |
| 319 | "uniform float u_strength;", |
| 320 | "uniform vec3 u_flashColor;", |
| 321 | "uniform float u_wade;", |
| 322 | "uniform float u_spriteHeight;", |
| 323 | TIGHT_FIT_BODY_MASK_GLSL, |
| 324 | "void main() {", |
| 325 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 326 | " if (color.a <= 0.0) { discard; }", |
| 327 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 328 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 329 | " vec3 rgb = color.rgb;", |
| 330 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 331 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 332 | " }", |
| 333 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 334 | " rgb = mix(rgb, u_flashColor, u_strength);", |
| 335 | " float alpha = min(tightFitBodyAlpha(), color.a) * u_alpha;", |
| 336 | " if (alpha <= 0.0) { discard; }", |
| 337 | " gl_FragColor = vec4(rgb, alpha);", |
| 338 | "}" |
| 339 | ].join("\n"); |
| 340 | |
| 341 | const ATLAS_LIGHTING_FRAG = [ |
| 342 | "precision mediump float;", |
| 343 | "varying vec2 v_texCoord;", |
| 344 | "uniform sampler2D u_texture;", |
| 345 | "uniform sampler2D u_secondary;", |
| 346 | "uniform float u_alpha;", |
| 347 | "uniform float u_ambientDark;", |
| 348 | "uniform float u_lightRow;", |
| 349 | "void main() {", |
| 350 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 351 | " if (color.a <= 0.0) { discard; }", |
| 352 | " vec2 lightUV = v_texCoord;", |
| 353 | " if (u_lightRow >= 0.0) {", |
| 354 | " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;", |
| 355 | " }", |
| 356 | " float lit = texture2D(u_secondary, lightUV).r;", |
| 357 | " float darkness = u_ambientDark * (1.0 - lit);", |
| 358 | " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);", |
| 359 | " gl_FragColor = vec4(rgb, color.a * u_alpha);", |
| 360 | "}" |
| 361 | ].join("\n"); |
| 362 | |
| 363 | /** |
| 364 | * Per-tile cliff sprite: high-chroma / authored magenta top → sample this chunk's |
| 365 | * ground atlas (u_bump) at the cliff's tile-local UV. Only assigned to |
| 366 | * `cliffGroundTop` blocks — never to chunk block-row atlases (those keep normal |
| 367 | * lighting so magenta wood tints are not mistaken for cliff tops). |
| 368 | */ |
| 369 | const SPRITE_CLIFF_GROUND_TOP_FRAG = [ |
| 370 | "precision mediump float;", |
| 371 | "varying vec2 v_texCoord;", |
| 372 | "uniform sampler2D u_texture;", |
| 373 | "uniform sampler2D u_bump;", |
| 374 | "uniform float u_alpha;", |
| 375 | "uniform float u_darkness;", |
| 376 | "uniform vec2 u_tileLocal;", |
| 377 | "void main() {", |
| 378 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 379 | " if (color.a <= 0.0) { discard; }", |
| 380 | " vec3 rgb = color.rgb;", |
| 381 | " float rbDiff = abs(rgb.r - rgb.b);", |
| 382 | " if (rbDiff < 0.02 && rgb.g < rgb.r) {", |
| 383 | " vec2 groundUV = (u_tileLocal + v_texCoord) / 16.0;", |
| 384 | " rgb = texture2D(u_bump, groundUV).rgb;", |
| 385 | " }", |
| 386 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 387 | " gl_FragColor = vec4(rgb, color.a * u_alpha);", |
| 388 | "}" |
| 389 | ].join("\n"); |
| 390 | |
| 391 | let spriteLightingShader = null; |
| 392 | let atlasLightingShader = null; |
| 393 | let cliffGroundTopShader = null; |
| 394 | let waterGroundShader = null; |
| 395 | let tintLitSpriteShader = null; |
| 396 | let dualTintLitSpriteShader = null; |
| 397 | let tightFitTintLitSpriteShader = null; |
| 398 | let tightFitLitSpriteShader = null; |
| 399 | |
| 400 | function getSpriteLightingShader () |
| 401 | { |
| 402 | if (!spriteLightingShader) |
| 403 | { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); } |
| 404 | return spriteLightingShader; |
| 405 | } |
| 406 | |
| 407 | function getAtlasLightingShader () |
| 408 | { |
| 409 | if (!atlasLightingShader) |
| 410 | { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); } |
| 411 | return atlasLightingShader; |
| 412 | } |
| 413 | |
| 414 | function getCliffGroundTopShader () |
| 415 | { |
| 416 | if (!cliffGroundTopShader) |
| 417 | { cliffGroundTopShader = Shader.fragment(SPRITE_CLIFF_GROUND_TOP_FRAG); } |
| 418 | return cliffGroundTopShader; |
| 419 | } |
| 420 | |
| 421 | function getWaterGroundShader () |
| 422 | { |
| 423 | if (!waterGroundShader) |
| 424 | { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); } |
| 425 | return waterGroundShader; |
| 426 | } |
| 427 | |
| 428 | function getTintLitSpriteShader () |
| 429 | { |
| 430 | if (!tintLitSpriteShader) |
| 431 | { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); } |
| 432 | return tintLitSpriteShader; |
| 433 | } |
| 434 | |
| 435 | function getDualTintLitSpriteShader () |
| 436 | { |
| 437 | if (!dualTintLitSpriteShader) |
| 438 | { dualTintLitSpriteShader = Shader.fragment(DUAL_TINT_LIT_SPRITE_FRAG); } |
| 439 | return dualTintLitSpriteShader; |
| 440 | } |
| 441 | |
| 442 | function getTightFitTintLitSpriteShader () |
| 443 | { |
| 444 | if (!tightFitTintLitSpriteShader) |
| 445 | { tightFitTintLitSpriteShader = Shader.fragment(TIGHT_FIT_TINT_LIT_SPRITE_FRAG); } |
| 446 | return tightFitTintLitSpriteShader; |
| 447 | } |
| 448 | |
| 449 | function getTightFitLitSpriteShader () |
| 450 | { |
| 451 | if (!tightFitLitSpriteShader) |
| 452 | { tightFitLitSpriteShader = Shader.fragment(TIGHT_FIT_LIT_SPRITE_FRAG); } |
| 453 | return tightFitLitSpriteShader; |
| 454 | } |
| 455 | |
| 456 | export class WorldView |
| 457 | { |
| 458 | #chunkRebuildKeys = new Set(); |
| 459 | #chunkRebuildRaf = 0; |
| 460 | #edgesDirty = false; |
| 461 | #CHUNK_REBUILD_BATCH = 2; |
| 462 | #pendingTextureCanvases = []; |
| 463 | #pendingTextureCanvasSet = new Set(); |
| 464 | #textureWarmRaf = 0; |
| 465 | #TEXTURE_WARM_BATCH = 3; |
| 466 | #atlasCache = createChunkAtlasCache(); |
| 467 | #idlePrefetchId = 0; |
| 468 | #playerChunkX = null; |
| 469 | #playerChunkY = null; |
| 470 | #playerMoveChunkDx = 0; |
| 471 | #playerMoveChunkDy = 0; |
| 472 | |
| 473 | constructor(game, scene, catalog = { grounds: {}, blocks: {} }) |
| 474 | { |
| 475 | this.game = game; |
| 476 | this.scene = scene; |
| 477 | this.catalog = catalog; |
| 478 | this.preview = null; |
| 479 | this.zoom = 2; |
| 480 | /** World-Y origin for viewport-relative depth sort (see {@link #depthLayer}). */ |
| 481 | this.ySortOrigin = 0; |
| 482 | this.chunks = new Map(); |
| 483 | this.bakedChunks = new Map(); |
| 484 | this.tiles = new Map(); |
| 485 | this.entities = new Map(); |
| 486 | this.groundItems = new Map(); |
| 487 | this.edges = new Map(); |
| 488 | this.localEntityId = null; |
| 489 | this.localBlind = false; |
| 490 | /** @type {string} */ |
| 491 | this.dimensionId = OVERWORLD_ID; |
| 492 | /** @type {string} */ |
| 493 | this.dimensionLightingMode = "dayNight"; |
| 494 | /** @type {string} */ |
| 495 | this.dimensionSeasonMode = "auto"; |
| 496 | /** Calendar season from worldStatus when dimension season is auto. */ |
| 497 | this.calendarSeason = seasonIdAt(); |
| 498 | /** @type {"soft"|"simple"} */ |
| 499 | this.lightingMode = "soft"; |
| 500 | /** @type {boolean} */ |
| 501 | this.bloomEnabled = true; |
| 502 | /** Soft edge blend for blendable grounds (grass, dirt, …). */ |
| 503 | this.softTerrain = false; |
| 504 | this.settings = { ...DEFAULT_WORLD_SETTINGS }; |
| 505 | this.worldHour = 12; |
| 506 | /** Calendar season for seasonal ground/block visuals (`spring` / `summer` / `fall` / `winter`). */ |
| 507 | this.worldSeason = seasonIdAt(); |
| 508 | this.nightPreview = null; |
| 509 | this.followPlayer = true; |
| 510 | this.dynamicLights = []; |
| 511 | /** Persistent Light-spell tile lights (server-driven). */ |
| 512 | this.spellLights = new Map(); |
| 513 | /** Persistent Dark-spell tile darkness (server-driven). */ |
| 514 | this.spellDarks = new Map(); |
| 515 | this.swipes = []; |
| 516 | this.damageFloats = []; |
| 517 | this.damageNumbersEl = document.getElementById("damage-numbers"); |
| 518 | this.skillLevelFloats = []; |
| 519 | this.skillLevelFloatsEl = document.getElementById("skill-level-floats"); |
| 520 | /** @type {Map<string, { object: object, tileX: number, tileY: number, spriteName: string }>} */ |
| 521 | this.editorSpawners = new Map(); |
| 522 | this.spawnRangeHighlight = null; |
| 523 | this.wanderRangeHighlight = null; |
| 524 | this.spellTargetHighlight = null; |
| 525 | this.#syncBloomLayer(); |
| 526 | } |
| 527 | |
| 528 | setSettings (settings) |
| 529 | { |
| 530 | this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings }; |
| 531 | this.#syncBloomLayer(); |
| 532 | } |
| 533 | |
| 534 | /** |
| 535 | * Client graphics prefs (lighting Soft/Simple, bloom On/Off, soft terrain). |
| 536 | * @param {{ lighting?: string, bloom?: string, softTerrain?: string }} prefs |
| 537 | */ |
| 538 | setGraphicsPrefs (prefs) |
| 539 | { |
| 540 | if (prefs?.lighting === "simple" || prefs?.lighting === "soft") |
| 541 | { this.lightingMode = prefs.lighting; } |
| 542 | if (prefs?.bloom === "off" || prefs?.bloom === "on") |
| 543 | { |
| 544 | const enabled = prefs.bloom !== "off"; |
| 545 | if (enabled !== this.bloomEnabled) |
| 546 | { |
| 547 | this.bloomEnabled = enabled; |
| 548 | this.#syncBloomLayer(); |
| 549 | } |
| 550 | else |
| 551 | { this.bloomEnabled = enabled; } |
| 552 | } |
| 553 | if (prefs?.softTerrain === "on" || prefs?.softTerrain === "off") |
| 554 | { |
| 555 | const enabled = prefs.softTerrain === "on"; |
| 556 | if (enabled !== this.softTerrain) |
| 557 | { |
| 558 | this.softTerrain = enabled; |
| 559 | this.#rebakeAllChunks(); |
| 560 | } |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | /** Apply server (or local) calendar season; rebakes chunks when it changes. */ |
| 565 | setWorldSeason (season) |
| 566 | { |
| 567 | const calendar = season === SeasonId.spring |
| 568 | || season === SeasonId.fall |
| 569 | || season === SeasonId.winter |
| 570 | || season === SeasonId.summer |
| 571 | ? season |
| 572 | : seasonIdAt(); |
| 573 | this.calendarSeason = calendar; |
| 574 | const forced = resolveDimensionSeasonId(this.dimensionSeasonMode); |
| 575 | const next = forced ?? calendar; |
| 576 | if (next === this.worldSeason) |
| 577 | { return; } |
| 578 | this.worldSeason = next; |
| 579 | this.#rebakeAllChunks(); |
| 580 | } |
| 581 | |
| 582 | setDimensionId (dimensionId) |
| 583 | { |
| 584 | this.dimensionId = normalizeDimensionId(dimensionId); |
| 585 | } |
| 586 | |
| 587 | setDimensionModes (lightingMode, seasonMode) |
| 588 | { |
| 589 | this.dimensionLightingMode = normalizeLightingMode(lightingMode); |
| 590 | this.dimensionSeasonMode = normalizeSeasonMode(seasonMode); |
| 591 | const forced = resolveDimensionSeasonId(this.dimensionSeasonMode); |
| 592 | const next = forced ?? this.calendarSeason ?? seasonIdAt(); |
| 593 | if (next !== this.worldSeason) |
| 594 | { |
| 595 | this.worldSeason = next; |
| 596 | this.#rebakeAllChunks(); |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | clearAllChunks () |
| 601 | { |
| 602 | for (const key of [...this.chunks.keys()]) |
| 603 | { |
| 604 | const [chunkX, chunkY] = key.split(",").map(Number); |
| 605 | this.removeChunk(chunkX, chunkY); |
| 606 | } |
| 607 | for (const [id] of [...this.entities.entries()]) |
| 608 | { |
| 609 | if (id === this.localEntityId) |
| 610 | { continue; } |
| 611 | this.despawnEntity(id, { immediate: true }); |
| 612 | } |
| 613 | for (const [id] of [...this.groundItems.entries()]) |
| 614 | { this.despawnGroundItem(id); } |
| 615 | } |
| 616 | |
| 617 | /** Full client wipe when leaving the world (menu / disconnect). Includes the local player. */ |
| 618 | clearPlaySession () |
| 619 | { |
| 620 | this.#cancelIdlePrefetch(); |
| 621 | this.#chunkRebuildKeys.clear(); |
| 622 | this.#playerChunkX = null; |
| 623 | this.#playerChunkY = null; |
| 624 | this.#playerMoveChunkDx = 0; |
| 625 | this.#playerMoveChunkDy = 0; |
| 626 | this.localEntityId = null; |
| 627 | for (const key of [...this.chunks.keys()]) |
| 628 | { |
| 629 | const [chunkX, chunkY] = key.split(",").map(Number); |
| 630 | this.removeChunk(chunkX, chunkY); |
| 631 | } |
| 632 | for (const [id] of [...this.entities.entries()]) |
| 633 | { this.despawnEntity(id, { immediate: true }); } |
| 634 | for (const [id] of [...this.groundItems.entries()]) |
| 635 | { this.despawnGroundItem(id); } |
| 636 | } |
| 637 | |
| 638 | applySnapshot (snapshot) |
| 639 | { |
| 640 | const snapDim = normalizeDimensionId(snapshot.dimensionId ?? OVERWORLD_ID); |
| 641 | if (normalizeDimensionId(this.dimensionId) !== snapDim) |
| 642 | { return; } |
| 643 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 644 | snapshot.occlusion = bakeChunkOcclusion(snapshot); |
| 645 | this.chunks.set(key, snapshot); |
| 646 | this.#scheduleChunkRebuild(snapshot); |
| 647 | this.#redrawPreview(); |
| 648 | this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY); |
| 649 | if (snapshot.staticOnly) |
| 650 | { |
| 651 | this.#stripChunkDynamic(snapshot.chunkX, snapshot.chunkY); |
| 652 | this.#scheduleEdgeRebuild(); |
| 653 | return; |
| 654 | } |
| 655 | for (const entity of snapshot.entities ?? []) |
| 656 | { this.#upsertEntity(entity); } |
| 657 | for (const [id, item] of [...this.groundItems.entries()]) |
| 658 | { |
| 659 | if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY) |
| 660 | { this.despawnGroundItem(id); } |
| 661 | } |
| 662 | for (const item of snapshot.groundItems ?? []) |
| 663 | { this.upsertGroundItem(item); } |
| 664 | this.#scheduleEdgeRebuild(); |
| 665 | } |
| 666 | |
| 667 | setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null, skullValue = 0) |
| 668 | { |
| 669 | this.localEntityId = entityId; |
| 670 | this.#upsertEntity({ |
| 671 | entityId, |
| 672 | characterId, |
| 673 | tileX, |
| 674 | tileY, |
| 675 | gait, |
| 676 | sex, |
| 677 | firstName, |
| 678 | lastName, |
| 679 | layers: layers ?? undefined, |
| 680 | skullValue: skullValue | 0, |
| 681 | ...(health != null ? { health } : {}), |
| 682 | ...(maxHealth != null ? { maxHealth } : {}) |
| 683 | }); |
| 684 | this.#notePlayerTile(tileX, tileY); |
| 685 | } |
| 686 | |
| 687 | #stripChunkDynamic (chunkX, chunkY) |
| 688 | { |
| 689 | for (const [id, item] of [...this.groundItems.entries()]) |
| 690 | { |
| 691 | if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) |
| 692 | { this.despawnGroundItem(id); } |
| 693 | } |
| 694 | for (const [id, entity] of [...this.entities.entries()]) |
| 695 | { |
| 696 | if (id === this.localEntityId) |
| 697 | { continue; } |
| 698 | if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX |
| 699 | && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY) |
| 700 | { this.despawnEntity(id, { immediate: true }); } |
| 701 | } |
| 702 | } |
| 703 | |
| 704 | removeChunk (chunkX, chunkY) |
| 705 | { |
| 706 | const key = `${chunkX},${chunkY}`; |
| 707 | this.chunks.delete(key); |
| 708 | this.#destroyBakedChunk(key); |
| 709 | this.#destroyEdges(key); |
| 710 | const prefix = `${chunkX},${chunkY}:`; |
| 711 | for (const [spawnerKey, entry] of [...this.editorSpawners.entries()]) |
| 712 | { |
| 713 | if (!spawnerKey.startsWith(prefix)) |
| 714 | { continue; } |
| 715 | this.#destroyEditorSpawnerEntry(entry); |
| 716 | this.editorSpawners.delete(spawnerKey); |
| 717 | } |
| 718 | for (const [tileKey, objects] of [...this.tiles.entries()]) |
| 719 | { |
| 720 | if (objects.chunkX === chunkX && objects.chunkY === chunkY) |
| 721 | { |
| 722 | objects.ground?.destroy(); |
| 723 | objects.groundBloom?.destroy(); |
| 724 | objects.block?.destroy(); |
| 725 | objects.blockBloom?.destroy(); |
| 726 | this.tiles.delete(tileKey); |
| 727 | } |
| 728 | } |
| 729 | for (const [id, item] of [...this.groundItems.entries()]) |
| 730 | { |
| 731 | if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) |
| 732 | { this.despawnGroundItem(id); } |
| 733 | } |
| 734 | // Server sends unsubscribeChunk when a chunk leaves the static 5×5 ring. |
| 735 | // Entity replication is limited to the inner 3×3; static-only chunks strip dynamics via staticOnly snapshots. |
| 736 | for (const [id, entity] of [...this.entities.entries()]) |
| 737 | { |
| 738 | if (id === this.localEntityId) |
| 739 | { continue; } |
| 740 | if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX |
| 741 | && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY) |
| 742 | { this.despawnEntity(id, { immediate: true }); } |
| 743 | } |
| 744 | this.#rebuildAllEdges(); |
| 745 | } |
| 746 | |
| 747 | setChunkOpen (chunkX, chunkY, open) |
| 748 | { |
| 749 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 750 | if (!snapshot) |
| 751 | { return; } |
| 752 | snapshot.open = !!open; |
| 753 | this.#rebuildAllEdges(); |
| 754 | } |
| 755 | |
| 756 | spawnEntity (payload) |
| 757 | { |
| 758 | // Fresh spawn is authoritative; do not let an older deferred hit overwrite HP. |
| 759 | this.cancelDeferredCombatHits(payload?.entityId); |
| 760 | this.#upsertEntity(payload); |
| 761 | } |
| 762 | |
| 763 | moveEntity (payload) |
| 764 | { |
| 765 | const existing = this.entities.get(payload.entityId); |
| 766 | // Move payloads lack appearance/mobTypeId — never invent a stub entity |
| 767 | // (that looked like a nameless humanoid "target"). Wait for entity-spawn. |
| 768 | if (!existing) |
| 769 | { return; } |
| 770 | // Fading corpses stay put; respawn restores via reviveAfterDeath / spawn. |
| 771 | if (existing.dying) |
| 772 | { return; } |
| 773 | const size = this.tileSize(); |
| 774 | existing.fromX = existing.visualX; |
| 775 | existing.fromY = existing.visualY; |
| 776 | existing.shadeFromTileX = existing.tileX; |
| 777 | existing.shadeFromTileY = existing.tileY; |
| 778 | if (existing.tileX !== payload.tileX || existing.tileY !== payload.tileY) |
| 779 | { |
| 780 | existing.previousTileX = existing.tileX; |
| 781 | existing.previousTileY = existing.tileY; |
| 782 | } |
| 783 | existing.tileX = payload.tileX; |
| 784 | existing.tileY = payload.tileY; |
| 785 | existing.gait = payload.gait; |
| 786 | existing.freeFlight = !!payload.freeFlight || existing.freeFlight; |
| 787 | if (payload.worldX != null && payload.worldY != null) |
| 788 | { |
| 789 | existing.worldX = payload.worldX; |
| 790 | existing.worldY = payload.worldY; |
| 791 | existing.targetX = payload.worldX * size; |
| 792 | existing.targetY = payload.worldY * size; |
| 793 | } |
| 794 | else |
| 795 | { |
| 796 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 797 | existing.targetX = pivot.x; |
| 798 | existing.targetY = pivot.y; |
| 799 | } |
| 800 | existing.lerpStarted = performance.now(); |
| 801 | existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait); |
| 802 | if (payload.entityId === this.localEntityId) |
| 803 | { this.#notePlayerTile(payload.tileX, payload.tileY); } |
| 804 | } |
| 805 | |
| 806 | despawnEntity (entityId, { immediate = false, combatDeath = false } = {}) |
| 807 | { |
| 808 | const existing = this.entities.get(entityId); |
| 809 | if (!existing) |
| 810 | { return; } |
| 811 | if (existing.dying) |
| 812 | { |
| 813 | if (immediate) |
| 814 | { this.#finishEntityFade(entityId); } |
| 815 | else if (combatDeath) |
| 816 | { this.#upgradeToDeathDissolve(existing); } |
| 817 | return; |
| 818 | } |
| 819 | // Chunk unload / session wipe: drop instantly. |
| 820 | if (immediate) |
| 821 | { |
| 822 | this.cancelDeferredCombatHits(entityId); |
| 823 | this.#destroyEntityVisuals(existing); |
| 824 | this.entities.delete(entityId); |
| 825 | return; |
| 826 | } |
| 827 | // Combat death → red silhouette. Leaving 3×3 / summons / etc. → plain fade. |
| 828 | if (combatDeath) |
| 829 | { this.#beginDeathDissolve(existing); } |
| 830 | else |
| 831 | { this.#beginDespawnFade(existing); } |
| 832 | } |
| 833 | |
| 834 | /** |
| 835 | * Start the red silhouette fade without requiring a despawn message |
| 836 | * (e.g. local playerDied arrives before entityDespawn). |
| 837 | */ |
| 838 | beginDeathDissolve (entityId) |
| 839 | { |
| 840 | const existing = this.entities.get(entityId); |
| 841 | if (!existing) |
| 842 | { return; } |
| 843 | if (existing.dying) |
| 844 | { |
| 845 | this.#upgradeToDeathDissolve(existing); |
| 846 | return; |
| 847 | } |
| 848 | this.#beginDeathDissolve(existing); |
| 849 | } |
| 850 | |
| 851 | /** |
| 852 | * Abort an in-progress (or finished) death fade and snap the sprite back. |
| 853 | * Local players are never entity-despawned, so respawn must restore — not |
| 854 | * destroy — the visual. Remotes get a fresh entity-spawn instead. |
| 855 | */ |
| 856 | reviveAfterDeath (entityId, { tileX, tileY, health, maxHealth, skullValue } = {}) |
| 857 | { |
| 858 | const entity = this.entities.get(entityId); |
| 859 | if (!entity) |
| 860 | { return false; } |
| 861 | this.#abortEntityFade(entity); |
| 862 | if (tileX != null && tileY != null) |
| 863 | { this.#snapEntityToTile(entity, tileX, tileY); } |
| 864 | if (health != null) |
| 865 | { entity.health = health; } |
| 866 | if (maxHealth != null) |
| 867 | { entity.maxHealth = maxHealth; } |
| 868 | if (skullValue != null) |
| 869 | { entity.skullValue = Math.max(0, skullValue | 0); } |
| 870 | this.#syncHpBar(entity); |
| 871 | this.#syncSkullMarker(entity); |
| 872 | this.#placeEntity(entity, performance.now()); |
| 873 | return true; |
| 874 | } |
| 875 | |
| 876 | #destroyEntityVisuals (existing) |
| 877 | { |
| 878 | existing.object?.destroy(); |
| 879 | existing.hpBar?.destroy(); |
| 880 | existing.skullMarker?.destroy(); |
| 881 | for (const overlay of existing.overlays ?? []) |
| 882 | { overlay.destroy(); } |
| 883 | for (const overlay of existing.bloomOverlays ?? []) |
| 884 | { overlay.destroy(); } |
| 885 | } |
| 886 | |
| 887 | #stripEntityChrome (entity) |
| 888 | { |
| 889 | entity.hpBar?.destroy(); |
| 890 | entity.hpBar = null; |
| 891 | entity.skullMarker?.destroy(); |
| 892 | entity.skullMarker = null; |
| 893 | } |
| 894 | |
| 895 | #beginDespawnFade (entity) |
| 896 | { |
| 897 | const now = performance.now(); |
| 898 | entity.dying = true; |
| 899 | entity.deathDissolve = false; |
| 900 | entity.untargetable = true; |
| 901 | entity.deathFadeStarted = now; |
| 902 | entity.deathFadeMs = DESPAWN_FADE_MS; |
| 903 | this.#stripEntityChrome(entity); |
| 904 | } |
| 905 | |
| 906 | #beginDeathDissolve (entity) |
| 907 | { |
| 908 | const now = performance.now(); |
| 909 | entity.dying = true; |
| 910 | entity.deathDissolve = true; |
| 911 | entity.untargetable = true; |
| 912 | entity.deathFadeStarted = now; |
| 913 | entity.deathFadeMs = DEATH_FADE_MS; |
| 914 | // Keep a full red silhouette for the whole fade (hit flash may already be running). |
| 915 | entity.damageFlashUntil = now + DEATH_FADE_MS; |
| 916 | entity.damageFlashColor = FLASH_COLOR_DAMAGE; |
| 917 | this.#stripEntityChrome(entity); |
| 918 | // Leave deferred projectile impacts queued so knockback / float still play on arrival. |
| 919 | } |
| 920 | |
| 921 | /** Promote an in-progress plain despawn fade to the red combat dissolve. */ |
| 922 | #upgradeToDeathDissolve (entity) |
| 923 | { |
| 924 | if (entity.deathDissolve) |
| 925 | { return; } |
| 926 | const now = performance.now(); |
| 927 | const elapsed = Math.max(0, now - (entity.deathFadeStarted ?? now)); |
| 928 | const remaining = Math.max(1, (entity.deathFadeMs ?? DESPAWN_FADE_MS) - elapsed); |
| 929 | entity.deathDissolve = true; |
| 930 | entity.deathFadeStarted = now; |
| 931 | entity.deathFadeMs = Math.min(DEATH_FADE_MS, remaining); |
| 932 | entity.damageFlashUntil = now + entity.deathFadeMs; |
| 933 | entity.damageFlashColor = FLASH_COLOR_DAMAGE; |
| 934 | } |
| 935 | |
| 936 | #abortEntityFade (entity) |
| 937 | { |
| 938 | entity.dying = false; |
| 939 | entity.deathDissolve = false; |
| 940 | entity.untargetable = false; |
| 941 | entity.deathFadeStarted = null; |
| 942 | entity.deathFadeMs = null; |
| 943 | entity.damageFlashUntil = 0; |
| 944 | entity.damageFlashColor = null; |
| 945 | if (entity.object?.renderer) |
| 946 | { entity.object.renderer.alpha = 1; } |
| 947 | for (const overlay of entity.overlays ?? []) |
| 948 | { |
| 949 | if (overlay.renderer) |
| 950 | { overlay.renderer.alpha = 1; } |
| 951 | } |
| 952 | for (const overlay of entity.bloomOverlays ?? []) |
| 953 | { |
| 954 | if (overlay.renderer) |
| 955 | { overlay.renderer.alpha = 1; } |
| 956 | } |
| 957 | } |
| 958 | |
| 959 | #snapEntityToTile (entity, tileX, tileY) |
| 960 | { |
| 961 | const size = this.tileSize(); |
| 962 | const pivot = tilePivot(tileX, tileY, size); |
| 963 | entity.tileX = tileX; |
| 964 | entity.tileY = tileY; |
| 965 | entity.visualX = pivot.x; |
| 966 | entity.visualY = pivot.y; |
| 967 | entity.targetX = pivot.x; |
| 968 | entity.targetY = pivot.y; |
| 969 | entity.fromX = pivot.x; |
| 970 | entity.fromY = pivot.y; |
| 971 | entity.lerpStarted = null; |
| 972 | entity.previousTileX = null; |
| 973 | entity.previousTileY = null; |
| 974 | entity.shadeFromTileX = null; |
| 975 | entity.shadeFromTileY = null; |
| 976 | entity.shoveOffsetX = 0; |
| 977 | entity.shoveOffsetY = 0; |
| 978 | if (entity.entityId === this.localEntityId) |
| 979 | { this.#notePlayerTile(tileX, tileY); } |
| 980 | } |
| 981 | |
| 982 | #finishEntityFade (entityId) |
| 983 | { |
| 984 | this.cancelDeferredCombatHits(entityId); |
| 985 | const existing = this.entities.get(entityId); |
| 986 | if (!existing) |
| 987 | { return; } |
| 988 | this.#destroyEntityVisuals(existing); |
| 989 | this.entities.delete(entityId); |
| 990 | } |
| 991 | |
| 992 | /** |
| 993 | * Drop queued combat-hit/block presentation for a target. |
| 994 | * Killing blows often defer health=0 until a projectile lands; if the |
| 995 | * target already finished dissolving or respawned, that stale apply must not run. |
| 996 | */ |
| 997 | cancelDeferredCombatHits (targetId) |
| 998 | { |
| 999 | if (targetId == null) |
| 1000 | { return; } |
| 1001 | for (const swipe of this.swipes) |
| 1002 | { |
| 1003 | if (swipe.targetId !== targetId) |
| 1004 | { continue; } |
| 1005 | swipe.onImpact = null; |
| 1006 | swipe.trackTarget = false; |
| 1007 | } |
| 1008 | } |
| 1009 | |
| 1010 | updateEntitySkull (entityId, skullValue) |
| 1011 | { |
| 1012 | const entity = this.entities.get(entityId); |
| 1013 | if (!entity) |
| 1014 | { return; } |
| 1015 | entity.skullValue = Math.max(0, skullValue | 0); |
| 1016 | const pivotX = (entity.visualX ?? 0) + (entity.shoveOffsetX ?? 0) + (entity.stackOffsetX ?? 0); |
| 1017 | const pivotY = (entity.visualY ?? 0) + (entity.shoveOffsetY ?? 0) + (entity.stackOffsetY ?? 0); |
| 1018 | const tileShade = this.#entityShadeAlpha?.(entity, performance.now()) |
| 1019 | ?? this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha |
| 1020 | ?? 0; |
| 1021 | this.#placeSkullMarker(entity, pivotX, pivotY, tileShade); |
| 1022 | } |
| 1023 | |
| 1024 | updateEntityHealth (entityId, health, maxHealth) |
| 1025 | { |
| 1026 | const entity = this.entities.get(entityId); |
| 1027 | if (!entity || entity.dying) |
| 1028 | { return; } |
| 1029 | entity.health = health; |
| 1030 | entity.maxHealth = maxHealth; |
| 1031 | this.#syncHpBar(entity); |
| 1032 | } |
| 1033 | |
| 1034 | flashDamage (entityId) |
| 1035 | { |
| 1036 | this.#flashEntity(entityId, FLASH_COLOR_DAMAGE); |
| 1037 | } |
| 1038 | |
| 1039 | flashBlock (entityId) |
| 1040 | { |
| 1041 | this.#flashEntity(entityId, FLASH_COLOR_BLOCK); |
| 1042 | } |
| 1043 | |
| 1044 | #flashEntity (entityId, color) |
| 1045 | { |
| 1046 | const entity = this.entities.get(entityId); |
| 1047 | if (!entity) |
| 1048 | { return; } |
| 1049 | entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS; |
| 1050 | entity.damageFlashColor = color ?? FLASH_COLOR_DAMAGE; |
| 1051 | } |
| 1052 | |
| 1053 | /** Target knocks back away from attacker (hit). */ |
| 1054 | spawnCombatKnockback (payload) |
| 1055 | { |
| 1056 | const attacker = this.entities.get(payload?.attackerId); |
| 1057 | const target = this.entities.get(payload?.targetId); |
| 1058 | if (!attacker || !target) |
| 1059 | { return; } |
| 1060 | const ax = attacker.visualX + (attacker.stackOffsetX ?? 0); |
| 1061 | const ay = attacker.visualY + (attacker.stackOffsetY ?? 0); |
| 1062 | const tx = target.visualX + (target.stackOffsetX ?? 0); |
| 1063 | const ty = target.visualY + (target.stackOffsetY ?? 0); |
| 1064 | this.#applyShoveInDirection(target, tx - ax, ty - ay); |
| 1065 | } |
| 1066 | |
| 1067 | /** Target sidesteps perpendicular to the attack (dodge / miss). */ |
| 1068 | spawnCombatDodge (payload) |
| 1069 | { |
| 1070 | const attacker = this.entities.get(payload?.attackerId); |
| 1071 | const target = this.entities.get(payload?.targetId); |
| 1072 | if (!attacker || !target) |
| 1073 | { return; } |
| 1074 | const ax = attacker.visualX + (attacker.stackOffsetX ?? 0); |
| 1075 | const ay = attacker.visualY + (attacker.stackOffsetY ?? 0); |
| 1076 | const tx = target.visualX + (target.stackOffsetX ?? 0); |
| 1077 | const ty = target.visualY + (target.stackOffsetY ?? 0); |
| 1078 | const dx = tx - ax; |
| 1079 | const dy = ty - ay; |
| 1080 | const side = Math.random() < 0.5 ? 1 : -1; |
| 1081 | this.#applyShoveInDirection(target, -dy * side, dx * side); |
| 1082 | } |
| 1083 | |
| 1084 | spawnDamageNumber (entityId, damage) |
| 1085 | { |
| 1086 | const amount = damage | 0; |
| 1087 | if (amount <= 0) |
| 1088 | { return; } |
| 1089 | this.damageFloats.push({ |
| 1090 | entityId, |
| 1091 | damage: amount, |
| 1092 | started: performance.now() |
| 1093 | }); |
| 1094 | } |
| 1095 | |
| 1096 | /** |
| 1097 | * Queue combat-hit presentation until a matching in-flight projectile lands. |
| 1098 | * Returns true when deferred; caller should apply immediately when false. |
| 1099 | */ |
| 1100 | deferCombatHit (message, apply) |
| 1101 | { |
| 1102 | if (typeof apply !== "function" || message?.targetId == null) |
| 1103 | { return false; } |
| 1104 | const attackerId = message.attackerId ?? null; |
| 1105 | const targetId = message.targetId; |
| 1106 | const swipe = this.swipes.find((entry) => |
| 1107 | entry.lerp |
| 1108 | && entry.onImpact == null |
| 1109 | && entry.targetId === targetId |
| 1110 | && (attackerId == null || entry.attackerId === attackerId) |
| 1111 | && (entry.until ?? 0) > performance.now()); |
| 1112 | if (!swipe) |
| 1113 | { return false; } |
| 1114 | swipe.onImpact = apply; |
| 1115 | swipe.trackTarget = true; |
| 1116 | return true; |
| 1117 | } |
| 1118 | |
| 1119 | /** Stop tracking a living target (misses fly to a fixed tile). */ |
| 1120 | markProjectileMiss (message) |
| 1121 | { |
| 1122 | const attackerId = message?.attackerId ?? null; |
| 1123 | const targetId = message?.targetId ?? null; |
| 1124 | for (const swipe of this.swipes) |
| 1125 | { |
| 1126 | if (!swipe.lerp || swipe.onImpact != null) |
| 1127 | { continue; } |
| 1128 | if (targetId != null && swipe.targetId !== targetId) |
| 1129 | { continue; } |
| 1130 | if (attackerId != null && swipe.attackerId !== attackerId) |
| 1131 | { continue; } |
| 1132 | swipe.trackTarget = false; |
| 1133 | if (message.tileX != null) |
| 1134 | { swipe.tileX = message.tileX; } |
| 1135 | if (message.tileY != null) |
| 1136 | { swipe.tileY = message.tileY; } |
| 1137 | } |
| 1138 | } |
| 1139 | |
| 1140 | spawnSkillLevelUp (entityId, payload) |
| 1141 | { |
| 1142 | const level = payload?.level | 0; |
| 1143 | if (level <= 0 || !payload?.icon) |
| 1144 | { return; } |
| 1145 | this.skillLevelFloats.push({ |
| 1146 | entityId, |
| 1147 | level, |
| 1148 | icon: payload.icon, |
| 1149 | displayName: payload.displayName ?? payload.skillId ?? "", |
| 1150 | started: performance.now() |
| 1151 | }); |
| 1152 | } |
| 1153 | |
| 1154 | setAppearance (payload) |
| 1155 | { |
| 1156 | const existing = this.entities.get(payload.entityId); |
| 1157 | if (!existing) |
| 1158 | { return; } |
| 1159 | existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0; |
| 1160 | if (payload.lightIntensity != null) |
| 1161 | { existing.lightIntensity = Number(payload.lightIntensity) || 1; } |
| 1162 | if (payload.visualScale != null) |
| 1163 | { existing.visualScale = Number(payload.visualScale) || 1; } |
| 1164 | this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]); |
| 1165 | this.#placeEntity(existing); |
| 1166 | } |
| 1167 | |
| 1168 | /** |
| 1169 | * Render the live entity (body + overlays, same tint/tight-fit shaders as the |
| 1170 | * world, unlit) into an offscreen FBO, crop the top square, and return a |
| 1171 | * pixel-scaled canvas for UI (e.g. dialogue speaker icons). |
| 1172 | * @param {number} entityId |
| 1173 | * @param {{ size?: number }} [options] |
| 1174 | * @returns {HTMLCanvasElement | null} |
| 1175 | */ |
| 1176 | captureEntityPortrait (entityId, { size = 64 } = {}) |
| 1177 | { |
| 1178 | const entity = this.entities.get(entityId); |
| 1179 | const body = entity?.object?.renderer?.sprite; |
| 1180 | const glCtx = this.scene?.glContext; |
| 1181 | const gl = glCtx?.gl; |
| 1182 | if (!entity || !body || !gl) |
| 1183 | { return null; } |
| 1184 | |
| 1185 | const frameW = Math.max(1, body.width | 0 || SPRITE_SIZE_PX); |
| 1186 | const frameH = Math.max(1, body.height | 0 || SPRITE_SIZE_PX); |
| 1187 | if (!this.#ensurePortraitTarget(gl, frameW, frameH)) |
| 1188 | { return null; } |
| 1189 | |
| 1190 | const prevFb = gl.getParameter(gl.FRAMEBUFFER_BINDING); |
| 1191 | const prevViewport = gl.getParameter(gl.VIEWPORT); |
| 1192 | const prevW = glCtx._lastWidth; |
| 1193 | const prevH = glCtx._lastHeight; |
| 1194 | const prevBlend = gl.isEnabled(gl.BLEND); |
| 1195 | |
| 1196 | try |
| 1197 | { |
| 1198 | // drawSprite projects with _lastWidth/_lastHeight — match the FBO. |
| 1199 | glCtx._lastWidth = frameW; |
| 1200 | glCtx._lastHeight = frameH; |
| 1201 | gl.bindFramebuffer(gl.FRAMEBUFFER, this._portrait.fb); |
| 1202 | gl.viewport(0, 0, frameW, frameH); |
| 1203 | gl.enable(gl.BLEND); |
| 1204 | gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); |
| 1205 | gl.clearColor(0, 0, 0, 0); |
| 1206 | gl.clear(gl.COLOR_BUFFER_BIT); |
| 1207 | |
| 1208 | const pivotX = frameW * 0.5; |
| 1209 | const pivotY = frameH - PIVOT_FROM_BOTTOM_PX; |
| 1210 | this._portraitBodyMap = body.g_image ?? null; |
| 1211 | this._portraitTightFitEntity = entity; |
| 1212 | this.#drawPortraitLayer(glCtx, entity.object, pivotX, pivotY, null, false); |
| 1213 | |
| 1214 | const overlays = entity.overlays ?? []; |
| 1215 | const tints = entity.overlayTints ?? []; |
| 1216 | const dualTints = entity.overlayDualTints ?? []; |
| 1217 | const tight = entity.overlayTightFit ?? []; |
| 1218 | for (let index = 0; index < overlays.length; index++) |
| 1219 | { |
| 1220 | this.#drawPortraitLayer( |
| 1221 | glCtx, |
| 1222 | overlays[index], |
| 1223 | pivotX, |
| 1224 | pivotY, |
| 1225 | tints[index] ?? null, |
| 1226 | !!tight[index], |
| 1227 | dualTints[index] ?? null |
| 1228 | ); |
| 1229 | } |
| 1230 | this._portraitBodyMap = null; |
| 1231 | this._portraitTightFitEntity = null; |
| 1232 | |
| 1233 | const pixels = this._portrait.pixels; |
| 1234 | gl.readPixels(0, 0, frameW, frameH, gl.RGBA, gl.UNSIGNED_BYTE, pixels); |
| 1235 | } |
| 1236 | finally |
| 1237 | { |
| 1238 | glCtx._lastWidth = prevW; |
| 1239 | glCtx._lastHeight = prevH; |
| 1240 | gl.bindFramebuffer(gl.FRAMEBUFFER, prevFb); |
| 1241 | gl.viewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]); |
| 1242 | if (!prevBlend) |
| 1243 | { gl.disable(gl.BLEND); } |
| 1244 | gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); |
| 1245 | } |
| 1246 | |
| 1247 | return this.#portraitPixelsToCanvas(frameW, frameH, size); |
| 1248 | } |
| 1249 | |
| 1250 | #ensurePortraitTarget (gl, width, height) |
| 1251 | { |
| 1252 | const prev = this._portrait; |
| 1253 | if (prev && prev.w === width && prev.h === height && prev.fb && prev.tex) |
| 1254 | { return true; } |
| 1255 | if (prev?.fb) |
| 1256 | { gl.deleteFramebuffer(prev.fb); } |
| 1257 | if (prev?.tex) |
| 1258 | { gl.deleteTexture(prev.tex); } |
| 1259 | |
| 1260 | const tex = gl.createTexture(); |
| 1261 | gl.bindTexture(gl.TEXTURE_2D, tex); |
| 1262 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); |
| 1263 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); |
| 1264 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); |
| 1265 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); |
| 1266 | gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); |
| 1267 | |
| 1268 | const fb = gl.createFramebuffer(); |
| 1269 | gl.bindFramebuffer(gl.FRAMEBUFFER, fb); |
| 1270 | gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0); |
| 1271 | const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); |
| 1272 | gl.bindFramebuffer(gl.FRAMEBUFFER, null); |
| 1273 | if (status !== gl.FRAMEBUFFER_COMPLETE) |
| 1274 | { |
| 1275 | gl.deleteFramebuffer(fb); |
| 1276 | gl.deleteTexture(tex); |
| 1277 | this._portrait = null; |
| 1278 | return false; |
| 1279 | } |
| 1280 | this._portrait = { |
| 1281 | fb, |
| 1282 | tex, |
| 1283 | w: width, |
| 1284 | h: height, |
| 1285 | pixels: new Uint8Array(width * height * 4), |
| 1286 | scratch: document.createElement("canvas") |
| 1287 | }; |
| 1288 | return true; |
| 1289 | } |
| 1290 | |
| 1291 | #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit, dualTint = null) |
| 1292 | { |
| 1293 | const sprite = object?.renderer?.sprite; |
| 1294 | if (!sprite?.g_image) |
| 1295 | { return; } |
| 1296 | const subImage = object.renderer.subImage | 0; |
| 1297 | const height = sprite.height || SPRITE_SIZE_PX; |
| 1298 | const draw = spriteDrawSize(sprite.width, sprite.height, 1); |
| 1299 | const center = spriteCenterFromPivot(pivotX, pivotY, height, 1); |
| 1300 | const tint = tintColor ? normalizeRgb(tintColor) : null; |
| 1301 | let shader = glCtx.defaultShader; |
| 1302 | let uniforms = null; |
| 1303 | let secondaryHtml = null; |
| 1304 | |
| 1305 | const bodyHtml = this._portraitBodyMap; |
| 1306 | const portraitEntity = this._portraitTightFitEntity; |
| 1307 | const maskUniforms = tightFit && portraitEntity |
| 1308 | ? this.#tightFitMaskUniforms(object, portraitEntity) |
| 1309 | : null; |
| 1310 | if (dualTint) |
| 1311 | { |
| 1312 | const shaft = normalizeRgb(dualTint.shaft); |
| 1313 | const tip = normalizeRgb(dualTint.tip); |
| 1314 | const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null; |
| 1315 | shader = getDualTintLitSpriteShader(); |
| 1316 | uniforms = { |
| 1317 | u_darkness: 0, |
| 1318 | u_strength: 0, |
| 1319 | u_flashColor: FLASH_COLOR_DAMAGE, |
| 1320 | u_wade: 0, |
| 1321 | u_spriteHeight: height, |
| 1322 | u_shaftTint: [shaft.r, shaft.g, shaft.b], |
| 1323 | u_tipTint: [tip.r, tip.g, tip.b], |
| 1324 | u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0], |
| 1325 | u_hasCoat: coat ? 1 : 0 |
| 1326 | }; |
| 1327 | } |
| 1328 | else if (tightFit && bodyHtml && maskUniforms) |
| 1329 | { |
| 1330 | secondaryHtml = bodyHtml; |
| 1331 | if (tint) |
| 1332 | { |
| 1333 | shader = getTightFitTintLitSpriteShader(); |
| 1334 | uniforms = { |
| 1335 | u_darkness: 0, |
| 1336 | u_strength: 0, |
| 1337 | u_flashColor: FLASH_COLOR_DAMAGE, |
| 1338 | u_wade: 0, |
| 1339 | u_spriteHeight: height, |
| 1340 | u_useTint: 1, |
| 1341 | u_tintColor: [tint.r, tint.g, tint.b], |
| 1342 | ...maskUniforms |
| 1343 | }; |
| 1344 | } |
| 1345 | else |
| 1346 | { |
| 1347 | shader = getTightFitLitSpriteShader(); |
| 1348 | uniforms = { |
| 1349 | u_darkness: 0, |
| 1350 | u_strength: 0, |
| 1351 | u_flashColor: FLASH_COLOR_DAMAGE, |
| 1352 | u_wade: 0, |
| 1353 | u_spriteHeight: height, |
| 1354 | ...maskUniforms |
| 1355 | }; |
| 1356 | } |
| 1357 | } |
| 1358 | else if (tint) |
| 1359 | { |
| 1360 | shader = getTintLitSpriteShader(); |
| 1361 | uniforms = { |
| 1362 | u_darkness: 0, |
| 1363 | u_strength: 0, |
| 1364 | u_flashColor: FLASH_COLOR_DAMAGE, |
| 1365 | u_wade: 0, |
| 1366 | u_spriteHeight: height, |
| 1367 | u_useTint: 1, |
| 1368 | u_tintColor: [tint.r, tint.g, tint.b] |
| 1369 | }; |
| 1370 | } |
| 1371 | else |
| 1372 | { |
| 1373 | shader = getSpriteLightingShader(); |
| 1374 | uniforms = { |
| 1375 | u_darkness: 0, |
| 1376 | u_strength: 0, |
| 1377 | u_flashColor: FLASH_COLOR_DAMAGE, |
| 1378 | u_wade: 0, |
| 1379 | u_spriteHeight: height |
| 1380 | }; |
| 1381 | } |
| 1382 | |
| 1383 | glCtx.drawSprite({ |
| 1384 | texture: glCtx.getTexture(sprite.g_image), |
| 1385 | x: center.x, |
| 1386 | y: center.y, |
| 1387 | w: draw.w, |
| 1388 | h: draw.h, |
| 1389 | rotationDeg: 0, |
| 1390 | mirrorX: false, |
| 1391 | mirrorY: false, |
| 1392 | alpha: 1, |
| 1393 | uvRect: sprite.getUvRect(subImage), |
| 1394 | shader, |
| 1395 | uniforms, |
| 1396 | textures: secondaryHtml ? { u_secondary: glCtx.getTexture(secondaryHtml) } : null, |
| 1397 | lights: null |
| 1398 | }); |
| 1399 | } |
| 1400 | |
| 1401 | #portraitPixelsToCanvas (frameW, frameH, size) |
| 1402 | { |
| 1403 | const pixels = this._portrait?.pixels; |
| 1404 | if (!pixels) |
| 1405 | { return null; } |
| 1406 | const scratch = this._portrait.scratch; |
| 1407 | scratch.width = frameW; |
| 1408 | scratch.height = frameH; |
| 1409 | const sctx = scratch.getContext("2d"); |
| 1410 | const imageData = sctx.createImageData(frameW, frameH); |
| 1411 | // WebGL y=0 is bottom — flip to top-down image order. |
| 1412 | for (let y = 0; y < frameH; y++) |
| 1413 | { |
| 1414 | const src = (frameH - 1 - y) * frameW * 4; |
| 1415 | const dst = y * frameW * 4; |
| 1416 | imageData.data.set(pixels.subarray(src, src + frameW * 4), dst); |
| 1417 | } |
| 1418 | sctx.putImageData(imageData, 0, 0); |
| 1419 | |
| 1420 | const crop = Math.min(frameW, frameH); |
| 1421 | const out = document.createElement("canvas"); |
| 1422 | out.width = size; |
| 1423 | out.height = size; |
| 1424 | const octx = out.getContext("2d"); |
| 1425 | octx.imageSmoothingEnabled = false; |
| 1426 | octx.clearRect(0, 0, size, size); |
| 1427 | octx.drawImage(scratch, 0, 0, crop, crop, 0, 0, size, size); |
| 1428 | return out; |
| 1429 | } |
| 1430 | |
| 1431 | upsertGroundItem (payload) |
| 1432 | { |
| 1433 | const size = this.tileSize(); |
| 1434 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 1435 | const potion = payload.instance?.kind === "potion" ? payload.instance : null; |
| 1436 | const spriteName = potion |
| 1437 | ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`) |
| 1438 | : (payload.sprite ?? itemSpriteNameForStack({ |
| 1439 | itemId: payload.itemId, |
| 1440 | instance: payload.instance, |
| 1441 | quantity: payload.quantity |
| 1442 | })); |
| 1443 | let item = this.groundItems.get(payload.groundItemId); |
| 1444 | if (!item) |
| 1445 | { |
| 1446 | const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK); |
| 1447 | this.scene.addObject(object); |
| 1448 | item = { object }; |
| 1449 | this.groundItems.set(payload.groundItemId, item); |
| 1450 | } |
| 1451 | else if (item.object?.renderer && this.game.images[spriteName]) |
| 1452 | { item.object.renderer.sprite = this.game.images[spriteName]; } |
| 1453 | item.groundItemId = payload.groundItemId; |
| 1454 | item.tileX = payload.tileX; |
| 1455 | item.tileY = payload.tileY; |
| 1456 | item.itemId = payload.itemId; |
| 1457 | item.quantity = payload.quantity; |
| 1458 | item.displayName = payload.displayName; |
| 1459 | item.sprite = spriteName; |
| 1460 | item.instance = payload.instance ?? null; |
| 1461 | const stack = { itemId: payload.itemId, instance: payload.instance ?? null }; |
| 1462 | const def = itemDefinition(payload.itemId); |
| 1463 | item.dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def); |
| 1464 | item.tintColor = item.dualTint ? null : resolveItemTint(stack, def); |
| 1465 | if (item.object?.renderer && itemMaxCharges(def) != null) |
| 1466 | { item.object.renderer.setSubImage?.(chargeSpriteFrameIndex(stack)); } |
| 1467 | this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); |
| 1468 | this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0); |
| 1469 | } |
| 1470 | |
| 1471 | despawnGroundItem (groundItemId) |
| 1472 | { |
| 1473 | const item = this.groundItems.get(groundItemId); |
| 1474 | if (!item) |
| 1475 | { return; } |
| 1476 | item.object?.destroy(); |
| 1477 | this.groundItems.delete(groundItemId); |
| 1478 | } |
| 1479 | |
| 1480 | groundItemAtTile (tileX, tileY) |
| 1481 | { |
| 1482 | return this.groundItemsAtTile(tileX, tileY)[0] ?? null; |
| 1483 | } |
| 1484 | |
| 1485 | groundItemsAtTile (tileX, tileY) |
| 1486 | { |
| 1487 | const items = []; |
| 1488 | for (const item of this.groundItems.values()) |
| 1489 | { |
| 1490 | if (item.tileX === tileX && item.tileY === tileY) |
| 1491 | { items.push(item); } |
| 1492 | } |
| 1493 | return items; |
| 1494 | } |
| 1495 | |
| 1496 | entitiesAtTile (tileX, tileY, options = {}) |
| 1497 | { |
| 1498 | const includePrevious = !!options.includePrevious; |
| 1499 | const matches = []; |
| 1500 | for (const entity of this.entities.values()) |
| 1501 | { |
| 1502 | if (entity.tileX === tileX && entity.tileY === tileY) |
| 1503 | { |
| 1504 | matches.push(entity); |
| 1505 | continue; |
| 1506 | } |
| 1507 | if ( |
| 1508 | includePrevious |
| 1509 | && entity.lerpStarted != null |
| 1510 | && entity.previousTileX === tileX |
| 1511 | && entity.previousTileY === tileY |
| 1512 | ) |
| 1513 | { matches.push(entity); } |
| 1514 | } |
| 1515 | matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0)); |
| 1516 | return matches; |
| 1517 | } |
| 1518 | |
| 1519 | setZoom (zoom, limits = { min: 2, max: 4 }) |
| 1520 | { |
| 1521 | const min = limits.min ?? 1; |
| 1522 | const max = limits.max ?? 4; |
| 1523 | this.zoom = Math.min(max, Math.max(min, zoom)); |
| 1524 | for (const snapshot of this.chunks.values()) |
| 1525 | { this.#relayoutChunk(snapshot); } |
| 1526 | const size = this.tileSize(); |
| 1527 | for (const entity of this.entities.values()) |
| 1528 | { |
| 1529 | entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x; |
| 1530 | entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y; |
| 1531 | entity.fromX = entity.visualX; |
| 1532 | entity.fromY = entity.visualY; |
| 1533 | entity.targetX = entity.visualX; |
| 1534 | entity.targetY = entity.visualY; |
| 1535 | entity.lerpStarted = null; |
| 1536 | this.#placeEntity(entity); |
| 1537 | } |
| 1538 | for (const item of this.groundItems.values()) |
| 1539 | { |
| 1540 | const pivot = tilePivot(item.tileX, item.tileY, size); |
| 1541 | this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); |
| 1542 | } |
| 1543 | this.#rebuildAllEdges(); |
| 1544 | this.#relayoutEditorSpawners(); |
| 1545 | this.#relayoutSpawnRangeHighlight(); |
| 1546 | this.#relayoutSpellTargetHighlight(); |
| 1547 | // Play: recenter + refresh cull flags with the new tile size immediately. |
| 1548 | // Editor sets the camera via frameNeighborhood after setZoom — call refreshViewport there. |
| 1549 | if (this.followPlayer) |
| 1550 | { this.refreshViewport(); } |
| 1551 | } |
| 1552 | |
| 1553 | /** Recenter (when following) and refresh off-screen cull flags after zoom/layout. */ |
| 1554 | refreshViewport () |
| 1555 | { |
| 1556 | this.#centerCamera(); |
| 1557 | this.#syncYSortOrigin(); |
| 1558 | this.#refreshBakedDepthLayers(); |
| 1559 | this.#cullOffscreenDrawables(); |
| 1560 | } |
| 1561 | |
| 1562 | tileSize () |
| 1563 | { |
| 1564 | return SPRITE_SIZE_PX * this.zoom; |
| 1565 | } |
| 1566 | |
| 1567 | screenToTile (mouseX, mouseY) |
| 1568 | { |
| 1569 | const size = this.tileSize(); |
| 1570 | const worldX = mouseX - this.scene.cameraPosition.x; |
| 1571 | const worldY = mouseY - this.scene.cameraPosition.y; |
| 1572 | return { |
| 1573 | tileX: Math.floor(worldX / size), |
| 1574 | tileY: Math.floor(worldY / size) |
| 1575 | }; |
| 1576 | } |
| 1577 | |
| 1578 | entityAtScreen (mouseX, mouseY) |
| 1579 | { |
| 1580 | let best = null; |
| 1581 | let bestLayer = -Infinity; |
| 1582 | for (const entity of this.entities.values()) |
| 1583 | { |
| 1584 | const box = this.#entityScreenBox(entity); |
| 1585 | if (!box) |
| 1586 | { continue; } |
| 1587 | if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom) |
| 1588 | { |
| 1589 | const layer = entity.object?.layer ?? 0; |
| 1590 | if (layer >= bestLayer) |
| 1591 | { |
| 1592 | best = entity; |
| 1593 | bestLayer = layer; |
| 1594 | } |
| 1595 | } |
| 1596 | } |
| 1597 | return best; |
| 1598 | } |
| 1599 | |
| 1600 | nametagAnchor (entity) |
| 1601 | { |
| 1602 | const box = this.#entityScreenBox(entity); |
| 1603 | if (!box) |
| 1604 | { return null; } |
| 1605 | return { x: (box.left + box.right) / 2, y: box.top }; |
| 1606 | } |
| 1607 | |
| 1608 | #entityScreenBox (entity) |
| 1609 | { |
| 1610 | const object = entity?.object; |
| 1611 | if (!object) |
| 1612 | { return null; } |
| 1613 | const size = object.transform.size; |
| 1614 | const x = object.transform.position.x + this.scene.cameraPosition.x; |
| 1615 | const y = object.transform.position.y + this.scene.cameraPosition.y; |
| 1616 | return { |
| 1617 | left: x - size.x / 2, |
| 1618 | right: x + size.x / 2, |
| 1619 | top: y - size.y / 2, |
| 1620 | bottom: y + size.y / 2 |
| 1621 | }; |
| 1622 | } |
| 1623 | |
| 1624 | update (deltaTime) |
| 1625 | { |
| 1626 | const now = performance.now(); |
| 1627 | const size = this.tileSize(); |
| 1628 | this.#refreshStackTargets(); |
| 1629 | for (const entity of this.entities.values()) |
| 1630 | { |
| 1631 | const target = entity.targetX != null && entity.targetY != null |
| 1632 | ? { x: entity.targetX, y: entity.targetY } |
| 1633 | : tilePivot(entity.tileX, entity.tileY, size); |
| 1634 | if (entity.lerpStarted != null) |
| 1635 | { |
| 1636 | const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs)); |
| 1637 | entity.visualX = entity.fromX + (target.x - entity.fromX) * t; |
| 1638 | entity.visualY = entity.fromY + (target.y - entity.fromY) * t; |
| 1639 | if (t >= 1) |
| 1640 | { |
| 1641 | entity.lerpStarted = null; |
| 1642 | entity.previousTileX = null; |
| 1643 | entity.previousTileY = null; |
| 1644 | } |
| 1645 | } |
| 1646 | else |
| 1647 | { |
| 1648 | entity.visualX = target.x; |
| 1649 | entity.visualY = target.y; |
| 1650 | } |
| 1651 | this.#updateStackOffset(entity, now); |
| 1652 | this.#updateShove(entity, now, size); |
| 1653 | this.#expireGatherToolOverlay(entity, now); |
| 1654 | this.#placeEntity(entity, now); |
| 1655 | } |
| 1656 | |
| 1657 | this.#updateSwipes(now); |
| 1658 | this.#updateDamageNumbers(now); |
| 1659 | this.#updateSkillLevelFloats(now); |
| 1660 | this.#relayoutSpellTargetHighlight(); |
| 1661 | this.#centerCamera(); |
| 1662 | this.#refreshBakedDepthLayers(); |
| 1663 | this.#cullOffscreenDrawables(); |
| 1664 | this.#updateShade(deltaTime); |
| 1665 | } |
| 1666 | |
| 1667 | /** |
| 1668 | * Desired circle offsets for stacked entities (applied via {@link #updateStackOffset}). |
| 1669 | * Stable assignment by entityId; free-flight entities stay unshifted. |
| 1670 | */ |
| 1671 | #refreshStackTargets () |
| 1672 | { |
| 1673 | const byTile = new Map(); |
| 1674 | for (const entity of this.entities.values()) |
| 1675 | { |
| 1676 | if (entity.freeFlight || entity.dying) |
| 1677 | { |
| 1678 | entity.stackTargetX = 0; |
| 1679 | entity.stackTargetY = 0; |
| 1680 | continue; |
| 1681 | } |
| 1682 | const key = `${entity.tileX},${entity.tileY}`; |
| 1683 | let list = byTile.get(key); |
| 1684 | if (!list) |
| 1685 | { |
| 1686 | list = []; |
| 1687 | byTile.set(key, list); |
| 1688 | } |
| 1689 | list.push(entity); |
| 1690 | } |
| 1691 | const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2; |
| 1692 | for (const list of byTile.values()) |
| 1693 | { |
| 1694 | if (list.length <= 1) |
| 1695 | { |
| 1696 | for (const entity of list) |
| 1697 | { |
| 1698 | entity.stackTargetX = 0; |
| 1699 | entity.stackTargetY = 0; |
| 1700 | } |
| 1701 | continue; |
| 1702 | } |
| 1703 | list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId))); |
| 1704 | const n = list.length; |
| 1705 | for (let i = 0; i < n; i++) |
| 1706 | { |
| 1707 | const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n; |
| 1708 | list[i].stackTargetX = Math.cos(angle) * radius; |
| 1709 | list[i].stackTargetY = Math.sin(angle) * radius; |
| 1710 | } |
| 1711 | } |
| 1712 | } |
| 1713 | |
| 1714 | #updateStackOffset (entity, now) |
| 1715 | { |
| 1716 | const tx = entity.stackTargetX ?? 0; |
| 1717 | const ty = entity.stackTargetY ?? 0; |
| 1718 | const cx = entity.stackOffsetX ?? 0; |
| 1719 | const cy = entity.stackOffsetY ?? 0; |
| 1720 | if (entity.stackLerpToX !== tx || entity.stackLerpToY !== ty) |
| 1721 | { |
| 1722 | entity.stackFromX = cx; |
| 1723 | entity.stackFromY = cy; |
| 1724 | entity.stackLerpToX = tx; |
| 1725 | entity.stackLerpToY = ty; |
| 1726 | entity.stackLerpStarted = now; |
| 1727 | } |
| 1728 | if (entity.stackLerpStarted == null) |
| 1729 | { |
| 1730 | entity.stackOffsetX = tx; |
| 1731 | entity.stackOffsetY = ty; |
| 1732 | return; |
| 1733 | } |
| 1734 | const t = Math.min(1, (now - entity.stackLerpStarted) / STACK_SPREAD_LERP_MS); |
| 1735 | entity.stackOffsetX = entity.stackFromX + (tx - entity.stackFromX) * t; |
| 1736 | entity.stackOffsetY = entity.stackFromY + (ty - entity.stackFromY) * t; |
| 1737 | if (t >= 1) |
| 1738 | { |
| 1739 | entity.stackOffsetX = tx; |
| 1740 | entity.stackOffsetY = ty; |
| 1741 | entity.stackLerpStarted = null; |
| 1742 | } |
| 1743 | } |
| 1744 | |
| 1745 | #updateShove (entity, now, tileSize) |
| 1746 | { |
| 1747 | if (!entity.shove) |
| 1748 | { |
| 1749 | entity.shoveOffsetX = 0; |
| 1750 | entity.shoveOffsetY = 0; |
| 1751 | return; |
| 1752 | } |
| 1753 | const elapsed = now - entity.shove.started; |
| 1754 | const t = Math.min(1, elapsed / entity.shove.durationMs); |
| 1755 | const maxDist = tileSize * SHOVE_TILE_FRACTION; |
| 1756 | const dx = entity.shove.targetVisualX - entity.shove.startVisualX; |
| 1757 | const dy = entity.shove.targetVisualY - entity.shove.startVisualY; |
| 1758 | const dist = Math.hypot(dx, dy) || 1; |
| 1759 | const ux = dx / dist; |
| 1760 | const uy = dy / dist; |
| 1761 | let phase; |
| 1762 | if (t < 0.45) |
| 1763 | { phase = t / 0.45; } |
| 1764 | else |
| 1765 | { phase = 1 - (t - 0.45) / 0.55; } |
| 1766 | entity.shoveOffsetX = ux * maxDist * phase; |
| 1767 | entity.shoveOffsetY = uy * maxDist * phase; |
| 1768 | if (t >= 1) |
| 1769 | { entity.shove = null; } |
| 1770 | } |
| 1771 | |
| 1772 | spawnCombatSwing (payload) |
| 1773 | { |
| 1774 | const attacker = this.entities.get(payload.attackerId); |
| 1775 | const target = this.entities.get(payload.targetId); |
| 1776 | if (!attacker || !target) |
| 1777 | { return; } |
| 1778 | const ax = attacker.visualX + (attacker.stackOffsetX ?? 0); |
| 1779 | const ay = attacker.visualY + (attacker.stackOffsetY ?? 0); |
| 1780 | const tx = target.visualX + (target.stackOffsetX ?? 0); |
| 1781 | const ty = target.visualY + (target.stackOffsetY ?? 0); |
| 1782 | this.#applyShove(attacker, tx, ty); |
| 1783 | const midX = (ax + tx) / 2; |
| 1784 | const midY = (ay + ty) / 2; |
| 1785 | const sortY = Math.max(ay, ty) + 0.02; |
| 1786 | const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI); |
| 1787 | const jitter = (Math.random() * 2 - 1) * MELEE_SWIPE_JITTER_DEG; |
| 1788 | const spriteName = "fx:melee-swipe:melee-swipe"; |
| 1789 | const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX); |
| 1790 | if (object.transform) |
| 1791 | { object.transform.rotation = angle + jitter; } |
| 1792 | if (object.renderer) |
| 1793 | { object.renderer.alpha = 1; } |
| 1794 | this.scene.addObject(object); |
| 1795 | this.#placePivoted(object, midX, midY, sortY, SORT_FX); |
| 1796 | this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY); |
| 1797 | const started = performance.now(); |
| 1798 | this.swipes.push({ |
| 1799 | object, |
| 1800 | until: started + MELEE_SWIPE_MS, |
| 1801 | started, |
| 1802 | durationMs: MELEE_SWIPE_MS, |
| 1803 | fadeOpacity: true, |
| 1804 | fromTileX: payload.fromTileX, |
| 1805 | fromTileY: payload.fromTileY, |
| 1806 | tileX: payload.tileX, |
| 1807 | tileY: payload.tileY |
| 1808 | }); |
| 1809 | } |
| 1810 | |
| 1811 | /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */ |
| 1812 | spawnGatherSwing (payload) |
| 1813 | { |
| 1814 | const attacker = this.entities.get(payload.attackerId); |
| 1815 | if (!attacker) |
| 1816 | { return; } |
| 1817 | const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize()); |
| 1818 | this.#applyShove(attacker, pivot.x, pivot.y); |
| 1819 | if (payload.toolItemId != null) |
| 1820 | { this.#setGatherToolOverlay(attacker, payload.toolItemId); } |
| 1821 | } |
| 1822 | |
| 1823 | #applyShove (entity, targetVisualX, targetVisualY) |
| 1824 | { |
| 1825 | entity.shove = { |
| 1826 | startVisualX: entity.visualX, |
| 1827 | startVisualY: entity.visualY, |
| 1828 | targetVisualX, |
| 1829 | targetVisualY, |
| 1830 | started: performance.now(), |
| 1831 | durationMs: SHOVE_MS |
| 1832 | }; |
| 1833 | } |
| 1834 | |
| 1835 | #applyShoveInDirection (entity, dirX, dirY) |
| 1836 | { |
| 1837 | const len = Math.hypot(dirX, dirY); |
| 1838 | if (len < 1e-4) |
| 1839 | { return; } |
| 1840 | const tileSize = this.tileSize(); |
| 1841 | const ux = dirX / len; |
| 1842 | const uy = dirY / len; |
| 1843 | this.#applyShove( |
| 1844 | entity, |
| 1845 | entity.visualX + ux * tileSize, |
| 1846 | entity.visualY + uy * tileSize |
| 1847 | ); |
| 1848 | } |
| 1849 | |
| 1850 | /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */ |
| 1851 | spawnPhysicalProjectileFx (payload) |
| 1852 | { |
| 1853 | const spriteName = payload.sprite ?? "fx:projectile:arrow"; |
| 1854 | const image = this.game.images[spriteName]; |
| 1855 | if (!image) |
| 1856 | { return; } |
| 1857 | const dualTint = this.#dualTintFromPayload(payload); |
| 1858 | const fromPivot = this.#projectileLaunchPoint( |
| 1859 | payload.attackerId ?? null, |
| 1860 | payload.fromTileX, |
| 1861 | payload.fromTileY |
| 1862 | ); |
| 1863 | const toPivot = this.#projectileAimPoint( |
| 1864 | payload.targetId ?? null, |
| 1865 | payload.tileX, |
| 1866 | payload.tileY |
| 1867 | ); |
| 1868 | const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02; |
| 1869 | const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI); |
| 1870 | const object = new GameObject(0, 0, image, SORT_FX); |
| 1871 | if (object.transform) |
| 1872 | { object.transform.rotation = angle; } |
| 1873 | this.scene.addObject(object); |
| 1874 | this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX); |
| 1875 | this.#applyPhysicalCombatFxDarkness( |
| 1876 | object, |
| 1877 | payload.fromTileX, |
| 1878 | payload.fromTileY, |
| 1879 | payload.tileX, |
| 1880 | payload.tileY, |
| 1881 | dualTint |
| 1882 | ); |
| 1883 | const started = performance.now(); |
| 1884 | const durationMs = payload.durationMs ?? 400; |
| 1885 | const trackTarget = payload.trackTarget !== false && payload.targetId != null; |
| 1886 | this.swipes.push({ |
| 1887 | object, |
| 1888 | until: started + durationMs, |
| 1889 | started, |
| 1890 | durationMs, |
| 1891 | lerp: true, |
| 1892 | dualTint, |
| 1893 | fromTileX: payload.fromTileX, |
| 1894 | fromTileY: payload.fromTileY, |
| 1895 | tileX: payload.tileX, |
| 1896 | tileY: payload.tileY, |
| 1897 | attackerId: payload.attackerId ?? null, |
| 1898 | targetId: payload.targetId ?? null, |
| 1899 | trackTarget, |
| 1900 | onImpact: null |
| 1901 | }); |
| 1902 | } |
| 1903 | |
| 1904 | /** Bloom-layer spell projectiles — magenta-tinted, unique art per spell. */ |
| 1905 | spawnSpellProjectileFx (payload) |
| 1906 | { |
| 1907 | const spellId = payload.spellId ?? null; |
| 1908 | const def = spellId != null ? spellDefinition(spellId) : null; |
| 1909 | const spriteName = payload.sprite |
| 1910 | ?? def?.projectileSprite |
| 1911 | ?? "fx:projectile:spell-none-1-mana-bullet"; |
| 1912 | const image = this.game.images[spriteName]; |
| 1913 | if (!image) |
| 1914 | { return; } |
| 1915 | const tint = spellProjectileTint(def?.element); |
| 1916 | const fromPivot = this.#projectileLaunchPoint( |
| 1917 | payload.casterId ?? null, |
| 1918 | payload.fromTileX, |
| 1919 | payload.fromTileY |
| 1920 | ); |
| 1921 | const toPivot = this.#projectileAimPoint( |
| 1922 | payload.targetId ?? null, |
| 1923 | payload.tileX, |
| 1924 | payload.tileY |
| 1925 | ); |
| 1926 | const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02; |
| 1927 | const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI); |
| 1928 | const object = new GameObject(0, 0, image, SORT_FX); |
| 1929 | object.renderer.layer = RENDER_LAYER_BLOOM; |
| 1930 | this.#markUnlit(object); |
| 1931 | this.#syncUnlitTintSprite(object, tint); |
| 1932 | if (object.transform) |
| 1933 | { object.transform.rotation = angle; } |
| 1934 | this.scene.addObject(object); |
| 1935 | this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX); |
| 1936 | const started = performance.now(); |
| 1937 | const durationMs = payload.durationMs ?? 2000; |
| 1938 | this.swipes.push({ |
| 1939 | object, |
| 1940 | until: started + durationMs, |
| 1941 | started, |
| 1942 | durationMs, |
| 1943 | lerp: true, |
| 1944 | spellProjectile: true, |
| 1945 | tint, |
| 1946 | fromTileX: payload.fromTileX, |
| 1947 | fromTileY: payload.fromTileY, |
| 1948 | tileX: payload.tileX, |
| 1949 | tileY: payload.tileY, |
| 1950 | attackerId: payload.casterId ?? null, |
| 1951 | targetId: payload.targetId ?? null, |
| 1952 | trackTarget: payload.targetId != null, |
| 1953 | onImpact: null |
| 1954 | }); |
| 1955 | } |
| 1956 | |
| 1957 | spawnSpellFizzleFx (_payload) |
| 1958 | { |
| 1959 | // Visual-only fizzle; no dynamic light (cast flashes skip lightmap rebakes). |
| 1960 | } |
| 1961 | |
| 1962 | /** |
| 1963 | * Authoritative Light-spell tile light from the server. |
| 1964 | * Kept out of short-lived `dynamicLights` so duration follows `remainingMs` updates. |
| 1965 | */ |
| 1966 | setSpellLight (payload) |
| 1967 | { |
| 1968 | const key = `${payload.tileX},${payload.tileY}`; |
| 1969 | this.spellLights.set(key, { |
| 1970 | tileX: payload.tileX, |
| 1971 | tileY: payload.tileY, |
| 1972 | until: performance.now() + Math.max(0, payload.remainingMs ?? 0), |
| 1973 | range: payload.rangeTiles ?? 6, |
| 1974 | intensity: payload.intensity ?? 0.88 |
| 1975 | }); |
| 1976 | this.#invalidateNeighborLightmapCaches( |
| 1977 | Math.floor(payload.tileX / CHUNK_SIZE), |
| 1978 | Math.floor(payload.tileY / CHUNK_SIZE) |
| 1979 | ); |
| 1980 | } |
| 1981 | |
| 1982 | removeSpellLight (payload) |
| 1983 | { |
| 1984 | this.spellLights.delete(`${payload.tileX},${payload.tileY}`); |
| 1985 | this.#invalidateNeighborLightmapCaches( |
| 1986 | Math.floor(payload.tileX / CHUNK_SIZE), |
| 1987 | Math.floor(payload.tileY / CHUNK_SIZE) |
| 1988 | ); |
| 1989 | } |
| 1990 | |
| 1991 | setSpellDark (payload) |
| 1992 | { |
| 1993 | const key = `${payload.tileX},${payload.tileY}`; |
| 1994 | this.spellDarks.set(key, { |
| 1995 | tileX: payload.tileX, |
| 1996 | tileY: payload.tileY, |
| 1997 | until: performance.now() + Math.max(0, payload.remainingMs ?? 0), |
| 1998 | range: payload.rangeTiles ?? 6, |
| 1999 | intensity: payload.intensity ?? 0.88 |
| 2000 | }); |
| 2001 | this.#invalidateNeighborLightmapCaches( |
| 2002 | Math.floor(payload.tileX / CHUNK_SIZE), |
| 2003 | Math.floor(payload.tileY / CHUNK_SIZE) |
| 2004 | ); |
| 2005 | } |
| 2006 | |
| 2007 | removeSpellDark (payload) |
| 2008 | { |
| 2009 | this.spellDarks.delete(`${payload.tileX},${payload.tileY}`); |
| 2010 | this.#invalidateNeighborLightmapCaches( |
| 2011 | Math.floor(payload.tileX / CHUNK_SIZE), |
| 2012 | Math.floor(payload.tileY / CHUNK_SIZE) |
| 2013 | ); |
| 2014 | } |
| 2015 | |
| 2016 | addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 }) |
| 2017 | { |
| 2018 | this.dynamicLights.push({ |
| 2019 | tileX: Math.floor(worldX), |
| 2020 | tileY: Math.floor(worldY), |
| 2021 | range: radiusTiles, |
| 2022 | intensity, |
| 2023 | until: performance.now() + durationMs |
| 2024 | }); |
| 2025 | } |
| 2026 | |
| 2027 | updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {}) |
| 2028 | { |
| 2029 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 2030 | if (!snapshot) |
| 2031 | { return; } |
| 2032 | const index = localY * CHUNK_SIZE + localX; |
| 2033 | if (ground !== undefined) |
| 2034 | { snapshot.grounds[index] = ground; } |
| 2035 | if (block !== undefined) |
| 2036 | { snapshot.blocks[index] = block; } |
| 2037 | if (light !== undefined) |
| 2038 | { snapshot.light[index] = light; } |
| 2039 | if (ground !== undefined || block !== undefined) |
| 2040 | { |
| 2041 | if (!Array.isArray(snapshot.occlusion) || snapshot.occlusion.length < CHUNK_SIZE * CHUNK_SIZE) |
| 2042 | { snapshot.occlusion = bakeChunkOcclusion(snapshot); } |
| 2043 | else |
| 2044 | { snapshot.occlusion[index] = tileLightOcclusionAt(snapshot.grounds, snapshot.blocks, localX, localY); } |
| 2045 | } |
| 2046 | const tileX = chunkX * CHUNK_SIZE + localX; |
| 2047 | const tileY = chunkY * CHUNK_SIZE + localY; |
| 2048 | if (block !== undefined) |
| 2049 | { |
| 2050 | this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); |
| 2051 | this.#drawTile(tileX, tileY); |
| 2052 | return; |
| 2053 | } |
| 2054 | this.#scheduleChunkRebuild(snapshot); |
| 2055 | if (ground !== undefined) |
| 2056 | { this.#drawTile(tileX, tileY); } |
| 2057 | } |
| 2058 | |
| 2059 | /** |
| 2060 | * Editor-only mob markers for authored spawners (invisible during play). |
| 2061 | * Humanoid / town guard / CE show body + equipment overlays. |
| 2062 | * @param {number} chunkX |
| 2063 | * @param {number} chunkY |
| 2064 | * @param {Array<{ localX: number, localY: number, config?: object }>} spawners |
| 2065 | * @param {(mobTypeId: number) => string} resolveSprite |
| 2066 | */ |
| 2067 | setEditorSpawners (chunkX, chunkY, spawners, resolveSprite) |
| 2068 | { |
| 2069 | const prefix = `${chunkX},${chunkY}:`; |
| 2070 | for (const [key, entry] of [...this.editorSpawners.entries()]) |
| 2071 | { |
| 2072 | if (!key.startsWith(prefix)) |
| 2073 | { continue; } |
| 2074 | this.#destroyEditorSpawnerEntry(entry); |
| 2075 | this.editorSpawners.delete(key); |
| 2076 | } |
| 2077 | const size = this.tileSize(); |
| 2078 | for (const spawner of spawners ?? []) |
| 2079 | { |
| 2080 | const tileX = chunkX * CHUNK_SIZE + spawner.localX; |
| 2081 | const tileY = chunkY * CHUNK_SIZE + spawner.localY; |
| 2082 | const layers = layersFromSpawnerConfig(spawner.config); |
| 2083 | const bodySpriteName = layers?.[0]?.sprite |
| 2084 | ?? resolveSprite?.(spawner.config?.mobTypeId) |
| 2085 | ?? null; |
| 2086 | if (!bodySpriteName) |
| 2087 | { continue; } |
| 2088 | const key = `${prefix}${spawner.localX},${spawner.localY}`; |
| 2089 | const object = this.#ensureSprite(null, bodySpriteName, SORT_ENTITY); |
| 2090 | if (!object) |
| 2091 | { continue; } |
| 2092 | object.renderer.alpha = 0.85; |
| 2093 | const bodyTint = layers?.[0]?.tint ? normalizeRgb(layers[0].tint) : null; |
| 2094 | if (bodyTint) |
| 2095 | { this.#syncUnlitTintSprite(object, bodyTint); } |
| 2096 | else |
| 2097 | { this.#markUnlit(object); } |
| 2098 | const overlays = []; |
| 2099 | for (const layer of layers?.slice(1) ?? []) |
| 2100 | { |
| 2101 | const overlay = this.#ensureSprite(null, layer.sprite, SORT_ENTITY); |
| 2102 | if (!overlay) |
| 2103 | { continue; } |
| 2104 | overlay.renderer.alpha = 0.85; |
| 2105 | this.#applyEditorSpawnerOverlayLook(overlay, layer); |
| 2106 | overlays.push(overlay); |
| 2107 | } |
| 2108 | const pivot = tilePivot(tileX, tileY, size); |
| 2109 | this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY); |
| 2110 | for (let i = 0; i < overlays.length; i++) |
| 2111 | { |
| 2112 | this.#placePivoted( |
| 2113 | overlays[i], |
| 2114 | pivot.x, |
| 2115 | pivot.y, |
| 2116 | pivot.y + 0.05 + 0.001 * (i + 1), |
| 2117 | SORT_ENTITY |
| 2118 | ); |
| 2119 | } |
| 2120 | this.editorSpawners.set(key, { |
| 2121 | object, |
| 2122 | overlays, |
| 2123 | tileX, |
| 2124 | tileY, |
| 2125 | spriteName: bodySpriteName |
| 2126 | }); |
| 2127 | } |
| 2128 | } |
| 2129 | |
| 2130 | #destroyEditorSpawnerEntry (entry) |
| 2131 | { |
| 2132 | entry?.object?.destroy(); |
| 2133 | for (const overlay of entry?.overlays ?? []) |
| 2134 | { overlay?.destroy(); } |
| 2135 | } |
| 2136 | |
| 2137 | #applyEditorSpawnerOverlayLook (overlay, layer) |
| 2138 | { |
| 2139 | const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null; |
| 2140 | const dualTint = layerDef?.iconTintFromTier |
| 2141 | ? null |
| 2142 | : (layer.itemId != null |
| 2143 | ? resolveEquipDualTint({ itemId: layer.itemId }, layerDef) |
| 2144 | : null); |
| 2145 | const tint = layer.tint |
| 2146 | ? normalizeRgb(layer.tint) |
| 2147 | : (dualTint |
| 2148 | ? null |
| 2149 | : (layerDef?.iconTintFromTier |
| 2150 | ? resolveItemTint({ itemId: layer.itemId }, layerDef) |
| 2151 | : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null))); |
| 2152 | if (dualTint) |
| 2153 | { |
| 2154 | overlay._lit = true; |
| 2155 | this.#syncDualTintLitSprite(overlay, 0, dualTint, 0, false); |
| 2156 | return; |
| 2157 | } |
| 2158 | if (tint) |
| 2159 | { |
| 2160 | this.#syncUnlitTintSprite(overlay, tint); |
| 2161 | return; |
| 2162 | } |
| 2163 | this.#markUnlit(overlay); |
| 2164 | } |
| 2165 | |
| 2166 | clearEditorSpawners () |
| 2167 | { |
| 2168 | for (const entry of this.editorSpawners.values()) |
| 2169 | { this.#destroyEditorSpawnerEntry(entry); } |
| 2170 | this.editorSpawners.clear(); |
| 2171 | } |
| 2172 | |
| 2173 | #relayoutEditorSpawners () |
| 2174 | { |
| 2175 | const size = this.tileSize(); |
| 2176 | for (const entry of this.editorSpawners.values()) |
| 2177 | { |
| 2178 | if (!entry.object) |
| 2179 | { continue; } |
| 2180 | const pivot = tilePivot(entry.tileX, entry.tileY, size); |
| 2181 | this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY); |
| 2182 | const overlays = entry.overlays ?? []; |
| 2183 | for (let i = 0; i < overlays.length; i++) |
| 2184 | { |
| 2185 | this.#placePivoted( |
| 2186 | overlays[i], |
| 2187 | pivot.x, |
| 2188 | pivot.y, |
| 2189 | pivot.y + 0.05 + 0.001 * (i + 1), |
| 2190 | SORT_ENTITY |
| 2191 | ); |
| 2192 | } |
| 2193 | } |
| 2194 | } |
| 2195 | |
| 2196 | /** |
| 2197 | * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares). |
| 2198 | */ |
| 2199 | setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null) |
| 2200 | { |
| 2201 | const spawnRadius = Math.max(0, spawnRange | 0); |
| 2202 | const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0)); |
| 2203 | if (this.spawnRangeHighlight |
| 2204 | && this.wanderRangeHighlight |
| 2205 | && this.spawnRangeHighlight.tileX === tileX |
| 2206 | && this.spawnRangeHighlight.tileY === tileY |
| 2207 | && this.spawnRangeHighlight.range === spawnRadius |
| 2208 | && this.wanderRangeHighlight.range === wanderRadius) |
| 2209 | { |
| 2210 | this.#relayoutSpawnRangeHighlight(); |
| 2211 | return; |
| 2212 | } |
| 2213 | this.clearSpawnRangeHighlight(); |
| 2214 | const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE); |
| 2215 | const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE); |
| 2216 | if (wanderObject) |
| 2217 | { |
| 2218 | this.#markUnlit(wanderObject); |
| 2219 | wanderObject.renderer.alpha = 1; |
| 2220 | this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius }; |
| 2221 | } |
| 2222 | if (spawnObject) |
| 2223 | { |
| 2224 | this.#markUnlit(spawnObject); |
| 2225 | spawnObject.renderer.alpha = 1; |
| 2226 | this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius }; |
| 2227 | } |
| 2228 | this.#relayoutSpawnRangeHighlight(); |
| 2229 | } |
| 2230 | |
| 2231 | clearSpawnRangeHighlight () |
| 2232 | { |
| 2233 | this.spawnRangeHighlight?.object?.destroy(); |
| 2234 | this.wanderRangeHighlight?.object?.destroy(); |
| 2235 | this.spawnRangeHighlight = null; |
| 2236 | this.wanderRangeHighlight = null; |
| 2237 | } |
| 2238 | |
| 2239 | setSpellTargetHighlight (tileX, tileY, inRange = true) |
| 2240 | { |
| 2241 | if ( |
| 2242 | this.spellTargetHighlight |
| 2243 | && this.spellTargetHighlight.mode === "tile" |
| 2244 | && this.spellTargetHighlight.tileX === tileX |
| 2245 | && this.spellTargetHighlight.tileY === tileY |
| 2246 | && this.spellTargetHighlight.inRange === inRange |
| 2247 | ) |
| 2248 | { |
| 2249 | this.#relayoutSpellTargetHighlight(); |
| 2250 | return; |
| 2251 | } |
| 2252 | this.clearSpellTargetHighlight(); |
| 2253 | const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid"; |
| 2254 | const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1); |
| 2255 | if (!object) |
| 2256 | { return; } |
| 2257 | this.#markUnlit(object); |
| 2258 | object.renderer.alpha = 1; |
| 2259 | this.spellTargetHighlight = { |
| 2260 | mode: "tile", |
| 2261 | object, |
| 2262 | tileX, |
| 2263 | tileY, |
| 2264 | entityId: null, |
| 2265 | inRange, |
| 2266 | spriteName |
| 2267 | }; |
| 2268 | this.#relayoutSpellTargetHighlight(); |
| 2269 | } |
| 2270 | |
| 2271 | /** Outline box around a living entity (mob / player) for entity-target spells. */ |
| 2272 | setSpellEntityTargetHighlight (entityId, inRange = true) |
| 2273 | { |
| 2274 | const id = entityId | 0; |
| 2275 | if ( |
| 2276 | this.spellTargetHighlight |
| 2277 | && this.spellTargetHighlight.mode === "entity" |
| 2278 | && this.spellTargetHighlight.entityId === id |
| 2279 | && this.spellTargetHighlight.inRange === inRange |
| 2280 | ) |
| 2281 | { |
| 2282 | this.#relayoutSpellTargetHighlight(); |
| 2283 | return; |
| 2284 | } |
| 2285 | this.clearSpellTargetHighlight(); |
| 2286 | if (!this.entities.has(id)) |
| 2287 | { return; } |
| 2288 | const spriteName = inRange ? "spell-target-entity" : "spell-target-entity-invalid"; |
| 2289 | const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1); |
| 2290 | if (!object) |
| 2291 | { return; } |
| 2292 | this.#markUnlit(object); |
| 2293 | object.renderer.alpha = 1; |
| 2294 | this.spellTargetHighlight = { |
| 2295 | mode: "entity", |
| 2296 | object, |
| 2297 | tileX: 0, |
| 2298 | tileY: 0, |
| 2299 | entityId: id, |
| 2300 | inRange, |
| 2301 | spriteName |
| 2302 | }; |
| 2303 | this.#relayoutSpellTargetHighlight(); |
| 2304 | } |
| 2305 | |
| 2306 | clearSpellTargetHighlight () |
| 2307 | { |
| 2308 | this.spellTargetHighlight?.object?.destroy(); |
| 2309 | this.spellTargetHighlight = null; |
| 2310 | } |
| 2311 | |
| 2312 | #relayoutSpellTargetHighlight () |
| 2313 | { |
| 2314 | const highlight = this.spellTargetHighlight; |
| 2315 | if (!highlight?.object) |
| 2316 | { return; } |
| 2317 | if (highlight.mode === "entity") |
| 2318 | { |
| 2319 | const entity = this.entities.get(highlight.entityId); |
| 2320 | if (!entity?.object) |
| 2321 | { |
| 2322 | this.clearSpellTargetHighlight(); |
| 2323 | return; |
| 2324 | } |
| 2325 | const pad = this.tileSize() * 0.12; |
| 2326 | const src = entity.object.transform; |
| 2327 | highlight.object.transform.position.x = src.position.x; |
| 2328 | highlight.object.transform.position.y = src.position.y; |
| 2329 | highlight.object.transform.size = new vector(src.size.x + pad, src.size.y + pad); |
| 2330 | highlight.object.layer = LAYER_EDGE - 1; |
| 2331 | highlight.tileX = entity.tileX; |
| 2332 | highlight.tileY = entity.tileY; |
| 2333 | this.#markSortDirty(); |
| 2334 | return; |
| 2335 | } |
| 2336 | const size = this.tileSize(); |
| 2337 | const left = highlight.tileX * size; |
| 2338 | const top = highlight.tileY * size; |
| 2339 | highlight.object.transform.position.x = left + size / 2; |
| 2340 | highlight.object.transform.position.y = top + size / 2; |
| 2341 | highlight.object.transform.size = new vector(size, size); |
| 2342 | highlight.object.layer = LAYER_EDGE - 1; |
| 2343 | this.#markSortDirty(); |
| 2344 | } |
| 2345 | |
| 2346 | #relayoutSpawnRangeHighlight () |
| 2347 | { |
| 2348 | this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2); |
| 2349 | this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1); |
| 2350 | } |
| 2351 | |
| 2352 | #layoutRangeOverlay (highlight, layer) |
| 2353 | { |
| 2354 | if (!highlight?.object) |
| 2355 | { return; } |
| 2356 | const size = this.tileSize(); |
| 2357 | const side = (2 * highlight.range + 1) * size; |
| 2358 | const left = (highlight.tileX - highlight.range) * size; |
| 2359 | const top = (highlight.tileY - highlight.range) * size; |
| 2360 | highlight.object.transform.position.x = left + side / 2; |
| 2361 | highlight.object.transform.position.y = top + side / 2; |
| 2362 | highlight.object.transform.size = new vector(side, side); |
| 2363 | highlight.object.layer = layer; |
| 2364 | this.#markSortDirty(); |
| 2365 | } |
| 2366 | |
| 2367 | setTilePreview (tileX, tileY, override) |
| 2368 | { |
| 2369 | const next = { tileX, tileY, ...override }; |
| 2370 | if (this.#previewEqual(this.preview, next)) |
| 2371 | { return; } |
| 2372 | const previous = this.preview; |
| 2373 | this.preview = next; |
| 2374 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 2375 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 2376 | this.#scheduleChunkRebuild(this.chunks.get(`${chunkX},${chunkY}`)); |
| 2377 | if (previous && (previous.tileX !== tileX || previous.tileY !== tileY)) |
| 2378 | { |
| 2379 | const prevKey = `${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`; |
| 2380 | if (prevKey !== `${chunkX},${chunkY}`) |
| 2381 | { this.#scheduleChunkRebuild(this.chunks.get(prevKey)); } |
| 2382 | // Per-tile blocks (doors, campfires, …) are not in the atlas — refresh sprites. |
| 2383 | this.#drawTile(previous.tileX, previous.tileY); |
| 2384 | } |
| 2385 | this.#drawTile(tileX, tileY); |
| 2386 | } |
| 2387 | |
| 2388 | clearTilePreview () |
| 2389 | { |
| 2390 | if (!this.preview) |
| 2391 | { return; } |
| 2392 | const previous = this.preview; |
| 2393 | this.preview = null; |
| 2394 | const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`); |
| 2395 | this.#scheduleChunkRebuild(snapshot); |
| 2396 | this.#drawTile(previous.tileX, previous.tileY); |
| 2397 | } |
| 2398 | |
| 2399 | #lerpMs (gait) |
| 2400 | { |
| 2401 | const walk = this.settings.walkTilesPerSecond || 2; |
| 2402 | const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk; |
| 2403 | return seconds * 1000; |
| 2404 | } |
| 2405 | |
| 2406 | #centerCamera () |
| 2407 | { |
| 2408 | if (!this.followPlayer) |
| 2409 | { return; } |
| 2410 | const local = this.entities.get(this.localEntityId); |
| 2411 | if (!local) |
| 2412 | { return; } |
| 2413 | const x = local.visualX + (local.stackOffsetX ?? 0); |
| 2414 | const y = local.visualY + (local.stackOffsetY ?? 0); |
| 2415 | this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x; |
| 2416 | this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y; |
| 2417 | this.#syncYSortOrigin(); |
| 2418 | } |
| 2419 | |
| 2420 | /** |
| 2421 | * World Y at the viewport centre. Depth sort uses worldY − this so layers stay |
| 2422 | * bounded (absolute tileY×zoom otherwise overflows past LAYER_EDGE). |
| 2423 | */ |
| 2424 | #syncYSortOrigin () |
| 2425 | { |
| 2426 | const camY = this.scene.cameraPosition.y; |
| 2427 | const screenH = this.scene.real_size.y; |
| 2428 | this.ySortOrigin = -camY + screenH / 2; |
| 2429 | } |
| 2430 | |
| 2431 | /** Viewport-relative y-sort layer for world sprites. */ |
| 2432 | #depthLayer (sortY, subOrder, flight = false) |
| 2433 | { |
| 2434 | const relative = sortY - (this.ySortOrigin ?? 0); |
| 2435 | return flight ? flightSortLayer(relative, subOrder) : ySortLayer(relative, subOrder); |
| 2436 | } |
| 2437 | |
| 2438 | /** Re-apply baked chunk row depth after the y-sort origin moves with the camera. */ |
| 2439 | #refreshBakedDepthLayers () |
| 2440 | { |
| 2441 | const size = this.tileSize(); |
| 2442 | for (const baked of this.bakedChunks.values()) |
| 2443 | { |
| 2444 | const top = baked.chunkY * CHUNK_SIZE * size; |
| 2445 | const chunkPx = CHUNK_SIZE * size; |
| 2446 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 2447 | { |
| 2448 | const object = baked.blockObjects?.[row]; |
| 2449 | if (!object) |
| 2450 | { continue; } |
| 2451 | const rowY = top + row * size + size / 2; |
| 2452 | object.layer = this.#depthLayer(rowY, SORT_BLOCK); |
| 2453 | } |
| 2454 | if (baked.bloomObject) |
| 2455 | { baked.bloomObject.layer = this.#depthLayer(top + chunkPx, SORT_BLOCK); } |
| 2456 | } |
| 2457 | this.#markSortDirty(); |
| 2458 | } |
| 2459 | |
| 2460 | /** |
| 2461 | * World-pixel AABB of the screen, expanded for tall block sprites (zoom-aware). |
| 2462 | * Tiles fully outside this rect are not drawn. |
| 2463 | */ |
| 2464 | #drawBounds () |
| 2465 | { |
| 2466 | const pad = this.tileSize() * 2; |
| 2467 | const camX = this.scene.cameraPosition.x; |
| 2468 | const camY = this.scene.cameraPosition.y; |
| 2469 | const w = this.scene.real_size.x; |
| 2470 | const h = this.scene.real_size.y; |
| 2471 | return { |
| 2472 | left: -camX - pad, |
| 2473 | right: -camX + w + pad, |
| 2474 | top: -camY - pad, |
| 2475 | bottom: -camY + h + pad |
| 2476 | }; |
| 2477 | } |
| 2478 | |
| 2479 | #rectIntersects (left, top, right, bottom, bounds) |
| 2480 | { |
| 2481 | return right >= bounds.left |
| 2482 | && left <= bounds.right |
| 2483 | && bottom >= bounds.top |
| 2484 | && top <= bounds.bottom; |
| 2485 | } |
| 2486 | |
| 2487 | #setRendererVisible (object, visible) |
| 2488 | { |
| 2489 | if (object?.renderer) |
| 2490 | { object.renderer.visible = !!visible; } |
| 2491 | } |
| 2492 | |
| 2493 | /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */ |
| 2494 | #cullOffscreenDrawables () |
| 2495 | { |
| 2496 | const bounds = this.#drawBounds(); |
| 2497 | const size = this.tileSize(); |
| 2498 | |
| 2499 | for (const baked of this.bakedChunks.values()) |
| 2500 | { |
| 2501 | const left = baked.chunkX * CHUNK_SIZE * size; |
| 2502 | const top = baked.chunkY * CHUNK_SIZE * size; |
| 2503 | const chunkPx = CHUNK_SIZE * size; |
| 2504 | const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds); |
| 2505 | this.#setRendererVisible(baked.groundObject, chunkVisible); |
| 2506 | this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled); |
| 2507 | baked._inViewport = chunkVisible; |
| 2508 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 2509 | { |
| 2510 | const rowTop = top + row * size; |
| 2511 | const rowVisible = chunkVisible && this.#rectIntersects( |
| 2512 | left, rowTop, left + chunkPx, rowTop + size, bounds |
| 2513 | ); |
| 2514 | this.#setRendererVisible(baked.blockObjects?.[row], rowVisible); |
| 2515 | } |
| 2516 | } |
| 2517 | |
| 2518 | for (const objects of this.tiles.values()) |
| 2519 | { |
| 2520 | const left = objects.tileX * size; |
| 2521 | const top = objects.tileY * size; |
| 2522 | const visible = this.#rectIntersects(left, top, left + size, top + size, bounds); |
| 2523 | objects._inViewport = visible; |
| 2524 | this.#setRendererVisible(objects.ground, visible); |
| 2525 | this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled); |
| 2526 | this.#setRendererVisible(objects.block, visible); |
| 2527 | this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled); |
| 2528 | if (objects.waterEdges) |
| 2529 | { |
| 2530 | for (const edge of Object.values(objects.waterEdges)) |
| 2531 | { this.#setRendererVisible(edge, visible); } |
| 2532 | } |
| 2533 | } |
| 2534 | } |
| 2535 | |
| 2536 | #upsertEntity (payload) |
| 2537 | { |
| 2538 | const size = this.tileSize(); |
| 2539 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 2540 | let entity = this.entities.get(payload.entityId); |
| 2541 | if (entity?.dying) |
| 2542 | { |
| 2543 | if (entity.entityId === this.localEntityId) |
| 2544 | { this.#abortEntityFade(entity); } |
| 2545 | else |
| 2546 | { |
| 2547 | this.#finishEntityFade(payload.entityId); |
| 2548 | entity = null; |
| 2549 | } |
| 2550 | } |
| 2551 | if (!entity) |
| 2552 | { |
| 2553 | const spriteName = payload.layers?.[0]?.sprite |
| 2554 | ?? payload.sprite |
| 2555 | ?? bodySpriteName(payload.sex); |
| 2556 | const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY); |
| 2557 | this.scene.addObject(object); |
| 2558 | this.#startIdleAnimation(object); |
| 2559 | entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y }; |
| 2560 | this.entities.set(payload.entityId, entity); |
| 2561 | } |
| 2562 | entity.entityId = payload.entityId; |
| 2563 | entity.tileX = payload.tileX; |
| 2564 | entity.tileY = payload.tileY; |
| 2565 | entity.gait = payload.gait; |
| 2566 | entity.sex = payload.sex ?? entity.sex; |
| 2567 | entity.characterId = payload.characterId ?? entity.characterId ?? null; |
| 2568 | entity.accountId = payload.accountId ?? entity.accountId ?? null; |
| 2569 | entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null; |
| 2570 | if (payload.level != null) |
| 2571 | { entity.level = payload.level | 0; } |
| 2572 | entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile; |
| 2573 | entity.aggressive = payload.aggressive != null |
| 2574 | ? !!payload.aggressive |
| 2575 | : (payload.hostile != null ? !!payload.hostile : !!entity.aggressive); |
| 2576 | entity.canFight = payload.canFight != null |
| 2577 | ? !!payload.canFight |
| 2578 | : !!(entity.canFight || (payload.mobTypeId && !payload.talkable)); |
| 2579 | entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable; |
| 2580 | entity.hasDialogue = payload.hasDialogue != null ? !!payload.hasDialogue : !!entity.hasDialogue; |
| 2581 | entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop; |
| 2582 | entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable; |
| 2583 | entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight; |
| 2584 | entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0; |
| 2585 | if (payload.lightIntensity != null) |
| 2586 | { entity.lightIntensity = Number(payload.lightIntensity) || 1; } |
| 2587 | else if (entity.lightIntensity == null) |
| 2588 | { entity.lightIntensity = 1; } |
| 2589 | if (payload.visualScale != null) |
| 2590 | { entity.visualScale = Number(payload.visualScale) || 1; } |
| 2591 | else if (entity.visualScale == null) |
| 2592 | { entity.visualScale = 1; } |
| 2593 | if (payload.health != null) |
| 2594 | { entity.health = payload.health; } |
| 2595 | if (payload.maxHealth != null) |
| 2596 | { entity.maxHealth = payload.maxHealth; } |
| 2597 | if (payload.skullValue != null) |
| 2598 | { entity.skullValue = Math.max(0, payload.skullValue | 0); } |
| 2599 | else if (entity.skullValue == null) |
| 2600 | { entity.skullValue = 0; } |
| 2601 | if (payload.firstName) |
| 2602 | { entity.firstName = payload.firstName; } |
| 2603 | if (payload.lastName) |
| 2604 | { entity.lastName = payload.lastName; } |
| 2605 | entity.firstName = entity.firstName ?? ""; |
| 2606 | entity.lastName = entity.lastName ?? ""; |
| 2607 | if (payload.worldX != null && payload.worldY != null) |
| 2608 | { |
| 2609 | entity.worldX = payload.worldX; |
| 2610 | entity.worldY = payload.worldY; |
| 2611 | entity.visualX = payload.worldX * size; |
| 2612 | entity.visualY = payload.worldY * size; |
| 2613 | entity.targetX = entity.visualX; |
| 2614 | entity.targetY = entity.visualY; |
| 2615 | } |
| 2616 | else |
| 2617 | { |
| 2618 | entity.visualX = pivot.x; |
| 2619 | entity.visualY = pivot.y; |
| 2620 | entity.targetX = pivot.x; |
| 2621 | entity.targetY = pivot.y; |
| 2622 | } |
| 2623 | entity.fromX = entity.visualX; |
| 2624 | entity.fromY = entity.visualY; |
| 2625 | if (payload.layers) |
| 2626 | { this.#applyLayers(entity, payload.layers); } |
| 2627 | this.#syncHpBar(entity); |
| 2628 | this.#syncSkullMarker(entity); |
| 2629 | this.#placeEntity(entity, performance.now()); |
| 2630 | } |
| 2631 | |
| 2632 | #applyLayers (entity, layers) |
| 2633 | { |
| 2634 | entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }]; |
| 2635 | this.#rebuildOverlays(entity); |
| 2636 | } |
| 2637 | |
| 2638 | #setGatherToolOverlay (entity, toolItemId) |
| 2639 | { |
| 2640 | entity.gatherToolItemId = toolItemId; |
| 2641 | entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS; |
| 2642 | this.#rebuildOverlays(entity); |
| 2643 | this.#placeEntity(entity, performance.now()); |
| 2644 | } |
| 2645 | |
| 2646 | #expireGatherToolOverlay (entity, now) |
| 2647 | { |
| 2648 | if (entity.gatherToolItemId == null) |
| 2649 | { return; } |
| 2650 | if ((entity.gatherToolUntil ?? 0) > now) |
| 2651 | { return; } |
| 2652 | entity.gatherToolItemId = null; |
| 2653 | entity.gatherToolUntil = 0; |
| 2654 | this.#rebuildOverlays(entity); |
| 2655 | } |
| 2656 | |
| 2657 | /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */ |
| 2658 | #layersForDisplay (entity) |
| 2659 | { |
| 2660 | const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer })); |
| 2661 | const toolId = entity.gatherToolItemId; |
| 2662 | if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now()) |
| 2663 | { return layers; } |
| 2664 | const equip = itemEquipSprite(toolId); |
| 2665 | if (!equip || !this.game.images[equip]) |
| 2666 | { return layers; } |
| 2667 | const replacement = { |
| 2668 | sprite: equip, |
| 2669 | itemId: toolId, |
| 2670 | tint: resolveEquipTint(toolId) |
| 2671 | }; |
| 2672 | for (let index = layers.length - 1; index >= 1; index--) |
| 2673 | { |
| 2674 | const def = itemDefinition(layers[index].itemId); |
| 2675 | if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon) |
| 2676 | { |
| 2677 | layers[index] = replacement; |
| 2678 | return layers; |
| 2679 | } |
| 2680 | } |
| 2681 | layers.push(replacement); |
| 2682 | return layers; |
| 2683 | } |
| 2684 | |
| 2685 | #rebuildOverlays (entity) |
| 2686 | { |
| 2687 | const layers = this.#layersForDisplay(entity); |
| 2688 | const base = layers[0]?.sprite |
| 2689 | ?? bodySpriteName(entity.sex); |
| 2690 | if (this.game.images[base]) |
| 2691 | { |
| 2692 | entity.object.renderer.sprite = this.game.images[base]; |
| 2693 | this.#startIdleAnimation(entity.object); |
| 2694 | } |
| 2695 | entity.bodyTint = layers[0]?.tint ? normalizeRgb(layers[0].tint) : null; |
| 2696 | entity.bodyDualTint = layers[0]?.dualTint |
| 2697 | ? { |
| 2698 | shaft: normalizeRgb(layers[0].dualTint.shaft), |
| 2699 | tip: normalizeRgb(layers[0].dualTint.tip), |
| 2700 | ...(layers[0].dualTint.coat |
| 2701 | ? { coat: normalizeRgb(layers[0].dualTint.coat) } |
| 2702 | : {}) |
| 2703 | } |
| 2704 | : null; |
| 2705 | entity.bloomBody = !!layers[0]?.bloomBody; |
| 2706 | for (const overlay of entity.overlays ?? []) |
| 2707 | { overlay.destroy(); } |
| 2708 | for (const overlay of entity.bloomOverlays ?? []) |
| 2709 | { overlay.destroy(); } |
| 2710 | entity.overlays = []; |
| 2711 | entity.overlayTints = []; |
| 2712 | entity.overlayDualTints = []; |
| 2713 | entity.overlayTightFit = []; |
| 2714 | entity.bloomOverlays = []; |
| 2715 | entity.bloomOverlayTints = []; |
| 2716 | entity.bloomOverlayDualTints = []; |
| 2717 | if (entity.bloomBody && this.game.images[base]) |
| 2718 | { |
| 2719 | const bloomName = bloomCompanionName(base); |
| 2720 | const bloomImage = this.game.images[bloomName] ?? this.game.images[base]; |
| 2721 | if (bloomImage) |
| 2722 | { |
| 2723 | const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY); |
| 2724 | bloom.renderer.layer = RENDER_LAYER_BLOOM; |
| 2725 | this.#markUnlit(bloom); |
| 2726 | this.#startIdleAnimation(bloom); |
| 2727 | this.scene.addObject(bloom); |
| 2728 | entity.bloomOverlays.push(bloom); |
| 2729 | entity.bloomOverlayTints.push(entity.bodyTint); |
| 2730 | entity.bloomOverlayDualTints.push(entity.bodyDualTint); |
| 2731 | } |
| 2732 | } |
| 2733 | for (const layer of layers.slice(1)) |
| 2734 | { |
| 2735 | const image = this.game.images[layer.sprite]; |
| 2736 | if (!image) |
| 2737 | { continue; } |
| 2738 | const object = new GameObject(0, 0, image, SORT_ENTITY); |
| 2739 | this.scene.addObject(object); |
| 2740 | entity.overlays.push(object); |
| 2741 | const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null; |
| 2742 | entity.overlayTightFit.push(!!layerDef?.tightFit); |
| 2743 | const dualTint = layer.dualTint |
| 2744 | ? { |
| 2745 | shaft: normalizeRgb(layer.dualTint.shaft), |
| 2746 | tip: normalizeRgb(layer.dualTint.tip), |
| 2747 | ...(layer.dualTint.coat |
| 2748 | ? { coat: normalizeRgb(layer.dualTint.coat) } |
| 2749 | : {}) |
| 2750 | } |
| 2751 | : (layer.itemId != null |
| 2752 | ? resolveEquipDualTint({ itemId: layer.itemId }, layerDef) |
| 2753 | : null); |
| 2754 | entity.overlayDualTints.push(dualTint); |
| 2755 | entity.overlayTints.push( |
| 2756 | dualTint |
| 2757 | ? null |
| 2758 | : (layer.tint |
| 2759 | ? normalizeRgb(layer.tint) |
| 2760 | : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)) |
| 2761 | ); |
| 2762 | const bloomName = bloomCompanionName(layer.sprite); |
| 2763 | const bloomImage = this.game.images[bloomName]; |
| 2764 | if (!bloomImage) |
| 2765 | { continue; } |
| 2766 | const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY); |
| 2767 | bloom.renderer.layer = RENDER_LAYER_BLOOM; |
| 2768 | this.#markUnlit(bloom); |
| 2769 | this.scene.addObject(bloom); |
| 2770 | entity.bloomOverlays.push(bloom); |
| 2771 | entity.bloomOverlayTints.push( |
| 2772 | layer.tint ? normalizeRgb(layer.tint) : null |
| 2773 | ); |
| 2774 | } |
| 2775 | } |
| 2776 | |
| 2777 | #placeEntity (entity, now = performance.now()) |
| 2778 | { |
| 2779 | const zoom = this.zoom; |
| 2780 | const offsetX = entity.shoveOffsetX ?? 0; |
| 2781 | const offsetY = entity.shoveOffsetY ?? 0; |
| 2782 | const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0); |
| 2783 | const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0); |
| 2784 | let walkTilt = 0; |
| 2785 | if (entity.lerpStarted != null) |
| 2786 | { |
| 2787 | const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait)); |
| 2788 | const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2; |
| 2789 | const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG; |
| 2790 | walkTilt = Math.sin(cycles) * tilt; |
| 2791 | } |
| 2792 | let flashStrength = (entity.damageFlashUntil ?? 0) > now |
| 2793 | ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS |
| 2794 | : 0; |
| 2795 | let deathAlpha = 1; |
| 2796 | if (entity.dying) |
| 2797 | { |
| 2798 | const fadeMs = Math.max(1, entity.deathFadeMs ?? DEATH_FADE_MS); |
| 2799 | const fadeT = (now - (entity.deathFadeStarted ?? now)) / fadeMs; |
| 2800 | if (fadeT >= 1 && entity.entityId !== this.localEntityId) |
| 2801 | { |
| 2802 | this.#finishEntityFade(entity.entityId); |
| 2803 | return; |
| 2804 | } |
| 2805 | deathAlpha = Math.max(0, 1 - fadeT); |
| 2806 | // Red silhouette only for combat death; plain despawn keeps lit colours + darkness. |
| 2807 | if (entity.deathDissolve) |
| 2808 | { flashStrength = 1; } |
| 2809 | } |
| 2810 | const flashColor = entity.damageFlashColor ?? FLASH_COLOR_DAMAGE; |
| 2811 | const tileShade = this.#entityShadeAlpha(entity, now); |
| 2812 | const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason); |
| 2813 | |
| 2814 | entity.object.transform.rotation = walkTilt; |
| 2815 | if (entity.object.renderer) |
| 2816 | { entity.object.renderer.alpha = deathAlpha; } |
| 2817 | if (entity.bodyDualTint) |
| 2818 | { |
| 2819 | this.#syncDualTintLitSprite( |
| 2820 | entity.object, |
| 2821 | tileShade, |
| 2822 | entity.bodyDualTint, |
| 2823 | flashStrength, |
| 2824 | wade, |
| 2825 | flashColor |
| 2826 | ); |
| 2827 | } |
| 2828 | else |
| 2829 | { |
| 2830 | this.#syncLitSprite(entity.object, tileShade, flashStrength, wade, entity.bodyTint ?? null, flashColor); |
| 2831 | } |
| 2832 | const flight = !!entity.freeFlight; |
| 2833 | this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1, flight); |
| 2834 | for (let index = 0; index < (entity.overlays ?? []).length; index++) |
| 2835 | { |
| 2836 | const overlay = entity.overlays[index]; |
| 2837 | const overlaySort = Math.min(SORT_HP_BAR - 2, SORT_ENTITY + 1 + index); |
| 2838 | overlay.transform.rotation = walkTilt; |
| 2839 | if (overlay.renderer) |
| 2840 | { overlay.renderer.alpha = deathAlpha; } |
| 2841 | const dualTint = entity.overlayDualTints?.[index] ?? null; |
| 2842 | if (dualTint) |
| 2843 | { |
| 2844 | this.#syncDualTintLitSprite(overlay, tileShade, dualTint, flashStrength, wade, flashColor); |
| 2845 | } |
| 2846 | else if (entity.overlayTightFit?.[index]) |
| 2847 | { |
| 2848 | this.#syncTightFitLitSprite( |
| 2849 | overlay, |
| 2850 | entity, |
| 2851 | tileShade, |
| 2852 | flashStrength, |
| 2853 | wade, |
| 2854 | entity.overlayTints?.[index] ?? null, |
| 2855 | flashColor |
| 2856 | ); |
| 2857 | } |
| 2858 | else |
| 2859 | { |
| 2860 | this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null, flashColor); |
| 2861 | } |
| 2862 | this.#placePivoted(overlay, pivotX, pivotY, pivotY, overlaySort, entity.visualScale ?? 1, flight); |
| 2863 | } |
| 2864 | for (let index = 0; index < (entity.bloomOverlays ?? []).length; index++) |
| 2865 | { |
| 2866 | const overlay = entity.bloomOverlays[index]; |
| 2867 | this.#setRendererVisible(overlay, this.bloomEnabled && deathAlpha > 0.02); |
| 2868 | if (!this.bloomEnabled) |
| 2869 | { continue; } |
| 2870 | /** Multi-frame body bloom locks to the base sprite; static bodies leave bloom free to animate. */ |
| 2871 | if (entity.bloomBody && index === 0 && entity.object?.renderer) |
| 2872 | { |
| 2873 | const bodySprite = entity.object.renderer.sprite; |
| 2874 | const bloomSprite = overlay.renderer.sprite; |
| 2875 | const bodyFrames = Number(bodySprite?.subImages) || Number(bodySprite?.subImgTotal) || 1; |
| 2876 | const bloomFrames = Number(bloomSprite?.subImages) || Number(bloomSprite?.subImgTotal) || 1; |
| 2877 | if (bodyFrames > 1 && bloomFrames === bodyFrames) |
| 2878 | { |
| 2879 | overlay.renderer.cycle = null; |
| 2880 | overlay.renderer.subImage = entity.object.renderer.subImage | 0; |
| 2881 | } |
| 2882 | } |
| 2883 | overlay.transform.rotation = walkTilt; |
| 2884 | if (overlay.renderer) |
| 2885 | { overlay.renderer.alpha = deathAlpha; } |
| 2886 | const bloomDual = entity.bloomOverlayDualTints?.[index] ?? null; |
| 2887 | const bloomTint = entity.bloomOverlayTints?.[index] ?? entity.bodyTint ?? null; |
| 2888 | if (bloomDual) |
| 2889 | { this.#syncDualTintLitSprite(overlay, 0, bloomDual); } |
| 2890 | else if (bloomTint) |
| 2891 | { this.#syncUnlitTintSprite(overlay, bloomTint); } |
| 2892 | else |
| 2893 | { this.#markUnlit(overlay); } |
| 2894 | this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1, flight); |
| 2895 | } |
| 2896 | if (!entity.dying) |
| 2897 | { |
| 2898 | this.#placeHpBar(entity, pivotX, pivotY); |
| 2899 | this.#placeSkullMarker(entity, pivotX, pivotY, tileShade); |
| 2900 | } |
| 2901 | } |
| 2902 | |
| 2903 | #markUnlit (object) |
| 2904 | { |
| 2905 | if (!object?.renderer) |
| 2906 | { return; } |
| 2907 | object._lit = false; |
| 2908 | object.renderer.shader = null; |
| 2909 | object.renderer.shaderUniforms = null; |
| 2910 | object.renderer.secondaryMap = null; |
| 2911 | } |
| 2912 | |
| 2913 | /** Bloom / unlit overlays that still need magenta channel tint (e.g. elemental sprites). */ |
| 2914 | #syncUnlitTintSprite (object, tintColor) |
| 2915 | { |
| 2916 | if (!object?.renderer || !tintColor) |
| 2917 | { return; } |
| 2918 | const tint = normalizeRgb(tintColor); |
| 2919 | const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX; |
| 2920 | object.renderer.shader = getTintLitSpriteShader(); |
| 2921 | object.renderer.shaderUniforms = { |
| 2922 | u_darkness: 0, |
| 2923 | u_strength: 0, |
| 2924 | u_flashColor: FLASH_COLOR_DAMAGE, |
| 2925 | u_wade: 0, |
| 2926 | u_spriteHeight: height, |
| 2927 | u_useTint: 1, |
| 2928 | u_tintColor: [tint.r, tint.g, tint.b] |
| 2929 | }; |
| 2930 | object.renderer.secondaryMap = null; |
| 2931 | } |
| 2932 | |
| 2933 | #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null) |
| 2934 | { |
| 2935 | if (!object?.renderer || object._lit === false) |
| 2936 | { return; } |
| 2937 | object._lit = true; |
| 2938 | const dark = Math.min(1, Math.max(0, darkness ?? 0)); |
| 2939 | const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); |
| 2940 | const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX; |
| 2941 | const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE; |
| 2942 | const tint = tintColor ? normalizeRgb(tintColor) : null; |
| 2943 | if (tint) |
| 2944 | { |
| 2945 | object.renderer.shader = getTintLitSpriteShader(); |
| 2946 | object.renderer.shaderUniforms = { |
| 2947 | u_darkness: dark, |
| 2948 | u_strength: flash, |
| 2949 | u_flashColor: flashRgb, |
| 2950 | u_wade: wade ? 1 : 0, |
| 2951 | u_spriteHeight: height, |
| 2952 | u_useTint: 1, |
| 2953 | u_tintColor: [tint.r, tint.g, tint.b] |
| 2954 | }; |
| 2955 | } |
| 2956 | else |
| 2957 | { |
| 2958 | object.renderer.shader = getSpriteLightingShader(); |
| 2959 | object.renderer.shaderUniforms = { |
| 2960 | u_darkness: dark, |
| 2961 | u_strength: flash, |
| 2962 | u_flashColor: flashRgb, |
| 2963 | u_wade: wade ? 1 : 0, |
| 2964 | u_spriteHeight: height |
| 2965 | }; |
| 2966 | } |
| 2967 | object.renderer.secondaryMap = null; |
| 2968 | } |
| 2969 | |
| 2970 | #bodySecondaryMap (entity) |
| 2971 | { |
| 2972 | return entity?.object?.renderer?.sprite?.g_image ?? null; |
| 2973 | } |
| 2974 | |
| 2975 | #tightFitMaskUniforms (overlay, entity) |
| 2976 | { |
| 2977 | const bodyRenderer = entity?.object?.renderer; |
| 2978 | const clothRenderer = overlay?.renderer; |
| 2979 | const bodySprite = bodyRenderer?.sprite; |
| 2980 | const clothSprite = clothRenderer?.sprite; |
| 2981 | if (!bodySprite || !clothSprite) |
| 2982 | { return null; } |
| 2983 | const clothUv = clothSprite.getUvRect?.(clothRenderer.subImage | 0) |
| 2984 | ?? { u0: 0, v0: 0, u1: 1, v1: 1 }; |
| 2985 | const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0) |
| 2986 | ?? { u0: 0, v0: 0, u1: 1, v1: 1 }; |
| 2987 | return { |
| 2988 | u_clothSize: [clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX], |
| 2989 | u_bodySize: [bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX], |
| 2990 | u_pivotFromBottom: PIVOT_FROM_BOTTOM_PX, |
| 2991 | u_clothUvRect: [clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1], |
| 2992 | u_bodyUvRect: [bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1] |
| 2993 | }; |
| 2994 | } |
| 2995 | |
| 2996 | #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null) |
| 2997 | { |
| 2998 | if (!overlay?.renderer || entity?.object?.renderer == null) |
| 2999 | { return; } |
| 3000 | const bodyMap = this.#bodySecondaryMap(entity); |
| 3001 | const maskUniforms = this.#tightFitMaskUniforms(overlay, entity); |
| 3002 | const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE; |
| 3003 | if (!bodyMap || !maskUniforms) |
| 3004 | { |
| 3005 | this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb); |
| 3006 | return; |
| 3007 | } |
| 3008 | overlay._lit = true; |
| 3009 | const dark = Math.min(1, Math.max(0, darkness ?? 0)); |
| 3010 | const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); |
| 3011 | const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX; |
| 3012 | const tint = tintColor ? normalizeRgb(tintColor) : null; |
| 3013 | overlay.renderer.secondaryMap = bodyMap; |
| 3014 | if (tint) |
| 3015 | { |
| 3016 | overlay.renderer.shader = getTightFitTintLitSpriteShader(); |
| 3017 | overlay.renderer.shaderUniforms = { |
| 3018 | u_darkness: dark, |
| 3019 | u_strength: flash, |
| 3020 | u_flashColor: flashRgb, |
| 3021 | u_wade: wade ? 1 : 0, |
| 3022 | u_spriteHeight: height, |
| 3023 | u_useTint: 1, |
| 3024 | u_tintColor: [tint.r, tint.g, tint.b], |
| 3025 | ...maskUniforms |
| 3026 | }; |
| 3027 | } |
| 3028 | else |
| 3029 | { |
| 3030 | overlay.renderer.shader = getTightFitLitSpriteShader(); |
| 3031 | overlay.renderer.shaderUniforms = { |
| 3032 | u_darkness: dark, |
| 3033 | u_strength: flash, |
| 3034 | u_flashColor: flashRgb, |
| 3035 | u_wade: wade ? 1 : 0, |
| 3036 | u_spriteHeight: height, |
| 3037 | ...maskUniforms |
| 3038 | }; |
| 3039 | } |
| 3040 | } |
| 3041 | |
| 3042 | #syncDualTintLitSprite (object, darkness, dualTint, flashStrength = 0, wade = false, flashColor = null) |
| 3043 | { |
| 3044 | if (!object?.renderer || !dualTint) |
| 3045 | { return; } |
| 3046 | const shaft = normalizeRgb(dualTint.shaft); |
| 3047 | const tip = normalizeRgb(dualTint.tip); |
| 3048 | const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null; |
| 3049 | const dark = object._lit === false |
| 3050 | ? 0 |
| 3051 | : Math.min(1, Math.max(0, darkness ?? 0)); |
| 3052 | if (object._lit !== false) |
| 3053 | { object._lit = true; } |
| 3054 | const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); |
| 3055 | const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX; |
| 3056 | object.renderer.shader = getDualTintLitSpriteShader(); |
| 3057 | object.renderer.shaderUniforms = { |
| 3058 | u_darkness: dark, |
| 3059 | u_strength: flash, |
| 3060 | u_flashColor: flashColor ?? FLASH_COLOR_DAMAGE, |
| 3061 | u_wade: wade ? 1 : 0, |
| 3062 | u_spriteHeight: height, |
| 3063 | u_shaftTint: [shaft.r, shaft.g, shaft.b], |
| 3064 | u_tipTint: [tip.r, tip.g, tip.b], |
| 3065 | u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0], |
| 3066 | u_hasCoat: coat ? 1 : 0 |
| 3067 | }; |
| 3068 | object.renderer.secondaryMap = null; |
| 3069 | } |
| 3070 | |
| 3071 | #syncGroundItemSprite (item, darkness) |
| 3072 | { |
| 3073 | if (item?.dualTint) |
| 3074 | { |
| 3075 | this.#syncDualTintLitSprite(item.object, darkness, item.dualTint); |
| 3076 | return; |
| 3077 | } |
| 3078 | this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null); |
| 3079 | } |
| 3080 | |
| 3081 | #groundTypeAt (tileX, tileY) |
| 3082 | { |
| 3083 | const ground = this.#groundAtTile(tileX, tileY); |
| 3084 | return ground == null ? null : normalizeGround(ground).typeId; |
| 3085 | } |
| 3086 | |
| 3087 | /** Ground entry at a world tile, including editor hover preview when present. */ |
| 3088 | #groundAtTile (tileX, tileY) |
| 3089 | { |
| 3090 | if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY |
| 3091 | && this.preview.ground !== undefined) |
| 3092 | { return this.preview.ground; } |
| 3093 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 3094 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 3095 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 3096 | if (!snapshot) |
| 3097 | { return null; } |
| 3098 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 3099 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 3100 | const index = localY * CHUNK_SIZE + localX; |
| 3101 | return snapshot.grounds?.[index] ?? null; |
| 3102 | } |
| 3103 | |
| 3104 | #waterCoastEdges (tileX, tileY) |
| 3105 | { |
| 3106 | const season = this.worldSeason; |
| 3107 | return { |
| 3108 | n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0, |
| 3109 | e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0, |
| 3110 | s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0, |
| 3111 | w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 0 |
| 3112 | }; |
| 3113 | } |
| 3114 | |
| 3115 | #syncWaterGroundSprite (object, corners, ambientDark, edges, timeSec, fallbackLit = 1) |
| 3116 | { |
| 3117 | if (!object?.renderer) |
| 3118 | { return; } |
| 3119 | const lit = corners ?? { |
| 3120 | nw: fallbackLit, |
| 3121 | ne: fallbackLit, |
| 3122 | sw: fallbackLit, |
| 3123 | se: fallbackLit |
| 3124 | }; |
| 3125 | const dark = Math.min(1, Math.max(0, ambientDark ?? 0)); |
| 3126 | object._lit = true; |
| 3127 | object.renderer.shader = getWaterGroundShader(); |
| 3128 | object.renderer.secondaryMap = null; |
| 3129 | object.renderer.shaderUniforms = { |
| 3130 | u_ambientDark: dark, |
| 3131 | u_litNW: lit.nw, |
| 3132 | u_litNE: lit.ne, |
| 3133 | u_litSW: lit.sw, |
| 3134 | u_litSE: lit.se, |
| 3135 | u_time: timeSec, |
| 3136 | u_edgeN: edges?.n ?? 0, |
| 3137 | u_edgeE: edges?.e ?? 0, |
| 3138 | u_edgeS: edges?.s ?? 0, |
| 3139 | u_edgeW: edges?.w ?? 0 |
| 3140 | }; |
| 3141 | } |
| 3142 | |
| 3143 | /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */ |
| 3144 | #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null) |
| 3145 | { |
| 3146 | if (!objects?.ground) |
| 3147 | { return; } |
| 3148 | if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason)) |
| 3149 | { |
| 3150 | objects.waterEdges = null; |
| 3151 | this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0); |
| 3152 | return; |
| 3153 | } |
| 3154 | const fallbackLit = 1 - (objects.shadeAlpha ?? 0); |
| 3155 | const chunkX = Math.floor(objects.tileX / CHUNK_SIZE); |
| 3156 | const chunkY = Math.floor(objects.tileY / CHUNK_SIZE); |
| 3157 | const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`); |
| 3158 | const localX = objects.tileX - chunkX * CHUNK_SIZE; |
| 3159 | const localY = objects.tileY - chunkY * CHUNK_SIZE; |
| 3160 | let litCorners = null; |
| 3161 | if (chunkBaked) |
| 3162 | { |
| 3163 | if (this.lightingMode === "simple") |
| 3164 | { |
| 3165 | const gridW = CHUNK_SIZE + 2; |
| 3166 | const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit; |
| 3167 | litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity }; |
| 3168 | } |
| 3169 | else |
| 3170 | { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); } |
| 3171 | } |
| 3172 | objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY); |
| 3173 | this.#syncWaterGroundSprite( |
| 3174 | objects.ground, |
| 3175 | litCorners, |
| 3176 | ambientDark, |
| 3177 | objects.waterEdges, |
| 3178 | timeSec, |
| 3179 | fallbackLit |
| 3180 | ); |
| 3181 | } |
| 3182 | |
| 3183 | #ambientDarkness () |
| 3184 | { |
| 3185 | const hour = this.nightPreview ?? this.worldHour; |
| 3186 | const calendar = nightFactor(hour, this.settings.nightDarkness); |
| 3187 | let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar); |
| 3188 | if (dark == null) |
| 3189 | { dark = calendar; } |
| 3190 | if (this.localBlind) |
| 3191 | { dark = Math.min(1, dark + 0.85); } |
| 3192 | return dark; |
| 3193 | } |
| 3194 | |
| 3195 | setLocalBlind (blind) |
| 3196 | { |
| 3197 | this.localBlind = !!blind; |
| 3198 | } |
| 3199 | |
| 3200 | /** Soft vision bubble while blinded (client-only; stacks with ambient). */ |
| 3201 | #blindVisionLight () |
| 3202 | { |
| 3203 | if (!this.localBlind) |
| 3204 | { return null; } |
| 3205 | const local = this.entities.get(this.localEntityId); |
| 3206 | if (!local) |
| 3207 | { return null; } |
| 3208 | const tileSize = this.tileSize(); |
| 3209 | return { |
| 3210 | tileX: Math.floor(local.visualX / tileSize), |
| 3211 | tileY: Math.floor(local.visualY / tileSize), |
| 3212 | range: 2.25, |
| 3213 | intensity: 1 |
| 3214 | }; |
| 3215 | } |
| 3216 | |
| 3217 | #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null) |
| 3218 | { |
| 3219 | const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0; |
| 3220 | const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0; |
| 3221 | const dark = (fromAlpha + toAlpha) / 2; |
| 3222 | if (dualTint) |
| 3223 | { |
| 3224 | this.#syncDualTintLitSprite(object, dark, dualTint); |
| 3225 | return; |
| 3226 | } |
| 3227 | this.#syncLitSprite(object, dark); |
| 3228 | } |
| 3229 | |
| 3230 | #dualTintFromPayload (payload) |
| 3231 | { |
| 3232 | if (!payload?.shaftTint || !payload?.tipTint) |
| 3233 | { return null; } |
| 3234 | return { |
| 3235 | shaft: payload.shaftTint, |
| 3236 | tip: payload.tipTint, |
| 3237 | ...(payload.coatTint ? { coat: payload.coatTint } : {}) |
| 3238 | }; |
| 3239 | } |
| 3240 | |
| 3241 | #syncHpBar (entity) |
| 3242 | { |
| 3243 | const current = entity.health; |
| 3244 | const max = entity.maxHealth; |
| 3245 | const show = current != null |
| 3246 | && max != null |
| 3247 | && max > 0 |
| 3248 | && current < max; |
| 3249 | if (!show) |
| 3250 | { |
| 3251 | entity.hpBar?.destroy(); |
| 3252 | entity.hpBar = null; |
| 3253 | entity.hpBarCanvas = null; |
| 3254 | return; |
| 3255 | } |
| 3256 | if (!entity.hpBarCanvas) |
| 3257 | { |
| 3258 | entity.hpBarCanvas = document.createElement("canvas"); |
| 3259 | entity.hpBarCanvas.width = HP_BAR_W; |
| 3260 | entity.hpBarCanvas.height = HP_BAR_H; |
| 3261 | const image = frameworkImageFromCanvas(entity.hpBarCanvas); |
| 3262 | entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR); |
| 3263 | this.#markUnlit(entity.hpBar); |
| 3264 | this.scene.addObject(entity.hpBar); |
| 3265 | } |
| 3266 | drawHpBar(entity.hpBarCanvas, current, max); |
| 3267 | invalidateCanvasTexture(this.scene, entity.hpBarCanvas); |
| 3268 | } |
| 3269 | |
| 3270 | #placeHpBar (entity, pivotX, pivotY) |
| 3271 | { |
| 3272 | if (!entity.hpBar) |
| 3273 | { return; } |
| 3274 | const sprite = entity.object?.renderer?.sprite; |
| 3275 | if (!sprite) |
| 3276 | { return; } |
| 3277 | const zoom = this.zoom; |
| 3278 | const drawH = sprite.height * zoom; |
| 3279 | const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom); |
| 3280 | const spriteTop = centerY - drawH / 2; |
| 3281 | const barW = HP_BAR_W * zoom; |
| 3282 | const barH = HP_BAR_H * zoom; |
| 3283 | entity.hpBar.transform.position.x = pivotX; |
| 3284 | entity.hpBar.transform.position.y = spriteTop - barH / 2; |
| 3285 | entity.hpBar.transform.size = new vector(barW, barH); |
| 3286 | entity.hpBar.layer = this.#depthLayer(pivotY, SORT_HP_BAR); |
| 3287 | this.#markSortDirty(); |
| 3288 | } |
| 3289 | |
| 3290 | #syncSkullMarker (entity) |
| 3291 | { |
| 3292 | if (!entity?.characterId) |
| 3293 | { |
| 3294 | entity.skullMarker?.destroy(); |
| 3295 | entity.skullMarker = null; |
| 3296 | return; |
| 3297 | } |
| 3298 | const tint = skullTintColor(entity.skullValue | 0); |
| 3299 | if (!tint) |
| 3300 | { |
| 3301 | entity.skullMarker?.destroy(); |
| 3302 | entity.skullMarker = null; |
| 3303 | return; |
| 3304 | } |
| 3305 | const image = this.game.images[SKULL_SPRITE] |
| 3306 | ?? this.game.images["item:skull:skull"]; |
| 3307 | if (!image) |
| 3308 | { return; } |
| 3309 | if (!entity.skullMarker) |
| 3310 | { |
| 3311 | entity.skullMarker = new GameObject(0, 0, image, SORT_HP_BAR); |
| 3312 | this.scene.addObject(entity.skullMarker); |
| 3313 | } |
| 3314 | entity.skullTint = tint; |
| 3315 | entity.skullMarker.renderer.sprite = image; |
| 3316 | } |
| 3317 | |
| 3318 | /** |
| 3319 | * Bottom edge of the skull sprite sits exactly on the character sprite's top edge. |
| 3320 | */ |
| 3321 | #placeSkullMarker (entity, pivotX, pivotY, darkness) |
| 3322 | { |
| 3323 | this.#syncSkullMarker(entity); |
| 3324 | if (!entity.skullMarker) |
| 3325 | { return; } |
| 3326 | const body = entity.object?.renderer?.sprite; |
| 3327 | const skull = entity.skullMarker.renderer?.sprite; |
| 3328 | if (!body || !skull) |
| 3329 | { return; } |
| 3330 | const zoom = this.zoom; |
| 3331 | const scale = entity.visualScale ?? 1; |
| 3332 | const bodyH = body.height * zoom * scale; |
| 3333 | const skullH = skull.height * zoom; |
| 3334 | const skullW = skull.width * zoom; |
| 3335 | const bodyCenterY = pivotY - (bodyH / 2 - PIVOT_FROM_BOTTOM_PX * zoom * scale); |
| 3336 | const bodyTop = bodyCenterY - bodyH / 2; |
| 3337 | // GameObject position is sprite center; bottom of skull at bodyTop ⇒ center at bodyTop - skullH/2 |
| 3338 | entity.skullMarker.transform.position.x = pivotX; |
| 3339 | entity.skullMarker.transform.position.y = bodyTop - skullH / 2; |
| 3340 | entity.skullMarker.transform.size = new vector(skullW, skullH); |
| 3341 | entity.skullMarker.layer = this.#depthLayer(pivotY, SORT_HP_BAR); |
| 3342 | this.#syncLitSprite(entity.skullMarker, darkness, 0, false, entity.skullTint); |
| 3343 | this.#markSortDirty(); |
| 3344 | } |
| 3345 | |
| 3346 | #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {}) |
| 3347 | { |
| 3348 | this.#bakeAndPlaceChunk(snapshot); |
| 3349 | this.#relayoutChunkTiles(snapshot); |
| 3350 | if (this.softTerrain && refreshSoftNeighbors) |
| 3351 | { this.#rebuildSoftTerrainNeighborChunks(snapshot); } |
| 3352 | } |
| 3353 | |
| 3354 | #relayoutChunk (snapshot) |
| 3355 | { |
| 3356 | this.#layoutBakedChunk(snapshot); |
| 3357 | this.#relayoutChunkTiles(snapshot); |
| 3358 | } |
| 3359 | |
| 3360 | #relayoutChunkTiles (snapshot) |
| 3361 | { |
| 3362 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 3363 | { |
| 3364 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 3365 | { |
| 3366 | const tileX = snapshot.chunkX * CHUNK_SIZE + localX; |
| 3367 | const tileY = snapshot.chunkY * CHUNK_SIZE + localY; |
| 3368 | this.#drawTile(tileX, tileY); |
| 3369 | } |
| 3370 | } |
| 3371 | } |
| 3372 | |
| 3373 | #scheduleChunkRebuild (snapshot) |
| 3374 | { |
| 3375 | if (!snapshot) |
| 3376 | { return; } |
| 3377 | this.#chunkRebuildKeys.add(`${snapshot.chunkX},${snapshot.chunkY}`); |
| 3378 | this.#cancelIdlePrefetch(); |
| 3379 | this.#ensureChunkFlushScheduled(); |
| 3380 | } |
| 3381 | |
| 3382 | #scheduleEdgeRebuild () |
| 3383 | { |
| 3384 | this.#edgesDirty = true; |
| 3385 | this.#cancelIdlePrefetch(); |
| 3386 | this.#ensureChunkFlushScheduled(); |
| 3387 | } |
| 3388 | |
| 3389 | #ensureChunkFlushScheduled () |
| 3390 | { |
| 3391 | if (this.#chunkRebuildRaf) |
| 3392 | { return; } |
| 3393 | this.#cancelIdlePrefetch(); |
| 3394 | this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork()); |
| 3395 | } |
| 3396 | |
| 3397 | #notePlayerTile (tileX, tileY) |
| 3398 | { |
| 3399 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 3400 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 3401 | const prevX = this.#playerChunkX; |
| 3402 | const prevY = this.#playerChunkY; |
| 3403 | if (prevX != null |
| 3404 | && (chunkX !== prevX || chunkY !== prevY)) |
| 3405 | { |
| 3406 | const dx = chunkX - prevX; |
| 3407 | const dy = chunkY - prevY; |
| 3408 | if (dx !== 0) |
| 3409 | { this.#playerMoveChunkDx = Math.sign(dx); } |
| 3410 | if (dy !== 0) |
| 3411 | { this.#playerMoveChunkDy = Math.sign(dy); } |
| 3412 | this.#onActiveLightingCenterChanged(prevX, prevY, chunkX, chunkY); |
| 3413 | } |
| 3414 | this.#playerChunkX = chunkX; |
| 3415 | this.#playerChunkY = chunkY; |
| 3416 | } |
| 3417 | |
| 3418 | /** When the 3×3 lighting center moves: refresh door sprites (resting vs live) and lightmaps. */ |
| 3419 | #onActiveLightingCenterChanged (prevChunkX, prevChunkY, chunkX, chunkY) |
| 3420 | { |
| 3421 | this.#invalidateNeighborLightmapCaches(prevChunkX, prevChunkY); |
| 3422 | this.#invalidateNeighborLightmapCaches(chunkX, chunkY); |
| 3423 | const doorChunks = new Set(); |
| 3424 | for (const [cx, cy] of [[prevChunkX, prevChunkY], [chunkX, chunkY]]) |
| 3425 | { |
| 3426 | for (let dy = -1; dy <= 1; dy++) |
| 3427 | { |
| 3428 | for (let dx = -1; dx <= 1; dx++) |
| 3429 | { doorChunks.add(`${cx + dx},${cy + dy}`); } |
| 3430 | } |
| 3431 | } |
| 3432 | for (const key of doorChunks) |
| 3433 | { |
| 3434 | const [cx, cy] = key.split(",").map(Number); |
| 3435 | this.#redrawDoorTilesInChunk(cx, cy); |
| 3436 | } |
| 3437 | } |
| 3438 | |
| 3439 | #redrawDoorTilesInChunk (chunkX, chunkY) |
| 3440 | { |
| 3441 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 3442 | if (!snapshot?.blocks) |
| 3443 | { return; } |
| 3444 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 3445 | { |
| 3446 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 3447 | { |
| 3448 | const block = snapshot.blocks[localY * CHUNK_SIZE + localX]; |
| 3449 | if (!blockDefinition(block?.typeId)?.door) |
| 3450 | { continue; } |
| 3451 | this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY); |
| 3452 | } |
| 3453 | } |
| 3454 | } |
| 3455 | |
| 3456 | #playerChunkCoords () |
| 3457 | { |
| 3458 | const local = this.entities.get(this.localEntityId); |
| 3459 | if (local) |
| 3460 | { |
| 3461 | return { |
| 3462 | chunkX: Math.floor(local.tileX / CHUNK_SIZE), |
| 3463 | chunkY: Math.floor(local.tileY / CHUNK_SIZE) |
| 3464 | }; |
| 3465 | } |
| 3466 | if (this.#playerChunkX != null && this.#playerChunkY != null) |
| 3467 | { |
| 3468 | return { chunkX: this.#playerChunkX, chunkY: this.#playerChunkY }; |
| 3469 | } |
| 3470 | return null; |
| 3471 | } |
| 3472 | |
| 3473 | /** Lower score = bake sooner in urgent mode; idle mode inverts distance. */ |
| 3474 | #chunkRebuildScore (key, mode = "urgent") |
| 3475 | { |
| 3476 | const [chunkX, chunkY] = key.split(",").map(Number); |
| 3477 | const player = this.#playerChunkCoords(); |
| 3478 | if (!player) |
| 3479 | { return 0; } |
| 3480 | const dx = chunkX - player.chunkX; |
| 3481 | const dy = chunkY - player.chunkY; |
| 3482 | const dist = Math.abs(dx) + Math.abs(dy); |
| 3483 | let ahead = 0; |
| 3484 | if (this.#playerMoveChunkDx !== 0 || this.#playerMoveChunkDy !== 0) |
| 3485 | { ahead = dx * this.#playerMoveChunkDx + dy * this.#playerMoveChunkDy; } |
| 3486 | if (mode === "idle") |
| 3487 | { |
| 3488 | return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0)); |
| 3489 | } |
| 3490 | return dist * 10 - Math.max(0, ahead) * 3; |
| 3491 | } |
| 3492 | |
| 3493 | #sortedChunkRebuildKeys (mode = "urgent") |
| 3494 | { |
| 3495 | return [...this.#chunkRebuildKeys].sort((a, b) => |
| 3496 | this.#chunkRebuildScore(a, mode) - this.#chunkRebuildScore(b, mode)); |
| 3497 | } |
| 3498 | |
| 3499 | #discoverUnbakedChunks () |
| 3500 | { |
| 3501 | for (const key of this.chunks.keys()) |
| 3502 | { |
| 3503 | if (!this.bakedChunks.has(key)) |
| 3504 | { this.#chunkRebuildKeys.add(key); } |
| 3505 | } |
| 3506 | } |
| 3507 | |
| 3508 | #hasUnbakedChunks () |
| 3509 | { |
| 3510 | for (const key of this.chunks.keys()) |
| 3511 | { |
| 3512 | if (!this.bakedChunks.has(key)) |
| 3513 | { return true; } |
| 3514 | } |
| 3515 | return false; |
| 3516 | } |
| 3517 | |
| 3518 | #pickIdlePrefetchSnapshot () |
| 3519 | { |
| 3520 | let best = null; |
| 3521 | let bestScore = Infinity; |
| 3522 | for (const snapshot of this.chunks.values()) |
| 3523 | { |
| 3524 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 3525 | if (this.bakedChunks.has(key) || this.#chunkRebuildKeys.has(key)) |
| 3526 | { continue; } |
| 3527 | const score = this.#chunkRebuildScore(key, "idle"); |
| 3528 | if (score < bestScore) |
| 3529 | { |
| 3530 | bestScore = score; |
| 3531 | best = snapshot; |
| 3532 | } |
| 3533 | } |
| 3534 | return best; |
| 3535 | } |
| 3536 | |
| 3537 | #cancelIdlePrefetch () |
| 3538 | { |
| 3539 | if (this.#idlePrefetchId && typeof cancelIdleCallback === "function") |
| 3540 | { cancelIdleCallback(this.#idlePrefetchId); } |
| 3541 | this.#idlePrefetchId = 0; |
| 3542 | } |
| 3543 | |
| 3544 | #scheduleIdleChunkPrefetch () |
| 3545 | { |
| 3546 | if (this.#idlePrefetchId || this.#chunkRebuildRaf || this.#chunkRebuildKeys.size) |
| 3547 | { return; } |
| 3548 | if (typeof requestIdleCallback !== "function") |
| 3549 | { return; } |
| 3550 | if (!this.#hasUnbakedChunks()) |
| 3551 | { return; } |
| 3552 | this.#idlePrefetchId = requestIdleCallback( |
| 3553 | (deadline) => this.#runIdleChunkPrefetch(deadline), |
| 3554 | { timeout: 2500 } |
| 3555 | ); |
| 3556 | } |
| 3557 | |
| 3558 | #runIdleChunkPrefetch (deadline) |
| 3559 | { |
| 3560 | this.#idlePrefetchId = 0; |
| 3561 | if (this.#chunkRebuildRaf || this.#chunkRebuildKeys.size) |
| 3562 | { return; } |
| 3563 | this.#discoverUnbakedChunks(); |
| 3564 | if (this.#chunkRebuildKeys.size) |
| 3565 | { |
| 3566 | this.#ensureChunkFlushScheduled(); |
| 3567 | return; |
| 3568 | } |
| 3569 | const snapshot = this.#pickIdlePrefetchSnapshot(); |
| 3570 | if (!snapshot) |
| 3571 | { return; } |
| 3572 | if (deadline.timeRemaining() <= 4 && !deadline.didTimeout) |
| 3573 | { |
| 3574 | this.#scheduleIdleChunkPrefetch(); |
| 3575 | return; |
| 3576 | } |
| 3577 | this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); |
| 3578 | if (this.#hasUnbakedChunks()) |
| 3579 | { this.#scheduleIdleChunkPrefetch(); } |
| 3580 | } |
| 3581 | |
| 3582 | #flushChunkWork () |
| 3583 | { |
| 3584 | this.#chunkRebuildRaf = 0; |
| 3585 | const keys = this.#sortedChunkRebuildKeys("urgent"); |
| 3586 | const batch = keys.slice(0, this.#CHUNK_REBUILD_BATCH); |
| 3587 | const rest = keys.slice(this.#CHUNK_REBUILD_BATCH); |
| 3588 | this.#chunkRebuildKeys.clear(); |
| 3589 | for (const key of rest) |
| 3590 | { this.#chunkRebuildKeys.add(key); } |
| 3591 | for (const key of batch) |
| 3592 | { |
| 3593 | const snap = this.chunks.get(key); |
| 3594 | if (snap) |
| 3595 | { this.#rebuildChunk(snap, { refreshSoftNeighbors: false }); } |
| 3596 | } |
| 3597 | if (this.#chunkRebuildKeys.size) |
| 3598 | { |
| 3599 | this.#ensureChunkFlushScheduled(); |
| 3600 | return; |
| 3601 | } |
| 3602 | if (this.#edgesDirty) |
| 3603 | { |
| 3604 | this.#rebuildAllEdges(); |
| 3605 | this.#edgesDirty = false; |
| 3606 | } |
| 3607 | this.#scheduleIdleChunkPrefetch(); |
| 3608 | } |
| 3609 | |
| 3610 | #previewEqual (a, b) |
| 3611 | { |
| 3612 | if (a === b) |
| 3613 | { return true; } |
| 3614 | if (!a || !b) |
| 3615 | { return false; } |
| 3616 | return a.tileX === b.tileX |
| 3617 | && a.tileY === b.tileY |
| 3618 | && this.#previewPart(a.ground) === this.#previewPart(b.ground) |
| 3619 | && this.#previewPart(a.block) === this.#previewPart(b.block); |
| 3620 | } |
| 3621 | |
| 3622 | #previewPart (value) |
| 3623 | { |
| 3624 | return value === undefined ? undefined : JSON.stringify(value); |
| 3625 | } |
| 3626 | |
| 3627 | #rebuildSoftTerrainNeighborChunks (snapshot) |
| 3628 | { |
| 3629 | for (let dy = -1; dy <= 1; dy++) |
| 3630 | { |
| 3631 | for (let dx = -1; dx <= 1; dx++) |
| 3632 | { |
| 3633 | if (dx === 0 && dy === 0) |
| 3634 | { continue; } |
| 3635 | const neighbor = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`); |
| 3636 | if (neighbor) |
| 3637 | { this.#rebuildChunk(neighbor, { refreshSoftNeighbors: false }); } |
| 3638 | } |
| 3639 | } |
| 3640 | } |
| 3641 | |
| 3642 | #rebakeAllChunks () |
| 3643 | { |
| 3644 | for (const snapshot of this.chunks.values()) |
| 3645 | { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); } |
| 3646 | } |
| 3647 | |
| 3648 | #bakeAndPlaceChunk (snapshot) |
| 3649 | { |
| 3650 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 3651 | const atlases = bakeChunkAtlases({ |
| 3652 | snapshot, |
| 3653 | catalog: this.catalog, |
| 3654 | images: this.game.images, |
| 3655 | preview: this.preview, |
| 3656 | season: this.worldSeason, |
| 3657 | softTerrain: this.softTerrain, |
| 3658 | resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY), |
| 3659 | cache: this.#atlasCache |
| 3660 | }); |
| 3661 | const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX; |
| 3662 | let baked = this.bakedChunks.get(key); |
| 3663 | this.#releaseBakedAtlasRefs(baked); |
| 3664 | |
| 3665 | const groundImage = this.#atlasCache.getImage(atlases.cacheRefs?.ground); |
| 3666 | const blockImages = atlases.cacheRefs?.blockRows.map((entry) => this.#atlasCache.getImage(entry)) |
| 3667 | ?? atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)); |
| 3668 | const bloomImage = this.#atlasCache.getImage(atlases.cacheRefs?.bloom) |
| 3669 | ?? frameworkImageFromCanvas(atlases.bloom); |
| 3670 | |
| 3671 | if (!baked) |
| 3672 | { |
| 3673 | const lightmapCanvas = makeLightmapCanvas(atlasPx); |
| 3674 | baked = { |
| 3675 | groundCanvas: atlases.ground, |
| 3676 | blockCanvases: atlases.blockRows, |
| 3677 | bloomCanvas: atlases.bloom, |
| 3678 | lightmapCanvas, |
| 3679 | groundImage, |
| 3680 | blockImages, |
| 3681 | bloomImage, |
| 3682 | lightmapImage: frameworkImageFromCanvas(lightmapCanvas), |
| 3683 | groundObject: null, |
| 3684 | blockObjects: [], |
| 3685 | bloomObject: null, |
| 3686 | tallBlocks: atlases.tallBlocks, |
| 3687 | animatedGrounds: atlases.animatedGrounds, |
| 3688 | lightmapPixels: null, |
| 3689 | atlasCacheRefs: atlases.cacheRefs |
| 3690 | }; |
| 3691 | baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND); |
| 3692 | this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1); |
| 3693 | this.scene.addObject(baked.groundObject); |
| 3694 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 3695 | { |
| 3696 | const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK); |
| 3697 | this.#applyAtlasLighting(object, baked.lightmapImage, row); |
| 3698 | this.scene.addObject(object); |
| 3699 | baked.blockObjects.push(object); |
| 3700 | } |
| 3701 | baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK); |
| 3702 | baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; |
| 3703 | this.#markUnlit(baked.bloomObject); |
| 3704 | this.scene.addObject(baked.bloomObject); |
| 3705 | this.bakedChunks.set(key, baked); |
| 3706 | } |
| 3707 | else |
| 3708 | { |
| 3709 | if (baked.groundCanvas !== atlases.ground) |
| 3710 | { |
| 3711 | baked.groundCanvas = atlases.ground; |
| 3712 | baked.groundImage = groundImage; |
| 3713 | baked.groundObject.renderer.sprite = groundImage; |
| 3714 | this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1); |
| 3715 | } |
| 3716 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 3717 | { |
| 3718 | if (baked.blockCanvases[row] !== atlases.blockRows[row]) |
| 3719 | { |
| 3720 | baked.blockCanvases[row] = atlases.blockRows[row]; |
| 3721 | baked.blockImages[row] = blockImages[row]; |
| 3722 | baked.blockObjects[row].renderer.sprite = blockImages[row]; |
| 3723 | } |
| 3724 | this.#applyAtlasLighting( |
| 3725 | baked.blockObjects[row], |
| 3726 | baked.lightmapImage, |
| 3727 | row |
| 3728 | ); |
| 3729 | } |
| 3730 | if (baked.bloomCanvas !== atlases.bloom) |
| 3731 | { |
| 3732 | baked.bloomCanvas = atlases.bloom; |
| 3733 | baked.bloomImage = bloomImage; |
| 3734 | baked.bloomObject.renderer.sprite = bloomImage; |
| 3735 | } |
| 3736 | baked.tallBlocks = atlases.tallBlocks; |
| 3737 | baked.animatedGrounds = atlases.animatedGrounds; |
| 3738 | baked.atlasCacheRefs = atlases.cacheRefs; |
| 3739 | } |
| 3740 | baked.chunkX = snapshot.chunkX; |
| 3741 | baked.chunkY = snapshot.chunkY; |
| 3742 | baked.lightmapCacheKey = null; |
| 3743 | this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY); |
| 3744 | this.#layoutBakedChunk(snapshot); |
| 3745 | this.#queueBakedChunkTextures(baked, snapshot.chunkX, snapshot.chunkY); |
| 3746 | } |
| 3747 | |
| 3748 | #releaseBakedAtlasRefs (baked) |
| 3749 | { |
| 3750 | if (!baked?.atlasCacheRefs) |
| 3751 | { return; } |
| 3752 | this.#atlasCache.release(baked.atlasCacheRefs.ground); |
| 3753 | for (const entry of baked.atlasCacheRefs.blockRows ?? []) |
| 3754 | { this.#atlasCache.release(entry); } |
| 3755 | this.#atlasCache.release(baked.atlasCacheRefs.bloom); |
| 3756 | baked.atlasCacheRefs = null; |
| 3757 | } |
| 3758 | |
| 3759 | #chunkTextureWarmPriority (chunkX, chunkY) |
| 3760 | { |
| 3761 | const local = this.entities.get(this.localEntityId); |
| 3762 | if (!local) |
| 3763 | { return 999; } |
| 3764 | const playerChunkX = Math.floor(local.tileX / CHUNK_SIZE); |
| 3765 | const playerChunkY = Math.floor(local.tileY / CHUNK_SIZE); |
| 3766 | return Math.abs(chunkX - playerChunkX) + Math.abs(chunkY - playerChunkY); |
| 3767 | } |
| 3768 | |
| 3769 | #queueCanvasTextureWarm (canvas, chunkX, chunkY) |
| 3770 | { |
| 3771 | if (!canvas || this.#pendingTextureCanvasSet.has(canvas)) |
| 3772 | { return; } |
| 3773 | this.#pendingTextureCanvasSet.add(canvas); |
| 3774 | this.#pendingTextureCanvases.push({ |
| 3775 | canvas, |
| 3776 | priority: this.#chunkTextureWarmPriority(chunkX, chunkY) |
| 3777 | }); |
| 3778 | this.#scheduleTextureWarm(); |
| 3779 | } |
| 3780 | |
| 3781 | #queueBakedChunkTextures (baked, chunkX, chunkY) |
| 3782 | { |
| 3783 | if (!baked) |
| 3784 | { return; } |
| 3785 | const refs = baked.atlasCacheRefs; |
| 3786 | const maybeWarm = (canvas, entry) => |
| 3787 | { |
| 3788 | if (!canvas) |
| 3789 | { return; } |
| 3790 | if (entry && this.#atlasCache.isWarmed(canvas)) |
| 3791 | { return; } |
| 3792 | this.#queueCanvasTextureWarm(canvas, chunkX, chunkY); |
| 3793 | }; |
| 3794 | maybeWarm(baked.groundCanvas, refs?.ground); |
| 3795 | for (let row = 0; row < (baked.blockCanvases ?? []).length; row++) |
| 3796 | { maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); } |
| 3797 | maybeWarm(baked.bloomCanvas, refs?.bloom); |
| 3798 | this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY); |
| 3799 | } |
| 3800 | |
| 3801 | #scheduleTextureWarm () |
| 3802 | { |
| 3803 | if (this.#textureWarmRaf) |
| 3804 | { return; } |
| 3805 | this.#textureWarmRaf = requestAnimationFrame(() => this.#flushTextureWarm()); |
| 3806 | } |
| 3807 | |
| 3808 | #flushTextureWarm () |
| 3809 | { |
| 3810 | this.#textureWarmRaf = 0; |
| 3811 | if (!this.#pendingTextureCanvases.length) |
| 3812 | { return; } |
| 3813 | this.#pendingTextureCanvases.sort((a, b) => a.priority - b.priority); |
| 3814 | const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH); |
| 3815 | for (const entry of batch) |
| 3816 | { |
| 3817 | this.#pendingTextureCanvasSet.delete(entry.canvas); |
| 3818 | setNearestFilter(this.scene, entry.canvas); |
| 3819 | this.#atlasCache.markWarmed(entry.canvas); |
| 3820 | } |
| 3821 | if (this.#pendingTextureCanvases.length) |
| 3822 | { this.#scheduleTextureWarm(); } |
| 3823 | } |
| 3824 | |
| 3825 | #applyAtlasLighting (object, lightmapImage, lightRow) |
| 3826 | { |
| 3827 | if (!object?.renderer) |
| 3828 | { return; } |
| 3829 | object._lit = true; |
| 3830 | object.renderer.shader = getAtlasLightingShader(); |
| 3831 | object.renderer.bumpMap = null; |
| 3832 | object.renderer.secondaryMap = lightmapImage; |
| 3833 | object.renderer.shaderUniforms = { |
| 3834 | u_ambientDark: 0, |
| 3835 | u_lightRow: lightRow |
| 3836 | }; |
| 3837 | } |
| 3838 | |
| 3839 | #syncCliffGroundTopSprite (object, darkness, groundImage, localX, localY) |
| 3840 | { |
| 3841 | if (!object?.renderer) |
| 3842 | { return; } |
| 3843 | object._lit = true; |
| 3844 | const dark = Math.min(1, Math.max(0, darkness ?? 0)); |
| 3845 | object.renderer.shader = getCliffGroundTopShader(); |
| 3846 | object.renderer.bumpMap = groundImage ?? null; |
| 3847 | object.renderer.secondaryMap = null; |
| 3848 | object.renderer.shaderUniforms = { |
| 3849 | u_darkness: dark, |
| 3850 | u_tileLocal: [localX, localY] |
| 3851 | }; |
| 3852 | } |
| 3853 | |
| 3854 | #layoutBakedChunk (snapshot) |
| 3855 | { |
| 3856 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 3857 | const baked = this.bakedChunks.get(key); |
| 3858 | if (!baked) |
| 3859 | { return; } |
| 3860 | const size = this.tileSize(); |
| 3861 | const left = snapshot.chunkX * CHUNK_SIZE * size; |
| 3862 | const top = snapshot.chunkY * CHUNK_SIZE * size; |
| 3863 | const chunkPx = CHUNK_SIZE * size; |
| 3864 | baked.groundObject.transform.position.x = left + chunkPx / 2; |
| 3865 | baked.groundObject.transform.position.y = top + chunkPx / 2; |
| 3866 | baked.groundObject.transform.size = new vector(chunkPx, chunkPx); |
| 3867 | baked.groundObject.layer = LAYER_GROUND; |
| 3868 | |
| 3869 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 3870 | { |
| 3871 | const object = baked.blockObjects[row]; |
| 3872 | const rowY = top + row * size + size / 2; |
| 3873 | object.transform.position.x = left + chunkPx / 2; |
| 3874 | object.transform.position.y = rowY; |
| 3875 | object.transform.size = new vector(chunkPx, size); |
| 3876 | object.layer = this.#depthLayer(rowY, SORT_BLOCK); |
| 3877 | } |
| 3878 | |
| 3879 | baked.bloomObject.transform.position.x = left + chunkPx / 2; |
| 3880 | baked.bloomObject.transform.position.y = top + chunkPx / 2; |
| 3881 | baked.bloomObject.transform.size = new vector(chunkPx, chunkPx); |
| 3882 | baked.bloomObject.layer = this.#depthLayer(top + chunkPx, SORT_BLOCK); |
| 3883 | baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; |
| 3884 | this.#markSortDirty(); |
| 3885 | } |
| 3886 | |
| 3887 | #destroyBakedChunk (key) |
| 3888 | { |
| 3889 | const baked = this.bakedChunks.get(key); |
| 3890 | if (!baked) |
| 3891 | { return; } |
| 3892 | this.#releaseBakedAtlasRefs(baked); |
| 3893 | baked.groundObject?.destroy(); |
| 3894 | for (const object of baked.blockObjects ?? []) |
| 3895 | { object.destroy(); } |
| 3896 | baked.bloomObject?.destroy(); |
| 3897 | invalidateCanvasTexture(this.scene, baked.lightmapCanvas); |
| 3898 | this.bakedChunks.delete(key); |
| 3899 | } |
| 3900 | |
| 3901 | #redrawPreview () |
| 3902 | { |
| 3903 | if (!this.preview) |
| 3904 | { return; } |
| 3905 | const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`); |
| 3906 | if (snapshot) |
| 3907 | { this.#rebuildChunk(snapshot); } |
| 3908 | } |
| 3909 | |
| 3910 | #refreshWaterCoastsNear (chunkX, chunkY) |
| 3911 | { |
| 3912 | const timeSec = performance.now() / 1000; |
| 3913 | for (const objects of this.tiles.values()) |
| 3914 | { |
| 3915 | if (!objects.ground || !isWaterGround(objects.groundTypeId)) |
| 3916 | { continue; } |
| 3917 | if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1) |
| 3918 | { continue; } |
| 3919 | // Light intensity grid is visible light (1 − shade); water shader uses ambient=1. |
| 3920 | this.#syncGroundWaterFx(objects, 1, timeSec); |
| 3921 | } |
| 3922 | } |
| 3923 | |
| 3924 | #drawTile (tileX, tileY) |
| 3925 | { |
| 3926 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 3927 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 3928 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 3929 | if (!snapshot) |
| 3930 | { return; } |
| 3931 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 3932 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 3933 | const index = localY * CHUNK_SIZE + localX; |
| 3934 | const key = `${tileX},${tileY}`; |
| 3935 | let objects = this.tiles.get(key); |
| 3936 | if (!objects) |
| 3937 | { |
| 3938 | objects = { chunkX, chunkY, tileX, tileY }; |
| 3939 | this.tiles.set(key, objects); |
| 3940 | } |
| 3941 | objects.tileX = tileX; |
| 3942 | objects.tileY = tileY; |
| 3943 | objects.chunkX = chunkX; |
| 3944 | objects.chunkY = chunkY; |
| 3945 | objects.light = snapshot.light[index] ?? 0; |
| 3946 | |
| 3947 | const baked = this.bakedChunks.get(`${chunkX},${chunkY}`); |
| 3948 | const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY); |
| 3949 | if (animatedGround) |
| 3950 | { |
| 3951 | objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND); |
| 3952 | if (objects.ground) |
| 3953 | { |
| 3954 | const size = this.tileSize(); |
| 3955 | objects.ground.transform.position.x = tileX * size + size / 2; |
| 3956 | objects.ground.transform.position.y = tileY * size + size / 2; |
| 3957 | objects.ground.transform.size = new vector(size, size); |
| 3958 | objects.ground.layer = LAYER_GROUND; |
| 3959 | objects.groundTypeId = animatedGround.typeId; |
| 3960 | this.#syncGroundWaterFx(objects, 1, performance.now() / 1000); |
| 3961 | this.#markSortDirty(); |
| 3962 | } |
| 3963 | if (animatedGround.bloom) |
| 3964 | { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); } |
| 3965 | else |
| 3966 | { |
| 3967 | objects.groundBloom?.destroy(); |
| 3968 | objects.groundBloom = null; |
| 3969 | } |
| 3970 | } |
| 3971 | else |
| 3972 | { |
| 3973 | objects.ground?.destroy(); |
| 3974 | objects.ground = null; |
| 3975 | objects.groundBloom?.destroy(); |
| 3976 | objects.groundBloom = null; |
| 3977 | objects.groundTypeId = null; |
| 3978 | objects.waterEdges = null; |
| 3979 | } |
| 3980 | |
| 3981 | let blockSource = snapshot.blocks[index]; |
| 3982 | if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY && this.preview.block !== undefined) |
| 3983 | { blockSource = this.preview.block; } |
| 3984 | // Outer map ring: always show doors at resting (matches baked light; no entities there). |
| 3985 | if ( |
| 3986 | blockSource |
| 3987 | && blockDefinition(blockSource.typeId)?.door |
| 3988 | && !this.#isActiveLightingChunk(chunkX, chunkY) |
| 3989 | ) |
| 3990 | { |
| 3991 | const resting = doorRestingState(blockSource); |
| 3992 | if (resting && resting !== blockSource.state) |
| 3993 | { blockSource = { ...blockSource, state: resting }; } |
| 3994 | } |
| 3995 | const tileBlock = tileBlockSpriteEntry( |
| 3996 | this.catalog, |
| 3997 | this.game.images, |
| 3998 | blockSource, |
| 3999 | this.worldSeason |
| 4000 | ); |
| 4001 | if (tileBlock) |
| 4002 | { |
| 4003 | const pivot = tilePivot(tileX, tileY, this.tileSize()); |
| 4004 | const blockEntry = normalizeBlock(blockSource); |
| 4005 | const blockDef = blockDefinition(blockEntry?.typeId); |
| 4006 | const blockSort = blockDef?.door |
| 4007 | ? doorSortSubOrder(blockEntry?.state, SORT_ENTITY) |
| 4008 | : SORT_ENTITY; |
| 4009 | objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, blockSort); |
| 4010 | objects.cliffGroundTop = !!blockDef?.cliffGroundTop; |
| 4011 | if (objects.block) |
| 4012 | { |
| 4013 | this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, blockSort); |
| 4014 | if (objects.cliffGroundTop) |
| 4015 | { |
| 4016 | const localX = ((tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; |
| 4017 | const localY = ((tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; |
| 4018 | this.#syncCliffGroundTopSprite( |
| 4019 | objects.block, |
| 4020 | objects.shadeAlpha ?? 0, |
| 4021 | baked?.groundImage ?? null, |
| 4022 | localX, |
| 4023 | localY |
| 4024 | ); |
| 4025 | } |
| 4026 | else |
| 4027 | { this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0); } |
| 4028 | } |
| 4029 | objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tileBlock.bloom, pivot, SORT_ENTITY); |
| 4030 | } |
| 4031 | else |
| 4032 | { |
| 4033 | objects.block?.destroy(); |
| 4034 | objects.block = null; |
| 4035 | objects.blockBloom?.destroy(); |
| 4036 | objects.blockBloom = null; |
| 4037 | objects.cliffGroundTop = false; |
| 4038 | } |
| 4039 | } |
| 4040 | |
| 4041 | #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK) |
| 4042 | { |
| 4043 | if (!name) |
| 4044 | { |
| 4045 | existing?.destroy(); |
| 4046 | return null; |
| 4047 | } |
| 4048 | const object = this.#ensureSprite(existing, name, sortOrder); |
| 4049 | if (!object) |
| 4050 | { return null; } |
| 4051 | object.renderer.layer = RENDER_LAYER_BLOOM; |
| 4052 | this.#markUnlit(object); |
| 4053 | this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder); |
| 4054 | return object; |
| 4055 | } |
| 4056 | |
| 4057 | #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1, flight = false) |
| 4058 | { |
| 4059 | const sprite = object?.renderer?.sprite; |
| 4060 | if (!sprite) |
| 4061 | { return; } |
| 4062 | const zoom = this.zoom; |
| 4063 | const draw = spriteDrawSize(sprite.width, sprite.height, zoom); |
| 4064 | const factor = Math.max(0.1, Number(scale) || 1); |
| 4065 | const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom); |
| 4066 | object.transform.position.x = center.x; |
| 4067 | object.transform.position.y = center.y; |
| 4068 | object.transform.size = new vector(draw.w * factor, draw.h * factor); |
| 4069 | object.layer = this.#depthLayer(sortY, subOrder, flight); |
| 4070 | this.#markSortDirty(); |
| 4071 | } |
| 4072 | |
| 4073 | #ensureSprite (existing, name, layer) |
| 4074 | { |
| 4075 | const sprite = this.game.images[name]; |
| 4076 | if (!sprite) |
| 4077 | { |
| 4078 | existing?.destroy(); |
| 4079 | return null; |
| 4080 | } |
| 4081 | if (!existing || existing.renderer.sprite !== sprite) |
| 4082 | { |
| 4083 | existing?.destroy(); |
| 4084 | existing = new GameObject(0, 0, sprite, layer); |
| 4085 | this.#syncLitSprite(existing, 0); |
| 4086 | this.scene.addObject(existing); |
| 4087 | this.#startIdleAnimation(existing); |
| 4088 | } |
| 4089 | return existing; |
| 4090 | } |
| 4091 | |
| 4092 | #startIdleAnimation (object) |
| 4093 | { |
| 4094 | const sprite = object?.renderer?.sprite; |
| 4095 | if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0) |
| 4096 | { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); } |
| 4097 | } |
| 4098 | |
| 4099 | #neighborClosed (snapshot, dir, dx, dy) |
| 4100 | { |
| 4101 | const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`); |
| 4102 | if (other) |
| 4103 | { return !other.open; } |
| 4104 | return !!snapshot.closedEdges?.[dir]; |
| 4105 | } |
| 4106 | |
| 4107 | #rebuildAllEdges () |
| 4108 | { |
| 4109 | const seen = new Set(); |
| 4110 | for (const snapshot of this.chunks.values()) |
| 4111 | { |
| 4112 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 4113 | seen.add(key); |
| 4114 | this.#rebuildChunkEdges(snapshot); |
| 4115 | } |
| 4116 | for (const key of [...this.edges.keys()]) |
| 4117 | { |
| 4118 | if (!seen.has(key)) |
| 4119 | { this.#destroyEdges(key); } |
| 4120 | } |
| 4121 | } |
| 4122 | |
| 4123 | #rebuildChunkEdges (snapshot) |
| 4124 | { |
| 4125 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 4126 | let bars = this.edges.get(key); |
| 4127 | if (!bars) |
| 4128 | { |
| 4129 | bars = {}; |
| 4130 | this.edges.set(key, bars); |
| 4131 | } |
| 4132 | |
| 4133 | const size = this.tileSize(); |
| 4134 | const chunkPx = CHUNK_SIZE * size; |
| 4135 | const left = snapshot.chunkX * CHUNK_SIZE * size; |
| 4136 | const top = snapshot.chunkY * CHUNK_SIZE * size; |
| 4137 | const centerX = left + chunkPx / 2; |
| 4138 | const centerY = top + chunkPx / 2; |
| 4139 | const thickness = Math.max(2, Math.round(2 * this.zoom)); |
| 4140 | const draw = snapshot.open === true; |
| 4141 | |
| 4142 | bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1), |
| 4143 | centerX, top, chunkPx, thickness, true); |
| 4144 | bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1), |
| 4145 | centerX, top + chunkPx, chunkPx, thickness, true); |
| 4146 | bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0), |
| 4147 | left, centerY, chunkPx, thickness, false); |
| 4148 | bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0), |
| 4149 | left + chunkPx, centerY, chunkPx, thickness, false); |
| 4150 | } |
| 4151 | |
| 4152 | #edgeBar (existing, visible, x, y, length, thickness, horizontal) |
| 4153 | { |
| 4154 | if (!visible) |
| 4155 | { |
| 4156 | if (existing) |
| 4157 | { existing.renderer.visible = false; } |
| 4158 | return existing; |
| 4159 | } |
| 4160 | |
| 4161 | existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE); |
| 4162 | this.#markUnlit(existing); |
| 4163 | existing.renderer.visible = true; |
| 4164 | existing.transform.position.x = x; |
| 4165 | existing.transform.position.y = y; |
| 4166 | existing.transform.size = horizontal |
| 4167 | ? new vector(length, thickness) |
| 4168 | : new vector(thickness, length); |
| 4169 | existing.layer = LAYER_EDGE; |
| 4170 | this.#markSortDirty(); |
| 4171 | return existing; |
| 4172 | } |
| 4173 | |
| 4174 | #destroyEdges (key) |
| 4175 | { |
| 4176 | const bars = this.edges.get(key); |
| 4177 | if (!bars) |
| 4178 | { return; } |
| 4179 | bars.north?.destroy(); |
| 4180 | bars.east?.destroy(); |
| 4181 | bars.south?.destroy(); |
| 4182 | bars.west?.destroy(); |
| 4183 | this.edges.delete(key); |
| 4184 | } |
| 4185 | |
| 4186 | #entityShadeAlpha (entity, now) |
| 4187 | { |
| 4188 | const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0; |
| 4189 | if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null) |
| 4190 | { return toAlpha; } |
| 4191 | const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0; |
| 4192 | const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1)); |
| 4193 | return fromAlpha + (toAlpha - fromAlpha) * t; |
| 4194 | } |
| 4195 | |
| 4196 | #markSortDirty () |
| 4197 | { |
| 4198 | this.scene._sortDirty = true; |
| 4199 | } |
| 4200 | |
| 4201 | /** Player chunk for dynamic lighting; null in editor / before spawn → no 3×3 limit. */ |
| 4202 | #activeLightingCenterChunk () |
| 4203 | { |
| 4204 | const local = this.entities.get(this.localEntityId); |
| 4205 | if (!local) |
| 4206 | { return null; } |
| 4207 | return { |
| 4208 | chunkX: Math.floor(local.tileX / CHUNK_SIZE), |
| 4209 | chunkY: Math.floor(local.tileY / CHUNK_SIZE) |
| 4210 | }; |
| 4211 | } |
| 4212 | |
| 4213 | #isActiveLightingChunk (chunkX, chunkY) |
| 4214 | { |
| 4215 | const center = this.#activeLightingCenterChunk(); |
| 4216 | if (!center) |
| 4217 | { return true; } |
| 4218 | return Math.abs(chunkX - center.chunkX) <= 1 && Math.abs(chunkY - center.chunkY) <= 1; |
| 4219 | } |
| 4220 | |
| 4221 | #isActiveLightingTile (tileX, tileY) |
| 4222 | { |
| 4223 | return this.#isActiveLightingChunk( |
| 4224 | Math.floor(tileX / CHUNK_SIZE), |
| 4225 | Math.floor(tileY / CHUNK_SIZE) |
| 4226 | ); |
| 4227 | } |
| 4228 | |
| 4229 | /** Dynamic light sources that originate inside the player 3×3 (never from the outer ring). */ |
| 4230 | #innerDynamicLights (activeLights) |
| 4231 | { |
| 4232 | return activeLights.filter((light) => this.#isActiveLightingTile(light.tileX, light.tileY)); |
| 4233 | } |
| 4234 | |
| 4235 | /** |
| 4236 | * Lights to simulate for one chunk. |
| 4237 | * Inner 3×3: mobile lights from the inner region + authored block lights that reach the chunk. |
| 4238 | * Outer ring: baked base + spill from any dynamic source that originates inside the 3×3 |
| 4239 | * (lanterns, spells, and torches) so the boundary stays seamless. |
| 4240 | */ |
| 4241 | #dynamicLightsForChunk (chunkX, chunkY, mobileLights, blockLights = []) |
| 4242 | { |
| 4243 | const center = this.#activeLightingCenterChunk(); |
| 4244 | if (!center) |
| 4245 | { return [...mobileLights, ...blockLights]; } |
| 4246 | if (this.#isActiveLightingChunk(chunkX, chunkY)) |
| 4247 | { |
| 4248 | const inner = this.#innerDynamicLights(mobileLights); |
| 4249 | const blocks = blockLights.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY)); |
| 4250 | return [...inner, ...blocks]; |
| 4251 | } |
| 4252 | const spill = this.#innerDynamicLights([...mobileLights, ...blockLights]); |
| 4253 | return spill.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY)); |
| 4254 | } |
| 4255 | |
| 4256 | #dynamicLightsForTile (tileX, tileY, mobileLights, blockLights = []) |
| 4257 | { |
| 4258 | return this.#dynamicLightsForChunk( |
| 4259 | Math.floor(tileX / CHUNK_SIZE), |
| 4260 | Math.floor(tileY / CHUNK_SIZE), |
| 4261 | mobileLights, |
| 4262 | blockLights |
| 4263 | ); |
| 4264 | } |
| 4265 | |
| 4266 | /** Authored torches/furnaces in chunks that can light the active 3×3 (or all chunks in editor). */ |
| 4267 | #collectBlockLightsForShading () |
| 4268 | { |
| 4269 | const center = this.#activeLightingCenterChunk(); |
| 4270 | const maxRange = maxBlockLightRangeTiles(); |
| 4271 | const halo = Math.ceil(maxRange / CHUNK_SIZE) + 1; |
| 4272 | const sources = []; |
| 4273 | if (!center) |
| 4274 | { |
| 4275 | for (const snapshot of this.chunks.values()) |
| 4276 | { sources.push(...collectBlockLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.blocks)); } |
| 4277 | return sources; |
| 4278 | } |
| 4279 | for (let dy = -1 - halo; dy <= 1 + halo; dy++) |
| 4280 | { |
| 4281 | for (let dx = -1 - halo; dx <= 1 + halo; dx++) |
| 4282 | { |
| 4283 | const snapshot = this.chunks.get(`${center.chunkX + dx},${center.chunkY + dy}`); |
| 4284 | if (!snapshot?.blocks) |
| 4285 | { continue; } |
| 4286 | sources.push(...collectBlockLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.blocks)); |
| 4287 | } |
| 4288 | } |
| 4289 | return sources; |
| 4290 | } |
| 4291 | |
| 4292 | #updateShade () |
| 4293 | { |
| 4294 | const ambientDark = this.#ambientDarkness(); |
| 4295 | const now = performance.now(); |
| 4296 | this.dynamicLights = this.dynamicLights.filter((light) => light.until > now); |
| 4297 | |
| 4298 | const mobileLights = [...this.dynamicLights]; |
| 4299 | for (const light of this.spellLights.values()) |
| 4300 | { |
| 4301 | if (light.until <= now) |
| 4302 | { continue; } |
| 4303 | mobileLights.push({ |
| 4304 | tileX: light.tileX, |
| 4305 | tileY: light.tileY, |
| 4306 | range: light.range, |
| 4307 | intensity: light.intensity |
| 4308 | }); |
| 4309 | } |
| 4310 | for (const key of [...this.spellLights.keys()]) |
| 4311 | { |
| 4312 | if (this.spellLights.get(key).until <= now) |
| 4313 | { |
| 4314 | const expired = this.spellLights.get(key); |
| 4315 | this.spellLights.delete(key); |
| 4316 | this.#invalidateNeighborLightmapCaches( |
| 4317 | Math.floor(expired.tileX / CHUNK_SIZE), |
| 4318 | Math.floor(expired.tileY / CHUNK_SIZE) |
| 4319 | ); |
| 4320 | } |
| 4321 | } |
| 4322 | const activeDarks = []; |
| 4323 | for (const dark of this.spellDarks.values()) |
| 4324 | { |
| 4325 | if (dark.until <= now) |
| 4326 | { continue; } |
| 4327 | activeDarks.push({ |
| 4328 | tileX: dark.tileX, |
| 4329 | tileY: dark.tileY, |
| 4330 | range: dark.range, |
| 4331 | intensity: dark.intensity |
| 4332 | }); |
| 4333 | } |
| 4334 | for (const key of [...this.spellDarks.keys()]) |
| 4335 | { |
| 4336 | if (this.spellDarks.get(key).until <= now) |
| 4337 | { |
| 4338 | const expired = this.spellDarks.get(key); |
| 4339 | this.spellDarks.delete(key); |
| 4340 | this.#invalidateNeighborLightmapCaches( |
| 4341 | Math.floor(expired.tileX / CHUNK_SIZE), |
| 4342 | Math.floor(expired.tileY / CHUNK_SIZE) |
| 4343 | ); |
| 4344 | } |
| 4345 | } |
| 4346 | this._activeSpellDarks = activeDarks; |
| 4347 | const tileSize = this.tileSize(); |
| 4348 | const blindLight = this.#blindVisionLight(); |
| 4349 | if (blindLight) |
| 4350 | { mobileLights.push(blindLight); } |
| 4351 | for (const entity of this.entities.values()) |
| 4352 | { |
| 4353 | const range = entity.lightRadiusTiles ?? 0; |
| 4354 | if (range <= 0) |
| 4355 | { continue; } |
| 4356 | mobileLights.push({ |
| 4357 | tileX: Math.floor(entity.visualX / tileSize), |
| 4358 | tileY: Math.floor(entity.visualY / tileSize), |
| 4359 | range, |
| 4360 | intensity: entity.lightIntensity ?? 1 |
| 4361 | }); |
| 4362 | } |
| 4363 | const blockLights = this.#collectBlockLightsForShading(); |
| 4364 | |
| 4365 | const lightOcclusion = makeSnapshotLightOcclusion(this.chunks); |
| 4366 | |
| 4367 | for (const objects of this.tiles.values()) |
| 4368 | { |
| 4369 | if (objects._inViewport === false) |
| 4370 | { continue; } |
| 4371 | const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, mobileLights, blockLights); |
| 4372 | objects.shadeAlpha = this.#tileShadeAlpha(objects, lights, lightOcclusion, ambientDark); |
| 4373 | } |
| 4374 | |
| 4375 | for (const baked of this.bakedChunks.values()) |
| 4376 | { |
| 4377 | if (baked._inViewport === false) |
| 4378 | { continue; } |
| 4379 | const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, mobileLights, blockLights); |
| 4380 | this.#writeChunkLightmap(baked, lights, mobileLights, blockLights, lightOcclusion, ambientDark); |
| 4381 | // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit. |
| 4382 | if (baked.groundObject?.renderer?.shaderUniforms) |
| 4383 | { baked.groundObject.renderer.shaderUniforms.u_ambientDark = 1; } |
| 4384 | for (const object of baked.blockObjects ?? []) |
| 4385 | { |
| 4386 | if (object?.renderer?.shaderUniforms) |
| 4387 | { object.renderer.shaderUniforms.u_ambientDark = 1; } |
| 4388 | } |
| 4389 | } |
| 4390 | |
| 4391 | const timeSec = now / 1000; |
| 4392 | for (const objects of this.tiles.values()) |
| 4393 | { |
| 4394 | if (objects._inViewport === false) |
| 4395 | { continue; } |
| 4396 | if (objects.block) |
| 4397 | { |
| 4398 | if (objects.cliffGroundTop) |
| 4399 | { |
| 4400 | const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`); |
| 4401 | const localX = ((objects.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; |
| 4402 | const localY = ((objects.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; |
| 4403 | this.#syncCliffGroundTopSprite( |
| 4404 | objects.block, |
| 4405 | objects.shadeAlpha, |
| 4406 | baked?.groundImage ?? null, |
| 4407 | localX, |
| 4408 | localY |
| 4409 | ); |
| 4410 | } |
| 4411 | else |
| 4412 | { this.#syncLitSprite(objects.block, objects.shadeAlpha); } |
| 4413 | } |
| 4414 | if (objects.ground && isWaterGround(objects.groundTypeId)) |
| 4415 | { |
| 4416 | const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`); |
| 4417 | // Light intensity grid is visible light (1 − shade); water shader uses ambient=1. |
| 4418 | this.#syncGroundWaterFx(objects, 1, timeSec, baked); |
| 4419 | } |
| 4420 | else if (objects.ground) |
| 4421 | { this.#syncLitSprite(objects.ground, objects.shadeAlpha); } |
| 4422 | } |
| 4423 | |
| 4424 | for (const item of this.groundItems.values()) |
| 4425 | { |
| 4426 | const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0; |
| 4427 | this.#syncGroundItemSprite(item, alpha); |
| 4428 | } |
| 4429 | } |
| 4430 | |
| 4431 | #tileLightSources (objects, activeLights, lightOcclusion) |
| 4432 | { |
| 4433 | // Inner 3×3: ignore baked (stale behind doors); outer ring keeps authored lightmaps. |
| 4434 | const useBaked = !this.#isActiveLightingTile(objects.tileX, objects.tileY); |
| 4435 | const baked = useBaked ? lightIntensity(objects.light ?? 0) : 0; |
| 4436 | const dynamic = dynamicLightAtTile( |
| 4437 | objects.tileX, |
| 4438 | objects.tileY, |
| 4439 | activeLights, |
| 4440 | lightOcclusion |
| 4441 | ); |
| 4442 | const dark = dynamicDarknessAtTile( |
| 4443 | objects.tileX, |
| 4444 | objects.tileY, |
| 4445 | this._activeSpellDarks ?? [], |
| 4446 | lightOcclusion |
| 4447 | ); |
| 4448 | return { lights: Math.max(baked, dynamic), dark }; |
| 4449 | } |
| 4450 | |
| 4451 | /** Shade 0–1: night ambient over unlit tiles, plus Dark spell dimming daylight/torches. */ |
| 4452 | #tileShadeAlpha (objects, activeLights, lightOcclusion, ambientDark) |
| 4453 | { |
| 4454 | const { lights, dark } = this.#tileLightSources(objects, activeLights, lightOcclusion); |
| 4455 | return Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark); |
| 4456 | } |
| 4457 | |
| 4458 | #tileLightIntensity (objects, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness()) |
| 4459 | { |
| 4460 | return 1 - this.#tileShadeAlpha(objects, activeLights, lightOcclusion, ambientDark); |
| 4461 | } |
| 4462 | |
| 4463 | /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */ |
| 4464 | #intensityAtTile (tileX, tileY, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness()) |
| 4465 | { |
| 4466 | const tileObjects = this.tiles.get(`${tileX},${tileY}`); |
| 4467 | if (tileObjects) |
| 4468 | { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion, ambientDark); } |
| 4469 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 4470 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 4471 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 4472 | if (!snapshot) |
| 4473 | { return 1 - Math.min(1, Math.max(0, ambientDark)); } |
| 4474 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 4475 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 4476 | const index = localY * CHUNK_SIZE + localX; |
| 4477 | const useBaked = !this.#isActiveLightingTile(tileX, tileY); |
| 4478 | const bakedLit = useBaked ? lightIntensity(snapshot.light[index] ?? 0) : 0; |
| 4479 | const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion); |
| 4480 | const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion); |
| 4481 | const lights = Math.max(bakedLit, dynamic); |
| 4482 | const shade = Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark); |
| 4483 | return 1 - shade; |
| 4484 | } |
| 4485 | |
| 4486 | /** True when ground or block on this tile occludes light rays (same rules as bake). */ |
| 4487 | #tileOccludesLight (tileX, tileY) |
| 4488 | { |
| 4489 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 4490 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 4491 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 4492 | if (!snapshot) |
| 4493 | { return false; } |
| 4494 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 4495 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 4496 | if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE) |
| 4497 | { return false; } |
| 4498 | const index = localY * CHUNK_SIZE + localX; |
| 4499 | const ground = normalizeGround(snapshot.grounds?.[index]); |
| 4500 | if (!isGroundPassable(ground.typeId)) |
| 4501 | { return true; } |
| 4502 | return blockLightOcclusionForBlock(snapshot.blocks?.[index]) === LightOcclusion.solid; |
| 4503 | } |
| 4504 | |
| 4505 | #fillChunkLightGrids (baked, mobileLights, blockLights, lightOcclusion, ambientDark) |
| 4506 | { |
| 4507 | const gridW = CHUNK_SIZE + 2; |
| 4508 | const gridSize = gridW * gridW; |
| 4509 | if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize) |
| 4510 | { baked.lightIntensityGrid = new Float32Array(gridSize); } |
| 4511 | if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize) |
| 4512 | { baked.lightOccludeGrid = new Uint8Array(gridSize); } |
| 4513 | const grid = baked.lightIntensityGrid; |
| 4514 | const occlude = baked.lightOccludeGrid; |
| 4515 | for (let ly = -1; ly <= CHUNK_SIZE; ly++) |
| 4516 | { |
| 4517 | for (let lx = -1; lx <= CHUNK_SIZE; lx++) |
| 4518 | { |
| 4519 | const tileX = baked.chunkX * CHUNK_SIZE + lx; |
| 4520 | const tileY = baked.chunkY * CHUNK_SIZE + ly; |
| 4521 | const gi = (ly + 1) * gridW + (lx + 1); |
| 4522 | // Halo tiles may sit in the other lighting region (3×3 vs outer). Resolve |
| 4523 | // sources per tile so corner blends match the neighbour chunk's shading. |
| 4524 | const lights = this.#dynamicLightsForTile(tileX, tileY, mobileLights, blockLights); |
| 4525 | grid[gi] = this.#intensityAtTile(tileX, tileY, lights, lightOcclusion, ambientDark); |
| 4526 | occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0; |
| 4527 | } |
| 4528 | } |
| 4529 | return { grid, occlude, gridW }; |
| 4530 | } |
| 4531 | |
| 4532 | #makeLightCornerSampler (grid, occlude, gridW) |
| 4533 | { |
| 4534 | const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)]; |
| 4535 | const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0; |
| 4536 | const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) => smoothLitCorner({ |
| 4537 | homeLit: sample(homeLx, homeLy), |
| 4538 | homeBlocks: blocks(homeLx, homeLy), |
| 4539 | aLit: sample(aLx, aLy), |
| 4540 | aBlocks: blocks(aLx, aLy), |
| 4541 | bLit: sample(bLx, bLy), |
| 4542 | bBlocks: blocks(bLx, bLy), |
| 4543 | dLit: sample(dLx, dLy), |
| 4544 | dBlocks: blocks(dLx, dLy) |
| 4545 | }); |
| 4546 | return { smoothCorner }; |
| 4547 | } |
| 4548 | |
| 4549 | /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */ |
| 4550 | #tileLitCorners (baked, localX, localY) |
| 4551 | { |
| 4552 | const grid = baked?.lightIntensityGrid; |
| 4553 | const occlude = baked?.lightOccludeGrid; |
| 4554 | if (!grid?.length || !occlude?.length) |
| 4555 | { return null; } |
| 4556 | const gridW = CHUNK_SIZE + 2; |
| 4557 | const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW); |
| 4558 | return { |
| 4559 | nw: smoothCorner( |
| 4560 | localX, localY, |
| 4561 | localX - 1, localY, |
| 4562 | localX, localY - 1, |
| 4563 | localX - 1, localY - 1 |
| 4564 | ), |
| 4565 | ne: smoothCorner( |
| 4566 | localX, localY, |
| 4567 | localX + 1, localY, |
| 4568 | localX, localY - 1, |
| 4569 | localX + 1, localY - 1 |
| 4570 | ), |
| 4571 | sw: smoothCorner( |
| 4572 | localX, localY, |
| 4573 | localX - 1, localY, |
| 4574 | localX, localY + 1, |
| 4575 | localX - 1, localY + 1 |
| 4576 | ), |
| 4577 | se: smoothCorner( |
| 4578 | localX, localY, |
| 4579 | localX + 1, localY, |
| 4580 | localX, localY + 1, |
| 4581 | localX + 1, localY + 1 |
| 4582 | ) |
| 4583 | }; |
| 4584 | } |
| 4585 | |
| 4586 | #hashUint8Array (values) |
| 4587 | { |
| 4588 | let hash = 2166136261; |
| 4589 | for (let i = 0; i < values.length; i++) |
| 4590 | { |
| 4591 | hash ^= values[i]; |
| 4592 | hash = Math.imul(hash, 16777619); |
| 4593 | } |
| 4594 | return hash >>> 0; |
| 4595 | } |
| 4596 | |
| 4597 | #lightAffectsChunkBounds (light, chunkX, chunkY) |
| 4598 | { |
| 4599 | const minX = chunkX * CHUNK_SIZE - 1; |
| 4600 | const minY = chunkY * CHUNK_SIZE - 1; |
| 4601 | const maxX = chunkX * CHUNK_SIZE + CHUNK_SIZE; |
| 4602 | const maxY = chunkY * CHUNK_SIZE + CHUNK_SIZE; |
| 4603 | const closestX = Math.max(minX, Math.min(light.tileX, maxX)); |
| 4604 | const closestY = Math.max(minY, Math.min(light.tileY, maxY)); |
| 4605 | return Math.hypot(light.tileX - closestX, light.tileY - closestY) <= light.range; |
| 4606 | } |
| 4607 | |
| 4608 | #chunkLightmapCacheKey (baked, activeLights, ambientDark = this.#ambientDarkness()) |
| 4609 | { |
| 4610 | const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`); |
| 4611 | if (!snapshot?.light) |
| 4612 | { return null; } |
| 4613 | const bakedHash = this.#hashUint8Array(snapshot.light); |
| 4614 | // Caller already scoped lights for this chunk (incl. 3×3 spill onto the outer ring). |
| 4615 | const lights = activeLights; |
| 4616 | const darks = this._activeSpellDarks ?? []; |
| 4617 | const mode = this.lightingMode === "simple" ? "s" : "f"; |
| 4618 | const ambientKey = Math.round(Math.max(0, ambientDark) * 1000); |
| 4619 | let lightsKey = ""; |
| 4620 | for (const light of lights) |
| 4621 | { |
| 4622 | if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY)) |
| 4623 | { continue; } |
| 4624 | lightsKey += `l${light.tileX},${light.tileY},${light.range},${light.intensity ?? 1};`; |
| 4625 | } |
| 4626 | let darksKey = ""; |
| 4627 | for (const dark of darks) |
| 4628 | { |
| 4629 | if (!this.#lightAffectsChunkBounds(dark, baked.chunkX, baked.chunkY)) |
| 4630 | { continue; } |
| 4631 | darksKey += `d${dark.tileX},${dark.tileY},${dark.range},${dark.intensity ?? 1};`; |
| 4632 | } |
| 4633 | return `a:${mode}:${ambientKey}:${bakedHash}:${lightsKey}|${darksKey}`; |
| 4634 | } |
| 4635 | |
| 4636 | #invalidateNeighborLightmapCaches (chunkX, chunkY) |
| 4637 | { |
| 4638 | // Halo grid is ±1 tile; outer map ring is ±2 chunks from the player. |
| 4639 | for (let dy = -2; dy <= 2; dy++) |
| 4640 | { |
| 4641 | for (let dx = -2; dx <= 2; dx++) |
| 4642 | { |
| 4643 | const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`); |
| 4644 | if (baked) |
| 4645 | { baked.lightmapCacheKey = null; } |
| 4646 | } |
| 4647 | } |
| 4648 | } |
| 4649 | |
| 4650 | /** |
| 4651 | * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours; |
| 4652 | * occluding tiles stay flat and contribute 0 into others so light does not bleed |
| 4653 | * through a wall to the far side. Diagonals only when both cardinals are clear. |
| 4654 | * @param chunkLights Sources that affect this chunk (cache key + in-chunk samples). |
| 4655 | * @param mobileLights / blockLights Full lists so the ±1 halo can sample across the 3×3 boundary. |
| 4656 | */ |
| 4657 | #writeChunkLightmap ( |
| 4658 | baked, |
| 4659 | chunkLights, |
| 4660 | mobileLights, |
| 4661 | blockLights, |
| 4662 | lightOcclusion, |
| 4663 | ambientDark = this.#ambientDarkness() |
| 4664 | ) |
| 4665 | { |
| 4666 | const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`); |
| 4667 | if (!snapshot) |
| 4668 | { return; } |
| 4669 | const cacheKey = this.#chunkLightmapCacheKey(baked, chunkLights, ambientDark); |
| 4670 | if (cacheKey && baked.lightmapCacheKey === cacheKey) |
| 4671 | { return; } |
| 4672 | const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX; |
| 4673 | const pixelCount = atlasPx * atlasPx * 4; |
| 4674 | if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount) |
| 4675 | { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); } |
| 4676 | const pixels = baked.lightmapPixels; |
| 4677 | |
| 4678 | this.#fillChunkLightGrids(baked, mobileLights, blockLights, lightOcclusion, ambientDark); |
| 4679 | const simple = this.lightingMode === "simple"; |
| 4680 | |
| 4681 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 4682 | { |
| 4683 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 4684 | { |
| 4685 | const baseX = localX * SPRITE_SIZE_PX; |
| 4686 | const baseY = localY * SPRITE_SIZE_PX; |
| 4687 | if (simple) |
| 4688 | { |
| 4689 | const gridW = CHUNK_SIZE + 2; |
| 4690 | const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0; |
| 4691 | const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255); |
| 4692 | for (let py = 0; py < SPRITE_SIZE_PX; py++) |
| 4693 | { |
| 4694 | for (let px = 0; px < SPRITE_SIZE_PX; px++) |
| 4695 | { |
| 4696 | const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4; |
| 4697 | pixels[offset] = value; |
| 4698 | pixels[offset + 1] = value; |
| 4699 | pixels[offset + 2] = value; |
| 4700 | pixels[offset + 3] = 255; |
| 4701 | } |
| 4702 | } |
| 4703 | continue; |
| 4704 | } |
| 4705 | const corners = this.#tileLitCorners(baked, localX, localY); |
| 4706 | const nw = corners.nw; |
| 4707 | const ne = corners.ne; |
| 4708 | const sw = corners.sw; |
| 4709 | const se = corners.se; |
| 4710 | for (let py = 0; py < SPRITE_SIZE_PX; py++) |
| 4711 | { |
| 4712 | const v = (py + 0.5) / SPRITE_SIZE_PX; |
| 4713 | const left = nw + (sw - nw) * v; |
| 4714 | const right = ne + (se - ne) * v; |
| 4715 | for (let px = 0; px < SPRITE_SIZE_PX; px++) |
| 4716 | { |
| 4717 | const u = (px + 0.5) / SPRITE_SIZE_PX; |
| 4718 | const intensity = left + (right - left) * u; |
| 4719 | const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255); |
| 4720 | const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4; |
| 4721 | pixels[offset] = value; |
| 4722 | pixels[offset + 1] = value; |
| 4723 | pixels[offset + 2] = value; |
| 4724 | pixels[offset + 3] = 255; |
| 4725 | } |
| 4726 | } |
| 4727 | } |
| 4728 | } |
| 4729 | const ctx = baked.lightmapCanvas.getContext("2d"); |
| 4730 | ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0); |
| 4731 | invalidateCanvasTexture(this.scene, baked.lightmapCanvas); |
| 4732 | this.#queueCanvasTextureWarm(baked.lightmapCanvas, baked.chunkX, baked.chunkY); |
| 4733 | baked.lightmapCacheKey = cacheKey; |
| 4734 | } |
| 4735 | |
| 4736 | #updateSwipes (now) |
| 4737 | { |
| 4738 | this.swipes = this.swipes.filter((swipe) => |
| 4739 | { |
| 4740 | if (swipe.lerp && swipe.started != null) |
| 4741 | { |
| 4742 | const durationMs = swipe.durationMs ?? 400; |
| 4743 | const t = Math.min(1, (now - swipe.started) / durationMs); |
| 4744 | const fromPivot = this.#projectileLaunchPoint( |
| 4745 | swipe.attackerId ?? null, |
| 4746 | swipe.fromTileX, |
| 4747 | swipe.fromTileY |
| 4748 | ); |
| 4749 | const toPivot = this.#projectileEndPivot(swipe); |
| 4750 | const x = fromPivot.x + (toPivot.x - fromPivot.x) * t; |
| 4751 | const y = fromPivot.y + (toPivot.y - fromPivot.y) * t; |
| 4752 | const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02; |
| 4753 | if (swipe.object?.transform) |
| 4754 | { |
| 4755 | swipe.object.transform.rotation = Math.atan2( |
| 4756 | toPivot.y - fromPivot.y, |
| 4757 | toPivot.x - fromPivot.x |
| 4758 | ) * (180 / Math.PI); |
| 4759 | } |
| 4760 | if (swipe.spellProjectile && swipe.tint) |
| 4761 | { this.#syncUnlitTintSprite(swipe.object, swipe.tint); } |
| 4762 | this.#placePivoted(swipe.object, x, y, sortY, SORT_FX); |
| 4763 | if (!swipe.spellProjectile) |
| 4764 | { |
| 4765 | this.#applyPhysicalCombatFxDarkness( |
| 4766 | swipe.object, |
| 4767 | swipe.fromTileX, |
| 4768 | swipe.fromTileY, |
| 4769 | swipe.tileX, |
| 4770 | swipe.tileY, |
| 4771 | swipe.dualTint ?? null |
| 4772 | ); |
| 4773 | } |
| 4774 | } |
| 4775 | else if (swipe.fromTileX != null && !swipe.spellProjectile) |
| 4776 | { |
| 4777 | this.#applyPhysicalCombatFxDarkness( |
| 4778 | swipe.object, |
| 4779 | swipe.fromTileX, |
| 4780 | swipe.fromTileY, |
| 4781 | swipe.tileX, |
| 4782 | swipe.tileY, |
| 4783 | swipe.dualTint ?? null |
| 4784 | ); |
| 4785 | } |
| 4786 | if (swipe.fadeOpacity && swipe.started != null && swipe.object?.renderer) |
| 4787 | { |
| 4788 | const durationMs = swipe.durationMs ?? MELEE_SWIPE_MS; |
| 4789 | const t = Math.min(1, Math.max(0, (now - swipe.started) / durationMs)); |
| 4790 | swipe.object.renderer.alpha = 1 - t; |
| 4791 | } |
| 4792 | if (swipe.until > now) |
| 4793 | { return true; } |
| 4794 | const onImpact = swipe.onImpact; |
| 4795 | swipe.onImpact = null; |
| 4796 | swipe.object?.destroy(); |
| 4797 | if (typeof onImpact === "function") |
| 4798 | { |
| 4799 | try |
| 4800 | { onImpact(); } |
| 4801 | catch (_) |
| 4802 | { /* presentation only */ } |
| 4803 | } |
| 4804 | return false; |
| 4805 | }); |
| 4806 | } |
| 4807 | |
| 4808 | #projectileEndPivot (swipe) |
| 4809 | { |
| 4810 | if (swipe.trackTarget && swipe.targetId != null) |
| 4811 | { return this.#projectileAimPoint(swipe.targetId, swipe.tileX, swipe.tileY); } |
| 4812 | return this.#projectileAimPoint(null, swipe.tileX, swipe.tileY); |
| 4813 | } |
| 4814 | |
| 4815 | /** |
| 4816 | * Launch point: 4px below the top of the caster sprite (falls back to tile centre). |
| 4817 | */ |
| 4818 | #projectileLaunchPoint (entityId, tileX, tileY) |
| 4819 | { |
| 4820 | const entity = entityId != null ? this.entities.get(entityId) : null; |
| 4821 | if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY)) |
| 4822 | { |
| 4823 | const zoom = this.zoom; |
| 4824 | const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX; |
| 4825 | const pivotX = entity.visualX + (entity.stackOffsetX ?? 0); |
| 4826 | const pivotY = entity.visualY + (entity.stackOffsetY ?? 0); |
| 4827 | const topY = pivotY - (spriteH - PIVOT_FROM_BOTTOM_PX) * zoom; |
| 4828 | return { |
| 4829 | x: pivotX, |
| 4830 | y: topY + PROJECTILE_LAUNCH_FROM_TOP_PX * zoom |
| 4831 | }; |
| 4832 | } |
| 4833 | return tilePivot(tileX, tileY, this.tileSize()); |
| 4834 | } |
| 4835 | |
| 4836 | /** |
| 4837 | * Aim point: sprite centre for creatures, tile centre for tile targets. |
| 4838 | */ |
| 4839 | #projectileAimPoint (entityId, tileX, tileY) |
| 4840 | { |
| 4841 | const entity = entityId != null ? this.entities.get(entityId) : null; |
| 4842 | if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY)) |
| 4843 | { |
| 4844 | const zoom = this.zoom; |
| 4845 | const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX; |
| 4846 | const pivotX = entity.visualX + (entity.stackOffsetX ?? 0); |
| 4847 | const pivotY = entity.visualY + (entity.stackOffsetY ?? 0); |
| 4848 | return spriteCenterFromPivot(pivotX, pivotY, spriteH, zoom); |
| 4849 | } |
| 4850 | return tilePivot(tileX, tileY, this.tileSize()); |
| 4851 | } |
| 4852 | |
| 4853 | #updateDamageNumbers (now) |
| 4854 | { |
| 4855 | const layer = this.damageNumbersEl; |
| 4856 | if (!layer) |
| 4857 | { return; } |
| 4858 | this.damageFloats = this.damageFloats.filter((entry) => |
| 4859 | { |
| 4860 | const elapsed = now - entry.started; |
| 4861 | if (elapsed >= DAMAGE_FLOAT_MS) |
| 4862 | { |
| 4863 | entry.element?.remove(); |
| 4864 | return false; |
| 4865 | } |
| 4866 | const entity = this.entities.get(entry.entityId); |
| 4867 | if (!entity) |
| 4868 | { |
| 4869 | entry.element?.remove(); |
| 4870 | return false; |
| 4871 | } |
| 4872 | if (!entry.element) |
| 4873 | { |
| 4874 | entry.element = document.createElement("span"); |
| 4875 | entry.element.className = "damage-number"; |
| 4876 | entry.element.textContent = String(entry.damage); |
| 4877 | layer.append(entry.element); |
| 4878 | } |
| 4879 | const anchor = this.nametagAnchor(entity); |
| 4880 | if (!anchor) |
| 4881 | { return true; } |
| 4882 | const t = elapsed / DAMAGE_FLOAT_MS; |
| 4883 | entry.element.style.left = `${anchor.x}px`; |
| 4884 | entry.element.style.top = `${anchor.y - 6 - t * 28}px`; |
| 4885 | entry.element.style.opacity = String(1 - t); |
| 4886 | return true; |
| 4887 | }); |
| 4888 | } |
| 4889 | |
| 4890 | #updateSkillLevelFloats (now) |
| 4891 | { |
| 4892 | const layer = this.skillLevelFloatsEl; |
| 4893 | if (!layer) |
| 4894 | { return; } |
| 4895 | this.skillLevelFloats = this.skillLevelFloats.filter((entry) => |
| 4896 | { |
| 4897 | const elapsed = now - entry.started; |
| 4898 | if (elapsed >= SKILL_LEVEL_FLOAT_MS) |
| 4899 | { |
| 4900 | entry.element?.remove(); |
| 4901 | return false; |
| 4902 | } |
| 4903 | const entity = this.entities.get(entry.entityId); |
| 4904 | if (!entity) |
| 4905 | { |
| 4906 | entry.element?.remove(); |
| 4907 | return false; |
| 4908 | } |
| 4909 | if (!entry.element) |
| 4910 | { |
| 4911 | const root = document.createElement("div"); |
| 4912 | root.className = "skill-level-float"; |
| 4913 | |
| 4914 | const levelEl = document.createElement("div"); |
| 4915 | levelEl.className = "skill-level-float-level"; |
| 4916 | levelEl.textContent = `↑${entry.level}↑`; |
| 4917 | |
| 4918 | const icon = document.createElement("img"); |
| 4919 | icon.className = "skill-level-float-icon"; |
| 4920 | icon.src = entry.icon; |
| 4921 | icon.alt = entry.displayName || ""; |
| 4922 | |
| 4923 | root.append(levelEl, icon); |
| 4924 | entry.element = root; |
| 4925 | layer.append(entry.element); |
| 4926 | } |
| 4927 | const anchor = this.nametagAnchor(entity); |
| 4928 | if (!anchor) |
| 4929 | { return true; } |
| 4930 | const t = elapsed / SKILL_LEVEL_FLOAT_MS; |
| 4931 | entry.element.style.left = `${anchor.x}px`; |
| 4932 | entry.element.style.top = `${anchor.y - 10 - t * 18}px`; |
| 4933 | entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85)); |
| 4934 | return true; |
| 4935 | }); |
| 4936 | } |
| 4937 | |
| 4938 | #syncBloomLayer () |
| 4939 | { |
| 4940 | if (!this.bloomEnabled) |
| 4941 | { |
| 4942 | this.scene.setLayers([{ name: "default" }]); |
| 4943 | return; |
| 4944 | } |
| 4945 | const settings = this.settings ?? DEFAULT_WORLD_SETTINGS; |
| 4946 | this.scene.setLayers([ |
| 4947 | { name: "default" }, |
| 4948 | { |
| 4949 | name: RENDER_LAYER_BLOOM, |
| 4950 | composite: "add", |
| 4951 | postShaders: Shader.getBloomPostChain({ |
| 4952 | threshold: settings.bloomThreshold, |
| 4953 | softKnee: settings.bloomSoftKnee, |
| 4954 | intensity: settings.bloomIntensity, |
| 4955 | blurSize: settings.bloomBlurSize, |
| 4956 | saturation: settings.bloomSaturation, |
| 4957 | colorPreserve: settings.bloomColorPreserve, |
| 4958 | dilate: settings.bloomDilate, |
| 4959 | scales: Math.max(1, Math.round(settings.bloomScales ?? 1)), |
| 4960 | halfRes: (settings.bloomHalfRes ?? 1) >= 0.5 |
| 4961 | }) |
| 4962 | } |
| 4963 | ]); |
| 4964 | } |
| 4965 | } |
| 4966 | |
| 4967 | export function nightFactor (hour, nightDarkness = 0.72) |
| 4968 | { |
| 4969 | const peak = Math.min(1, Math.max(0, nightDarkness)); |
| 4970 | if (hour >= 8 && hour <= 16) |
| 4971 | { return 0; } |
| 4972 | if (hour >= 22 || hour <= 5) |
| 4973 | { return peak; } |
| 4974 | if (hour < 8) |
| 4975 | { return lerp(peak, 0, (hour - 5) / 3); } |
| 4976 | return lerp(0, peak, (hour - 16) / 6); |
| 4977 | } |
| 4978 | |
| 4979 | function bodySpriteName (sex) |
| 4980 | { |
| 4981 | const key = sex === "female" ? "player-body-female" : "player-body-male"; |
| 4982 | return spriteImageName("character", key, key); |
| 4983 | } |
| 4984 | |
| 4985 | function lerp (a, b, t) |
| 4986 | { |
| 4987 | return a + (b - a) * Math.min(1, Math.max(0, t)); |
| 4988 | } |
| 4989 | |
| 4990 | function makeLightmapCanvas (size) |
| 4991 | { |
| 4992 | const canvas = document.createElement("canvas"); |
| 4993 | canvas.width = size; |
| 4994 | canvas.height = size; |
| 4995 | return canvas; |
| 4996 | } |
| 4997 | |
| 4998 | function copyCanvas (source, dest) |
| 4999 | { |
| 5000 | const ctx = dest.getContext("2d"); |
| 5001 | ctx.imageSmoothingEnabled = false; |
| 5002 | ctx.clearRect(0, 0, dest.width, dest.height); |
| 5003 | ctx.drawImage(source, 0, 0); |
| 5004 | } |
| 5005 | |
| 5006 | function drawHpBar (canvas, current, max) |
| 5007 | { |
| 5008 | const ctx = canvas.getContext("2d"); |
| 5009 | ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H); |
| 5010 | ctx.fillStyle = "#000000"; |
| 5011 | ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H); |
| 5012 | const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0; |
| 5013 | const fillW = Math.round(12 * ratio); |
| 5014 | if (fillW > 0) |
| 5015 | { |
| 5016 | ctx.fillStyle = "#ff0000"; |
| 5017 | ctx.fillRect(1, 1, fillW, 2); |
| 5018 | } |
| 5019 | } |