| 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, lightIntensity } from "/shared/lighting/raycast.js"; |
| 3 | import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js"; |
| 4 | import { bakeChunkOcclusion } from "/shared/lighting/chunkOcclusion.js"; |
| 5 | import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js"; |
| 6 | import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js"; |
| 7 | import { resolveItemTint, resolveEquipTint, resolveItemDualTint, normalizeRgb } from "/shared/render/tint.js"; |
| 8 | import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight, LightOcclusion } from "/shared/definitions/tiles.js"; |
| 9 | import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js"; |
| 10 | import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js"; |
| 11 | import { createChunkAtlasCache } from "./chunkAtlasCache.js"; |
| 12 | import |
| 13 | { |
| 14 | frameworkImageFromCanvas, |
| 15 | invalidateCanvasTexture |
| 16 | } from "./canvasSprite.js"; |
| 17 | import { setNearestFilter } from "./sprites.js"; |
| 18 | import { SeasonId, seasonIdAt } from "/shared/world/season.js"; |
| 19 | import |
| 20 | { |
| 21 | OVERWORLD_ID, |
| 22 | normalizeDimensionId, |
| 23 | normalizeLightingMode, |
| 24 | normalizeSeasonMode, |
| 25 | resolveDimensionDarknessFactor, |
| 26 | resolveDimensionSeasonId |
| 27 | } from "/shared/world/dimensions.js"; |
| 28 | import { SPELL_PROJECTILE_FRAME_MS } from "/shared/spells/constants.js"; |
| 29 | |
| 30 | const LAYER_GROUND = 0; |
| 31 | const LAYER_EDGE = 900000; |
| 32 | const SORT_BLOCK = 2; |
| 33 | const SORT_ENTITY = 3; |
| 34 | const SORT_HP_BAR = 4; |
| 35 | const SORT_FX = 5; |
| 36 | const RENDER_LAYER_BLOOM = "bloom"; |
| 37 | |
| 38 | const HP_BAR_W = 14; |
| 39 | const HP_BAR_H = 4; |
| 40 | const WALK_TILT_DEG = 6; |
| 41 | const RUN_TILT_DEG = 8; |
| 42 | const SHOVE_TILE_FRACTION = 0.25; |
| 43 | const SHOVE_MS = 280; |
| 44 | /** Soft reflow when stack circle targets change (join/leave a shared tile). */ |
| 45 | const STACK_SPREAD_LERP_MS = 280; |
| 46 | /** Hold gather-tool equip overlay slightly past swing interval so it stays visible between swings. */ |
| 47 | const GATHER_TOOL_HOLD_MS = 1100; |
| 48 | const DAMAGE_FLASH_MS = 180; |
| 49 | const DAMAGE_FLOAT_MS = 900; |
| 50 | const SKILL_LEVEL_FLOAT_MS = 2800; |
| 51 | |
| 52 | const SPRITE_LIGHTING_FRAG = [ |
| 53 | "precision mediump float;", |
| 54 | "varying vec2 v_texCoord;", |
| 55 | "uniform sampler2D u_texture;", |
| 56 | "uniform float u_darkness;", |
| 57 | "uniform float u_strength;", |
| 58 | "uniform float u_wade;", |
| 59 | "uniform float u_spriteHeight;", |
| 60 | "void main() {", |
| 61 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 62 | " if (color.a <= 0.0) { discard; }", |
| 63 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 64 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 65 | " vec3 rgb = color.rgb;", |
| 66 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 67 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 68 | " }", |
| 69 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 70 | " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);", |
| 71 | " gl_FragColor = vec4(rgb, color.a);", |
| 72 | "}" |
| 73 | ].join("\n"); |
| 74 | |
| 75 | const WATER_GROUND_FRAG = [ |
| 76 | "precision mediump float;", |
| 77 | "varying vec2 v_texCoord;", |
| 78 | "uniform sampler2D u_texture;", |
| 79 | "uniform float u_ambientDark;", |
| 80 | "uniform float u_litNW;", |
| 81 | "uniform float u_litNE;", |
| 82 | "uniform float u_litSW;", |
| 83 | "uniform float u_litSE;", |
| 84 | "uniform float u_time;", |
| 85 | "uniform float u_edgeN;", |
| 86 | "uniform float u_edgeE;", |
| 87 | "uniform float u_edgeS;", |
| 88 | "uniform float u_edgeW;", |
| 89 | "void main() {", |
| 90 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 91 | " if (color.a <= 0.0) { discard; }", |
| 92 | " vec3 rgb = color.rgb;", |
| 93 | " float foam = 0.0;", |
| 94 | " float pulse = 0.55 + 0.45 * sin(u_time * 3.2 + v_texCoord.x * 18.0 + v_texCoord.y * 10.0);", |
| 95 | " if (u_edgeN > 0.5 && v_texCoord.y < 0.22) {", |
| 96 | " foam = max(foam, (1.0 - v_texCoord.y / 0.22) * pulse);", |
| 97 | " }", |
| 98 | " if (u_edgeS > 0.5 && v_texCoord.y > 0.78) {", |
| 99 | " foam = max(foam, ((v_texCoord.y - 0.78) / 0.22) * pulse);", |
| 100 | " }", |
| 101 | " if (u_edgeW > 0.5 && v_texCoord.x < 0.22) {", |
| 102 | " foam = max(foam, (1.0 - v_texCoord.x / 0.22) * pulse);", |
| 103 | " }", |
| 104 | " if (u_edgeE > 0.5 && v_texCoord.x > 0.78) {", |
| 105 | " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);", |
| 106 | " }", |
| 107 | " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));", |
| 108 | " float litTop = mix(u_litNW, u_litNE, v_texCoord.x);", |
| 109 | " float litBottom = mix(u_litSW, u_litSE, v_texCoord.x);", |
| 110 | " float lit = mix(litTop, litBottom, v_texCoord.y);", |
| 111 | " float darkness = u_ambientDark * (1.0 - lit);", |
| 112 | " rgb = mix(rgb, vec3(0.0), darkness);", |
| 113 | " gl_FragColor = vec4(rgb, color.a);", |
| 114 | "}" |
| 115 | ].join("\n"); |
| 116 | |
| 117 | /** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */ |
| 118 | const TINT_LIT_SPRITE_FRAG = [ |
| 119 | "precision mediump float;", |
| 120 | "varying vec2 v_texCoord;", |
| 121 | "uniform sampler2D u_texture;", |
| 122 | "uniform float u_darkness;", |
| 123 | "uniform float u_strength;", |
| 124 | "uniform float u_wade;", |
| 125 | "uniform float u_spriteHeight;", |
| 126 | "uniform float u_useTint;", |
| 127 | "uniform vec3 u_tintColor;", |
| 128 | "void main() {", |
| 129 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 130 | " if (color.a <= 0.0) { discard; }", |
| 131 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 132 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 133 | " vec3 rgb = color.rgb;", |
| 134 | " if (u_useTint > 0.5) {", |
| 135 | " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {", |
| 136 | " float L = color.r;", |
| 137 | " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;", |
| 138 | " float tintLuma = dot(u_tintColor, vec3(0.2126, 0.7152, 0.0722));", |
| 139 | " rgb = mix(u_tintColor, vec3(tintLuma), gBlend) * L;", |
| 140 | " }", |
| 141 | " }", |
| 142 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 143 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 144 | " }", |
| 145 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 146 | " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);", |
| 147 | " gl_FragColor = vec4(rgb, color.a);", |
| 148 | "}" |
| 149 | ].join("\n"); |
| 150 | |
| 151 | /** Dual-channel tint: red = shaft/wood, blue = tip/string, white unchanged; then darkness. */ |
| 152 | const DUAL_TINT_LIT_SPRITE_FRAG = [ |
| 153 | "precision mediump float;", |
| 154 | "varying vec2 v_texCoord;", |
| 155 | "uniform sampler2D u_texture;", |
| 156 | "uniform float u_darkness;", |
| 157 | "uniform float u_strength;", |
| 158 | "uniform float u_wade;", |
| 159 | "uniform float u_spriteHeight;", |
| 160 | "uniform vec3 u_shaftTint;", |
| 161 | "uniform vec3 u_tipTint;", |
| 162 | "void main() {", |
| 163 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 164 | " if (color.a <= 0.0) { discard; }", |
| 165 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 166 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 167 | " vec3 rgb = color.rgb;", |
| 168 | " float tipMask = clamp((color.b - max(color.r, color.g)) * 1.75, 0.0, 1.0);", |
| 169 | " if (tipMask > 0.0) {", |
| 170 | " float L = color.b;", |
| 171 | " float gBlend = L > 0.0 ? clamp(color.g / L, 0.0, 1.0) : 0.0;", |
| 172 | " float tipLuma = dot(u_tipTint, vec3(0.2126, 0.7152, 0.0722));", |
| 173 | " vec3 tipCol = mix(u_tipTint, vec3(tipLuma), gBlend) * L;", |
| 174 | " rgb = mix(rgb, tipCol, tipMask);", |
| 175 | " }", |
| 176 | " float shaftMask = clamp((color.r - max(color.g, color.b)) * 1.75, 0.0, 1.0);", |
| 177 | " if (shaftMask > 0.0) {", |
| 178 | " float L = color.r;", |
| 179 | " float gBlend = L > 0.0 ? clamp(color.g / L, 0.0, 1.0) : 0.0;", |
| 180 | " float shaftLuma = dot(u_shaftTint, vec3(0.2126, 0.7152, 0.0722));", |
| 181 | " vec3 shaftCol = mix(u_shaftTint, vec3(shaftLuma), gBlend) * L;", |
| 182 | " rgb = mix(rgb, shaftCol, shaftMask);", |
| 183 | " }", |
| 184 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 185 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 186 | " }", |
| 187 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 188 | " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);", |
| 189 | " gl_FragColor = vec4(rgb, color.a);", |
| 190 | "}" |
| 191 | ].join("\n"); |
| 192 | |
| 193 | /** Magenta-tint equip overlay that clips alpha to the worn body silhouette. */ |
| 194 | /** |
| 195 | * Tight-fit: clip clothing alpha to the body silhouette in *pivot space* |
| 196 | * (sizes may differ: shirt 20×24 vs body 16×24). Sample body UV remapped from |
| 197 | * clothing frame coords; 1px dilate fills armpit/crotch gaps in the body art. |
| 198 | */ |
| 199 | const TIGHT_FIT_BODY_MASK_GLSL = [ |
| 200 | "uniform vec2 u_clothSize;", |
| 201 | "uniform vec2 u_bodySize;", |
| 202 | "uniform float u_pivotFromBottom;", |
| 203 | "uniform vec4 u_clothUvRect;", |
| 204 | "uniform vec4 u_bodyUvRect;", |
| 205 | "float tightFitBodyAlpha() {", |
| 206 | " vec2 clothSpan = max(u_clothUvRect.zw - u_clothUvRect.xy, vec2(1e-5));", |
| 207 | " vec2 nu = (v_texCoord - u_clothUvRect.xy) / clothSpan;", |
| 208 | " float ox = (nu.x - 0.5) * u_clothSize.x;", |
| 209 | " float oy = nu.y * u_clothSize.y - (u_clothSize.y - u_pivotFromBottom);", |
| 210 | " vec2 bodySize = max(u_bodySize, vec2(1.0));", |
| 211 | " vec2 bodyNu = vec2(0.5 + ox / bodySize.x, ((u_bodySize.y - u_pivotFromBottom) + oy) / bodySize.y);", |
| 212 | " vec2 bodySpan = max(u_bodyUvRect.zw - u_bodyUvRect.xy, vec2(1e-5));", |
| 213 | " vec2 texel = 1.0 / bodySize;", |
| 214 | " float bodyA = 0.0;", |
| 215 | " for (int dy = -1; dy <= 1; dy++) {", |
| 216 | " for (int dx = -1; dx <= 1; dx++) {", |
| 217 | " vec2 sampleNu = bodyNu + vec2(float(dx), float(dy)) * texel;", |
| 218 | " if (sampleNu.x < 0.0 || sampleNu.x > 1.0 || sampleNu.y < 0.0 || sampleNu.y > 1.0) { continue; }", |
| 219 | " vec2 sampleUv = u_bodyUvRect.xy + sampleNu * bodySpan;", |
| 220 | " bodyA = max(bodyA, texture2D(u_secondary, sampleUv).a);", |
| 221 | " }", |
| 222 | " }", |
| 223 | " return bodyA;", |
| 224 | "}" |
| 225 | ].join("\n"); |
| 226 | |
| 227 | const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [ |
| 228 | "precision mediump float;", |
| 229 | "varying vec2 v_texCoord;", |
| 230 | "uniform sampler2D u_texture;", |
| 231 | "uniform sampler2D u_secondary;", |
| 232 | "uniform float u_darkness;", |
| 233 | "uniform float u_strength;", |
| 234 | "uniform float u_wade;", |
| 235 | "uniform float u_spriteHeight;", |
| 236 | "uniform float u_useTint;", |
| 237 | "uniform vec3 u_tintColor;", |
| 238 | TIGHT_FIT_BODY_MASK_GLSL, |
| 239 | "void main() {", |
| 240 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 241 | " if (color.a <= 0.0) { discard; }", |
| 242 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 243 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 244 | " vec3 rgb = color.rgb;", |
| 245 | " if (u_useTint > 0.5) {", |
| 246 | " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {", |
| 247 | " float L = color.r;", |
| 248 | " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;", |
| 249 | " float tintLuma = dot(u_tintColor, vec3(0.2126, 0.7152, 0.0722));", |
| 250 | " rgb = mix(u_tintColor, vec3(tintLuma), gBlend) * L;", |
| 251 | " }", |
| 252 | " }", |
| 253 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 254 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 255 | " }", |
| 256 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 257 | " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);", |
| 258 | " float alpha = min(tightFitBodyAlpha(), color.a);", |
| 259 | " if (alpha <= 0.0) { discard; }", |
| 260 | " gl_FragColor = vec4(rgb, alpha);", |
| 261 | "}" |
| 262 | ].join("\n"); |
| 263 | |
| 264 | /** Body-clipped equip overlay without dye recolour. */ |
| 265 | const TIGHT_FIT_LIT_SPRITE_FRAG = [ |
| 266 | "precision mediump float;", |
| 267 | "varying vec2 v_texCoord;", |
| 268 | "uniform sampler2D u_texture;", |
| 269 | "uniform sampler2D u_secondary;", |
| 270 | "uniform float u_darkness;", |
| 271 | "uniform float u_strength;", |
| 272 | "uniform float u_wade;", |
| 273 | "uniform float u_spriteHeight;", |
| 274 | TIGHT_FIT_BODY_MASK_GLSL, |
| 275 | "void main() {", |
| 276 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 277 | " if (color.a <= 0.0) { discard; }", |
| 278 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 279 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 280 | " vec3 rgb = color.rgb;", |
| 281 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 282 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 283 | " }", |
| 284 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 285 | " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);", |
| 286 | " float alpha = min(tightFitBodyAlpha(), color.a);", |
| 287 | " if (alpha <= 0.0) { discard; }", |
| 288 | " gl_FragColor = vec4(rgb, alpha);", |
| 289 | "}" |
| 290 | ].join("\n"); |
| 291 | |
| 292 | const ATLAS_LIGHTING_FRAG = [ |
| 293 | "precision mediump float;", |
| 294 | "varying vec2 v_texCoord;", |
| 295 | "uniform sampler2D u_texture;", |
| 296 | "uniform sampler2D u_secondary;", |
| 297 | "uniform float u_ambientDark;", |
| 298 | "uniform float u_lightRow;", |
| 299 | "void main() {", |
| 300 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 301 | " if (color.a <= 0.0) { discard; }", |
| 302 | " vec2 lightUV = v_texCoord;", |
| 303 | " if (u_lightRow >= 0.0) {", |
| 304 | " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;", |
| 305 | " }", |
| 306 | " float lit = texture2D(u_secondary, lightUV).r;", |
| 307 | " float darkness = u_ambientDark * (1.0 - lit);", |
| 308 | " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);", |
| 309 | " gl_FragColor = vec4(rgb, color.a);", |
| 310 | "}" |
| 311 | ].join("\n"); |
| 312 | |
| 313 | let spriteLightingShader = null; |
| 314 | let atlasLightingShader = null; |
| 315 | let waterGroundShader = null; |
| 316 | let tintLitSpriteShader = null; |
| 317 | let dualTintLitSpriteShader = null; |
| 318 | let tightFitTintLitSpriteShader = null; |
| 319 | let tightFitLitSpriteShader = null; |
| 320 | |
| 321 | function getSpriteLightingShader () |
| 322 | { |
| 323 | if (!spriteLightingShader) |
| 324 | { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); } |
| 325 | return spriteLightingShader; |
| 326 | } |
| 327 | |
| 328 | function getAtlasLightingShader () |
| 329 | { |
| 330 | if (!atlasLightingShader) |
| 331 | { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); } |
| 332 | return atlasLightingShader; |
| 333 | } |
| 334 | |
| 335 | function getWaterGroundShader () |
| 336 | { |
| 337 | if (!waterGroundShader) |
| 338 | { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); } |
| 339 | return waterGroundShader; |
| 340 | } |
| 341 | |
| 342 | function getTintLitSpriteShader () |
| 343 | { |
| 344 | if (!tintLitSpriteShader) |
| 345 | { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); } |
| 346 | return tintLitSpriteShader; |
| 347 | } |
| 348 | |
| 349 | function getDualTintLitSpriteShader () |
| 350 | { |
| 351 | if (!dualTintLitSpriteShader) |
| 352 | { dualTintLitSpriteShader = Shader.fragment(DUAL_TINT_LIT_SPRITE_FRAG); } |
| 353 | return dualTintLitSpriteShader; |
| 354 | } |
| 355 | |
| 356 | function getTightFitTintLitSpriteShader () |
| 357 | { |
| 358 | if (!tightFitTintLitSpriteShader) |
| 359 | { tightFitTintLitSpriteShader = Shader.fragment(TIGHT_FIT_TINT_LIT_SPRITE_FRAG); } |
| 360 | return tightFitTintLitSpriteShader; |
| 361 | } |
| 362 | |
| 363 | function getTightFitLitSpriteShader () |
| 364 | { |
| 365 | if (!tightFitLitSpriteShader) |
| 366 | { tightFitLitSpriteShader = Shader.fragment(TIGHT_FIT_LIT_SPRITE_FRAG); } |
| 367 | return tightFitLitSpriteShader; |
| 368 | } |
| 369 | |
| 370 | export class WorldView |
| 371 | { |
| 372 | #chunkRebuildKeys = new Set(); |
| 373 | #chunkRebuildRaf = 0; |
| 374 | #edgesDirty = false; |
| 375 | #CHUNK_REBUILD_BATCH = 2; |
| 376 | #pendingTextureCanvases = []; |
| 377 | #pendingTextureCanvasSet = new Set(); |
| 378 | #textureWarmRaf = 0; |
| 379 | #TEXTURE_WARM_BATCH = 3; |
| 380 | #atlasCache = createChunkAtlasCache(); |
| 381 | #idlePrefetchId = 0; |
| 382 | #playerChunkX = null; |
| 383 | #playerChunkY = null; |
| 384 | #playerMoveChunkDx = 0; |
| 385 | #playerMoveChunkDy = 0; |
| 386 | |
| 387 | constructor(game, scene, catalog = { grounds: {}, blocks: {} }) |
| 388 | { |
| 389 | this.game = game; |
| 390 | this.scene = scene; |
| 391 | this.catalog = catalog; |
| 392 | this.preview = null; |
| 393 | this.zoom = 2; |
| 394 | this.chunks = new Map(); |
| 395 | this.bakedChunks = new Map(); |
| 396 | this.tiles = new Map(); |
| 397 | this.entities = new Map(); |
| 398 | this.groundItems = new Map(); |
| 399 | this.edges = new Map(); |
| 400 | this.localEntityId = null; |
| 401 | this.localBlind = false; |
| 402 | /** @type {string} */ |
| 403 | this.dimensionId = OVERWORLD_ID; |
| 404 | /** @type {string} */ |
| 405 | this.dimensionLightingMode = "dayNight"; |
| 406 | /** @type {string} */ |
| 407 | this.dimensionSeasonMode = "auto"; |
| 408 | /** Calendar season from worldStatus when dimension season is auto. */ |
| 409 | this.calendarSeason = seasonIdAt(); |
| 410 | /** @type {"soft"|"simple"} */ |
| 411 | this.lightingMode = "soft"; |
| 412 | /** @type {boolean} */ |
| 413 | this.bloomEnabled = true; |
| 414 | /** Soft edge blend for blendable grounds (grass, dirt, …). */ |
| 415 | this.softTerrain = false; |
| 416 | this.settings = { ...DEFAULT_WORLD_SETTINGS }; |
| 417 | this.worldHour = 12; |
| 418 | /** Calendar season for seasonal ground/block visuals (`spring` / `summer` / `fall` / `winter`). */ |
| 419 | this.worldSeason = seasonIdAt(); |
| 420 | this.nightPreview = null; |
| 421 | this.followPlayer = true; |
| 422 | this.dynamicLights = []; |
| 423 | this.swipes = []; |
| 424 | this.damageFloats = []; |
| 425 | this.damageNumbersEl = document.getElementById("damage-numbers"); |
| 426 | this.skillLevelFloats = []; |
| 427 | this.skillLevelFloatsEl = document.getElementById("skill-level-floats"); |
| 428 | /** @type {Map<string, { object: object, tileX: number, tileY: number, spriteName: string }>} */ |
| 429 | this.editorSpawners = new Map(); |
| 430 | this.spawnRangeHighlight = null; |
| 431 | this.wanderRangeHighlight = null; |
| 432 | this.spellTargetHighlight = null; |
| 433 | this.#syncBloomLayer(); |
| 434 | } |
| 435 | |
| 436 | setSettings (settings) |
| 437 | { |
| 438 | this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings }; |
| 439 | this.#syncBloomLayer(); |
| 440 | } |
| 441 | |
| 442 | /** |
| 443 | * Client graphics prefs (lighting Soft/Simple, bloom On/Off, soft terrain). |
| 444 | * @param {{ lighting?: string, bloom?: string, softTerrain?: string }} prefs |
| 445 | */ |
| 446 | setGraphicsPrefs (prefs) |
| 447 | { |
| 448 | if (prefs?.lighting === "simple" || prefs?.lighting === "soft") |
| 449 | { this.lightingMode = prefs.lighting; } |
| 450 | if (prefs?.bloom === "off" || prefs?.bloom === "on") |
| 451 | { |
| 452 | const enabled = prefs.bloom !== "off"; |
| 453 | if (enabled !== this.bloomEnabled) |
| 454 | { |
| 455 | this.bloomEnabled = enabled; |
| 456 | this.#syncBloomLayer(); |
| 457 | } |
| 458 | else |
| 459 | { this.bloomEnabled = enabled; } |
| 460 | } |
| 461 | if (prefs?.softTerrain === "on" || prefs?.softTerrain === "off") |
| 462 | { |
| 463 | const enabled = prefs.softTerrain === "on"; |
| 464 | if (enabled !== this.softTerrain) |
| 465 | { |
| 466 | this.softTerrain = enabled; |
| 467 | this.#rebakeAllChunks(); |
| 468 | } |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | /** Apply server (or local) calendar season; rebakes chunks when it changes. */ |
| 473 | setWorldSeason (season) |
| 474 | { |
| 475 | const calendar = season === SeasonId.spring |
| 476 | || season === SeasonId.fall |
| 477 | || season === SeasonId.winter |
| 478 | || season === SeasonId.summer |
| 479 | ? season |
| 480 | : seasonIdAt(); |
| 481 | this.calendarSeason = calendar; |
| 482 | const forced = resolveDimensionSeasonId(this.dimensionSeasonMode); |
| 483 | const next = forced ?? calendar; |
| 484 | if (next === this.worldSeason) |
| 485 | { return; } |
| 486 | this.worldSeason = next; |
| 487 | this.#rebakeAllChunks(); |
| 488 | } |
| 489 | |
| 490 | setDimensionId (dimensionId) |
| 491 | { |
| 492 | this.dimensionId = normalizeDimensionId(dimensionId); |
| 493 | } |
| 494 | |
| 495 | setDimensionModes (lightingMode, seasonMode) |
| 496 | { |
| 497 | this.dimensionLightingMode = normalizeLightingMode(lightingMode); |
| 498 | this.dimensionSeasonMode = normalizeSeasonMode(seasonMode); |
| 499 | const forced = resolveDimensionSeasonId(this.dimensionSeasonMode); |
| 500 | const next = forced ?? this.calendarSeason ?? seasonIdAt(); |
| 501 | if (next !== this.worldSeason) |
| 502 | { |
| 503 | this.worldSeason = next; |
| 504 | this.#rebakeAllChunks(); |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | clearAllChunks () |
| 509 | { |
| 510 | for (const key of [...this.chunks.keys()]) |
| 511 | { |
| 512 | const [chunkX, chunkY] = key.split(",").map(Number); |
| 513 | this.removeChunk(chunkX, chunkY); |
| 514 | } |
| 515 | for (const [id] of [...this.entities.entries()]) |
| 516 | { |
| 517 | if (id === this.localEntityId) |
| 518 | { continue; } |
| 519 | this.despawnEntity(id); |
| 520 | } |
| 521 | for (const [id] of [...this.groundItems.entries()]) |
| 522 | { this.despawnGroundItem(id); } |
| 523 | } |
| 524 | |
| 525 | /** Full client wipe when leaving the world (menu / disconnect). Includes the local player. */ |
| 526 | clearPlaySession () |
| 527 | { |
| 528 | this.#cancelIdlePrefetch(); |
| 529 | this.#chunkRebuildKeys.clear(); |
| 530 | this.#playerChunkX = null; |
| 531 | this.#playerChunkY = null; |
| 532 | this.#playerMoveChunkDx = 0; |
| 533 | this.#playerMoveChunkDy = 0; |
| 534 | this.localEntityId = null; |
| 535 | for (const key of [...this.chunks.keys()]) |
| 536 | { |
| 537 | const [chunkX, chunkY] = key.split(",").map(Number); |
| 538 | this.removeChunk(chunkX, chunkY); |
| 539 | } |
| 540 | for (const [id] of [...this.entities.entries()]) |
| 541 | { this.despawnEntity(id); } |
| 542 | for (const [id] of [...this.groundItems.entries()]) |
| 543 | { this.despawnGroundItem(id); } |
| 544 | } |
| 545 | |
| 546 | applySnapshot (snapshot) |
| 547 | { |
| 548 | const snapDim = normalizeDimensionId(snapshot.dimensionId ?? OVERWORLD_ID); |
| 549 | if (normalizeDimensionId(this.dimensionId) !== snapDim) |
| 550 | { return; } |
| 551 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 552 | if (!Array.isArray(snapshot.occlusion) || snapshot.occlusion.length < CHUNK_SIZE * CHUNK_SIZE) |
| 553 | { |
| 554 | snapshot.occlusion = bakeChunkOcclusion(snapshot); |
| 555 | } |
| 556 | this.chunks.set(key, snapshot); |
| 557 | this.#scheduleChunkRebuild(snapshot); |
| 558 | this.#redrawPreview(); |
| 559 | this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY); |
| 560 | if (snapshot.staticOnly) |
| 561 | { |
| 562 | this.#stripChunkDynamic(snapshot.chunkX, snapshot.chunkY); |
| 563 | this.#scheduleEdgeRebuild(); |
| 564 | return; |
| 565 | } |
| 566 | for (const entity of snapshot.entities ?? []) |
| 567 | { this.#upsertEntity(entity); } |
| 568 | for (const [id, item] of [...this.groundItems.entries()]) |
| 569 | { |
| 570 | if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY) |
| 571 | { this.despawnGroundItem(id); } |
| 572 | } |
| 573 | for (const item of snapshot.groundItems ?? []) |
| 574 | { this.upsertGroundItem(item); } |
| 575 | this.#scheduleEdgeRebuild(); |
| 576 | } |
| 577 | |
| 578 | setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null) |
| 579 | { |
| 580 | this.localEntityId = entityId; |
| 581 | this.#upsertEntity({ |
| 582 | entityId, |
| 583 | characterId, |
| 584 | tileX, |
| 585 | tileY, |
| 586 | gait, |
| 587 | sex, |
| 588 | firstName, |
| 589 | lastName, |
| 590 | layers: layers ?? undefined, |
| 591 | ...(health != null ? { health } : {}), |
| 592 | ...(maxHealth != null ? { maxHealth } : {}) |
| 593 | }); |
| 594 | this.#notePlayerTile(tileX, tileY); |
| 595 | } |
| 596 | |
| 597 | #stripChunkDynamic (chunkX, chunkY) |
| 598 | { |
| 599 | for (const [id, item] of [...this.groundItems.entries()]) |
| 600 | { |
| 601 | if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) |
| 602 | { this.despawnGroundItem(id); } |
| 603 | } |
| 604 | for (const [id, entity] of [...this.entities.entries()]) |
| 605 | { |
| 606 | if (id === this.localEntityId) |
| 607 | { continue; } |
| 608 | if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX |
| 609 | && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY) |
| 610 | { this.despawnEntity(id); } |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | removeChunk (chunkX, chunkY) |
| 615 | { |
| 616 | const key = `${chunkX},${chunkY}`; |
| 617 | this.chunks.delete(key); |
| 618 | this.#destroyBakedChunk(key); |
| 619 | this.#destroyEdges(key); |
| 620 | const prefix = `${chunkX},${chunkY}:`; |
| 621 | for (const [spawnerKey, entry] of [...this.editorSpawners.entries()]) |
| 622 | { |
| 623 | if (!spawnerKey.startsWith(prefix)) |
| 624 | { continue; } |
| 625 | entry.object?.destroy(); |
| 626 | this.editorSpawners.delete(spawnerKey); |
| 627 | } |
| 628 | for (const [tileKey, objects] of [...this.tiles.entries()]) |
| 629 | { |
| 630 | if (objects.chunkX === chunkX && objects.chunkY === chunkY) |
| 631 | { |
| 632 | objects.ground?.destroy(); |
| 633 | objects.groundBloom?.destroy(); |
| 634 | objects.block?.destroy(); |
| 635 | objects.blockBloom?.destroy(); |
| 636 | this.tiles.delete(tileKey); |
| 637 | } |
| 638 | } |
| 639 | for (const [id, item] of [...this.groundItems.entries()]) |
| 640 | { |
| 641 | if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) |
| 642 | { this.despawnGroundItem(id); } |
| 643 | } |
| 644 | // Server sends unsubscribeChunk when a chunk leaves the static 5×5 ring. |
| 645 | // Entity replication is limited to the inner 3×3; static-only chunks strip dynamics via staticOnly snapshots. |
| 646 | for (const [id, entity] of [...this.entities.entries()]) |
| 647 | { |
| 648 | if (id === this.localEntityId) |
| 649 | { continue; } |
| 650 | if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX |
| 651 | && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY) |
| 652 | { this.despawnEntity(id); } |
| 653 | } |
| 654 | this.#rebuildAllEdges(); |
| 655 | } |
| 656 | |
| 657 | setChunkOpen (chunkX, chunkY, open) |
| 658 | { |
| 659 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 660 | if (!snapshot) |
| 661 | { return; } |
| 662 | snapshot.open = !!open; |
| 663 | this.#rebuildAllEdges(); |
| 664 | } |
| 665 | |
| 666 | spawnEntity (payload) |
| 667 | { |
| 668 | this.#upsertEntity(payload); |
| 669 | } |
| 670 | |
| 671 | moveEntity (payload) |
| 672 | { |
| 673 | const existing = this.entities.get(payload.entityId); |
| 674 | if (!existing) |
| 675 | { |
| 676 | this.#upsertEntity(payload); |
| 677 | return; |
| 678 | } |
| 679 | const size = this.tileSize(); |
| 680 | existing.fromX = existing.visualX; |
| 681 | existing.fromY = existing.visualY; |
| 682 | existing.shadeFromTileX = existing.tileX; |
| 683 | existing.shadeFromTileY = existing.tileY; |
| 684 | existing.tileX = payload.tileX; |
| 685 | existing.tileY = payload.tileY; |
| 686 | existing.gait = payload.gait; |
| 687 | existing.freeFlight = !!payload.freeFlight || existing.freeFlight; |
| 688 | if (payload.worldX != null && payload.worldY != null) |
| 689 | { |
| 690 | existing.worldX = payload.worldX; |
| 691 | existing.worldY = payload.worldY; |
| 692 | existing.targetX = payload.worldX * size; |
| 693 | existing.targetY = payload.worldY * size; |
| 694 | } |
| 695 | else |
| 696 | { |
| 697 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 698 | existing.targetX = pivot.x; |
| 699 | existing.targetY = pivot.y; |
| 700 | } |
| 701 | existing.lerpStarted = performance.now(); |
| 702 | existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait); |
| 703 | if (payload.entityId === this.localEntityId) |
| 704 | { this.#notePlayerTile(payload.tileX, payload.tileY); } |
| 705 | } |
| 706 | |
| 707 | despawnEntity (entityId) |
| 708 | { |
| 709 | const existing = this.entities.get(entityId); |
| 710 | if (!existing) |
| 711 | { return; } |
| 712 | existing.object?.destroy(); |
| 713 | existing.hpBar?.destroy(); |
| 714 | for (const overlay of existing.overlays ?? []) |
| 715 | { overlay.destroy(); } |
| 716 | for (const overlay of existing.bloomOverlays ?? []) |
| 717 | { overlay.destroy(); } |
| 718 | this.entities.delete(entityId); |
| 719 | } |
| 720 | |
| 721 | updateEntityHealth (entityId, health, maxHealth) |
| 722 | { |
| 723 | const entity = this.entities.get(entityId); |
| 724 | if (!entity) |
| 725 | { return; } |
| 726 | entity.health = health; |
| 727 | entity.maxHealth = maxHealth; |
| 728 | this.#syncHpBar(entity); |
| 729 | } |
| 730 | |
| 731 | flashDamage (entityId) |
| 732 | { |
| 733 | const entity = this.entities.get(entityId); |
| 734 | if (!entity) |
| 735 | { return; } |
| 736 | entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS; |
| 737 | } |
| 738 | |
| 739 | spawnDamageNumber (entityId, damage) |
| 740 | { |
| 741 | const amount = damage | 0; |
| 742 | if (amount <= 0) |
| 743 | { return; } |
| 744 | this.damageFloats.push({ |
| 745 | entityId, |
| 746 | damage: amount, |
| 747 | started: performance.now() |
| 748 | }); |
| 749 | } |
| 750 | |
| 751 | /** |
| 752 | * Queue combat-hit presentation until a matching in-flight projectile lands. |
| 753 | * Returns true when deferred; caller should apply immediately when false. |
| 754 | */ |
| 755 | deferCombatHit (message, apply) |
| 756 | { |
| 757 | if (typeof apply !== "function" || message?.targetId == null) |
| 758 | { return false; } |
| 759 | const attackerId = message.attackerId ?? null; |
| 760 | const targetId = message.targetId; |
| 761 | const swipe = this.swipes.find((entry) => |
| 762 | entry.lerp |
| 763 | && entry.onImpact == null |
| 764 | && entry.targetId === targetId |
| 765 | && (attackerId == null || entry.attackerId === attackerId) |
| 766 | && (entry.until ?? 0) > performance.now()); |
| 767 | if (!swipe) |
| 768 | { return false; } |
| 769 | swipe.onImpact = apply; |
| 770 | swipe.trackTarget = true; |
| 771 | return true; |
| 772 | } |
| 773 | |
| 774 | /** Stop tracking a living target (misses fly to a fixed tile). */ |
| 775 | markProjectileMiss (message) |
| 776 | { |
| 777 | const attackerId = message?.attackerId ?? null; |
| 778 | const targetId = message?.targetId ?? null; |
| 779 | for (const swipe of this.swipes) |
| 780 | { |
| 781 | if (!swipe.lerp || swipe.onImpact != null) |
| 782 | { continue; } |
| 783 | if (targetId != null && swipe.targetId !== targetId) |
| 784 | { continue; } |
| 785 | if (attackerId != null && swipe.attackerId !== attackerId) |
| 786 | { continue; } |
| 787 | swipe.trackTarget = false; |
| 788 | if (message.tileX != null) |
| 789 | { swipe.tileX = message.tileX; } |
| 790 | if (message.tileY != null) |
| 791 | { swipe.tileY = message.tileY; } |
| 792 | } |
| 793 | } |
| 794 | |
| 795 | spawnSkillLevelUp (entityId, payload) |
| 796 | { |
| 797 | const level = payload?.level | 0; |
| 798 | if (level <= 0 || !payload?.icon) |
| 799 | { return; } |
| 800 | this.skillLevelFloats.push({ |
| 801 | entityId, |
| 802 | level, |
| 803 | icon: payload.icon, |
| 804 | displayName: payload.displayName ?? payload.skillId ?? "", |
| 805 | started: performance.now() |
| 806 | }); |
| 807 | } |
| 808 | |
| 809 | setAppearance (payload) |
| 810 | { |
| 811 | const existing = this.entities.get(payload.entityId); |
| 812 | if (!existing) |
| 813 | { return; } |
| 814 | existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0; |
| 815 | if (payload.visualScale != null) |
| 816 | { existing.visualScale = Number(payload.visualScale) || 1; } |
| 817 | this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]); |
| 818 | this.#placeEntity(existing); |
| 819 | } |
| 820 | |
| 821 | /** |
| 822 | * Render the live entity (body + overlays, same tint/tight-fit shaders as the |
| 823 | * world, unlit) into an offscreen FBO, crop the top square, and return a |
| 824 | * pixel-scaled canvas for UI (e.g. dialogue speaker icons). |
| 825 | * @param {number} entityId |
| 826 | * @param {{ size?: number }} [options] |
| 827 | * @returns {HTMLCanvasElement | null} |
| 828 | */ |
| 829 | captureEntityPortrait (entityId, { size = 64 } = {}) |
| 830 | { |
| 831 | const entity = this.entities.get(entityId); |
| 832 | const body = entity?.object?.renderer?.sprite; |
| 833 | const glCtx = this.scene?.glContext; |
| 834 | const gl = glCtx?.gl; |
| 835 | if (!entity || !body || !gl) |
| 836 | { return null; } |
| 837 | |
| 838 | const frameW = Math.max(1, body.width | 0 || SPRITE_SIZE_PX); |
| 839 | const frameH = Math.max(1, body.height | 0 || SPRITE_SIZE_PX); |
| 840 | if (!this.#ensurePortraitTarget(gl, frameW, frameH)) |
| 841 | { return null; } |
| 842 | |
| 843 | const prevFb = gl.getParameter(gl.FRAMEBUFFER_BINDING); |
| 844 | const prevViewport = gl.getParameter(gl.VIEWPORT); |
| 845 | const prevW = glCtx._lastWidth; |
| 846 | const prevH = glCtx._lastHeight; |
| 847 | const prevBlend = gl.isEnabled(gl.BLEND); |
| 848 | |
| 849 | try |
| 850 | { |
| 851 | // drawSprite projects with _lastWidth/_lastHeight — match the FBO. |
| 852 | glCtx._lastWidth = frameW; |
| 853 | glCtx._lastHeight = frameH; |
| 854 | gl.bindFramebuffer(gl.FRAMEBUFFER, this._portrait.fb); |
| 855 | gl.viewport(0, 0, frameW, frameH); |
| 856 | gl.enable(gl.BLEND); |
| 857 | gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); |
| 858 | gl.clearColor(0, 0, 0, 0); |
| 859 | gl.clear(gl.COLOR_BUFFER_BIT); |
| 860 | |
| 861 | const pivotX = frameW * 0.5; |
| 862 | const pivotY = frameH - PIVOT_FROM_BOTTOM_PX; |
| 863 | this._portraitBodyMap = body.g_image ?? null; |
| 864 | this._portraitTightFitEntity = entity; |
| 865 | this.#drawPortraitLayer(glCtx, entity.object, pivotX, pivotY, null, false); |
| 866 | |
| 867 | const overlays = entity.overlays ?? []; |
| 868 | const tints = entity.overlayTints ?? []; |
| 869 | const dualTints = entity.overlayDualTints ?? []; |
| 870 | const tight = entity.overlayTightFit ?? []; |
| 871 | for (let index = 0; index < overlays.length; index++) |
| 872 | { |
| 873 | this.#drawPortraitLayer( |
| 874 | glCtx, |
| 875 | overlays[index], |
| 876 | pivotX, |
| 877 | pivotY, |
| 878 | tints[index] ?? null, |
| 879 | !!tight[index], |
| 880 | dualTints[index] ?? null |
| 881 | ); |
| 882 | } |
| 883 | this._portraitBodyMap = null; |
| 884 | this._portraitTightFitEntity = null; |
| 885 | |
| 886 | const pixels = this._portrait.pixels; |
| 887 | gl.readPixels(0, 0, frameW, frameH, gl.RGBA, gl.UNSIGNED_BYTE, pixels); |
| 888 | } |
| 889 | finally |
| 890 | { |
| 891 | glCtx._lastWidth = prevW; |
| 892 | glCtx._lastHeight = prevH; |
| 893 | gl.bindFramebuffer(gl.FRAMEBUFFER, prevFb); |
| 894 | gl.viewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]); |
| 895 | if (!prevBlend) |
| 896 | { gl.disable(gl.BLEND); } |
| 897 | gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); |
| 898 | } |
| 899 | |
| 900 | return this.#portraitPixelsToCanvas(frameW, frameH, size); |
| 901 | } |
| 902 | |
| 903 | #ensurePortraitTarget (gl, width, height) |
| 904 | { |
| 905 | const prev = this._portrait; |
| 906 | if (prev && prev.w === width && prev.h === height && prev.fb && prev.tex) |
| 907 | { return true; } |
| 908 | if (prev?.fb) |
| 909 | { gl.deleteFramebuffer(prev.fb); } |
| 910 | if (prev?.tex) |
| 911 | { gl.deleteTexture(prev.tex); } |
| 912 | |
| 913 | const tex = gl.createTexture(); |
| 914 | gl.bindTexture(gl.TEXTURE_2D, tex); |
| 915 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); |
| 916 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); |
| 917 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); |
| 918 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); |
| 919 | gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); |
| 920 | |
| 921 | const fb = gl.createFramebuffer(); |
| 922 | gl.bindFramebuffer(gl.FRAMEBUFFER, fb); |
| 923 | gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0); |
| 924 | const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); |
| 925 | gl.bindFramebuffer(gl.FRAMEBUFFER, null); |
| 926 | if (status !== gl.FRAMEBUFFER_COMPLETE) |
| 927 | { |
| 928 | gl.deleteFramebuffer(fb); |
| 929 | gl.deleteTexture(tex); |
| 930 | this._portrait = null; |
| 931 | return false; |
| 932 | } |
| 933 | this._portrait = { |
| 934 | fb, |
| 935 | tex, |
| 936 | w: width, |
| 937 | h: height, |
| 938 | pixels: new Uint8Array(width * height * 4), |
| 939 | scratch: document.createElement("canvas") |
| 940 | }; |
| 941 | return true; |
| 942 | } |
| 943 | |
| 944 | #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit, dualTint = null) |
| 945 | { |
| 946 | const sprite = object?.renderer?.sprite; |
| 947 | if (!sprite?.g_image) |
| 948 | { return; } |
| 949 | const subImage = object.renderer.subImage | 0; |
| 950 | const height = sprite.height || SPRITE_SIZE_PX; |
| 951 | const draw = spriteDrawSize(sprite.width, sprite.height, 1); |
| 952 | const center = spriteCenterFromPivot(pivotX, pivotY, height, 1); |
| 953 | const tint = tintColor ? normalizeRgb(tintColor) : null; |
| 954 | let shader = glCtx.defaultShader; |
| 955 | let uniforms = null; |
| 956 | let secondaryHtml = null; |
| 957 | |
| 958 | const bodyHtml = this._portraitBodyMap; |
| 959 | const portraitEntity = this._portraitTightFitEntity; |
| 960 | const maskUniforms = tightFit && portraitEntity |
| 961 | ? this.#tightFitMaskUniforms(object, portraitEntity) |
| 962 | : null; |
| 963 | if (dualTint) |
| 964 | { |
| 965 | const shaft = normalizeRgb(dualTint.shaft); |
| 966 | const tip = normalizeRgb(dualTint.tip); |
| 967 | shader = getDualTintLitSpriteShader(); |
| 968 | uniforms = { |
| 969 | u_darkness: 0, |
| 970 | u_strength: 0, |
| 971 | u_wade: 0, |
| 972 | u_spriteHeight: height, |
| 973 | u_shaftTint: [shaft.r, shaft.g, shaft.b], |
| 974 | u_tipTint: [tip.r, tip.g, tip.b] |
| 975 | }; |
| 976 | } |
| 977 | else if (tightFit && bodyHtml && maskUniforms) |
| 978 | { |
| 979 | secondaryHtml = bodyHtml; |
| 980 | if (tint) |
| 981 | { |
| 982 | shader = getTightFitTintLitSpriteShader(); |
| 983 | uniforms = { |
| 984 | u_darkness: 0, |
| 985 | u_strength: 0, |
| 986 | u_wade: 0, |
| 987 | u_spriteHeight: height, |
| 988 | u_useTint: 1, |
| 989 | u_tintColor: [tint.r, tint.g, tint.b], |
| 990 | ...maskUniforms |
| 991 | }; |
| 992 | } |
| 993 | else |
| 994 | { |
| 995 | shader = getTightFitLitSpriteShader(); |
| 996 | uniforms = { |
| 997 | u_darkness: 0, |
| 998 | u_strength: 0, |
| 999 | u_wade: 0, |
| 1000 | u_spriteHeight: height, |
| 1001 | ...maskUniforms |
| 1002 | }; |
| 1003 | } |
| 1004 | } |
| 1005 | else if (tint) |
| 1006 | { |
| 1007 | shader = getTintLitSpriteShader(); |
| 1008 | uniforms = { |
| 1009 | u_darkness: 0, |
| 1010 | u_strength: 0, |
| 1011 | u_wade: 0, |
| 1012 | u_spriteHeight: height, |
| 1013 | u_useTint: 1, |
| 1014 | u_tintColor: [tint.r, tint.g, tint.b] |
| 1015 | }; |
| 1016 | } |
| 1017 | else |
| 1018 | { |
| 1019 | shader = getSpriteLightingShader(); |
| 1020 | uniforms = { |
| 1021 | u_darkness: 0, |
| 1022 | u_strength: 0, |
| 1023 | u_wade: 0, |
| 1024 | u_spriteHeight: height |
| 1025 | }; |
| 1026 | } |
| 1027 | |
| 1028 | glCtx.drawSprite({ |
| 1029 | texture: glCtx.getTexture(sprite.g_image), |
| 1030 | x: center.x, |
| 1031 | y: center.y, |
| 1032 | w: draw.w, |
| 1033 | h: draw.h, |
| 1034 | rotationDeg: 0, |
| 1035 | mirrorX: false, |
| 1036 | mirrorY: false, |
| 1037 | alpha: 1, |
| 1038 | uvRect: sprite.getUvRect(subImage), |
| 1039 | shader, |
| 1040 | uniforms, |
| 1041 | textures: secondaryHtml ? { u_secondary: glCtx.getTexture(secondaryHtml) } : null, |
| 1042 | lights: null |
| 1043 | }); |
| 1044 | } |
| 1045 | |
| 1046 | #portraitPixelsToCanvas (frameW, frameH, size) |
| 1047 | { |
| 1048 | const pixels = this._portrait?.pixels; |
| 1049 | if (!pixels) |
| 1050 | { return null; } |
| 1051 | const scratch = this._portrait.scratch; |
| 1052 | scratch.width = frameW; |
| 1053 | scratch.height = frameH; |
| 1054 | const sctx = scratch.getContext("2d"); |
| 1055 | const imageData = sctx.createImageData(frameW, frameH); |
| 1056 | // WebGL y=0 is bottom — flip to top-down image order. |
| 1057 | for (let y = 0; y < frameH; y++) |
| 1058 | { |
| 1059 | const src = (frameH - 1 - y) * frameW * 4; |
| 1060 | const dst = y * frameW * 4; |
| 1061 | imageData.data.set(pixels.subarray(src, src + frameW * 4), dst); |
| 1062 | } |
| 1063 | sctx.putImageData(imageData, 0, 0); |
| 1064 | |
| 1065 | const crop = Math.min(frameW, frameH); |
| 1066 | const out = document.createElement("canvas"); |
| 1067 | out.width = size; |
| 1068 | out.height = size; |
| 1069 | const octx = out.getContext("2d"); |
| 1070 | octx.imageSmoothingEnabled = false; |
| 1071 | octx.clearRect(0, 0, size, size); |
| 1072 | octx.drawImage(scratch, 0, 0, crop, crop, 0, 0, size, size); |
| 1073 | return out; |
| 1074 | } |
| 1075 | |
| 1076 | upsertGroundItem (payload) |
| 1077 | { |
| 1078 | const size = this.tileSize(); |
| 1079 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 1080 | const potion = payload.instance?.kind === "potion" ? payload.instance : null; |
| 1081 | const spriteName = potion |
| 1082 | ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`) |
| 1083 | : (payload.sprite ?? itemSpriteName(payload.itemId, payload.instance)); |
| 1084 | let item = this.groundItems.get(payload.groundItemId); |
| 1085 | if (!item) |
| 1086 | { |
| 1087 | const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK); |
| 1088 | this.scene.addObject(object); |
| 1089 | item = { object }; |
| 1090 | this.groundItems.set(payload.groundItemId, item); |
| 1091 | } |
| 1092 | else if (item.object && this.game.images[spriteName]) |
| 1093 | { item.object.image = this.game.images[spriteName]; } |
| 1094 | item.groundItemId = payload.groundItemId; |
| 1095 | item.tileX = payload.tileX; |
| 1096 | item.tileY = payload.tileY; |
| 1097 | item.itemId = payload.itemId; |
| 1098 | item.quantity = payload.quantity; |
| 1099 | item.displayName = payload.displayName; |
| 1100 | item.sprite = spriteName; |
| 1101 | item.instance = payload.instance ?? null; |
| 1102 | const stack = { itemId: payload.itemId, instance: payload.instance ?? null }; |
| 1103 | item.dualTint = resolveItemDualTint(stack, itemDefinition(payload.itemId)); |
| 1104 | item.tintColor = item.dualTint ? null : resolveItemTint(stack, itemDefinition(payload.itemId)); |
| 1105 | this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); |
| 1106 | this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0); |
| 1107 | } |
| 1108 | |
| 1109 | despawnGroundItem (groundItemId) |
| 1110 | { |
| 1111 | const item = this.groundItems.get(groundItemId); |
| 1112 | if (!item) |
| 1113 | { return; } |
| 1114 | item.object?.destroy(); |
| 1115 | this.groundItems.delete(groundItemId); |
| 1116 | } |
| 1117 | |
| 1118 | groundItemAtTile (tileX, tileY) |
| 1119 | { |
| 1120 | return this.groundItemsAtTile(tileX, tileY)[0] ?? null; |
| 1121 | } |
| 1122 | |
| 1123 | groundItemsAtTile (tileX, tileY) |
| 1124 | { |
| 1125 | const items = []; |
| 1126 | for (const item of this.groundItems.values()) |
| 1127 | { |
| 1128 | if (item.tileX === tileX && item.tileY === tileY) |
| 1129 | { items.push(item); } |
| 1130 | } |
| 1131 | return items; |
| 1132 | } |
| 1133 | |
| 1134 | entitiesAtTile (tileX, tileY) |
| 1135 | { |
| 1136 | const matches = []; |
| 1137 | for (const entity of this.entities.values()) |
| 1138 | { |
| 1139 | if (entity.tileX === tileX && entity.tileY === tileY) |
| 1140 | { matches.push(entity); } |
| 1141 | } |
| 1142 | matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0)); |
| 1143 | return matches; |
| 1144 | } |
| 1145 | |
| 1146 | setZoom (zoom, limits = { min: 2, max: 4 }) |
| 1147 | { |
| 1148 | const min = limits.min ?? 1; |
| 1149 | const max = limits.max ?? 4; |
| 1150 | this.zoom = Math.min(max, Math.max(min, zoom)); |
| 1151 | for (const snapshot of this.chunks.values()) |
| 1152 | { this.#relayoutChunk(snapshot); } |
| 1153 | const size = this.tileSize(); |
| 1154 | for (const entity of this.entities.values()) |
| 1155 | { |
| 1156 | entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x; |
| 1157 | entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y; |
| 1158 | entity.fromX = entity.visualX; |
| 1159 | entity.fromY = entity.visualY; |
| 1160 | entity.targetX = entity.visualX; |
| 1161 | entity.targetY = entity.visualY; |
| 1162 | entity.lerpStarted = null; |
| 1163 | this.#placeEntity(entity); |
| 1164 | } |
| 1165 | for (const item of this.groundItems.values()) |
| 1166 | { |
| 1167 | const pivot = tilePivot(item.tileX, item.tileY, size); |
| 1168 | this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); |
| 1169 | } |
| 1170 | this.#rebuildAllEdges(); |
| 1171 | this.#relayoutEditorSpawners(); |
| 1172 | this.#relayoutSpawnRangeHighlight(); |
| 1173 | this.#relayoutSpellTargetHighlight(); |
| 1174 | } |
| 1175 | |
| 1176 | tileSize () |
| 1177 | { |
| 1178 | return SPRITE_SIZE_PX * this.zoom; |
| 1179 | } |
| 1180 | |
| 1181 | screenToTile (mouseX, mouseY) |
| 1182 | { |
| 1183 | const size = this.tileSize(); |
| 1184 | const worldX = mouseX - this.scene.cameraPosition.x; |
| 1185 | const worldY = mouseY - this.scene.cameraPosition.y; |
| 1186 | return { |
| 1187 | tileX: Math.floor(worldX / size), |
| 1188 | tileY: Math.floor(worldY / size) |
| 1189 | }; |
| 1190 | } |
| 1191 | |
| 1192 | entityAtScreen (mouseX, mouseY) |
| 1193 | { |
| 1194 | let best = null; |
| 1195 | let bestLayer = -Infinity; |
| 1196 | for (const entity of this.entities.values()) |
| 1197 | { |
| 1198 | const box = this.#entityScreenBox(entity); |
| 1199 | if (!box) |
| 1200 | { continue; } |
| 1201 | if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom) |
| 1202 | { |
| 1203 | const layer = entity.object?.layer ?? 0; |
| 1204 | if (layer >= bestLayer) |
| 1205 | { |
| 1206 | best = entity; |
| 1207 | bestLayer = layer; |
| 1208 | } |
| 1209 | } |
| 1210 | } |
| 1211 | return best; |
| 1212 | } |
| 1213 | |
| 1214 | nametagAnchor (entity) |
| 1215 | { |
| 1216 | const box = this.#entityScreenBox(entity); |
| 1217 | if (!box) |
| 1218 | { return null; } |
| 1219 | return { x: (box.left + box.right) / 2, y: box.top }; |
| 1220 | } |
| 1221 | |
| 1222 | #entityScreenBox (entity) |
| 1223 | { |
| 1224 | const object = entity?.object; |
| 1225 | if (!object) |
| 1226 | { return null; } |
| 1227 | const size = object.transform.size; |
| 1228 | const x = object.transform.position.x + this.scene.cameraPosition.x; |
| 1229 | const y = object.transform.position.y + this.scene.cameraPosition.y; |
| 1230 | return { |
| 1231 | left: x - size.x / 2, |
| 1232 | right: x + size.x / 2, |
| 1233 | top: y - size.y / 2, |
| 1234 | bottom: y + size.y / 2 |
| 1235 | }; |
| 1236 | } |
| 1237 | |
| 1238 | update (deltaTime) |
| 1239 | { |
| 1240 | const now = performance.now(); |
| 1241 | const size = this.tileSize(); |
| 1242 | this.#refreshStackTargets(); |
| 1243 | for (const entity of this.entities.values()) |
| 1244 | { |
| 1245 | const target = entity.targetX != null && entity.targetY != null |
| 1246 | ? { x: entity.targetX, y: entity.targetY } |
| 1247 | : tilePivot(entity.tileX, entity.tileY, size); |
| 1248 | if (entity.lerpStarted != null) |
| 1249 | { |
| 1250 | const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs)); |
| 1251 | entity.visualX = entity.fromX + (target.x - entity.fromX) * t; |
| 1252 | entity.visualY = entity.fromY + (target.y - entity.fromY) * t; |
| 1253 | if (t >= 1) |
| 1254 | { entity.lerpStarted = null; } |
| 1255 | } |
| 1256 | else |
| 1257 | { |
| 1258 | entity.visualX = target.x; |
| 1259 | entity.visualY = target.y; |
| 1260 | } |
| 1261 | this.#updateStackOffset(entity, now); |
| 1262 | this.#updateShove(entity, now, size); |
| 1263 | this.#expireGatherToolOverlay(entity, now); |
| 1264 | this.#placeEntity(entity, now); |
| 1265 | } |
| 1266 | |
| 1267 | this.#updateSwipes(now); |
| 1268 | this.#updateDamageNumbers(now); |
| 1269 | this.#updateSkillLevelFloats(now); |
| 1270 | this.#centerCamera(); |
| 1271 | this.#cullOffscreenDrawables(); |
| 1272 | this.#updateShade(deltaTime); |
| 1273 | } |
| 1274 | |
| 1275 | /** |
| 1276 | * Desired circle offsets for stacked entities (applied via {@link #updateStackOffset}). |
| 1277 | * Stable assignment by entityId; free-flight entities stay unshifted. |
| 1278 | */ |
| 1279 | #refreshStackTargets () |
| 1280 | { |
| 1281 | const byTile = new Map(); |
| 1282 | for (const entity of this.entities.values()) |
| 1283 | { |
| 1284 | if (entity.freeFlight) |
| 1285 | { |
| 1286 | entity.stackTargetX = 0; |
| 1287 | entity.stackTargetY = 0; |
| 1288 | continue; |
| 1289 | } |
| 1290 | const key = `${entity.tileX},${entity.tileY}`; |
| 1291 | let list = byTile.get(key); |
| 1292 | if (!list) |
| 1293 | { |
| 1294 | list = []; |
| 1295 | byTile.set(key, list); |
| 1296 | } |
| 1297 | list.push(entity); |
| 1298 | } |
| 1299 | const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2; |
| 1300 | for (const list of byTile.values()) |
| 1301 | { |
| 1302 | if (list.length <= 1) |
| 1303 | { |
| 1304 | for (const entity of list) |
| 1305 | { |
| 1306 | entity.stackTargetX = 0; |
| 1307 | entity.stackTargetY = 0; |
| 1308 | } |
| 1309 | continue; |
| 1310 | } |
| 1311 | list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId))); |
| 1312 | const n = list.length; |
| 1313 | for (let i = 0; i < n; i++) |
| 1314 | { |
| 1315 | const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n; |
| 1316 | list[i].stackTargetX = Math.cos(angle) * radius; |
| 1317 | list[i].stackTargetY = Math.sin(angle) * radius; |
| 1318 | } |
| 1319 | } |
| 1320 | } |
| 1321 | |
| 1322 | #updateStackOffset (entity, now) |
| 1323 | { |
| 1324 | const tx = entity.stackTargetX ?? 0; |
| 1325 | const ty = entity.stackTargetY ?? 0; |
| 1326 | const cx = entity.stackOffsetX ?? 0; |
| 1327 | const cy = entity.stackOffsetY ?? 0; |
| 1328 | if (entity.stackLerpToX !== tx || entity.stackLerpToY !== ty) |
| 1329 | { |
| 1330 | entity.stackFromX = cx; |
| 1331 | entity.stackFromY = cy; |
| 1332 | entity.stackLerpToX = tx; |
| 1333 | entity.stackLerpToY = ty; |
| 1334 | entity.stackLerpStarted = now; |
| 1335 | } |
| 1336 | if (entity.stackLerpStarted == null) |
| 1337 | { |
| 1338 | entity.stackOffsetX = tx; |
| 1339 | entity.stackOffsetY = ty; |
| 1340 | return; |
| 1341 | } |
| 1342 | const t = Math.min(1, (now - entity.stackLerpStarted) / STACK_SPREAD_LERP_MS); |
| 1343 | entity.stackOffsetX = entity.stackFromX + (tx - entity.stackFromX) * t; |
| 1344 | entity.stackOffsetY = entity.stackFromY + (ty - entity.stackFromY) * t; |
| 1345 | if (t >= 1) |
| 1346 | { |
| 1347 | entity.stackOffsetX = tx; |
| 1348 | entity.stackOffsetY = ty; |
| 1349 | entity.stackLerpStarted = null; |
| 1350 | } |
| 1351 | } |
| 1352 | |
| 1353 | #updateShove (entity, now, tileSize) |
| 1354 | { |
| 1355 | if (!entity.shove) |
| 1356 | { |
| 1357 | entity.shoveOffsetX = 0; |
| 1358 | entity.shoveOffsetY = 0; |
| 1359 | return; |
| 1360 | } |
| 1361 | const elapsed = now - entity.shove.started; |
| 1362 | const t = Math.min(1, elapsed / entity.shove.durationMs); |
| 1363 | const maxDist = tileSize * SHOVE_TILE_FRACTION; |
| 1364 | const dx = entity.shove.targetVisualX - entity.shove.startVisualX; |
| 1365 | const dy = entity.shove.targetVisualY - entity.shove.startVisualY; |
| 1366 | const dist = Math.hypot(dx, dy) || 1; |
| 1367 | const ux = dx / dist; |
| 1368 | const uy = dy / dist; |
| 1369 | let phase; |
| 1370 | if (t < 0.45) |
| 1371 | { phase = t / 0.45; } |
| 1372 | else |
| 1373 | { phase = 1 - (t - 0.45) / 0.55; } |
| 1374 | entity.shoveOffsetX = ux * maxDist * phase; |
| 1375 | entity.shoveOffsetY = uy * maxDist * phase; |
| 1376 | if (t >= 1) |
| 1377 | { entity.shove = null; } |
| 1378 | } |
| 1379 | |
| 1380 | spawnCombatSwing (payload) |
| 1381 | { |
| 1382 | const attacker = this.entities.get(payload.attackerId); |
| 1383 | const target = this.entities.get(payload.targetId); |
| 1384 | if (!attacker || !target) |
| 1385 | { return; } |
| 1386 | const ax = attacker.visualX + (attacker.stackOffsetX ?? 0); |
| 1387 | const ay = attacker.visualY + (attacker.stackOffsetY ?? 0); |
| 1388 | const tx = target.visualX + (target.stackOffsetX ?? 0); |
| 1389 | const ty = target.visualY + (target.stackOffsetY ?? 0); |
| 1390 | this.#applyShove(attacker, tx, ty); |
| 1391 | const midX = (ax + tx) / 2; |
| 1392 | const midY = (ay + ty) / 2; |
| 1393 | const sortY = Math.max(ay, ty) + 0.02; |
| 1394 | const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI); |
| 1395 | const spriteName = "fx:melee-swipe:melee-swipe"; |
| 1396 | const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX); |
| 1397 | if (object.transform) |
| 1398 | { object.transform.rotation = angle; } |
| 1399 | this.scene.addObject(object); |
| 1400 | this.#placePivoted(object, midX, midY, sortY, SORT_FX); |
| 1401 | this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY); |
| 1402 | this.swipes.push({ |
| 1403 | object, |
| 1404 | until: performance.now() + 500, |
| 1405 | fromTileX: payload.fromTileX, |
| 1406 | fromTileY: payload.fromTileY, |
| 1407 | tileX: payload.tileX, |
| 1408 | tileY: payload.tileY |
| 1409 | }); |
| 1410 | } |
| 1411 | |
| 1412 | /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */ |
| 1413 | spawnGatherSwing (payload) |
| 1414 | { |
| 1415 | const attacker = this.entities.get(payload.attackerId); |
| 1416 | if (!attacker) |
| 1417 | { return; } |
| 1418 | const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize()); |
| 1419 | this.#applyShove(attacker, pivot.x, pivot.y); |
| 1420 | if (payload.toolItemId != null) |
| 1421 | { this.#setGatherToolOverlay(attacker, payload.toolItemId); } |
| 1422 | } |
| 1423 | |
| 1424 | #applyShove (entity, targetVisualX, targetVisualY) |
| 1425 | { |
| 1426 | entity.shove = { |
| 1427 | startVisualX: entity.visualX, |
| 1428 | startVisualY: entity.visualY, |
| 1429 | targetVisualX, |
| 1430 | targetVisualY, |
| 1431 | started: performance.now(), |
| 1432 | durationMs: SHOVE_MS |
| 1433 | }; |
| 1434 | } |
| 1435 | |
| 1436 | /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */ |
| 1437 | spawnPhysicalProjectileFx (payload) |
| 1438 | { |
| 1439 | const spriteName = payload.sprite ?? "fx:projectile:arrow"; |
| 1440 | const image = this.game.images[spriteName]; |
| 1441 | if (!image) |
| 1442 | { return; } |
| 1443 | const dualTint = this.#dualTintFromPayload(payload); |
| 1444 | const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize()); |
| 1445 | const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize()); |
| 1446 | const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02; |
| 1447 | const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI); |
| 1448 | const object = new GameObject(0, 0, image, SORT_FX); |
| 1449 | if (object.transform) |
| 1450 | { object.transform.rotation = angle; } |
| 1451 | this.scene.addObject(object); |
| 1452 | this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX); |
| 1453 | this.#applyPhysicalCombatFxDarkness( |
| 1454 | object, |
| 1455 | payload.fromTileX, |
| 1456 | payload.fromTileY, |
| 1457 | payload.tileX, |
| 1458 | payload.tileY, |
| 1459 | dualTint |
| 1460 | ); |
| 1461 | const started = performance.now(); |
| 1462 | const durationMs = payload.durationMs ?? 400; |
| 1463 | const trackTarget = payload.trackTarget !== false && payload.targetId != null; |
| 1464 | this.swipes.push({ |
| 1465 | object, |
| 1466 | until: started + durationMs, |
| 1467 | started, |
| 1468 | durationMs, |
| 1469 | lerp: true, |
| 1470 | dualTint, |
| 1471 | fromTileX: payload.fromTileX, |
| 1472 | fromTileY: payload.fromTileY, |
| 1473 | tileX: payload.tileX, |
| 1474 | tileY: payload.tileY, |
| 1475 | attackerId: payload.attackerId ?? null, |
| 1476 | targetId: payload.targetId ?? null, |
| 1477 | trackTarget, |
| 1478 | onImpact: null |
| 1479 | }); |
| 1480 | } |
| 1481 | |
| 1482 | /** Bloom-layer spell projectiles — unlit, animated, 2s travel. */ |
| 1483 | spawnSpellProjectileFx (payload) |
| 1484 | { |
| 1485 | const baseSprite = payload.sprite ?? "fx:projectile:spell-light"; |
| 1486 | const image = this.#spellProjectileImage(baseSprite, 0); |
| 1487 | if (!image) |
| 1488 | { return; } |
| 1489 | const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize()); |
| 1490 | const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize()); |
| 1491 | const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02; |
| 1492 | const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI); |
| 1493 | const object = new GameObject(0, 0, image, SORT_FX); |
| 1494 | object.renderer.layer = RENDER_LAYER_BLOOM; |
| 1495 | this.#markUnlit(object); |
| 1496 | if (object.transform) |
| 1497 | { object.transform.rotation = angle; } |
| 1498 | this.scene.addObject(object); |
| 1499 | this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX); |
| 1500 | const started = performance.now(); |
| 1501 | const durationMs = payload.durationMs ?? 2000; |
| 1502 | this.swipes.push({ |
| 1503 | object, |
| 1504 | until: started + durationMs, |
| 1505 | started, |
| 1506 | durationMs, |
| 1507 | lerp: true, |
| 1508 | spellProjectile: true, |
| 1509 | baseSprite, |
| 1510 | fromTileX: payload.fromTileX, |
| 1511 | fromTileY: payload.fromTileY, |
| 1512 | tileX: payload.tileX, |
| 1513 | tileY: payload.tileY, |
| 1514 | attackerId: payload.casterId ?? null, |
| 1515 | targetId: payload.targetId ?? null, |
| 1516 | trackTarget: payload.targetId != null, |
| 1517 | onImpact: null |
| 1518 | }); |
| 1519 | } |
| 1520 | |
| 1521 | spawnSpellFizzleFx (_payload) |
| 1522 | { |
| 1523 | // Visual-only fizzle; no dynamic light (too expensive for lightmap rebakes). |
| 1524 | } |
| 1525 | |
| 1526 | #spellProjectileImage (baseSprite, frameIndex) |
| 1527 | { |
| 1528 | const frame = Math.max(0, Math.min(2, frameIndex | 0)); |
| 1529 | const stem = baseSprite.split(":").pop() ?? "spell-light"; |
| 1530 | const names = [ |
| 1531 | `${baseSprite}-${frame}`, |
| 1532 | `fx:projectile:${stem}-${frame}`, |
| 1533 | baseSprite, |
| 1534 | `fx:projectile:${stem}` |
| 1535 | ]; |
| 1536 | for (const name of names) |
| 1537 | { |
| 1538 | if (this.game.images[name]) |
| 1539 | { return this.game.images[name]; } |
| 1540 | } |
| 1541 | return null; |
| 1542 | } |
| 1543 | |
| 1544 | addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 }) |
| 1545 | { |
| 1546 | this.dynamicLights.push({ |
| 1547 | tileX: Math.floor(worldX), |
| 1548 | tileY: Math.floor(worldY), |
| 1549 | range: radiusTiles, |
| 1550 | intensity, |
| 1551 | until: performance.now() + durationMs |
| 1552 | }); |
| 1553 | } |
| 1554 | |
| 1555 | updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {}) |
| 1556 | { |
| 1557 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 1558 | if (!snapshot) |
| 1559 | { return; } |
| 1560 | const index = localY * CHUNK_SIZE + localX; |
| 1561 | if (ground !== undefined) |
| 1562 | { snapshot.grounds[index] = ground; } |
| 1563 | if (block !== undefined) |
| 1564 | { snapshot.blocks[index] = block; } |
| 1565 | if (light !== undefined) |
| 1566 | { snapshot.light[index] = light; } |
| 1567 | const tileX = chunkX * CHUNK_SIZE + localX; |
| 1568 | const tileY = chunkY * CHUNK_SIZE + localY; |
| 1569 | if (block !== undefined) |
| 1570 | { |
| 1571 | this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); |
| 1572 | this.#drawTile(tileX, tileY); |
| 1573 | return; |
| 1574 | } |
| 1575 | this.#scheduleChunkRebuild(snapshot); |
| 1576 | if (ground !== undefined) |
| 1577 | { this.#drawTile(tileX, tileY); } |
| 1578 | } |
| 1579 | |
| 1580 | /** |
| 1581 | * Editor-only mob markers for authored spawners (invisible during play). |
| 1582 | * @param {number} chunkX |
| 1583 | * @param {number} chunkY |
| 1584 | * @param {Array<{ localX: number, localY: number, config?: { mobTypeId?: string } }>} spawners |
| 1585 | * @param {(mobTypeId: string) => string} resolveSprite |
| 1586 | */ |
| 1587 | setEditorSpawners (chunkX, chunkY, spawners, resolveSprite) |
| 1588 | { |
| 1589 | const prefix = `${chunkX},${chunkY}:`; |
| 1590 | for (const [key, entry] of [...this.editorSpawners.entries()]) |
| 1591 | { |
| 1592 | if (!key.startsWith(prefix)) |
| 1593 | { continue; } |
| 1594 | entry.object?.destroy(); |
| 1595 | this.editorSpawners.delete(key); |
| 1596 | } |
| 1597 | for (const spawner of spawners ?? []) |
| 1598 | { |
| 1599 | const tileX = chunkX * CHUNK_SIZE + spawner.localX; |
| 1600 | const tileY = chunkY * CHUNK_SIZE + spawner.localY; |
| 1601 | const spriteName = resolveSprite?.(spawner.config?.mobTypeId) ?? null; |
| 1602 | if (!spriteName) |
| 1603 | { continue; } |
| 1604 | const key = `${prefix}${spawner.localX},${spawner.localY}`; |
| 1605 | const object = this.#ensureSprite(null, spriteName, SORT_ENTITY); |
| 1606 | if (!object) |
| 1607 | { continue; } |
| 1608 | object.renderer.alpha = 0.85; |
| 1609 | const pivot = tilePivot(tileX, tileY, this.tileSize()); |
| 1610 | this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY); |
| 1611 | this.#markUnlit(object); |
| 1612 | this.editorSpawners.set(key, { object, tileX, tileY, spriteName }); |
| 1613 | } |
| 1614 | } |
| 1615 | |
| 1616 | clearEditorSpawners () |
| 1617 | { |
| 1618 | for (const entry of this.editorSpawners.values()) |
| 1619 | { entry.object?.destroy(); } |
| 1620 | this.editorSpawners.clear(); |
| 1621 | } |
| 1622 | |
| 1623 | #relayoutEditorSpawners () |
| 1624 | { |
| 1625 | const size = this.tileSize(); |
| 1626 | for (const entry of this.editorSpawners.values()) |
| 1627 | { |
| 1628 | if (!entry.object) |
| 1629 | { continue; } |
| 1630 | const pivot = tilePivot(entry.tileX, entry.tileY, size); |
| 1631 | this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY); |
| 1632 | } |
| 1633 | } |
| 1634 | |
| 1635 | /** |
| 1636 | * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares). |
| 1637 | */ |
| 1638 | setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null) |
| 1639 | { |
| 1640 | const spawnRadius = Math.max(0, spawnRange | 0); |
| 1641 | const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0)); |
| 1642 | if (this.spawnRangeHighlight |
| 1643 | && this.wanderRangeHighlight |
| 1644 | && this.spawnRangeHighlight.tileX === tileX |
| 1645 | && this.spawnRangeHighlight.tileY === tileY |
| 1646 | && this.spawnRangeHighlight.range === spawnRadius |
| 1647 | && this.wanderRangeHighlight.range === wanderRadius) |
| 1648 | { |
| 1649 | this.#relayoutSpawnRangeHighlight(); |
| 1650 | return; |
| 1651 | } |
| 1652 | this.clearSpawnRangeHighlight(); |
| 1653 | const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE); |
| 1654 | const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE); |
| 1655 | if (wanderObject) |
| 1656 | { |
| 1657 | this.#markUnlit(wanderObject); |
| 1658 | wanderObject.renderer.alpha = 1; |
| 1659 | this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius }; |
| 1660 | } |
| 1661 | if (spawnObject) |
| 1662 | { |
| 1663 | this.#markUnlit(spawnObject); |
| 1664 | spawnObject.renderer.alpha = 1; |
| 1665 | this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius }; |
| 1666 | } |
| 1667 | this.#relayoutSpawnRangeHighlight(); |
| 1668 | } |
| 1669 | |
| 1670 | clearSpawnRangeHighlight () |
| 1671 | { |
| 1672 | this.spawnRangeHighlight?.object?.destroy(); |
| 1673 | this.wanderRangeHighlight?.object?.destroy(); |
| 1674 | this.spawnRangeHighlight = null; |
| 1675 | this.wanderRangeHighlight = null; |
| 1676 | } |
| 1677 | |
| 1678 | setSpellTargetHighlight (tileX, tileY, inRange = true) |
| 1679 | { |
| 1680 | if ( |
| 1681 | this.spellTargetHighlight |
| 1682 | && this.spellTargetHighlight.tileX === tileX |
| 1683 | && this.spellTargetHighlight.tileY === tileY |
| 1684 | && this.spellTargetHighlight.inRange === inRange |
| 1685 | ) |
| 1686 | { |
| 1687 | this.#relayoutSpellTargetHighlight(); |
| 1688 | return; |
| 1689 | } |
| 1690 | this.clearSpellTargetHighlight(); |
| 1691 | const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid"; |
| 1692 | const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1); |
| 1693 | if (!object) |
| 1694 | { return; } |
| 1695 | this.#markUnlit(object); |
| 1696 | object.renderer.alpha = 1; |
| 1697 | this.spellTargetHighlight = { object, tileX, tileY, inRange, spriteName }; |
| 1698 | this.#relayoutSpellTargetHighlight(); |
| 1699 | } |
| 1700 | |
| 1701 | clearSpellTargetHighlight () |
| 1702 | { |
| 1703 | this.spellTargetHighlight?.object?.destroy(); |
| 1704 | this.spellTargetHighlight = null; |
| 1705 | } |
| 1706 | |
| 1707 | #relayoutSpellTargetHighlight () |
| 1708 | { |
| 1709 | const highlight = this.spellTargetHighlight; |
| 1710 | if (!highlight?.object) |
| 1711 | { return; } |
| 1712 | const size = this.tileSize(); |
| 1713 | const left = highlight.tileX * size; |
| 1714 | const top = highlight.tileY * size; |
| 1715 | highlight.object.transform.position.x = left + size / 2; |
| 1716 | highlight.object.transform.position.y = top + size / 2; |
| 1717 | highlight.object.transform.size = new vector(size, size); |
| 1718 | highlight.object.layer = LAYER_EDGE - 1; |
| 1719 | this.#markSortDirty(); |
| 1720 | } |
| 1721 | |
| 1722 | #relayoutSpawnRangeHighlight () |
| 1723 | { |
| 1724 | this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2); |
| 1725 | this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1); |
| 1726 | } |
| 1727 | |
| 1728 | #layoutRangeOverlay (highlight, layer) |
| 1729 | { |
| 1730 | if (!highlight?.object) |
| 1731 | { return; } |
| 1732 | const size = this.tileSize(); |
| 1733 | const side = (2 * highlight.range + 1) * size; |
| 1734 | const left = (highlight.tileX - highlight.range) * size; |
| 1735 | const top = (highlight.tileY - highlight.range) * size; |
| 1736 | highlight.object.transform.position.x = left + side / 2; |
| 1737 | highlight.object.transform.position.y = top + side / 2; |
| 1738 | highlight.object.transform.size = new vector(side, side); |
| 1739 | highlight.object.layer = layer; |
| 1740 | this.#markSortDirty(); |
| 1741 | } |
| 1742 | |
| 1743 | setTilePreview (tileX, tileY, override) |
| 1744 | { |
| 1745 | const next = { tileX, tileY, ...override }; |
| 1746 | if (this.#previewEqual(this.preview, next)) |
| 1747 | { return; } |
| 1748 | const previous = this.preview; |
| 1749 | this.preview = next; |
| 1750 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 1751 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 1752 | this.#scheduleChunkRebuild(this.chunks.get(`${chunkX},${chunkY}`)); |
| 1753 | if (previous && (previous.tileX !== tileX || previous.tileY !== tileY)) |
| 1754 | { |
| 1755 | const prevKey = `${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`; |
| 1756 | if (prevKey !== `${chunkX},${chunkY}`) |
| 1757 | { this.#scheduleChunkRebuild(this.chunks.get(prevKey)); } |
| 1758 | } |
| 1759 | } |
| 1760 | |
| 1761 | clearTilePreview () |
| 1762 | { |
| 1763 | if (!this.preview) |
| 1764 | { return; } |
| 1765 | const previous = this.preview; |
| 1766 | this.preview = null; |
| 1767 | const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`); |
| 1768 | this.#scheduleChunkRebuild(snapshot); |
| 1769 | } |
| 1770 | |
| 1771 | #lerpMs (gait) |
| 1772 | { |
| 1773 | const walk = this.settings.walkTilesPerSecond || 2; |
| 1774 | const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk; |
| 1775 | return seconds * 1000; |
| 1776 | } |
| 1777 | |
| 1778 | #centerCamera () |
| 1779 | { |
| 1780 | if (!this.followPlayer) |
| 1781 | { return; } |
| 1782 | const local = this.entities.get(this.localEntityId); |
| 1783 | if (!local) |
| 1784 | { return; } |
| 1785 | const x = local.visualX + (local.stackOffsetX ?? 0); |
| 1786 | const y = local.visualY + (local.stackOffsetY ?? 0); |
| 1787 | this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x; |
| 1788 | this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y; |
| 1789 | } |
| 1790 | |
| 1791 | /** |
| 1792 | * World-pixel AABB of the screen, expanded by half a tile (zoom-aware). |
| 1793 | * Tiles fully outside this rect are not drawn. |
| 1794 | */ |
| 1795 | #drawBounds () |
| 1796 | { |
| 1797 | const pad = this.tileSize() * 0.5; |
| 1798 | const camX = this.scene.cameraPosition.x; |
| 1799 | const camY = this.scene.cameraPosition.y; |
| 1800 | const w = this.scene.real_size.x; |
| 1801 | const h = this.scene.real_size.y; |
| 1802 | return { |
| 1803 | left: -camX - pad, |
| 1804 | right: -camX + w + pad, |
| 1805 | top: -camY - pad, |
| 1806 | bottom: -camY + h + pad |
| 1807 | }; |
| 1808 | } |
| 1809 | |
| 1810 | #rectIntersects (left, top, right, bottom, bounds) |
| 1811 | { |
| 1812 | return right >= bounds.left |
| 1813 | && left <= bounds.right |
| 1814 | && bottom >= bounds.top |
| 1815 | && top <= bounds.bottom; |
| 1816 | } |
| 1817 | |
| 1818 | #setRendererVisible (object, visible) |
| 1819 | { |
| 1820 | if (object?.renderer) |
| 1821 | { object.renderer.visible = !!visible; } |
| 1822 | } |
| 1823 | |
| 1824 | /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */ |
| 1825 | #cullOffscreenDrawables () |
| 1826 | { |
| 1827 | const bounds = this.#drawBounds(); |
| 1828 | const size = this.tileSize(); |
| 1829 | |
| 1830 | for (const baked of this.bakedChunks.values()) |
| 1831 | { |
| 1832 | const left = baked.chunkX * CHUNK_SIZE * size; |
| 1833 | const top = baked.chunkY * CHUNK_SIZE * size; |
| 1834 | const chunkPx = CHUNK_SIZE * size; |
| 1835 | const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds); |
| 1836 | this.#setRendererVisible(baked.groundObject, chunkVisible); |
| 1837 | this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled); |
| 1838 | baked._inViewport = chunkVisible; |
| 1839 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 1840 | { |
| 1841 | const rowTop = top + row * size; |
| 1842 | const rowVisible = chunkVisible && this.#rectIntersects( |
| 1843 | left, rowTop, left + chunkPx, rowTop + size, bounds |
| 1844 | ); |
| 1845 | this.#setRendererVisible(baked.blockObjects?.[row], rowVisible); |
| 1846 | } |
| 1847 | } |
| 1848 | |
| 1849 | for (const objects of this.tiles.values()) |
| 1850 | { |
| 1851 | const left = objects.tileX * size; |
| 1852 | const top = objects.tileY * size; |
| 1853 | const visible = this.#rectIntersects(left, top, left + size, top + size, bounds); |
| 1854 | objects._inViewport = visible; |
| 1855 | this.#setRendererVisible(objects.ground, visible); |
| 1856 | this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled); |
| 1857 | this.#setRendererVisible(objects.block, visible); |
| 1858 | this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled); |
| 1859 | if (objects.waterEdges) |
| 1860 | { |
| 1861 | for (const edge of Object.values(objects.waterEdges)) |
| 1862 | { this.#setRendererVisible(edge, visible); } |
| 1863 | } |
| 1864 | } |
| 1865 | } |
| 1866 | |
| 1867 | #upsertEntity (payload) |
| 1868 | { |
| 1869 | const size = this.tileSize(); |
| 1870 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 1871 | let entity = this.entities.get(payload.entityId); |
| 1872 | if (!entity) |
| 1873 | { |
| 1874 | const spriteName = payload.layers?.[0]?.sprite |
| 1875 | ?? payload.sprite |
| 1876 | ?? bodySpriteName(payload.sex); |
| 1877 | const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY); |
| 1878 | this.scene.addObject(object); |
| 1879 | this.#startIdleAnimation(object); |
| 1880 | entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y }; |
| 1881 | this.entities.set(payload.entityId, entity); |
| 1882 | } |
| 1883 | entity.entityId = payload.entityId; |
| 1884 | entity.tileX = payload.tileX; |
| 1885 | entity.tileY = payload.tileY; |
| 1886 | entity.gait = payload.gait; |
| 1887 | entity.sex = payload.sex ?? entity.sex; |
| 1888 | entity.characterId = payload.characterId ?? entity.characterId ?? null; |
| 1889 | entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null; |
| 1890 | if (payload.level != null) |
| 1891 | { entity.level = payload.level | 0; } |
| 1892 | entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile; |
| 1893 | entity.canFight = payload.canFight != null |
| 1894 | ? !!payload.canFight |
| 1895 | : !!(entity.canFight || (payload.mobTypeId && !payload.talkable)); |
| 1896 | entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable; |
| 1897 | entity.hasDialogue = payload.hasDialogue != null ? !!payload.hasDialogue : !!entity.hasDialogue; |
| 1898 | entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop; |
| 1899 | entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable; |
| 1900 | entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight; |
| 1901 | entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0; |
| 1902 | if (payload.visualScale != null) |
| 1903 | { entity.visualScale = Number(payload.visualScale) || 1; } |
| 1904 | else if (entity.visualScale == null) |
| 1905 | { entity.visualScale = 1; } |
| 1906 | if (payload.health != null) |
| 1907 | { entity.health = payload.health; } |
| 1908 | if (payload.maxHealth != null) |
| 1909 | { entity.maxHealth = payload.maxHealth; } |
| 1910 | if (payload.firstName) |
| 1911 | { entity.firstName = payload.firstName; } |
| 1912 | if (payload.lastName) |
| 1913 | { entity.lastName = payload.lastName; } |
| 1914 | entity.firstName = entity.firstName ?? ""; |
| 1915 | entity.lastName = entity.lastName ?? ""; |
| 1916 | if (payload.worldX != null && payload.worldY != null) |
| 1917 | { |
| 1918 | entity.worldX = payload.worldX; |
| 1919 | entity.worldY = payload.worldY; |
| 1920 | entity.visualX = payload.worldX * size; |
| 1921 | entity.visualY = payload.worldY * size; |
| 1922 | entity.targetX = entity.visualX; |
| 1923 | entity.targetY = entity.visualY; |
| 1924 | } |
| 1925 | else |
| 1926 | { |
| 1927 | entity.visualX = pivot.x; |
| 1928 | entity.visualY = pivot.y; |
| 1929 | entity.targetX = pivot.x; |
| 1930 | entity.targetY = pivot.y; |
| 1931 | } |
| 1932 | entity.fromX = entity.visualX; |
| 1933 | entity.fromY = entity.visualY; |
| 1934 | if (payload.layers) |
| 1935 | { this.#applyLayers(entity, payload.layers); } |
| 1936 | this.#syncHpBar(entity); |
| 1937 | this.#placeEntity(entity, performance.now()); |
| 1938 | } |
| 1939 | |
| 1940 | #applyLayers (entity, layers) |
| 1941 | { |
| 1942 | entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }]; |
| 1943 | this.#rebuildOverlays(entity); |
| 1944 | } |
| 1945 | |
| 1946 | #setGatherToolOverlay (entity, toolItemId) |
| 1947 | { |
| 1948 | entity.gatherToolItemId = toolItemId; |
| 1949 | entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS; |
| 1950 | this.#rebuildOverlays(entity); |
| 1951 | this.#placeEntity(entity, performance.now()); |
| 1952 | } |
| 1953 | |
| 1954 | #expireGatherToolOverlay (entity, now) |
| 1955 | { |
| 1956 | if (entity.gatherToolItemId == null) |
| 1957 | { return; } |
| 1958 | if ((entity.gatherToolUntil ?? 0) > now) |
| 1959 | { return; } |
| 1960 | entity.gatherToolItemId = null; |
| 1961 | entity.gatherToolUntil = 0; |
| 1962 | this.#rebuildOverlays(entity); |
| 1963 | } |
| 1964 | |
| 1965 | /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */ |
| 1966 | #layersForDisplay (entity) |
| 1967 | { |
| 1968 | const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer })); |
| 1969 | const toolId = entity.gatherToolItemId; |
| 1970 | if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now()) |
| 1971 | { return layers; } |
| 1972 | const equip = itemEquipSprite(toolId); |
| 1973 | if (!equip || !this.game.images[equip]) |
| 1974 | { return layers; } |
| 1975 | const replacement = { |
| 1976 | sprite: equip, |
| 1977 | itemId: toolId, |
| 1978 | tint: resolveEquipTint(toolId) |
| 1979 | }; |
| 1980 | for (let index = layers.length - 1; index >= 1; index--) |
| 1981 | { |
| 1982 | const def = itemDefinition(layers[index].itemId); |
| 1983 | if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon) |
| 1984 | { |
| 1985 | layers[index] = replacement; |
| 1986 | return layers; |
| 1987 | } |
| 1988 | } |
| 1989 | layers.push(replacement); |
| 1990 | return layers; |
| 1991 | } |
| 1992 | |
| 1993 | #rebuildOverlays (entity) |
| 1994 | { |
| 1995 | const layers = this.#layersForDisplay(entity); |
| 1996 | const base = layers[0]?.sprite |
| 1997 | ?? bodySpriteName(entity.sex); |
| 1998 | if (this.game.images[base]) |
| 1999 | { |
| 2000 | entity.object.renderer.sprite = this.game.images[base]; |
| 2001 | this.#startIdleAnimation(entity.object); |
| 2002 | } |
| 2003 | for (const overlay of entity.overlays ?? []) |
| 2004 | { overlay.destroy(); } |
| 2005 | for (const overlay of entity.bloomOverlays ?? []) |
| 2006 | { overlay.destroy(); } |
| 2007 | entity.overlays = []; |
| 2008 | entity.overlayTints = []; |
| 2009 | entity.overlayDualTints = []; |
| 2010 | entity.overlayTightFit = []; |
| 2011 | entity.bloomOverlays = []; |
| 2012 | for (const layer of layers.slice(1)) |
| 2013 | { |
| 2014 | const image = this.game.images[layer.sprite]; |
| 2015 | if (!image) |
| 2016 | { continue; } |
| 2017 | const object = new GameObject(0, 0, image, SORT_ENTITY); |
| 2018 | this.scene.addObject(object); |
| 2019 | entity.overlays.push(object); |
| 2020 | const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null; |
| 2021 | entity.overlayTightFit.push(!!layerDef?.tightFit); |
| 2022 | const dualTint = layer.itemId != null |
| 2023 | ? resolveItemDualTint({ itemId: layer.itemId }, layerDef) |
| 2024 | : null; |
| 2025 | entity.overlayDualTints.push(dualTint); |
| 2026 | entity.overlayTints.push( |
| 2027 | dualTint |
| 2028 | ? null |
| 2029 | : (layer.tint |
| 2030 | ? normalizeRgb(layer.tint) |
| 2031 | : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)) |
| 2032 | ); |
| 2033 | const bloomName = bloomCompanionName(layer.sprite); |
| 2034 | const bloomImage = this.game.images[bloomName]; |
| 2035 | if (!bloomImage) |
| 2036 | { continue; } |
| 2037 | const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY); |
| 2038 | bloom.renderer.layer = RENDER_LAYER_BLOOM; |
| 2039 | this.#markUnlit(bloom); |
| 2040 | this.scene.addObject(bloom); |
| 2041 | entity.bloomOverlays.push(bloom); |
| 2042 | } |
| 2043 | } |
| 2044 | |
| 2045 | #placeEntity (entity, now = performance.now()) |
| 2046 | { |
| 2047 | const zoom = this.zoom; |
| 2048 | const offsetX = entity.shoveOffsetX ?? 0; |
| 2049 | const offsetY = entity.shoveOffsetY ?? 0; |
| 2050 | const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0); |
| 2051 | const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0); |
| 2052 | let walkTilt = 0; |
| 2053 | if (entity.lerpStarted != null) |
| 2054 | { |
| 2055 | const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait)); |
| 2056 | const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2; |
| 2057 | const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG; |
| 2058 | walkTilt = Math.sin(cycles) * tilt; |
| 2059 | } |
| 2060 | const flashStrength = (entity.damageFlashUntil ?? 0) > now |
| 2061 | ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS |
| 2062 | : 0; |
| 2063 | const tileShade = this.#entityShadeAlpha(entity, now); |
| 2064 | const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason); |
| 2065 | |
| 2066 | entity.object.transform.rotation = walkTilt; |
| 2067 | this.#syncLitSprite(entity.object, tileShade, flashStrength, wade); |
| 2068 | this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1); |
| 2069 | for (let index = 0; index < (entity.overlays ?? []).length; index++) |
| 2070 | { |
| 2071 | const overlay = entity.overlays[index]; |
| 2072 | const overlaySortY = pivotY + 0.5 * (index + 1); |
| 2073 | overlay.transform.rotation = walkTilt; |
| 2074 | const dualTint = entity.overlayDualTints?.[index] ?? null; |
| 2075 | if (dualTint) |
| 2076 | { |
| 2077 | this.#syncDualTintLitSprite(overlay, tileShade, dualTint, flashStrength, wade); |
| 2078 | } |
| 2079 | else if (entity.overlayTightFit?.[index]) |
| 2080 | { |
| 2081 | this.#syncTightFitLitSprite( |
| 2082 | overlay, |
| 2083 | entity, |
| 2084 | tileShade, |
| 2085 | flashStrength, |
| 2086 | wade, |
| 2087 | entity.overlayTints?.[index] ?? null |
| 2088 | ); |
| 2089 | } |
| 2090 | else |
| 2091 | { |
| 2092 | this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null); |
| 2093 | } |
| 2094 | this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY, entity.visualScale ?? 1); |
| 2095 | } |
| 2096 | for (const overlay of entity.bloomOverlays ?? []) |
| 2097 | { |
| 2098 | this.#setRendererVisible(overlay, this.bloomEnabled); |
| 2099 | if (!this.bloomEnabled) |
| 2100 | { continue; } |
| 2101 | overlay.transform.rotation = walkTilt; |
| 2102 | this.#syncLitSprite(overlay, tileShade, flashStrength, wade); |
| 2103 | this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1); |
| 2104 | } |
| 2105 | this.#placeHpBar(entity, pivotX, pivotY); |
| 2106 | } |
| 2107 | |
| 2108 | #markUnlit (object) |
| 2109 | { |
| 2110 | if (!object?.renderer) |
| 2111 | { return; } |
| 2112 | object._lit = false; |
| 2113 | object.renderer.shader = null; |
| 2114 | object.renderer.shaderUniforms = null; |
| 2115 | object.renderer.secondaryMap = null; |
| 2116 | } |
| 2117 | |
| 2118 | #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null) |
| 2119 | { |
| 2120 | if (!object?.renderer || object._lit === false) |
| 2121 | { return; } |
| 2122 | object._lit = true; |
| 2123 | const dark = Math.min(1, Math.max(0, darkness ?? 0)); |
| 2124 | const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); |
| 2125 | const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX; |
| 2126 | const tint = tintColor ? normalizeRgb(tintColor) : null; |
| 2127 | if (tint) |
| 2128 | { |
| 2129 | object.renderer.shader = getTintLitSpriteShader(); |
| 2130 | object.renderer.shaderUniforms = { |
| 2131 | u_darkness: dark, |
| 2132 | u_strength: flash, |
| 2133 | u_wade: wade ? 1 : 0, |
| 2134 | u_spriteHeight: height, |
| 2135 | u_useTint: 1, |
| 2136 | u_tintColor: [tint.r, tint.g, tint.b] |
| 2137 | }; |
| 2138 | } |
| 2139 | else |
| 2140 | { |
| 2141 | object.renderer.shader = getSpriteLightingShader(); |
| 2142 | object.renderer.shaderUniforms = { |
| 2143 | u_darkness: dark, |
| 2144 | u_strength: flash, |
| 2145 | u_wade: wade ? 1 : 0, |
| 2146 | u_spriteHeight: height |
| 2147 | }; |
| 2148 | } |
| 2149 | object.renderer.secondaryMap = null; |
| 2150 | } |
| 2151 | |
| 2152 | #bodySecondaryMap (entity) |
| 2153 | { |
| 2154 | return entity?.object?.renderer?.sprite?.g_image ?? null; |
| 2155 | } |
| 2156 | |
| 2157 | #tightFitMaskUniforms (overlay, entity) |
| 2158 | { |
| 2159 | const bodyRenderer = entity?.object?.renderer; |
| 2160 | const clothRenderer = overlay?.renderer; |
| 2161 | const bodySprite = bodyRenderer?.sprite; |
| 2162 | const clothSprite = clothRenderer?.sprite; |
| 2163 | if (!bodySprite || !clothSprite) |
| 2164 | { return null; } |
| 2165 | const clothUv = clothSprite.getUvRect?.(clothRenderer.subImage | 0) |
| 2166 | ?? { u0: 0, v0: 0, u1: 1, v1: 1 }; |
| 2167 | const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0) |
| 2168 | ?? { u0: 0, v0: 0, u1: 1, v1: 1 }; |
| 2169 | return { |
| 2170 | u_clothSize: [clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX], |
| 2171 | u_bodySize: [bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX], |
| 2172 | u_pivotFromBottom: PIVOT_FROM_BOTTOM_PX, |
| 2173 | u_clothUvRect: [clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1], |
| 2174 | u_bodyUvRect: [bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1] |
| 2175 | }; |
| 2176 | } |
| 2177 | |
| 2178 | #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null) |
| 2179 | { |
| 2180 | if (!overlay?.renderer || entity?.object?.renderer == null) |
| 2181 | { return; } |
| 2182 | const bodyMap = this.#bodySecondaryMap(entity); |
| 2183 | const maskUniforms = this.#tightFitMaskUniforms(overlay, entity); |
| 2184 | if (!bodyMap || !maskUniforms) |
| 2185 | { |
| 2186 | this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor); |
| 2187 | return; |
| 2188 | } |
| 2189 | overlay._lit = true; |
| 2190 | const dark = Math.min(1, Math.max(0, darkness ?? 0)); |
| 2191 | const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); |
| 2192 | const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX; |
| 2193 | const tint = tintColor ? normalizeRgb(tintColor) : null; |
| 2194 | overlay.renderer.secondaryMap = bodyMap; |
| 2195 | if (tint) |
| 2196 | { |
| 2197 | overlay.renderer.shader = getTightFitTintLitSpriteShader(); |
| 2198 | overlay.renderer.shaderUniforms = { |
| 2199 | u_darkness: dark, |
| 2200 | u_strength: flash, |
| 2201 | u_wade: wade ? 1 : 0, |
| 2202 | u_spriteHeight: height, |
| 2203 | u_useTint: 1, |
| 2204 | u_tintColor: [tint.r, tint.g, tint.b], |
| 2205 | ...maskUniforms |
| 2206 | }; |
| 2207 | } |
| 2208 | else |
| 2209 | { |
| 2210 | overlay.renderer.shader = getTightFitLitSpriteShader(); |
| 2211 | overlay.renderer.shaderUniforms = { |
| 2212 | u_darkness: dark, |
| 2213 | u_strength: flash, |
| 2214 | u_wade: wade ? 1 : 0, |
| 2215 | u_spriteHeight: height, |
| 2216 | ...maskUniforms |
| 2217 | }; |
| 2218 | } |
| 2219 | } |
| 2220 | |
| 2221 | #syncDualTintLitSprite (object, darkness, dualTint, flashStrength = 0, wade = false) |
| 2222 | { |
| 2223 | if (!object?.renderer || object._lit === false || !dualTint) |
| 2224 | { return; } |
| 2225 | object._lit = true; |
| 2226 | const shaft = normalizeRgb(dualTint.shaft); |
| 2227 | const tip = normalizeRgb(dualTint.tip); |
| 2228 | const dark = Math.min(1, Math.max(0, darkness ?? 0)); |
| 2229 | const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); |
| 2230 | const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX; |
| 2231 | object.renderer.shader = getDualTintLitSpriteShader(); |
| 2232 | object.renderer.shaderUniforms = { |
| 2233 | u_darkness: dark, |
| 2234 | u_strength: flash, |
| 2235 | u_wade: wade ? 1 : 0, |
| 2236 | u_spriteHeight: height, |
| 2237 | u_shaftTint: [shaft.r, shaft.g, shaft.b], |
| 2238 | u_tipTint: [tip.r, tip.g, tip.b] |
| 2239 | }; |
| 2240 | object.renderer.secondaryMap = null; |
| 2241 | } |
| 2242 | |
| 2243 | #syncGroundItemSprite (item, darkness) |
| 2244 | { |
| 2245 | if (item?.dualTint) |
| 2246 | { |
| 2247 | this.#syncDualTintLitSprite(item.object, darkness, item.dualTint); |
| 2248 | return; |
| 2249 | } |
| 2250 | this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null); |
| 2251 | } |
| 2252 | |
| 2253 | #groundTypeAt (tileX, tileY) |
| 2254 | { |
| 2255 | const ground = this.#groundAtTile(tileX, tileY); |
| 2256 | return ground == null ? null : normalizeGround(ground).typeId; |
| 2257 | } |
| 2258 | |
| 2259 | /** Ground entry at a world tile, including editor hover preview when present. */ |
| 2260 | #groundAtTile (tileX, tileY) |
| 2261 | { |
| 2262 | if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY |
| 2263 | && this.preview.ground !== undefined) |
| 2264 | { return this.preview.ground; } |
| 2265 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 2266 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 2267 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 2268 | if (!snapshot) |
| 2269 | { return null; } |
| 2270 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 2271 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 2272 | const index = localY * CHUNK_SIZE + localX; |
| 2273 | return snapshot.grounds?.[index] ?? null; |
| 2274 | } |
| 2275 | |
| 2276 | #waterCoastEdges (tileX, tileY) |
| 2277 | { |
| 2278 | const season = this.worldSeason; |
| 2279 | return { |
| 2280 | n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0, |
| 2281 | e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0, |
| 2282 | s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0, |
| 2283 | w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 0 |
| 2284 | }; |
| 2285 | } |
| 2286 | |
| 2287 | #syncWaterGroundSprite (object, corners, ambientDark, edges, timeSec, fallbackLit = 1) |
| 2288 | { |
| 2289 | if (!object?.renderer) |
| 2290 | { return; } |
| 2291 | const lit = corners ?? { |
| 2292 | nw: fallbackLit, |
| 2293 | ne: fallbackLit, |
| 2294 | sw: fallbackLit, |
| 2295 | se: fallbackLit |
| 2296 | }; |
| 2297 | const dark = Math.min(1, Math.max(0, ambientDark ?? 0)); |
| 2298 | object._lit = true; |
| 2299 | object.renderer.shader = getWaterGroundShader(); |
| 2300 | object.renderer.secondaryMap = null; |
| 2301 | object.renderer.shaderUniforms = { |
| 2302 | u_ambientDark: dark, |
| 2303 | u_litNW: lit.nw, |
| 2304 | u_litNE: lit.ne, |
| 2305 | u_litSW: lit.sw, |
| 2306 | u_litSE: lit.se, |
| 2307 | u_time: timeSec, |
| 2308 | u_edgeN: edges?.n ?? 0, |
| 2309 | u_edgeE: edges?.e ?? 0, |
| 2310 | u_edgeS: edges?.s ?? 0, |
| 2311 | u_edgeW: edges?.w ?? 0 |
| 2312 | }; |
| 2313 | } |
| 2314 | |
| 2315 | /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */ |
| 2316 | #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null) |
| 2317 | { |
| 2318 | if (!objects?.ground) |
| 2319 | { return; } |
| 2320 | if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason)) |
| 2321 | { |
| 2322 | objects.waterEdges = null; |
| 2323 | this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0); |
| 2324 | return; |
| 2325 | } |
| 2326 | const fallbackLit = ambientDark > 0 |
| 2327 | ? 1 - (objects.shadeAlpha ?? 0) / ambientDark |
| 2328 | : 1; |
| 2329 | const chunkX = Math.floor(objects.tileX / CHUNK_SIZE); |
| 2330 | const chunkY = Math.floor(objects.tileY / CHUNK_SIZE); |
| 2331 | const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`); |
| 2332 | const localX = objects.tileX - chunkX * CHUNK_SIZE; |
| 2333 | const localY = objects.tileY - chunkY * CHUNK_SIZE; |
| 2334 | let litCorners = null; |
| 2335 | if (chunkBaked) |
| 2336 | { |
| 2337 | if (this.lightingMode === "simple") |
| 2338 | { |
| 2339 | const gridW = CHUNK_SIZE + 2; |
| 2340 | const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit; |
| 2341 | litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity }; |
| 2342 | } |
| 2343 | else |
| 2344 | { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); } |
| 2345 | } |
| 2346 | objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY); |
| 2347 | this.#syncWaterGroundSprite( |
| 2348 | objects.ground, |
| 2349 | litCorners, |
| 2350 | ambientDark, |
| 2351 | objects.waterEdges, |
| 2352 | timeSec, |
| 2353 | fallbackLit |
| 2354 | ); |
| 2355 | } |
| 2356 | |
| 2357 | #ambientDarkness () |
| 2358 | { |
| 2359 | const hour = this.nightPreview ?? this.worldHour; |
| 2360 | const calendar = nightFactor(hour, this.settings.nightDarkness); |
| 2361 | let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar); |
| 2362 | if (dark == null) |
| 2363 | { dark = calendar; } |
| 2364 | if (this.localBlind) |
| 2365 | { dark = Math.min(1, dark + 0.85); } |
| 2366 | return dark; |
| 2367 | } |
| 2368 | |
| 2369 | setLocalBlind (blind) |
| 2370 | { |
| 2371 | this.localBlind = !!blind; |
| 2372 | } |
| 2373 | |
| 2374 | /** Soft vision bubble while blinded (client-only; stacks with ambient). */ |
| 2375 | #blindVisionLight () |
| 2376 | { |
| 2377 | if (!this.localBlind) |
| 2378 | { return null; } |
| 2379 | const local = this.entities.get(this.localEntityId); |
| 2380 | if (!local) |
| 2381 | { return null; } |
| 2382 | const tileSize = this.tileSize(); |
| 2383 | return { |
| 2384 | tileX: Math.floor(local.visualX / tileSize), |
| 2385 | tileY: Math.floor(local.visualY / tileSize), |
| 2386 | range: 2.25, |
| 2387 | intensity: 1 |
| 2388 | }; |
| 2389 | } |
| 2390 | |
| 2391 | #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null) |
| 2392 | { |
| 2393 | const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0; |
| 2394 | const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0; |
| 2395 | const dark = (fromAlpha + toAlpha) / 2; |
| 2396 | if (dualTint) |
| 2397 | { |
| 2398 | this.#syncDualTintLitSprite(object, dark, dualTint); |
| 2399 | return; |
| 2400 | } |
| 2401 | this.#syncLitSprite(object, dark); |
| 2402 | } |
| 2403 | |
| 2404 | #dualTintFromPayload (payload) |
| 2405 | { |
| 2406 | if (!payload?.shaftTint || !payload?.tipTint) |
| 2407 | { return null; } |
| 2408 | return { shaft: payload.shaftTint, tip: payload.tipTint }; |
| 2409 | } |
| 2410 | |
| 2411 | #syncHpBar (entity) |
| 2412 | { |
| 2413 | const current = entity.health; |
| 2414 | const max = entity.maxHealth; |
| 2415 | const show = current != null |
| 2416 | && max != null |
| 2417 | && max > 0 |
| 2418 | && current < max; |
| 2419 | if (!show) |
| 2420 | { |
| 2421 | entity.hpBar?.destroy(); |
| 2422 | entity.hpBar = null; |
| 2423 | entity.hpBarCanvas = null; |
| 2424 | return; |
| 2425 | } |
| 2426 | if (!entity.hpBarCanvas) |
| 2427 | { |
| 2428 | entity.hpBarCanvas = document.createElement("canvas"); |
| 2429 | entity.hpBarCanvas.width = HP_BAR_W; |
| 2430 | entity.hpBarCanvas.height = HP_BAR_H; |
| 2431 | const image = frameworkImageFromCanvas(entity.hpBarCanvas); |
| 2432 | entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR); |
| 2433 | this.#markUnlit(entity.hpBar); |
| 2434 | this.scene.addObject(entity.hpBar); |
| 2435 | } |
| 2436 | drawHpBar(entity.hpBarCanvas, current, max); |
| 2437 | invalidateCanvasTexture(this.scene, entity.hpBarCanvas); |
| 2438 | } |
| 2439 | |
| 2440 | #placeHpBar (entity, pivotX, pivotY) |
| 2441 | { |
| 2442 | if (!entity.hpBar) |
| 2443 | { return; } |
| 2444 | const sprite = entity.object?.renderer?.sprite; |
| 2445 | if (!sprite) |
| 2446 | { return; } |
| 2447 | const zoom = this.zoom; |
| 2448 | const drawH = sprite.height * zoom; |
| 2449 | const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom); |
| 2450 | const spriteTop = centerY - drawH / 2; |
| 2451 | const barW = HP_BAR_W * zoom; |
| 2452 | const barH = HP_BAR_H * zoom; |
| 2453 | entity.hpBar.transform.position.x = pivotX; |
| 2454 | entity.hpBar.transform.position.y = spriteTop - barH / 2; |
| 2455 | entity.hpBar.transform.size = new vector(barW, barH); |
| 2456 | entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR); |
| 2457 | this.#markSortDirty(); |
| 2458 | } |
| 2459 | |
| 2460 | #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {}) |
| 2461 | { |
| 2462 | this.#bakeAndPlaceChunk(snapshot); |
| 2463 | this.#relayoutChunkTiles(snapshot); |
| 2464 | if (this.softTerrain && refreshSoftNeighbors) |
| 2465 | { this.#rebuildSoftTerrainNeighborChunks(snapshot); } |
| 2466 | } |
| 2467 | |
| 2468 | #relayoutChunk (snapshot) |
| 2469 | { |
| 2470 | this.#layoutBakedChunk(snapshot); |
| 2471 | this.#relayoutChunkTiles(snapshot); |
| 2472 | } |
| 2473 | |
| 2474 | #relayoutChunkTiles (snapshot) |
| 2475 | { |
| 2476 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 2477 | { |
| 2478 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 2479 | { |
| 2480 | const tileX = snapshot.chunkX * CHUNK_SIZE + localX; |
| 2481 | const tileY = snapshot.chunkY * CHUNK_SIZE + localY; |
| 2482 | this.#drawTile(tileX, tileY); |
| 2483 | } |
| 2484 | } |
| 2485 | } |
| 2486 | |
| 2487 | #scheduleChunkRebuild (snapshot) |
| 2488 | { |
| 2489 | if (!snapshot) |
| 2490 | { return; } |
| 2491 | this.#chunkRebuildKeys.add(`${snapshot.chunkX},${snapshot.chunkY}`); |
| 2492 | this.#cancelIdlePrefetch(); |
| 2493 | this.#ensureChunkFlushScheduled(); |
| 2494 | } |
| 2495 | |
| 2496 | #scheduleEdgeRebuild () |
| 2497 | { |
| 2498 | this.#edgesDirty = true; |
| 2499 | this.#cancelIdlePrefetch(); |
| 2500 | this.#ensureChunkFlushScheduled(); |
| 2501 | } |
| 2502 | |
| 2503 | #ensureChunkFlushScheduled () |
| 2504 | { |
| 2505 | if (this.#chunkRebuildRaf) |
| 2506 | { return; } |
| 2507 | this.#cancelIdlePrefetch(); |
| 2508 | this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork()); |
| 2509 | } |
| 2510 | |
| 2511 | #notePlayerTile (tileX, tileY) |
| 2512 | { |
| 2513 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 2514 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 2515 | if (this.#playerChunkX != null |
| 2516 | && (chunkX !== this.#playerChunkX || chunkY !== this.#playerChunkY)) |
| 2517 | { |
| 2518 | const dx = chunkX - this.#playerChunkX; |
| 2519 | const dy = chunkY - this.#playerChunkY; |
| 2520 | if (dx !== 0) |
| 2521 | { this.#playerMoveChunkDx = Math.sign(dx); } |
| 2522 | if (dy !== 0) |
| 2523 | { this.#playerMoveChunkDy = Math.sign(dy); } |
| 2524 | } |
| 2525 | this.#playerChunkX = chunkX; |
| 2526 | this.#playerChunkY = chunkY; |
| 2527 | } |
| 2528 | |
| 2529 | #playerChunkCoords () |
| 2530 | { |
| 2531 | const local = this.entities.get(this.localEntityId); |
| 2532 | if (local) |
| 2533 | { |
| 2534 | return { |
| 2535 | chunkX: Math.floor(local.tileX / CHUNK_SIZE), |
| 2536 | chunkY: Math.floor(local.tileY / CHUNK_SIZE) |
| 2537 | }; |
| 2538 | } |
| 2539 | if (this.#playerChunkX != null && this.#playerChunkY != null) |
| 2540 | { |
| 2541 | return { chunkX: this.#playerChunkX, chunkY: this.#playerChunkY }; |
| 2542 | } |
| 2543 | return null; |
| 2544 | } |
| 2545 | |
| 2546 | /** Lower score = bake sooner in urgent mode; idle mode inverts distance. */ |
| 2547 | #chunkRebuildScore (key, mode = "urgent") |
| 2548 | { |
| 2549 | const [chunkX, chunkY] = key.split(",").map(Number); |
| 2550 | const player = this.#playerChunkCoords(); |
| 2551 | if (!player) |
| 2552 | { return 0; } |
| 2553 | const dx = chunkX - player.chunkX; |
| 2554 | const dy = chunkY - player.chunkY; |
| 2555 | const dist = Math.abs(dx) + Math.abs(dy); |
| 2556 | let ahead = 0; |
| 2557 | if (this.#playerMoveChunkDx !== 0 || this.#playerMoveChunkDy !== 0) |
| 2558 | { ahead = dx * this.#playerMoveChunkDx + dy * this.#playerMoveChunkDy; } |
| 2559 | if (mode === "idle") |
| 2560 | { |
| 2561 | return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0)); |
| 2562 | } |
| 2563 | return dist * 10 - Math.max(0, ahead) * 3; |
| 2564 | } |
| 2565 | |
| 2566 | #sortedChunkRebuildKeys (mode = "urgent") |
| 2567 | { |
| 2568 | return [...this.#chunkRebuildKeys].sort((a, b) => |
| 2569 | this.#chunkRebuildScore(a, mode) - this.#chunkRebuildScore(b, mode)); |
| 2570 | } |
| 2571 | |
| 2572 | #discoverUnbakedChunks () |
| 2573 | { |
| 2574 | for (const key of this.chunks.keys()) |
| 2575 | { |
| 2576 | if (!this.bakedChunks.has(key)) |
| 2577 | { this.#chunkRebuildKeys.add(key); } |
| 2578 | } |
| 2579 | } |
| 2580 | |
| 2581 | #hasUnbakedChunks () |
| 2582 | { |
| 2583 | for (const key of this.chunks.keys()) |
| 2584 | { |
| 2585 | if (!this.bakedChunks.has(key)) |
| 2586 | { return true; } |
| 2587 | } |
| 2588 | return false; |
| 2589 | } |
| 2590 | |
| 2591 | #pickIdlePrefetchSnapshot () |
| 2592 | { |
| 2593 | let best = null; |
| 2594 | let bestScore = Infinity; |
| 2595 | for (const snapshot of this.chunks.values()) |
| 2596 | { |
| 2597 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 2598 | if (this.bakedChunks.has(key) || this.#chunkRebuildKeys.has(key)) |
| 2599 | { continue; } |
| 2600 | const score = this.#chunkRebuildScore(key, "idle"); |
| 2601 | if (score < bestScore) |
| 2602 | { |
| 2603 | bestScore = score; |
| 2604 | best = snapshot; |
| 2605 | } |
| 2606 | } |
| 2607 | return best; |
| 2608 | } |
| 2609 | |
| 2610 | #cancelIdlePrefetch () |
| 2611 | { |
| 2612 | if (this.#idlePrefetchId && typeof cancelIdleCallback === "function") |
| 2613 | { cancelIdleCallback(this.#idlePrefetchId); } |
| 2614 | this.#idlePrefetchId = 0; |
| 2615 | } |
| 2616 | |
| 2617 | #scheduleIdleChunkPrefetch () |
| 2618 | { |
| 2619 | if (this.#idlePrefetchId || this.#chunkRebuildRaf || this.#chunkRebuildKeys.size) |
| 2620 | { return; } |
| 2621 | if (typeof requestIdleCallback !== "function") |
| 2622 | { return; } |
| 2623 | if (!this.#hasUnbakedChunks()) |
| 2624 | { return; } |
| 2625 | this.#idlePrefetchId = requestIdleCallback( |
| 2626 | (deadline) => this.#runIdleChunkPrefetch(deadline), |
| 2627 | { timeout: 2500 } |
| 2628 | ); |
| 2629 | } |
| 2630 | |
| 2631 | #runIdleChunkPrefetch (deadline) |
| 2632 | { |
| 2633 | this.#idlePrefetchId = 0; |
| 2634 | if (this.#chunkRebuildRaf || this.#chunkRebuildKeys.size) |
| 2635 | { return; } |
| 2636 | this.#discoverUnbakedChunks(); |
| 2637 | if (this.#chunkRebuildKeys.size) |
| 2638 | { |
| 2639 | this.#ensureChunkFlushScheduled(); |
| 2640 | return; |
| 2641 | } |
| 2642 | const snapshot = this.#pickIdlePrefetchSnapshot(); |
| 2643 | if (!snapshot) |
| 2644 | { return; } |
| 2645 | if (deadline.timeRemaining() <= 4 && !deadline.didTimeout) |
| 2646 | { |
| 2647 | this.#scheduleIdleChunkPrefetch(); |
| 2648 | return; |
| 2649 | } |
| 2650 | this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); |
| 2651 | if (this.#hasUnbakedChunks()) |
| 2652 | { this.#scheduleIdleChunkPrefetch(); } |
| 2653 | } |
| 2654 | |
| 2655 | #flushChunkWork () |
| 2656 | { |
| 2657 | this.#chunkRebuildRaf = 0; |
| 2658 | const keys = this.#sortedChunkRebuildKeys("urgent"); |
| 2659 | const batch = keys.slice(0, this.#CHUNK_REBUILD_BATCH); |
| 2660 | const rest = keys.slice(this.#CHUNK_REBUILD_BATCH); |
| 2661 | this.#chunkRebuildKeys.clear(); |
| 2662 | for (const key of rest) |
| 2663 | { this.#chunkRebuildKeys.add(key); } |
| 2664 | for (const key of batch) |
| 2665 | { |
| 2666 | const snap = this.chunks.get(key); |
| 2667 | if (snap) |
| 2668 | { this.#rebuildChunk(snap, { refreshSoftNeighbors: false }); } |
| 2669 | } |
| 2670 | if (this.#chunkRebuildKeys.size) |
| 2671 | { |
| 2672 | this.#ensureChunkFlushScheduled(); |
| 2673 | return; |
| 2674 | } |
| 2675 | if (this.#edgesDirty) |
| 2676 | { |
| 2677 | this.#rebuildAllEdges(); |
| 2678 | this.#edgesDirty = false; |
| 2679 | } |
| 2680 | this.#scheduleIdleChunkPrefetch(); |
| 2681 | } |
| 2682 | |
| 2683 | #previewEqual (a, b) |
| 2684 | { |
| 2685 | if (a === b) |
| 2686 | { return true; } |
| 2687 | if (!a || !b) |
| 2688 | { return false; } |
| 2689 | return a.tileX === b.tileX |
| 2690 | && a.tileY === b.tileY |
| 2691 | && this.#previewPart(a.ground) === this.#previewPart(b.ground) |
| 2692 | && this.#previewPart(a.block) === this.#previewPart(b.block); |
| 2693 | } |
| 2694 | |
| 2695 | #previewPart (value) |
| 2696 | { |
| 2697 | return value === undefined ? undefined : JSON.stringify(value); |
| 2698 | } |
| 2699 | |
| 2700 | #rebuildSoftTerrainNeighborChunks (snapshot) |
| 2701 | { |
| 2702 | for (let dy = -1; dy <= 1; dy++) |
| 2703 | { |
| 2704 | for (let dx = -1; dx <= 1; dx++) |
| 2705 | { |
| 2706 | if (dx === 0 && dy === 0) |
| 2707 | { continue; } |
| 2708 | const neighbor = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`); |
| 2709 | if (neighbor) |
| 2710 | { this.#rebuildChunk(neighbor, { refreshSoftNeighbors: false }); } |
| 2711 | } |
| 2712 | } |
| 2713 | } |
| 2714 | |
| 2715 | #rebakeAllChunks () |
| 2716 | { |
| 2717 | for (const snapshot of this.chunks.values()) |
| 2718 | { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); } |
| 2719 | } |
| 2720 | |
| 2721 | #bakeAndPlaceChunk (snapshot) |
| 2722 | { |
| 2723 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 2724 | const atlases = bakeChunkAtlases({ |
| 2725 | snapshot, |
| 2726 | catalog: this.catalog, |
| 2727 | images: this.game.images, |
| 2728 | preview: this.preview, |
| 2729 | season: this.worldSeason, |
| 2730 | softTerrain: this.softTerrain, |
| 2731 | resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY), |
| 2732 | cache: this.#atlasCache |
| 2733 | }); |
| 2734 | const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX; |
| 2735 | let baked = this.bakedChunks.get(key); |
| 2736 | this.#releaseBakedAtlasRefs(baked); |
| 2737 | |
| 2738 | const groundImage = this.#atlasCache.getImage(atlases.cacheRefs?.ground); |
| 2739 | const blockImages = atlases.cacheRefs?.blockRows.map((entry) => this.#atlasCache.getImage(entry)) |
| 2740 | ?? atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)); |
| 2741 | const bloomImage = this.#atlasCache.getImage(atlases.cacheRefs?.bloom) |
| 2742 | ?? frameworkImageFromCanvas(atlases.bloom); |
| 2743 | |
| 2744 | if (!baked) |
| 2745 | { |
| 2746 | const lightmapCanvas = makeLightmapCanvas(atlasPx); |
| 2747 | baked = { |
| 2748 | groundCanvas: atlases.ground, |
| 2749 | blockCanvases: atlases.blockRows, |
| 2750 | bloomCanvas: atlases.bloom, |
| 2751 | lightmapCanvas, |
| 2752 | groundImage, |
| 2753 | blockImages, |
| 2754 | bloomImage, |
| 2755 | lightmapImage: frameworkImageFromCanvas(lightmapCanvas), |
| 2756 | groundObject: null, |
| 2757 | blockObjects: [], |
| 2758 | bloomObject: null, |
| 2759 | tallBlocks: atlases.tallBlocks, |
| 2760 | animatedGrounds: atlases.animatedGrounds, |
| 2761 | lightmapPixels: null, |
| 2762 | atlasCacheRefs: atlases.cacheRefs |
| 2763 | }; |
| 2764 | baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND); |
| 2765 | this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1); |
| 2766 | this.scene.addObject(baked.groundObject); |
| 2767 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 2768 | { |
| 2769 | const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK); |
| 2770 | this.#applyAtlasLighting(object, baked.lightmapImage, row); |
| 2771 | this.scene.addObject(object); |
| 2772 | baked.blockObjects.push(object); |
| 2773 | } |
| 2774 | baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK); |
| 2775 | baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; |
| 2776 | this.#markUnlit(baked.bloomObject); |
| 2777 | this.scene.addObject(baked.bloomObject); |
| 2778 | this.bakedChunks.set(key, baked); |
| 2779 | } |
| 2780 | else |
| 2781 | { |
| 2782 | if (baked.groundCanvas !== atlases.ground) |
| 2783 | { |
| 2784 | baked.groundCanvas = atlases.ground; |
| 2785 | baked.groundImage = groundImage; |
| 2786 | baked.groundObject.image = groundImage; |
| 2787 | } |
| 2788 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 2789 | { |
| 2790 | if (baked.blockCanvases[row] !== atlases.blockRows[row]) |
| 2791 | { |
| 2792 | baked.blockCanvases[row] = atlases.blockRows[row]; |
| 2793 | baked.blockImages[row] = blockImages[row]; |
| 2794 | baked.blockObjects[row].image = blockImages[row]; |
| 2795 | } |
| 2796 | } |
| 2797 | if (baked.bloomCanvas !== atlases.bloom) |
| 2798 | { |
| 2799 | baked.bloomCanvas = atlases.bloom; |
| 2800 | baked.bloomImage = bloomImage; |
| 2801 | baked.bloomObject.image = bloomImage; |
| 2802 | } |
| 2803 | baked.tallBlocks = atlases.tallBlocks; |
| 2804 | baked.animatedGrounds = atlases.animatedGrounds; |
| 2805 | baked.atlasCacheRefs = atlases.cacheRefs; |
| 2806 | } |
| 2807 | baked.chunkX = snapshot.chunkX; |
| 2808 | baked.chunkY = snapshot.chunkY; |
| 2809 | baked.lightmapCacheKey = null; |
| 2810 | this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY); |
| 2811 | this.#layoutBakedChunk(snapshot); |
| 2812 | this.#queueBakedChunkTextures(baked, snapshot.chunkX, snapshot.chunkY); |
| 2813 | } |
| 2814 | |
| 2815 | #releaseBakedAtlasRefs (baked) |
| 2816 | { |
| 2817 | if (!baked?.atlasCacheRefs) |
| 2818 | { return; } |
| 2819 | this.#atlasCache.release(baked.atlasCacheRefs.ground); |
| 2820 | for (const entry of baked.atlasCacheRefs.blockRows ?? []) |
| 2821 | { this.#atlasCache.release(entry); } |
| 2822 | this.#atlasCache.release(baked.atlasCacheRefs.bloom); |
| 2823 | baked.atlasCacheRefs = null; |
| 2824 | } |
| 2825 | |
| 2826 | #chunkTextureWarmPriority (chunkX, chunkY) |
| 2827 | { |
| 2828 | const local = this.entities.get(this.localEntityId); |
| 2829 | if (!local) |
| 2830 | { return 999; } |
| 2831 | const playerChunkX = Math.floor(local.tileX / CHUNK_SIZE); |
| 2832 | const playerChunkY = Math.floor(local.tileY / CHUNK_SIZE); |
| 2833 | return Math.abs(chunkX - playerChunkX) + Math.abs(chunkY - playerChunkY); |
| 2834 | } |
| 2835 | |
| 2836 | #queueCanvasTextureWarm (canvas, chunkX, chunkY) |
| 2837 | { |
| 2838 | if (!canvas || this.#pendingTextureCanvasSet.has(canvas)) |
| 2839 | { return; } |
| 2840 | this.#pendingTextureCanvasSet.add(canvas); |
| 2841 | this.#pendingTextureCanvases.push({ |
| 2842 | canvas, |
| 2843 | priority: this.#chunkTextureWarmPriority(chunkX, chunkY) |
| 2844 | }); |
| 2845 | this.#scheduleTextureWarm(); |
| 2846 | } |
| 2847 | |
| 2848 | #queueBakedChunkTextures (baked, chunkX, chunkY) |
| 2849 | { |
| 2850 | if (!baked) |
| 2851 | { return; } |
| 2852 | const refs = baked.atlasCacheRefs; |
| 2853 | const maybeWarm = (canvas, entry) => |
| 2854 | { |
| 2855 | if (!canvas) |
| 2856 | { return; } |
| 2857 | if (entry && this.#atlasCache.isWarmed(canvas)) |
| 2858 | { return; } |
| 2859 | this.#queueCanvasTextureWarm(canvas, chunkX, chunkY); |
| 2860 | }; |
| 2861 | maybeWarm(baked.groundCanvas, refs?.ground); |
| 2862 | for (let row = 0; row < (baked.blockCanvases ?? []).length; row++) |
| 2863 | { maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); } |
| 2864 | maybeWarm(baked.bloomCanvas, refs?.bloom); |
| 2865 | this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY); |
| 2866 | } |
| 2867 | |
| 2868 | #scheduleTextureWarm () |
| 2869 | { |
| 2870 | if (this.#textureWarmRaf) |
| 2871 | { return; } |
| 2872 | this.#textureWarmRaf = requestAnimationFrame(() => this.#flushTextureWarm()); |
| 2873 | } |
| 2874 | |
| 2875 | #flushTextureWarm () |
| 2876 | { |
| 2877 | this.#textureWarmRaf = 0; |
| 2878 | if (!this.#pendingTextureCanvases.length) |
| 2879 | { return; } |
| 2880 | this.#pendingTextureCanvases.sort((a, b) => a.priority - b.priority); |
| 2881 | const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH); |
| 2882 | for (const entry of batch) |
| 2883 | { |
| 2884 | this.#pendingTextureCanvasSet.delete(entry.canvas); |
| 2885 | setNearestFilter(this.scene, entry.canvas); |
| 2886 | this.#atlasCache.markWarmed(entry.canvas); |
| 2887 | } |
| 2888 | if (this.#pendingTextureCanvases.length) |
| 2889 | { this.#scheduleTextureWarm(); } |
| 2890 | } |
| 2891 | |
| 2892 | #applyAtlasLighting (object, lightmapImage, lightRow) |
| 2893 | { |
| 2894 | if (!object?.renderer) |
| 2895 | { return; } |
| 2896 | object._lit = true; |
| 2897 | object.renderer.shader = getAtlasLightingShader(); |
| 2898 | object.renderer.secondaryMap = lightmapImage; |
| 2899 | object.renderer.shaderUniforms = { |
| 2900 | u_ambientDark: 0, |
| 2901 | u_lightRow: lightRow |
| 2902 | }; |
| 2903 | } |
| 2904 | |
| 2905 | #layoutBakedChunk (snapshot) |
| 2906 | { |
| 2907 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 2908 | const baked = this.bakedChunks.get(key); |
| 2909 | if (!baked) |
| 2910 | { return; } |
| 2911 | const size = this.tileSize(); |
| 2912 | const left = snapshot.chunkX * CHUNK_SIZE * size; |
| 2913 | const top = snapshot.chunkY * CHUNK_SIZE * size; |
| 2914 | const chunkPx = CHUNK_SIZE * size; |
| 2915 | baked.groundObject.transform.position.x = left + chunkPx / 2; |
| 2916 | baked.groundObject.transform.position.y = top + chunkPx / 2; |
| 2917 | baked.groundObject.transform.size = new vector(chunkPx, chunkPx); |
| 2918 | baked.groundObject.layer = LAYER_GROUND; |
| 2919 | |
| 2920 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 2921 | { |
| 2922 | const object = baked.blockObjects[row]; |
| 2923 | const rowY = top + row * size + size / 2; |
| 2924 | object.transform.position.x = left + chunkPx / 2; |
| 2925 | object.transform.position.y = rowY; |
| 2926 | object.transform.size = new vector(chunkPx, size); |
| 2927 | object.layer = ySortLayer(rowY, SORT_BLOCK); |
| 2928 | } |
| 2929 | |
| 2930 | baked.bloomObject.transform.position.x = left + chunkPx / 2; |
| 2931 | baked.bloomObject.transform.position.y = top + chunkPx / 2; |
| 2932 | baked.bloomObject.transform.size = new vector(chunkPx, chunkPx); |
| 2933 | baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK); |
| 2934 | baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; |
| 2935 | this.#markSortDirty(); |
| 2936 | } |
| 2937 | |
| 2938 | #destroyBakedChunk (key) |
| 2939 | { |
| 2940 | const baked = this.bakedChunks.get(key); |
| 2941 | if (!baked) |
| 2942 | { return; } |
| 2943 | this.#releaseBakedAtlasRefs(baked); |
| 2944 | baked.groundObject?.destroy(); |
| 2945 | for (const object of baked.blockObjects ?? []) |
| 2946 | { object.destroy(); } |
| 2947 | baked.bloomObject?.destroy(); |
| 2948 | invalidateCanvasTexture(this.scene, baked.lightmapCanvas); |
| 2949 | this.bakedChunks.delete(key); |
| 2950 | } |
| 2951 | |
| 2952 | #redrawPreview () |
| 2953 | { |
| 2954 | if (!this.preview) |
| 2955 | { return; } |
| 2956 | const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`); |
| 2957 | if (snapshot) |
| 2958 | { this.#rebuildChunk(snapshot); } |
| 2959 | } |
| 2960 | |
| 2961 | #refreshWaterCoastsNear (chunkX, chunkY) |
| 2962 | { |
| 2963 | const timeSec = performance.now() / 1000; |
| 2964 | for (const objects of this.tiles.values()) |
| 2965 | { |
| 2966 | if (!objects.ground || !isWaterGround(objects.groundTypeId)) |
| 2967 | { continue; } |
| 2968 | if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1) |
| 2969 | { continue; } |
| 2970 | this.#syncGroundWaterFx(objects, this.#ambientDarkness(), timeSec); |
| 2971 | } |
| 2972 | } |
| 2973 | |
| 2974 | #drawTile (tileX, tileY) |
| 2975 | { |
| 2976 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 2977 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 2978 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 2979 | if (!snapshot) |
| 2980 | { return; } |
| 2981 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 2982 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 2983 | const index = localY * CHUNK_SIZE + localX; |
| 2984 | const key = `${tileX},${tileY}`; |
| 2985 | let objects = this.tiles.get(key); |
| 2986 | if (!objects) |
| 2987 | { |
| 2988 | objects = { chunkX, chunkY, tileX, tileY }; |
| 2989 | this.tiles.set(key, objects); |
| 2990 | } |
| 2991 | objects.tileX = tileX; |
| 2992 | objects.tileY = tileY; |
| 2993 | objects.chunkX = chunkX; |
| 2994 | objects.chunkY = chunkY; |
| 2995 | objects.light = snapshot.light[index] ?? 0; |
| 2996 | |
| 2997 | const baked = this.bakedChunks.get(`${chunkX},${chunkY}`); |
| 2998 | const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY); |
| 2999 | if (animatedGround) |
| 3000 | { |
| 3001 | objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND); |
| 3002 | if (objects.ground) |
| 3003 | { |
| 3004 | const size = this.tileSize(); |
| 3005 | objects.ground.transform.position.x = tileX * size + size / 2; |
| 3006 | objects.ground.transform.position.y = tileY * size + size / 2; |
| 3007 | objects.ground.transform.size = new vector(size, size); |
| 3008 | objects.ground.layer = LAYER_GROUND; |
| 3009 | objects.groundTypeId = animatedGround.typeId; |
| 3010 | this.#syncGroundWaterFx(objects, this.#ambientDarkness(), performance.now() / 1000); |
| 3011 | this.#markSortDirty(); |
| 3012 | } |
| 3013 | if (animatedGround.bloom) |
| 3014 | { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); } |
| 3015 | else |
| 3016 | { |
| 3017 | objects.groundBloom?.destroy(); |
| 3018 | objects.groundBloom = null; |
| 3019 | } |
| 3020 | } |
| 3021 | else |
| 3022 | { |
| 3023 | objects.ground?.destroy(); |
| 3024 | objects.ground = null; |
| 3025 | objects.groundBloom?.destroy(); |
| 3026 | objects.groundBloom = null; |
| 3027 | objects.groundTypeId = null; |
| 3028 | objects.waterEdges = null; |
| 3029 | } |
| 3030 | |
| 3031 | const tileBlock = tileBlockSpriteEntry( |
| 3032 | this.catalog, |
| 3033 | this.game.images, |
| 3034 | snapshot.blocks[index], |
| 3035 | this.worldSeason |
| 3036 | ); |
| 3037 | if (tileBlock) |
| 3038 | { |
| 3039 | const pivot = tilePivot(tileX, tileY, this.tileSize()); |
| 3040 | objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, SORT_ENTITY); |
| 3041 | if (objects.block) |
| 3042 | { |
| 3043 | this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY); |
| 3044 | this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0); |
| 3045 | } |
| 3046 | objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tileBlock.bloom, pivot, SORT_ENTITY); |
| 3047 | } |
| 3048 | else |
| 3049 | { |
| 3050 | objects.block?.destroy(); |
| 3051 | objects.block = null; |
| 3052 | objects.blockBloom?.destroy(); |
| 3053 | objects.blockBloom = null; |
| 3054 | } |
| 3055 | } |
| 3056 | |
| 3057 | #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK) |
| 3058 | { |
| 3059 | if (!name) |
| 3060 | { |
| 3061 | existing?.destroy(); |
| 3062 | return null; |
| 3063 | } |
| 3064 | const object = this.#ensureSprite(existing, name, sortOrder); |
| 3065 | if (!object) |
| 3066 | { return null; } |
| 3067 | object.renderer.layer = RENDER_LAYER_BLOOM; |
| 3068 | this.#markUnlit(object); |
| 3069 | this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder); |
| 3070 | return object; |
| 3071 | } |
| 3072 | |
| 3073 | #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1) |
| 3074 | { |
| 3075 | const sprite = object?.renderer?.sprite; |
| 3076 | if (!sprite) |
| 3077 | { return; } |
| 3078 | const zoom = this.zoom; |
| 3079 | const draw = spriteDrawSize(sprite.width, sprite.height, zoom); |
| 3080 | const factor = Math.max(0.1, Number(scale) || 1); |
| 3081 | const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom); |
| 3082 | object.transform.position.x = center.x; |
| 3083 | object.transform.position.y = center.y; |
| 3084 | object.transform.size = new vector(draw.w * factor, draw.h * factor); |
| 3085 | object.layer = ySortLayer(sortY, subOrder); |
| 3086 | this.#markSortDirty(); |
| 3087 | } |
| 3088 | |
| 3089 | #ensureSprite (existing, name, layer) |
| 3090 | { |
| 3091 | const sprite = this.game.images[name]; |
| 3092 | if (!sprite) |
| 3093 | { |
| 3094 | existing?.destroy(); |
| 3095 | return null; |
| 3096 | } |
| 3097 | if (!existing || existing.renderer.sprite !== sprite) |
| 3098 | { |
| 3099 | existing?.destroy(); |
| 3100 | existing = new GameObject(0, 0, sprite, layer); |
| 3101 | this.#syncLitSprite(existing, 0); |
| 3102 | this.scene.addObject(existing); |
| 3103 | this.#startIdleAnimation(existing); |
| 3104 | } |
| 3105 | return existing; |
| 3106 | } |
| 3107 | |
| 3108 | #startIdleAnimation (object) |
| 3109 | { |
| 3110 | const sprite = object?.renderer?.sprite; |
| 3111 | if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0) |
| 3112 | { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); } |
| 3113 | } |
| 3114 | |
| 3115 | #neighborClosed (snapshot, dir, dx, dy) |
| 3116 | { |
| 3117 | const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`); |
| 3118 | if (other) |
| 3119 | { return !other.open; } |
| 3120 | return !!snapshot.closedEdges?.[dir]; |
| 3121 | } |
| 3122 | |
| 3123 | #rebuildAllEdges () |
| 3124 | { |
| 3125 | const seen = new Set(); |
| 3126 | for (const snapshot of this.chunks.values()) |
| 3127 | { |
| 3128 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 3129 | seen.add(key); |
| 3130 | this.#rebuildChunkEdges(snapshot); |
| 3131 | } |
| 3132 | for (const key of [...this.edges.keys()]) |
| 3133 | { |
| 3134 | if (!seen.has(key)) |
| 3135 | { this.#destroyEdges(key); } |
| 3136 | } |
| 3137 | } |
| 3138 | |
| 3139 | #rebuildChunkEdges (snapshot) |
| 3140 | { |
| 3141 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 3142 | let bars = this.edges.get(key); |
| 3143 | if (!bars) |
| 3144 | { |
| 3145 | bars = {}; |
| 3146 | this.edges.set(key, bars); |
| 3147 | } |
| 3148 | |
| 3149 | const size = this.tileSize(); |
| 3150 | const chunkPx = CHUNK_SIZE * size; |
| 3151 | const left = snapshot.chunkX * CHUNK_SIZE * size; |
| 3152 | const top = snapshot.chunkY * CHUNK_SIZE * size; |
| 3153 | const centerX = left + chunkPx / 2; |
| 3154 | const centerY = top + chunkPx / 2; |
| 3155 | const thickness = Math.max(2, Math.round(2 * this.zoom)); |
| 3156 | const draw = snapshot.open === true; |
| 3157 | |
| 3158 | bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1), |
| 3159 | centerX, top, chunkPx, thickness, true); |
| 3160 | bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1), |
| 3161 | centerX, top + chunkPx, chunkPx, thickness, true); |
| 3162 | bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0), |
| 3163 | left, centerY, chunkPx, thickness, false); |
| 3164 | bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0), |
| 3165 | left + chunkPx, centerY, chunkPx, thickness, false); |
| 3166 | } |
| 3167 | |
| 3168 | #edgeBar (existing, visible, x, y, length, thickness, horizontal) |
| 3169 | { |
| 3170 | if (!visible) |
| 3171 | { |
| 3172 | if (existing) |
| 3173 | { existing.renderer.visible = false; } |
| 3174 | return existing; |
| 3175 | } |
| 3176 | |
| 3177 | existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE); |
| 3178 | this.#markUnlit(existing); |
| 3179 | existing.renderer.visible = true; |
| 3180 | existing.transform.position.x = x; |
| 3181 | existing.transform.position.y = y; |
| 3182 | existing.transform.size = horizontal |
| 3183 | ? new vector(length, thickness) |
| 3184 | : new vector(thickness, length); |
| 3185 | existing.layer = LAYER_EDGE; |
| 3186 | this.#markSortDirty(); |
| 3187 | return existing; |
| 3188 | } |
| 3189 | |
| 3190 | #destroyEdges (key) |
| 3191 | { |
| 3192 | const bars = this.edges.get(key); |
| 3193 | if (!bars) |
| 3194 | { return; } |
| 3195 | bars.north?.destroy(); |
| 3196 | bars.east?.destroy(); |
| 3197 | bars.south?.destroy(); |
| 3198 | bars.west?.destroy(); |
| 3199 | this.edges.delete(key); |
| 3200 | } |
| 3201 | |
| 3202 | #entityShadeAlpha (entity, now) |
| 3203 | { |
| 3204 | const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0; |
| 3205 | if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null) |
| 3206 | { return toAlpha; } |
| 3207 | const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0; |
| 3208 | const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1)); |
| 3209 | return fromAlpha + (toAlpha - fromAlpha) * t; |
| 3210 | } |
| 3211 | |
| 3212 | #markSortDirty () |
| 3213 | { |
| 3214 | this.scene._sortDirty = true; |
| 3215 | } |
| 3216 | |
| 3217 | /** Player chunk for dynamic lighting; null in editor / before spawn → no 3×3 limit. */ |
| 3218 | #activeLightingCenterChunk () |
| 3219 | { |
| 3220 | const local = this.entities.get(this.localEntityId); |
| 3221 | if (!local) |
| 3222 | { return null; } |
| 3223 | return { |
| 3224 | chunkX: Math.floor(local.tileX / CHUNK_SIZE), |
| 3225 | chunkY: Math.floor(local.tileY / CHUNK_SIZE) |
| 3226 | }; |
| 3227 | } |
| 3228 | |
| 3229 | #isActiveLightingChunk (chunkX, chunkY) |
| 3230 | { |
| 3231 | const center = this.#activeLightingCenterChunk(); |
| 3232 | if (!center) |
| 3233 | { return true; } |
| 3234 | return Math.abs(chunkX - center.chunkX) <= 1 && Math.abs(chunkY - center.chunkY) <= 1; |
| 3235 | } |
| 3236 | |
| 3237 | #isActiveLightingTile (tileX, tileY) |
| 3238 | { |
| 3239 | return this.#isActiveLightingChunk( |
| 3240 | Math.floor(tileX / CHUNK_SIZE), |
| 3241 | Math.floor(tileY / CHUNK_SIZE) |
| 3242 | ); |
| 3243 | } |
| 3244 | |
| 3245 | #updateShade () |
| 3246 | { |
| 3247 | const ambientDark = this.#ambientDarkness(); |
| 3248 | const now = performance.now(); |
| 3249 | this.dynamicLights = this.dynamicLights.filter((light) => light.until > now); |
| 3250 | |
| 3251 | const activeLights = [...this.dynamicLights]; |
| 3252 | const tileSize = this.tileSize(); |
| 3253 | const blindLight = this.#blindVisionLight(); |
| 3254 | if (blindLight) |
| 3255 | { activeLights.push(blindLight); } |
| 3256 | for (const entity of this.entities.values()) |
| 3257 | { |
| 3258 | const range = entity.lightRadiusTiles ?? 0; |
| 3259 | if (range <= 0) |
| 3260 | { continue; } |
| 3261 | activeLights.push({ |
| 3262 | tileX: Math.floor(entity.visualX / tileSize), |
| 3263 | tileY: Math.floor(entity.visualY / tileSize), |
| 3264 | range, |
| 3265 | intensity: 1 |
| 3266 | }); |
| 3267 | } |
| 3268 | |
| 3269 | const lightOcclusion = makeSnapshotLightOcclusion(this.chunks); |
| 3270 | |
| 3271 | for (const objects of this.tiles.values()) |
| 3272 | { |
| 3273 | if (objects._inViewport === false) |
| 3274 | { continue; } |
| 3275 | const lights = this.#isActiveLightingTile(objects.tileX, objects.tileY) ? activeLights : []; |
| 3276 | const intensity = this.#tileLightIntensity(objects, lights, lightOcclusion); |
| 3277 | objects.shadeAlpha = ambientDark * (1 - intensity); |
| 3278 | } |
| 3279 | |
| 3280 | for (const baked of this.bakedChunks.values()) |
| 3281 | { |
| 3282 | if (baked._inViewport === false) |
| 3283 | { continue; } |
| 3284 | const lights = this.#isActiveLightingChunk(baked.chunkX, baked.chunkY) ? activeLights : []; |
| 3285 | this.#writeChunkLightmap(baked, lights, lightOcclusion); |
| 3286 | if (baked.groundObject?.renderer?.shaderUniforms) |
| 3287 | { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; } |
| 3288 | for (const object of baked.blockObjects ?? []) |
| 3289 | { |
| 3290 | if (object?.renderer?.shaderUniforms) |
| 3291 | { object.renderer.shaderUniforms.u_ambientDark = ambientDark; } |
| 3292 | } |
| 3293 | } |
| 3294 | |
| 3295 | const timeSec = now / 1000; |
| 3296 | for (const objects of this.tiles.values()) |
| 3297 | { |
| 3298 | if (objects._inViewport === false) |
| 3299 | { continue; } |
| 3300 | if (objects.block) |
| 3301 | { this.#syncLitSprite(objects.block, objects.shadeAlpha); } |
| 3302 | if (objects.ground && isWaterGround(objects.groundTypeId)) |
| 3303 | { |
| 3304 | const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`); |
| 3305 | this.#syncGroundWaterFx(objects, ambientDark, timeSec, baked); |
| 3306 | } |
| 3307 | else if (objects.ground) |
| 3308 | { this.#syncLitSprite(objects.ground, objects.shadeAlpha); } |
| 3309 | } |
| 3310 | |
| 3311 | for (const item of this.groundItems.values()) |
| 3312 | { |
| 3313 | const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0; |
| 3314 | this.#syncGroundItemSprite(item, alpha); |
| 3315 | } |
| 3316 | } |
| 3317 | |
| 3318 | #tileLightIntensity (objects, activeLights, lightOcclusion) |
| 3319 | { |
| 3320 | const baked = lightIntensity(objects.light ?? 0); |
| 3321 | const dynamic = dynamicLightAtTile( |
| 3322 | objects.tileX, |
| 3323 | objects.tileY, |
| 3324 | activeLights, |
| 3325 | lightOcclusion |
| 3326 | ); |
| 3327 | return Math.max(baked, dynamic); |
| 3328 | } |
| 3329 | |
| 3330 | /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */ |
| 3331 | #intensityAtTile (tileX, tileY, activeLights, lightOcclusion) |
| 3332 | { |
| 3333 | const tileObjects = this.tiles.get(`${tileX},${tileY}`); |
| 3334 | if (tileObjects) |
| 3335 | { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion); } |
| 3336 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 3337 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 3338 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 3339 | if (!snapshot) |
| 3340 | { return 0; } |
| 3341 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 3342 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 3343 | const index = localY * CHUNK_SIZE + localX; |
| 3344 | const bakedLit = lightIntensity(snapshot.light[index] ?? 0); |
| 3345 | const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion); |
| 3346 | return Math.max(bakedLit, dynamic); |
| 3347 | } |
| 3348 | |
| 3349 | /** True when ground or block on this tile occludes light rays (same rules as bake). */ |
| 3350 | #tileOccludesLight (tileX, tileY) |
| 3351 | { |
| 3352 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 3353 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 3354 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 3355 | if (!snapshot) |
| 3356 | { return false; } |
| 3357 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 3358 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 3359 | if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE) |
| 3360 | { return false; } |
| 3361 | const index = localY * CHUNK_SIZE + localX; |
| 3362 | if (Array.isArray(snapshot.occlusion) && snapshot.occlusion.length > index) |
| 3363 | { return (snapshot.occlusion[index] | 0) >= LightOcclusion.solid; } |
| 3364 | const ground = normalizeGround(snapshot.grounds?.[index]); |
| 3365 | if (!isGroundPassable(ground.typeId)) |
| 3366 | { return true; } |
| 3367 | return isBlockOccludingLight(snapshot.blocks?.[index]?.typeId ?? null); |
| 3368 | } |
| 3369 | |
| 3370 | #fillChunkLightGrids (baked, activeLights, lightOcclusion) |
| 3371 | { |
| 3372 | const gridW = CHUNK_SIZE + 2; |
| 3373 | const gridSize = gridW * gridW; |
| 3374 | if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize) |
| 3375 | { baked.lightIntensityGrid = new Float32Array(gridSize); } |
| 3376 | if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize) |
| 3377 | { baked.lightOccludeGrid = new Uint8Array(gridSize); } |
| 3378 | const grid = baked.lightIntensityGrid; |
| 3379 | const occlude = baked.lightOccludeGrid; |
| 3380 | for (let ly = -1; ly <= CHUNK_SIZE; ly++) |
| 3381 | { |
| 3382 | for (let lx = -1; lx <= CHUNK_SIZE; lx++) |
| 3383 | { |
| 3384 | const tileX = baked.chunkX * CHUNK_SIZE + lx; |
| 3385 | const tileY = baked.chunkY * CHUNK_SIZE + ly; |
| 3386 | const gi = (ly + 1) * gridW + (lx + 1); |
| 3387 | grid[gi] = this.#intensityAtTile(tileX, tileY, activeLights, lightOcclusion); |
| 3388 | occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0; |
| 3389 | } |
| 3390 | } |
| 3391 | return { grid, occlude, gridW }; |
| 3392 | } |
| 3393 | |
| 3394 | #makeLightCornerSampler (grid, occlude, gridW) |
| 3395 | { |
| 3396 | const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)]; |
| 3397 | const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0; |
| 3398 | const openSample = (lx, ly) => (blocks(lx, ly) ? 0 : sample(lx, ly)); |
| 3399 | const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) => |
| 3400 | { |
| 3401 | const home = sample(homeLx, homeLy); |
| 3402 | if (blocks(homeLx, homeLy)) |
| 3403 | { return home; } |
| 3404 | let sum = home; |
| 3405 | let count = 1; |
| 3406 | sum += openSample(aLx, aLy); |
| 3407 | count += 1; |
| 3408 | sum += openSample(bLx, bLy); |
| 3409 | count += 1; |
| 3410 | if (!blocks(aLx, aLy) && !blocks(bLx, bLy)) |
| 3411 | { |
| 3412 | sum += openSample(dLx, dLy); |
| 3413 | count += 1; |
| 3414 | } |
| 3415 | return sum / count; |
| 3416 | }; |
| 3417 | return { smoothCorner }; |
| 3418 | } |
| 3419 | |
| 3420 | /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */ |
| 3421 | #tileLitCorners (baked, localX, localY) |
| 3422 | { |
| 3423 | const grid = baked?.lightIntensityGrid; |
| 3424 | const occlude = baked?.lightOccludeGrid; |
| 3425 | if (!grid?.length || !occlude?.length) |
| 3426 | { return null; } |
| 3427 | const gridW = CHUNK_SIZE + 2; |
| 3428 | const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW); |
| 3429 | return { |
| 3430 | nw: smoothCorner( |
| 3431 | localX, localY, |
| 3432 | localX - 1, localY, |
| 3433 | localX, localY - 1, |
| 3434 | localX - 1, localY - 1 |
| 3435 | ), |
| 3436 | ne: smoothCorner( |
| 3437 | localX, localY, |
| 3438 | localX + 1, localY, |
| 3439 | localX, localY - 1, |
| 3440 | localX + 1, localY - 1 |
| 3441 | ), |
| 3442 | sw: smoothCorner( |
| 3443 | localX, localY, |
| 3444 | localX - 1, localY, |
| 3445 | localX, localY + 1, |
| 3446 | localX - 1, localY + 1 |
| 3447 | ), |
| 3448 | se: smoothCorner( |
| 3449 | localX, localY, |
| 3450 | localX + 1, localY, |
| 3451 | localX, localY + 1, |
| 3452 | localX + 1, localY + 1 |
| 3453 | ) |
| 3454 | }; |
| 3455 | } |
| 3456 | |
| 3457 | #hashUint8Array (values) |
| 3458 | { |
| 3459 | let hash = 2166136261; |
| 3460 | for (let i = 0; i < values.length; i++) |
| 3461 | { |
| 3462 | hash ^= values[i]; |
| 3463 | hash = Math.imul(hash, 16777619); |
| 3464 | } |
| 3465 | return hash >>> 0; |
| 3466 | } |
| 3467 | |
| 3468 | #lightAffectsChunkBounds (light, chunkX, chunkY) |
| 3469 | { |
| 3470 | const minX = chunkX * CHUNK_SIZE - 1; |
| 3471 | const minY = chunkY * CHUNK_SIZE - 1; |
| 3472 | const maxX = chunkX * CHUNK_SIZE + CHUNK_SIZE; |
| 3473 | const maxY = chunkY * CHUNK_SIZE + CHUNK_SIZE; |
| 3474 | const closestX = Math.max(minX, Math.min(light.tileX, maxX)); |
| 3475 | const closestY = Math.max(minY, Math.min(light.tileY, maxY)); |
| 3476 | return Math.hypot(light.tileX - closestX, light.tileY - closestY) <= light.range; |
| 3477 | } |
| 3478 | |
| 3479 | #chunkLightmapCacheKey (baked, activeLights) |
| 3480 | { |
| 3481 | const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`); |
| 3482 | if (!snapshot?.light) |
| 3483 | { return null; } |
| 3484 | const bakedHash = this.#hashUint8Array(snapshot.light); |
| 3485 | if (!this.#isActiveLightingChunk(baked.chunkX, baked.chunkY)) |
| 3486 | { return `i:${bakedHash}`; } |
| 3487 | const mode = this.lightingMode === "simple" ? "s" : "f"; |
| 3488 | let lightsKey = ""; |
| 3489 | for (const light of activeLights) |
| 3490 | { |
| 3491 | if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY)) |
| 3492 | { continue; } |
| 3493 | lightsKey += `${light.tileX},${light.tileY},${light.range},${light.intensity ?? 1};`; |
| 3494 | } |
| 3495 | return `a:${mode}:${bakedHash}:${lightsKey}`; |
| 3496 | } |
| 3497 | |
| 3498 | #invalidateNeighborLightmapCaches (chunkX, chunkY) |
| 3499 | { |
| 3500 | for (let dy = -1; dy <= 1; dy++) |
| 3501 | { |
| 3502 | for (let dx = -1; dx <= 1; dx++) |
| 3503 | { |
| 3504 | const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`); |
| 3505 | if (baked) |
| 3506 | { baked.lightmapCacheKey = null; } |
| 3507 | } |
| 3508 | } |
| 3509 | } |
| 3510 | |
| 3511 | /** |
| 3512 | * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours; |
| 3513 | * occluding tiles stay flat and contribute 0 into others so light does not bleed |
| 3514 | * through a wall to the far side. Diagonals only when both cardinals are clear. |
| 3515 | */ |
| 3516 | #writeChunkLightmap (baked, activeLights, lightOcclusion) |
| 3517 | { |
| 3518 | const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`); |
| 3519 | if (!snapshot) |
| 3520 | { return; } |
| 3521 | const cacheKey = this.#chunkLightmapCacheKey(baked, activeLights); |
| 3522 | if (cacheKey && baked.lightmapCacheKey === cacheKey) |
| 3523 | { return; } |
| 3524 | const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX; |
| 3525 | const pixelCount = atlasPx * atlasPx * 4; |
| 3526 | if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount) |
| 3527 | { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); } |
| 3528 | const pixels = baked.lightmapPixels; |
| 3529 | |
| 3530 | this.#fillChunkLightGrids(baked, activeLights, lightOcclusion); |
| 3531 | const simple = this.lightingMode === "simple"; |
| 3532 | |
| 3533 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 3534 | { |
| 3535 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 3536 | { |
| 3537 | const baseX = localX * SPRITE_SIZE_PX; |
| 3538 | const baseY = localY * SPRITE_SIZE_PX; |
| 3539 | if (simple) |
| 3540 | { |
| 3541 | const gridW = CHUNK_SIZE + 2; |
| 3542 | const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0; |
| 3543 | const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255); |
| 3544 | for (let py = 0; py < SPRITE_SIZE_PX; py++) |
| 3545 | { |
| 3546 | for (let px = 0; px < SPRITE_SIZE_PX; px++) |
| 3547 | { |
| 3548 | const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4; |
| 3549 | pixels[offset] = value; |
| 3550 | pixels[offset + 1] = value; |
| 3551 | pixels[offset + 2] = value; |
| 3552 | pixels[offset + 3] = 255; |
| 3553 | } |
| 3554 | } |
| 3555 | continue; |
| 3556 | } |
| 3557 | const corners = this.#tileLitCorners(baked, localX, localY); |
| 3558 | const nw = corners.nw; |
| 3559 | const ne = corners.ne; |
| 3560 | const sw = corners.sw; |
| 3561 | const se = corners.se; |
| 3562 | for (let py = 0; py < SPRITE_SIZE_PX; py++) |
| 3563 | { |
| 3564 | const v = (py + 0.5) / SPRITE_SIZE_PX; |
| 3565 | const left = nw + (sw - nw) * v; |
| 3566 | const right = ne + (se - ne) * v; |
| 3567 | for (let px = 0; px < SPRITE_SIZE_PX; px++) |
| 3568 | { |
| 3569 | const u = (px + 0.5) / SPRITE_SIZE_PX; |
| 3570 | const intensity = left + (right - left) * u; |
| 3571 | const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255); |
| 3572 | const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4; |
| 3573 | pixels[offset] = value; |
| 3574 | pixels[offset + 1] = value; |
| 3575 | pixels[offset + 2] = value; |
| 3576 | pixels[offset + 3] = 255; |
| 3577 | } |
| 3578 | } |
| 3579 | } |
| 3580 | } |
| 3581 | const ctx = baked.lightmapCanvas.getContext("2d"); |
| 3582 | ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0); |
| 3583 | invalidateCanvasTexture(this.scene, baked.lightmapCanvas); |
| 3584 | this.#queueCanvasTextureWarm(baked.lightmapCanvas, baked.chunkX, baked.chunkY); |
| 3585 | baked.lightmapCacheKey = cacheKey; |
| 3586 | } |
| 3587 | |
| 3588 | #updateSwipes (now) |
| 3589 | { |
| 3590 | this.swipes = this.swipes.filter((swipe) => |
| 3591 | { |
| 3592 | if (swipe.lerp && swipe.started != null) |
| 3593 | { |
| 3594 | const durationMs = swipe.durationMs ?? 400; |
| 3595 | const t = Math.min(1, (now - swipe.started) / durationMs); |
| 3596 | const fromPivot = tilePivot(swipe.fromTileX, swipe.fromTileY, this.tileSize()); |
| 3597 | const toPivot = this.#projectileEndPivot(swipe); |
| 3598 | const x = fromPivot.x + (toPivot.x - fromPivot.x) * t; |
| 3599 | const y = fromPivot.y + (toPivot.y - fromPivot.y) * t; |
| 3600 | const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02; |
| 3601 | if (swipe.object?.transform) |
| 3602 | { |
| 3603 | swipe.object.transform.rotation = Math.atan2( |
| 3604 | toPivot.y - fromPivot.y, |
| 3605 | toPivot.x - fromPivot.x |
| 3606 | ) * (180 / Math.PI); |
| 3607 | } |
| 3608 | if (swipe.spellProjectile && swipe.baseSprite) |
| 3609 | { |
| 3610 | const frame = Math.floor((now - swipe.started) / SPELL_PROJECTILE_FRAME_MS) % 3; |
| 3611 | const image = this.#spellProjectileImage(swipe.baseSprite, frame); |
| 3612 | if (image && swipe.object?.renderer) |
| 3613 | { swipe.object.renderer.sprite = image; } |
| 3614 | } |
| 3615 | this.#placePivoted(swipe.object, x, y, sortY, SORT_FX); |
| 3616 | if (!swipe.spellProjectile) |
| 3617 | { |
| 3618 | this.#applyPhysicalCombatFxDarkness( |
| 3619 | swipe.object, |
| 3620 | swipe.fromTileX, |
| 3621 | swipe.fromTileY, |
| 3622 | swipe.tileX, |
| 3623 | swipe.tileY, |
| 3624 | swipe.dualTint ?? null |
| 3625 | ); |
| 3626 | } |
| 3627 | } |
| 3628 | else if (swipe.fromTileX != null && !swipe.spellProjectile) |
| 3629 | { |
| 3630 | this.#applyPhysicalCombatFxDarkness( |
| 3631 | swipe.object, |
| 3632 | swipe.fromTileX, |
| 3633 | swipe.fromTileY, |
| 3634 | swipe.tileX, |
| 3635 | swipe.tileY, |
| 3636 | swipe.dualTint ?? null |
| 3637 | ); |
| 3638 | } |
| 3639 | if (swipe.until > now) |
| 3640 | { return true; } |
| 3641 | const onImpact = swipe.onImpact; |
| 3642 | swipe.onImpact = null; |
| 3643 | swipe.object?.destroy(); |
| 3644 | if (typeof onImpact === "function") |
| 3645 | { |
| 3646 | try |
| 3647 | { onImpact(); } |
| 3648 | catch (_) |
| 3649 | { /* presentation only */ } |
| 3650 | } |
| 3651 | return false; |
| 3652 | }); |
| 3653 | } |
| 3654 | |
| 3655 | #projectileEndPivot (swipe) |
| 3656 | { |
| 3657 | if (swipe.trackTarget && swipe.targetId != null) |
| 3658 | { |
| 3659 | const target = this.entities.get(swipe.targetId); |
| 3660 | if (target && Number.isFinite(target.visualX) && Number.isFinite(target.visualY)) |
| 3661 | { |
| 3662 | return { x: target.visualX, y: target.visualY }; |
| 3663 | } |
| 3664 | } |
| 3665 | return tilePivot(swipe.tileX, swipe.tileY, this.tileSize()); |
| 3666 | } |
| 3667 | |
| 3668 | #updateDamageNumbers (now) |
| 3669 | { |
| 3670 | const layer = this.damageNumbersEl; |
| 3671 | if (!layer) |
| 3672 | { return; } |
| 3673 | this.damageFloats = this.damageFloats.filter((entry) => |
| 3674 | { |
| 3675 | const elapsed = now - entry.started; |
| 3676 | if (elapsed >= DAMAGE_FLOAT_MS) |
| 3677 | { |
| 3678 | entry.element?.remove(); |
| 3679 | return false; |
| 3680 | } |
| 3681 | const entity = this.entities.get(entry.entityId); |
| 3682 | if (!entity) |
| 3683 | { |
| 3684 | entry.element?.remove(); |
| 3685 | return false; |
| 3686 | } |
| 3687 | if (!entry.element) |
| 3688 | { |
| 3689 | entry.element = document.createElement("span"); |
| 3690 | entry.element.className = "damage-number"; |
| 3691 | entry.element.textContent = String(entry.damage); |
| 3692 | layer.append(entry.element); |
| 3693 | } |
| 3694 | const anchor = this.nametagAnchor(entity); |
| 3695 | if (!anchor) |
| 3696 | { return true; } |
| 3697 | const t = elapsed / DAMAGE_FLOAT_MS; |
| 3698 | entry.element.style.left = `${anchor.x}px`; |
| 3699 | entry.element.style.top = `${anchor.y - 6 - t * 28}px`; |
| 3700 | entry.element.style.opacity = String(1 - t); |
| 3701 | return true; |
| 3702 | }); |
| 3703 | } |
| 3704 | |
| 3705 | #updateSkillLevelFloats (now) |
| 3706 | { |
| 3707 | const layer = this.skillLevelFloatsEl; |
| 3708 | if (!layer) |
| 3709 | { return; } |
| 3710 | this.skillLevelFloats = this.skillLevelFloats.filter((entry) => |
| 3711 | { |
| 3712 | const elapsed = now - entry.started; |
| 3713 | if (elapsed >= SKILL_LEVEL_FLOAT_MS) |
| 3714 | { |
| 3715 | entry.element?.remove(); |
| 3716 | return false; |
| 3717 | } |
| 3718 | const entity = this.entities.get(entry.entityId); |
| 3719 | if (!entity) |
| 3720 | { |
| 3721 | entry.element?.remove(); |
| 3722 | return false; |
| 3723 | } |
| 3724 | if (!entry.element) |
| 3725 | { |
| 3726 | const root = document.createElement("div"); |
| 3727 | root.className = "skill-level-float"; |
| 3728 | |
| 3729 | const levelEl = document.createElement("div"); |
| 3730 | levelEl.className = "skill-level-float-level"; |
| 3731 | levelEl.textContent = `↑${entry.level}↑`; |
| 3732 | |
| 3733 | const icon = document.createElement("img"); |
| 3734 | icon.className = "skill-level-float-icon"; |
| 3735 | icon.src = entry.icon; |
| 3736 | icon.alt = entry.displayName || ""; |
| 3737 | |
| 3738 | root.append(levelEl, icon); |
| 3739 | entry.element = root; |
| 3740 | layer.append(entry.element); |
| 3741 | } |
| 3742 | const anchor = this.nametagAnchor(entity); |
| 3743 | if (!anchor) |
| 3744 | { return true; } |
| 3745 | const t = elapsed / SKILL_LEVEL_FLOAT_MS; |
| 3746 | entry.element.style.left = `${anchor.x}px`; |
| 3747 | entry.element.style.top = `${anchor.y - 10 - t * 18}px`; |
| 3748 | entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85)); |
| 3749 | return true; |
| 3750 | }); |
| 3751 | } |
| 3752 | |
| 3753 | #syncBloomLayer () |
| 3754 | { |
| 3755 | if (!this.bloomEnabled) |
| 3756 | { |
| 3757 | this.scene.setLayers([{ name: "default" }]); |
| 3758 | return; |
| 3759 | } |
| 3760 | const settings = this.settings ?? DEFAULT_WORLD_SETTINGS; |
| 3761 | this.scene.setLayers([ |
| 3762 | { name: "default" }, |
| 3763 | { |
| 3764 | name: RENDER_LAYER_BLOOM, |
| 3765 | composite: "add", |
| 3766 | postShaders: Shader.getBloomPostChain({ |
| 3767 | threshold: settings.bloomThreshold, |
| 3768 | softKnee: settings.bloomSoftKnee, |
| 3769 | intensity: settings.bloomIntensity, |
| 3770 | blurSize: settings.bloomBlurSize, |
| 3771 | saturation: settings.bloomSaturation, |
| 3772 | colorPreserve: settings.bloomColorPreserve, |
| 3773 | dilate: settings.bloomDilate, |
| 3774 | scales: Math.max(1, Math.round(settings.bloomScales ?? 1)), |
| 3775 | halfRes: (settings.bloomHalfRes ?? 1) >= 0.5 |
| 3776 | }) |
| 3777 | } |
| 3778 | ]); |
| 3779 | } |
| 3780 | } |
| 3781 | |
| 3782 | export function nightFactor (hour, nightDarkness = 0.72) |
| 3783 | { |
| 3784 | const peak = Math.min(1, Math.max(0, nightDarkness)); |
| 3785 | if (hour >= 8 && hour <= 16) |
| 3786 | { return 0; } |
| 3787 | if (hour >= 22 || hour <= 5) |
| 3788 | { return peak; } |
| 3789 | if (hour < 8) |
| 3790 | { return lerp(peak, 0, (hour - 5) / 3); } |
| 3791 | return lerp(0, peak, (hour - 16) / 6); |
| 3792 | } |
| 3793 | |
| 3794 | function bodySpriteName (sex) |
| 3795 | { |
| 3796 | const key = sex === "female" ? "player-body-female" : "player-body-male"; |
| 3797 | return spriteImageName("character", key, key); |
| 3798 | } |
| 3799 | |
| 3800 | function lerp (a, b, t) |
| 3801 | { |
| 3802 | return a + (b - a) * Math.min(1, Math.max(0, t)); |
| 3803 | } |
| 3804 | |
| 3805 | function makeLightmapCanvas (size) |
| 3806 | { |
| 3807 | const canvas = document.createElement("canvas"); |
| 3808 | canvas.width = size; |
| 3809 | canvas.height = size; |
| 3810 | return canvas; |
| 3811 | } |
| 3812 | |
| 3813 | function copyCanvas (source, dest) |
| 3814 | { |
| 3815 | const ctx = dest.getContext("2d"); |
| 3816 | ctx.imageSmoothingEnabled = false; |
| 3817 | ctx.clearRect(0, 0, dest.width, dest.height); |
| 3818 | ctx.drawImage(source, 0, 0); |
| 3819 | } |
| 3820 | |
| 3821 | function drawHpBar (canvas, current, max) |
| 3822 | { |
| 3823 | const ctx = canvas.getContext("2d"); |
| 3824 | ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H); |
| 3825 | ctx.fillStyle = "#000000"; |
| 3826 | ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H); |
| 3827 | const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0; |
| 3828 | const fillW = Math.round(12 * ratio); |
| 3829 | if (fillW > 0) |
| 3830 | { |
| 3831 | ctx.fillStyle = "#ff0000"; |
| 3832 | ctx.fillRect(1, 1, fillW, 2); |
| 3833 | } |
| 3834 | } |