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