import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js"; import { dynamicLightAtTile, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js"; import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js"; import { bakeChunkOcclusion, tileLightOcclusionAt } from "/shared/lighting/chunkOcclusion.js"; import { collectBlockLightSources, collectGroundLightSources, maxBlockLightRangeTiles } from "/shared/lighting/blockLights.js"; import { smoothLitCorner } from "/shared/lighting/lightCorners.js"; import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js"; import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemSpriteNameForStack, itemDefinition } from "/shared/definitions/items.js"; import { resolveItemTint, resolveEquipTint, resolveItemDualTint, resolveEquipDualTint, normalizeRgb } from "/shared/render/tint.js"; import { layersFromSpawnerConfig } from "/shared/appearance/layers.js"; import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js"; import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLavaGround, isLiquidWaterGround, isGroundPassable, groundLightOcclusion, LightOcclusion, blockDefinition, blockLightOcclusionForBlock, GroundType, GROUND_DEFINITIONS, fluidCoastContinues } from "/shared/definitions/tiles.js"; import { doorSortSubOrder, doorRestingState } from "/shared/world/doors.js"; import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js"; import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js"; import { createChunkAtlasCache } from "./chunkAtlasCache.js"; import { frameworkImageFromCanvas, invalidateCanvasTexture, uploadCanvasTextureRgba } from "./canvasSprite.js"; import { setNearestFilter } from "./sprites.js"; import { waterDebugUniforms, lavaDebugUniforms } from "../play/waterDebug.js"; import { natureNoise01, natureTintUniforms, NATURE_TINT, NATURE_NOISE_SIZE, NATURE_NOISE_PAD } from "/shared/render/natureNoise.js"; import { SeasonId, seasonIdAt, resolveSeasonalVisualState } from "/shared/world/season.js"; import { OVERWORLD_ID, normalizeDimensionId, normalizeLightingMode, normalizeSeasonMode, resolveDimensionDarknessFactor, resolveDimensionSeasonId } from "/shared/world/dimensions.js"; import { spellDefinition, spellProjectileTint } from "/shared/definitions/spells.js"; import { skullTintColor } from "/shared/combat/skull.js"; const LAYER_GROUND = 0; const LAYER_EDGE = 900000; const SORT_BLOCK = 2; const SORT_ENTITY = 3; /** Equipment overlays use SORT_ENTITY + 1 + index (same sortY band). */ const SORT_HP_BAR = 14; const SORT_FX = 5; const RENDER_LAYER_BLOOM = "bloom"; const SKULL_SPRITE = "fx:skull:skull"; const HP_BAR_W = 14; const HP_BAR_H = 4; const WALK_TILT_DEG = 6; const RUN_TILT_DEG = 8; const SHOVE_TILE_FRACTION = 0.25; const SHOVE_MS = 280; /** Soft reflow when stack circle targets change (join/leave a shared tile). */ const STACK_SPREAD_LERP_MS = 280; /** Melee swipe fade: full opacity → transparent over this duration, then remove. */ const MELEE_SWIPE_MS = 500; /** Extra random yaw (±deg) on top of aim rotation. */ const MELEE_SWIPE_JITTER_DEG = 10; /** Hold gather-tool equip overlay slightly past swing interval so it stays visible between swings. */ const GATHER_TOOL_HOLD_MS = 1100; const DAMAGE_FLASH_MS = 180; const FLASH_COLOR_DAMAGE = Object.freeze([1.0, 0.12, 0.12]); const FLASH_COLOR_BLOCK = Object.freeze([1.0, 1.0, 1.0]); /** Combat death: full red silhouette fades to transparent after the killing blow. */ const DEATH_FADE_MS = 500; /** Interest leave / non-combat despawn: plain alpha fade (still lit / darkened). */ const DESPAWN_FADE_MS = 500; const DAMAGE_FLOAT_MS = 900; const SKILL_LEVEL_FLOAT_MS = 2800; /** Projectiles spawn this many sprite-pixels below the caster sprite top. */ const PROJECTILE_LAUNCH_FROM_TOP_PX = 4; const SPRITE_LIGHTING_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform float u_alpha;", "uniform float u_darkness;", "uniform float u_strength;", "uniform vec3 u_flashColor;", "uniform float u_wade;", "uniform float u_spriteHeight;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", " vec3 rgb = color.rgb;", " if (u_wade > 0.5 && fromBottom < 5.0) {", " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", " }", " rgb = mix(rgb, vec3(0.0), u_darkness);", " rgb = mix(rgb, u_flashColor, u_strength);", " gl_FragColor = vec4(rgb, color.a * u_alpha);", "}" ].join("\n"); const WATER_GROUND_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform sampler2D u_secondary;", "uniform float u_alpha;", "uniform float u_ambientDark;", "uniform float u_litNW;", "uniform float u_litNE;", "uniform float u_litSW;", "uniform float u_litSE;", "uniform float u_time;", "uniform float u_tileX;", "uniform float u_tileY;", "uniform float u_deepNW;", "uniform float u_deepNE;", "uniform float u_deepSW;", "uniform float u_deepSE;", "uniform float u_edgeN;", "uniform float u_edgeE;", "uniform float u_edgeS;", "uniform float u_edgeW;", "uniform float u_edgeNE;", "uniform float u_edgeNW;", "uniform float u_edgeSE;", "uniform float u_edgeSW;", "uniform float u_hasShore;", "uniform float u_shoreEdgeN;", "uniform float u_shoreEdgeE;", "uniform float u_shoreEdgeS;", "uniform float u_shoreEdgeW;", "uniform float u_shoreEdgeNE;", "uniform float u_shoreEdgeNW;", "uniform float u_shoreEdgeSE;", "uniform float u_shoreEdgeSW;", "uniform vec4 u_shoreUvRect;", "uniform float u_flowX;", "uniform float u_flowY;", "uniform float u_flowZ;", "uniform float u_waveScale;", "uniform float u_fbmAmp;", "uniform float u_texAmp;", "uniform float u_distort;", "uniform float u_normalZ;", "uniform float u_waveGain;", "uniform float u_crestLo;", "uniform float u_crestHi;", "uniform float u_crestPow;", "uniform float u_glitterPow;", "uniform float u_crestGlitter;", "uniform float u_glitterCap;", "uniform float u_glitterMix;", "uniform float u_shadeLo;", "uniform float u_shadeHi;", "uniform float u_bodyLo;", "uniform float u_bodyHi;", "uniform float u_litLo;", "uniform float u_litHi;", "uniform float u_litMix;", "uniform float u_edgeDark;", "uniform float u_lightDirX;", "uniform float u_lightDirY;", "uniform float u_lightDirZ;", "uniform float u_normalEps;", "uniform float u_foamStrength;", "uniform float u_shoreClip;", "uniform float u_deepDark;", "uniform float u_deepAbrupt;", // 3D simplex (Ashima / Gustavson style — OpenSimplex-class continuous field). "vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }", "vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }", "vec4 permute(vec4 x) { return mod289(((x * 34.0) + 1.0) * x); }", "vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }", "float snoise(vec3 v) {", " vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0);", " vec4 D = vec4(0.0, 0.5, 1.0, 2.0);", " vec3 i = floor(v + dot(v, C.yyy));", " vec3 x0 = v - i + dot(i, C.xxx);", " vec3 g = step(x0.yzx, x0.xyz);", " vec3 l = 1.0 - g;", " vec3 i1 = min(g.xyz, l.zxy);", " vec3 i2 = max(g.xyz, l.zxy);", " vec3 x1 = x0 - i1 + C.xxx;", " vec3 x2 = x0 - i2 + C.yyy;", " vec3 x3 = x0 - D.yyy;", " i = mod289(i);", " vec4 p = permute(permute(permute(", " i.z + vec4(0.0, i1.z, i2.z, 1.0))", " + i.y + vec4(0.0, i1.y, i2.y, 1.0))", " + i.x + vec4(0.0, i1.x, i2.x, 1.0));", " float n_ = 0.142857142857;", " vec3 ns = n_ * D.wyz - D.xzx;", " vec4 j = p - 49.0 * floor(p * ns.z * ns.z);", " vec4 x_ = floor(j * ns.z);", " vec4 y_ = floor(j - 7.0 * x_);", " vec4 x = x_ * ns.x + ns.yyyy;", " vec4 y = y_ * ns.x + ns.yyyy;", " vec4 h = 1.0 - abs(x) - abs(y);", " vec4 b0 = vec4(x.xy, y.xy);", " vec4 b1 = vec4(x.zw, y.zw);", " vec4 s0 = floor(b0) * 2.0 + 1.0;", " vec4 s1 = floor(b1) * 2.0 + 1.0;", " vec4 sh = -step(h, vec4(0.0));", " vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;", " vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;", " vec3 p0 = vec3(a0.xy, h.x);", " vec3 p1 = vec3(a0.zw, h.y);", " vec3 p2 = vec3(a1.xy, h.z);", " vec3 p3 = vec3(a1.zw, h.w);", " vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));", " p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w;", " vec4 m = max(0.6 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);", " m = m * m;", " return 42.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));", "}", // 4-octave FBM: freq ×2, amp ×0.5 each layer; time in Z for continuous ripple. "float fbm(vec3 p) {", " float sum = 0.0;", " float amp = 0.5;", " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;", " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;", " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;", " sum += amp * snoise(p);", " return sum;", "}", "vec2 wrapUv(vec2 uv) {", " return fract(uv) * 0.998 + 0.001;", "}", "float sampleShore(", " float enabled, float useShore, vec2 shoreNu,", " inout vec3 shoreRgb, inout float shoreW", ") {", " if (enabled < 0.5 || useShore < 0.5 || u_hasShore < 0.5) { return 0.0; }", " vec2 shoreUv = u_shoreUvRect.xy + shoreNu * (u_shoreUvRect.zw - u_shoreUvRect.xy);", " vec4 shore = texture2D(u_secondary, shoreUv);", " if (shore.a <= 0.1) { return 0.0; }", " shoreRgb = shore.rgb;", " shoreW = 1.0;", " return 1.0;", "}", "void main() {", " vec2 px = floor(v_texCoord * 16.0) + 0.5;", " vec2 puv = px / 16.0;", " vec2 world = vec2(u_tileX, u_tileY) + puv;", " float t = u_time;", " vec2 flow = vec2(t * u_flowX, t * u_flowY);", " float eps = max(u_normalEps, 0.001);", " vec3 base = vec3(world * u_waveScale + flow, t * u_flowZ);", " float nC = fbm(base);", " float nL = fbm(base + vec3(-eps, 0.0, 0.0));", " float nR = fbm(base + vec3(eps, 0.0, 0.0));", " float nD = fbm(base + vec3(0.0, -eps, 0.0));", " float nU = fbm(base + vec3(0.0, eps, 0.0));", " vec2 distort = vec2(nL - nR, nD - nU) * u_distort;", " float texN = texture2D(u_texture, wrapUv(world * 0.28 + flow * 0.6 + distort)).r;", " float h = nC * u_fbmAmp + (texN - 0.5) * u_texAmp;", " vec3 normal = normalize(vec3(nL - nR, nD - nU, max(u_normalZ, 0.05)));", " float ndotl = clamp(dot(normal, normalize(vec3(u_lightDirX, u_lightDirY, u_lightDirZ))), 0.0, 1.0);", " float wave = clamp(h * u_waveGain + 0.5, 0.0, 1.0);", " float crest = pow(smoothstep(u_crestLo, max(u_crestHi, u_crestLo + 0.01), wave), max(u_crestPow, 0.01));", " float glitter = pow(max(0.0, ndotl), max(u_glitterPow, 0.01)) * crest;", " glitter = max(glitter, pow(crest, 2.5) * u_crestGlitter);", " float edgeProx = 0.0;", " if (u_edgeN > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.y)); }", " if (u_edgeS > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.y)); }", " if (u_edgeW > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.x)); }", " if (u_edgeE > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.x)); }", " if (u_edgeNE > 0.5) {", " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, puv.y))));", " }", " if (u_edgeNW > 0.5) {", " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, puv.y))));", " }", " if (u_edgeSE > 0.5) {", " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, 1.0 - puv.y))));", " }", " if (u_edgeSW > 0.5) {", " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, 1.0 - puv.y))));", " }", " float waveBody = wave * (1.0 - edgeProx * 0.72);", " float deepTop = mix(u_deepNW, u_deepNE, puv.x);", " float deepBot = mix(u_deepSW, u_deepSE, puv.x);", " float deepMix = mix(deepTop, deepBot, puv.y);", " float deepAmt = pow(clamp(deepMix, 0.0, 1.0), max(u_deepAbrupt, 0.05));", " float darkW = clamp(u_deepDark, 0.0, 1.0);", " vec3 deepCol = mix(vec3(0.12, 0.34, 0.54), mix(vec3(0.05, 0.16, 0.34), vec3(0.015, 0.055, 0.14), darkW), deepAmt);", " vec3 midCol = mix(vec3(0.24, 0.52, 0.70), mix(vec3(0.10, 0.30, 0.50), vec3(0.04, 0.14, 0.28), darkW), deepAmt);", " vec3 litCol = mix(vec3(0.52, 0.78, 0.90), mix(vec3(0.26, 0.46, 0.66), vec3(0.12, 0.28, 0.46), darkW), deepAmt);", " vec3 sparkCol = mix(vec3(0.98, 1.0, 1.0), mix(vec3(0.72, 0.88, 0.98), vec3(0.48, 0.68, 0.86), darkW), deepAmt);", " vec3 foamCol = vec3(0.94, 0.99, 1.0);", " float shade = mix(u_shadeLo, u_shadeHi, ndotl);", " vec3 rgb = mix(deepCol, midCol, smoothstep(u_bodyLo, max(u_bodyHi, u_bodyLo + 0.01), waveBody));", " rgb = mix(rgb, litCol, smoothstep(u_litLo, max(u_litHi, u_litLo + 0.01), waveBody) * u_litMix);", " rgb *= shade;", " rgb = mix(rgb, sparkCol, min(glitter, u_glitterCap) * u_glitterMix * (1.0 - edgeProx * 0.7));", " rgb = mix(rgb, deepCol, edgeProx * u_edgeDark);", " float shoreW = 0.0;", " vec3 shoreRgb = rgb;", " if (u_edgeN > 0.5) {", " sampleShore(1.0, u_shoreEdgeN, vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);", " }", " if (u_edgeS > 0.5) {", " sampleShore(1.0, u_shoreEdgeS, vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);", " }", " if (u_edgeW > 0.5) {", " sampleShore(1.0, u_shoreEdgeW, vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);", " }", " if (u_edgeE > 0.5) {", " sampleShore(1.0, u_shoreEdgeE, vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);", " }", " if (u_edgeNE > 0.5) {", " sampleShore(1.0, max(u_shoreEdgeNE, u_hasShore), vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);", " }", " if (u_edgeNW > 0.5) {", " sampleShore(1.0, max(u_shoreEdgeNW, u_hasShore), vec2(puv.x, puv.y), shoreRgb, shoreW);", " }", " if (u_edgeSE > 0.5) {", " sampleShore(1.0, max(u_shoreEdgeSE, u_hasShore), vec2(1.0 - puv.x, 1.0 - puv.y), shoreRgb, shoreW);", " }", " if (u_edgeSW > 0.5) {", " sampleShore(1.0, max(u_shoreEdgeSW, u_hasShore), vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);", " }", " float darkAmt = 1.0 - smoothstep(0.18, 0.52, waveBody);", " float retreat = edgeProx * (0.35 + 0.65 * darkAmt);", " float shoreClip = u_shoreClip;", " float shoreMask = step(shoreClip, retreat) * shoreW;", " float foamAmt = (1.0 - shoreMask) * smoothstep(shoreClip - 0.24, shoreClip - 0.08, retreat)", " * (1.0 - smoothstep(shoreClip - 0.08, shoreClip, retreat));", " rgb = mix(rgb, foamCol, foamAmt * u_foamStrength);", " rgb = mix(rgb, shoreRgb, shoreMask);", " float litTop = mix(u_litNW, u_litNE, v_texCoord.x);", " float litBottom = mix(u_litSW, u_litSE, v_texCoord.x);", " float lit = mix(litTop, litBottom, v_texCoord.y);", " float darkness = u_ambientDark * (1.0 - lit);", " rgb = mix(rgb, vec3(0.0), darkness);", " gl_FragColor = vec4(rgb, u_alpha);", "}" ].join("\n"); /** Lava heat: dark red → red → orange → yellow; yellow drives bloom companion. */ const LAVA_FBM_COMMON = [ "vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }", "vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }", "vec4 permute(vec4 x) { return mod289(((x * 34.0) + 1.0) * x); }", "vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }", "float snoise(vec3 v) {", " vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0);", " vec4 D = vec4(0.0, 0.5, 1.0, 2.0);", " vec3 i = floor(v + dot(v, C.yyy));", " vec3 x0 = v - i + dot(i, C.xxx);", " vec3 g = step(x0.yzx, x0.xyz);", " vec3 l = 1.0 - g;", " vec3 i1 = min(g.xyz, l.zxy);", " vec3 i2 = max(g.xyz, l.zxy);", " vec3 x1 = x0 - i1 + C.xxx;", " vec3 x2 = x0 - i2 + C.yyy;", " vec3 x3 = x0 - D.yyy;", " i = mod289(i);", " vec4 p = permute(permute(permute(", " i.z + vec4(0.0, i1.z, i2.z, 1.0))", " + i.y + vec4(0.0, i1.y, i2.y, 1.0))", " + i.x + vec4(0.0, i1.x, i2.x, 1.0));", " float n_ = 0.142857142857;", " vec3 ns = n_ * D.wyz - D.xzx;", " vec4 j = p - 49.0 * floor(p * ns.z * ns.z);", " vec4 x_ = floor(j * ns.z);", " vec4 y_ = floor(j - 7.0 * x_);", " vec4 x = x_ * ns.x + ns.yyyy;", " vec4 y = y_ * ns.x + ns.yyyy;", " vec4 h = 1.0 - abs(x) - abs(y);", " vec4 b0 = vec4(x.xy, y.xy);", " vec4 b1 = vec4(x.zw, y.zw);", " vec4 s0 = floor(b0) * 2.0 + 1.0;", " vec4 s1 = floor(b1) * 2.0 + 1.0;", " vec4 sh = -step(h, vec4(0.0));", " vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;", " vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;", " vec3 p0 = vec3(a0.xy, h.x);", " vec3 p1 = vec3(a0.zw, h.y);", " vec3 p2 = vec3(a1.xy, h.z);", " vec3 p3 = vec3(a1.zw, h.w);", " vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));", " p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w;", " vec4 m = max(0.6 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);", " m = m * m;", " return 42.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));", "}", "float fbm(vec3 p) {", " float sum = 0.0;", " float amp = 0.5;", " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;", " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;", " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;", " sum += amp * snoise(p);", " return sum;", "}", "vec2 wrapUv(vec2 uv) {", " return fract(uv) * 0.998 + 0.001;", "}" ]; const LAVA_GROUND_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform float u_alpha;", "uniform float u_ambientDark;", "uniform float u_litNW;", "uniform float u_litNE;", "uniform float u_litSW;", "uniform float u_litSE;", "uniform float u_time;", "uniform float u_tileX;", "uniform float u_tileY;", "uniform float u_edgeN;", "uniform float u_edgeE;", "uniform float u_edgeS;", "uniform float u_edgeW;", "uniform float u_edgeNE;", "uniform float u_edgeNW;", "uniform float u_edgeSE;", "uniform float u_edgeSW;", "uniform float u_flowX;", "uniform float u_flowY;", "uniform float u_flowZ;", "uniform float u_waveScale;", "uniform float u_fbmAmp;", "uniform float u_texAmp;", "uniform float u_distort;", "uniform float u_normalZ;", "uniform float u_waveGain;", "uniform float u_crestLo;", "uniform float u_crestHi;", "uniform float u_crestPow;", "uniform float u_glitterPow;", "uniform float u_crestGlitter;", "uniform float u_glitterCap;", "uniform float u_glitterMix;", "uniform float u_shadeLo;", "uniform float u_shadeHi;", "uniform float u_bodyLo;", "uniform float u_bodyHi;", "uniform float u_litLo;", "uniform float u_litHi;", "uniform float u_litMix;", "uniform float u_edgeDark;", "uniform float u_lightDirX;", "uniform float u_lightDirY;", "uniform float u_lightDirZ;", "uniform float u_normalEps;", "uniform float u_shoreClip;", "uniform float u_hasShore;", "uniform float u_shoreEdgeN;", "uniform float u_shoreEdgeE;", "uniform float u_shoreEdgeS;", "uniform float u_shoreEdgeW;", "uniform float u_shoreEdgeNE;", "uniform float u_shoreEdgeNW;", "uniform float u_shoreEdgeSE;", "uniform float u_shoreEdgeSW;", "uniform vec4 u_shoreUvRect;", "uniform sampler2D u_secondary;", ...LAVA_FBM_COMMON, "float sampleShore(", " float enabled, float useShore, vec2 shoreNu,", " inout vec3 shoreRgb, inout float shoreW", ") {", " if (enabled < 0.5 || useShore < 0.5 || u_hasShore < 0.5) { return 0.0; }", " vec2 shoreUv = u_shoreUvRect.xy + shoreNu * (u_shoreUvRect.zw - u_shoreUvRect.xy);", " vec4 shore = texture2D(u_secondary, shoreUv);", " if (shore.a <= 0.1) { return 0.0; }", " shoreRgb = shore.rgb;", " shoreW = 1.0;", " return 1.0;", "}", "void main() {", " vec2 px = floor(v_texCoord * 16.0) + 0.5;", " vec2 puv = px / 16.0;", " vec2 world = vec2(u_tileX, u_tileY) + puv;", " float t = u_time;", " vec2 flow = vec2(t * u_flowX, t * u_flowY);", " float eps = max(u_normalEps, 0.001);", " vec3 base = vec3(world * u_waveScale + flow, t * u_flowZ);", " float nC = fbm(base);", " float nL = fbm(base + vec3(-eps, 0.0, 0.0));", " float nR = fbm(base + vec3(eps, 0.0, 0.0));", " float nD = fbm(base + vec3(0.0, -eps, 0.0));", " float nU = fbm(base + vec3(0.0, eps, 0.0));", " vec2 distort = vec2(nL - nR, nD - nU) * u_distort;", " float texN = texture2D(u_texture, wrapUv(world * 0.28 + flow * 0.6 + distort)).r;", " float h = nC * u_fbmAmp + (texN - 0.5) * u_texAmp;", " vec3 normal = normalize(vec3(nL - nR, nD - nU, max(u_normalZ, 0.05)));", " float ndotl = clamp(dot(normal, normalize(vec3(u_lightDirX, u_lightDirY, u_lightDirZ))), 0.0, 1.0);", " float wave = clamp(h * u_waveGain + 0.5, 0.0, 1.0);", " float crest = pow(smoothstep(u_crestLo, max(u_crestHi, u_crestLo + 0.01), wave), max(u_crestPow, 0.01));", " float glitter = pow(max(0.0, ndotl), max(u_glitterPow, 0.01)) * crest;", " glitter = max(glitter, pow(crest, 2.5) * u_crestGlitter);", " float edgeProx = 0.0;", " if (u_edgeN > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.y)); }", " if (u_edgeS > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.y)); }", " if (u_edgeW > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.x)); }", " if (u_edgeE > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.x)); }", " if (u_edgeNE > 0.5) {", " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, puv.y))));", " }", " if (u_edgeNW > 0.5) {", " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, puv.y))));", " }", " if (u_edgeSE > 0.5) {", " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, 1.0 - puv.y))));", " }", " if (u_edgeSW > 0.5) {", " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, 1.0 - puv.y))));", " }", " float waveBody = wave * (1.0 - edgeProx * 0.72);", " float heat = smoothstep(u_bodyLo, max(u_bodyHi, u_bodyLo + 0.01), waveBody);", " heat = mix(heat, 1.0, smoothstep(u_litLo, max(u_litHi, u_litLo + 0.01), waveBody) * u_litMix * 0.35);", " heat = clamp(heat + min(glitter, u_glitterCap) * u_glitterMix * 0.45, 0.0, 1.0);", " vec3 darkRed = vec3(0.16, 0.015, 0.01);", " vec3 brightRed = vec3(0.78, 0.08, 0.02);", " vec3 orange = vec3(0.98, 0.38, 0.04);", " vec3 yellow = vec3(1.0, 0.9, 0.28);", " vec3 rgb = mix(darkRed, brightRed, smoothstep(0.0, 0.38, heat));", " rgb = mix(rgb, orange, smoothstep(0.28, 0.68, heat));", " float yellowAmt = smoothstep(0.55, 0.98, heat);", " rgb = mix(rgb, yellow, yellowAmt);", " float shade = mix(u_shadeLo, u_shadeHi, ndotl);", " rgb *= shade;", " rgb = mix(rgb, darkRed, edgeProx * u_edgeDark * 0.35);", " float shoreW = 0.0;", " vec3 shoreRgb = rgb;", " if (u_edgeN > 0.5) {", " sampleShore(1.0, u_shoreEdgeN, vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);", " }", " if (u_edgeS > 0.5) {", " sampleShore(1.0, u_shoreEdgeS, vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);", " }", " if (u_edgeW > 0.5) {", " sampleShore(1.0, u_shoreEdgeW, vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);", " }", " if (u_edgeE > 0.5) {", " sampleShore(1.0, u_shoreEdgeE, vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);", " }", " if (u_edgeNE > 0.5) {", " sampleShore(1.0, max(u_shoreEdgeNE, u_hasShore), vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);", " }", " if (u_edgeNW > 0.5) {", " sampleShore(1.0, max(u_shoreEdgeNW, u_hasShore), vec2(puv.x, puv.y), shoreRgb, shoreW);", " }", " if (u_edgeSE > 0.5) {", " sampleShore(1.0, max(u_shoreEdgeSE, u_hasShore), vec2(1.0 - puv.x, 1.0 - puv.y), shoreRgb, shoreW);", " }", " if (u_edgeSW > 0.5) {", " sampleShore(1.0, max(u_shoreEdgeSW, u_hasShore), vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);", " }", " float darkAmt = 1.0 - smoothstep(0.12, 0.48, waveBody);", " float retreat = edgeProx * mix(0.72, 1.0, darkAmt);", " float shoreClip = u_shoreClip;", " float shoreMask = step(shoreClip, retreat) * shoreW;", " float crustAmt = (1.0 - shoreMask) * smoothstep(shoreClip - 0.2, shoreClip - 0.06, retreat)", " * (1.0 - smoothstep(shoreClip - 0.06, shoreClip, retreat));", " rgb = mix(rgb, vec3(0.05, 0.01, 0.0), crustAmt);", " rgb = mix(rgb, shoreRgb, shoreMask);", " float litTop = mix(u_litNW, u_litNE, v_texCoord.x);", " float litBottom = mix(u_litSW, u_litSE, v_texCoord.x);", " float lit = mix(litTop, litBottom, v_texCoord.y);", " float darkness = u_ambientDark * (1.0 - lit);", " rgb = mix(rgb, vec3(0.0), darkness);", " gl_FragColor = vec4(rgb, u_alpha);", "}" ].join("\n"); /** Unlit bloom overlay — strength tracks yellow heat (exempt from world darkness). */ const LAVA_BLOOM_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform float u_alpha;", "uniform float u_time;", "uniform float u_tileX;", "uniform float u_tileY;", "uniform float u_edgeN;", "uniform float u_edgeE;", "uniform float u_edgeS;", "uniform float u_edgeW;", "uniform float u_edgeNE;", "uniform float u_edgeNW;", "uniform float u_edgeSE;", "uniform float u_edgeSW;", "uniform float u_flowX;", "uniform float u_flowY;", "uniform float u_flowZ;", "uniform float u_waveScale;", "uniform float u_fbmAmp;", "uniform float u_texAmp;", "uniform float u_distort;", "uniform float u_normalZ;", "uniform float u_waveGain;", "uniform float u_crestLo;", "uniform float u_crestHi;", "uniform float u_crestPow;", "uniform float u_glitterPow;", "uniform float u_crestGlitter;", "uniform float u_glitterCap;", "uniform float u_glitterMix;", "uniform float u_bodyLo;", "uniform float u_bodyHi;", "uniform float u_litLo;", "uniform float u_litHi;", "uniform float u_litMix;", "uniform float u_lightDirX;", "uniform float u_lightDirY;", "uniform float u_lightDirZ;", "uniform float u_normalEps;", "uniform float u_bloomStrength;", "uniform float u_shoreClip;", ...LAVA_FBM_COMMON, "void main() {", " vec2 px = floor(v_texCoord * 16.0) + 0.5;", " vec2 puv = px / 16.0;", " vec2 world = vec2(u_tileX, u_tileY) + puv;", " float t = u_time;", " vec2 flow = vec2(t * u_flowX, t * u_flowY);", " float eps = max(u_normalEps, 0.001);", " vec3 base = vec3(world * u_waveScale + flow, t * u_flowZ);", " float nC = fbm(base);", " float nL = fbm(base + vec3(-eps, 0.0, 0.0));", " float nR = fbm(base + vec3(eps, 0.0, 0.0));", " float nD = fbm(base + vec3(0.0, -eps, 0.0));", " float nU = fbm(base + vec3(0.0, eps, 0.0));", " vec2 distort = vec2(nL - nR, nD - nU) * u_distort;", " float texN = texture2D(u_texture, wrapUv(world * 0.28 + flow * 0.6 + distort)).r;", " float h = nC * u_fbmAmp + (texN - 0.5) * u_texAmp;", " vec3 normal = normalize(vec3(nL - nR, nD - nU, max(u_normalZ, 0.05)));", " float ndotl = clamp(dot(normal, normalize(vec3(u_lightDirX, u_lightDirY, u_lightDirZ))), 0.0, 1.0);", " float wave = clamp(h * u_waveGain + 0.5, 0.0, 1.0);", " float crest = pow(smoothstep(u_crestLo, max(u_crestHi, u_crestLo + 0.01), wave), max(u_crestPow, 0.01));", " float glitter = pow(max(0.0, ndotl), max(u_glitterPow, 0.01)) * crest;", " glitter = max(glitter, pow(crest, 2.5) * u_crestGlitter);", " float edgeProx = 0.0;", " if (u_edgeN > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.y)); }", " if (u_edgeS > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.y)); }", " if (u_edgeW > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.x)); }", " if (u_edgeE > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.x)); }", " if (u_edgeNE > 0.5) {", " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, puv.y))));", " }", " if (u_edgeNW > 0.5) {", " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, puv.y))));", " }", " if (u_edgeSE > 0.5) {", " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, 1.0 - puv.y))));", " }", " if (u_edgeSW > 0.5) {", " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, 1.0 - puv.y))));", " }", " float waveBody = wave * (1.0 - edgeProx * 0.72);", " float heat = smoothstep(u_bodyLo, max(u_bodyHi, u_bodyLo + 0.01), waveBody);", " heat = mix(heat, 1.0, smoothstep(u_litLo, max(u_litHi, u_litLo + 0.01), waveBody) * u_litMix * 0.35);", " heat = clamp(heat + min(glitter, u_glitterCap) * u_glitterMix * 0.45, 0.0, 1.0);", " float darkAmt = 1.0 - smoothstep(0.12, 0.48, waveBody);", " float retreat = edgeProx * mix(0.72, 1.0, darkAmt);", " float hasEdge = max(max(u_edgeN, u_edgeE), max(u_edgeS, u_edgeW));", " hasEdge = max(hasEdge, max(max(u_edgeNE, u_edgeNW), max(u_edgeSE, u_edgeSW)));", " float shoreW = step(0.5, hasEdge);", " float shoreMask = step(u_shoreClip, retreat) * shoreW;", " float yellowAmt = smoothstep(0.55, 0.98, heat) * (1.0 - edgeProx * 0.85) * (1.0 - shoreMask);", " float bloom = yellowAmt * max(u_bloomStrength, 0.0);", " vec3 glow = vec3(1.0, 0.82, 0.28) * bloom;", " gl_FragColor = vec4(glow, bloom * u_alpha);", "}" ].join("\n"); /** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */ const TINT_LIT_SPRITE_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform float u_alpha;", "uniform float u_darkness;", "uniform float u_strength;", "uniform vec3 u_flashColor;", "uniform float u_wade;", "uniform float u_spriteHeight;", "uniform float u_useTint;", "uniform vec3 u_tintColor;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", " vec3 rgb = color.rgb;", " if (u_useTint > 0.5) {", " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {", " float L = color.r;", " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;", " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;", " }", " }", " if (u_wade > 0.5 && fromBottom < 5.0) {", " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", " }", " rgb = mix(rgb, vec3(0.0), u_darkness);", " rgb = mix(rgb, u_flashColor, u_strength);", " gl_FragColor = vec4(rgb, color.a * u_alpha);", "}" ].join("\n"); /** Dual/triple-channel tint: red = shaft, blue = tip, green = coat; then darkness. * Only when the primary channel is highest and the other two are equal; * equal non-zero secondaries lighten the assigned tint toward white. */ const DUAL_TINT_LIT_SPRITE_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform float u_alpha;", "uniform float u_darkness;", "uniform float u_strength;", "uniform vec3 u_flashColor;", "uniform float u_wade;", "uniform float u_spriteHeight;", "uniform vec3 u_shaftTint;", "uniform vec3 u_tipTint;", "uniform vec3 u_coatTint;", "uniform float u_hasCoat;", "vec3 channelTint(float L, float secondary, vec3 tint) {", " float blend = L > 0.0 ? clamp(secondary / L, 0.0, 1.0) : 0.0;", " return mix(tint, vec3(1.0), blend) * L;", "}", "float channelMask(float primary, float o1, float o2) {", " float equal = step(abs(o1 - o2), 0.04);", " return clamp((primary - max(o1, o2)) * 1.75, 0.0, 1.0) * equal;", "}", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", " vec3 rgb = color.rgb;", " if (u_hasCoat > 0.5) {", " float coatMask = channelMask(color.g, color.r, color.b);", " if (coatMask > 0.0) {", " vec3 coatCol = channelTint(color.g, color.r, u_coatTint);", " rgb = mix(rgb, coatCol, coatMask);", " }", " }", " float tipMask = channelMask(color.b, color.r, color.g);", " if (tipMask > 0.0) {", " vec3 tipCol = channelTint(color.b, color.r, u_tipTint);", " rgb = mix(rgb, tipCol, tipMask);", " }", " float shaftMask = channelMask(color.r, color.g, color.b);", " if (shaftMask > 0.0) {", " vec3 shaftCol = channelTint(color.r, color.g, u_shaftTint);", " rgb = mix(rgb, shaftCol, shaftMask);", " }", " if (u_wade > 0.5 && fromBottom < 5.0) {", " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", " }", " rgb = mix(rgb, vec3(0.0), u_darkness);", " rgb = mix(rgb, u_flashColor, u_strength);", " gl_FragColor = vec4(rgb, color.a * u_alpha);", "}" ].join("\n"); /** Magenta-tint equip overlay that clips alpha to the worn body silhouette. */ /** * Tight-fit: clip clothing alpha to the body silhouette in *pivot space* * (sizes may differ: shirt 20×24 vs body 16×24). Sample body UV remapped from * clothing frame coords; 1px dilate fills armpit/crotch gaps in the body art. */ const TIGHT_FIT_BODY_MASK_GLSL = [ "uniform vec2 u_clothSize;", "uniform vec2 u_bodySize;", "uniform float u_pivotFromBottom;", "uniform vec4 u_clothUvRect;", "uniform vec4 u_bodyUvRect;", "float tightFitBodyAlpha() {", " vec2 clothSpan = max(u_clothUvRect.zw - u_clothUvRect.xy, vec2(1e-5));", " vec2 nu = (v_texCoord - u_clothUvRect.xy) / clothSpan;", " float ox = (nu.x - 0.5) * u_clothSize.x;", " float oy = nu.y * u_clothSize.y - (u_clothSize.y - u_pivotFromBottom);", " vec2 bodySize = max(u_bodySize, vec2(1.0));", " vec2 bodyNu = vec2(0.5 + ox / bodySize.x, ((u_bodySize.y - u_pivotFromBottom) + oy) / bodySize.y);", " vec2 bodySpan = max(u_bodyUvRect.zw - u_bodyUvRect.xy, vec2(1e-5));", " vec2 texel = 1.0 / bodySize;", " float bodyA = 0.0;", " for (int dy = -1; dy <= 1; dy++) {", " for (int dx = -1; dx <= 1; dx++) {", " vec2 sampleNu = bodyNu + vec2(float(dx), float(dy)) * texel;", " if (sampleNu.x < 0.0 || sampleNu.x > 1.0 || sampleNu.y < 0.0 || sampleNu.y > 1.0) { continue; }", " vec2 sampleUv = u_bodyUvRect.xy + sampleNu * bodySpan;", " bodyA = max(bodyA, texture2D(u_secondary, sampleUv).a);", " }", " }", " return bodyA;", "}" ].join("\n"); const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform sampler2D u_secondary;", "uniform float u_alpha;", "uniform float u_darkness;", "uniform float u_strength;", "uniform vec3 u_flashColor;", "uniform float u_wade;", "uniform float u_spriteHeight;", "uniform float u_useTint;", "uniform vec3 u_tintColor;", TIGHT_FIT_BODY_MASK_GLSL, "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", " vec3 rgb = color.rgb;", " if (u_useTint > 0.5) {", " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {", " float L = color.r;", " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;", " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;", " }", " }", " if (u_wade > 0.5 && fromBottom < 5.0) {", " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", " }", " rgb = mix(rgb, vec3(0.0), u_darkness);", " rgb = mix(rgb, u_flashColor, u_strength);", " float alpha = min(tightFitBodyAlpha(), color.a) * u_alpha;", " if (alpha <= 0.0) { discard; }", " gl_FragColor = vec4(rgb, alpha);", "}" ].join("\n"); /** Body-clipped equip overlay without dye recolour. */ const TIGHT_FIT_LIT_SPRITE_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform sampler2D u_secondary;", "uniform float u_alpha;", "uniform float u_darkness;", "uniform float u_strength;", "uniform vec3 u_flashColor;", "uniform float u_wade;", "uniform float u_spriteHeight;", TIGHT_FIT_BODY_MASK_GLSL, "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", " vec3 rgb = color.rgb;", " if (u_wade > 0.5 && fromBottom < 5.0) {", " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", " }", " rgb = mix(rgb, vec3(0.0), u_darkness);", " rgb = mix(rgb, u_flashColor, u_strength);", " float alpha = min(tightFitBodyAlpha(), color.a) * u_alpha;", " if (alpha <= 0.0) { discard; }", " gl_FragColor = vec4(rgb, alpha);", "}" ].join("\n"); const ATLAS_LIGHTING_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform sampler2D u_secondary;", "uniform sampler2D u_bump;", "uniform float u_alpha;", "uniform float u_ambientDark;", "uniform float u_lightRow;", "uniform float u_useNature;", "uniform float u_natureTint;", "uniform float u_natureDark;", "uniform float u_natureContrast;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " vec3 rgb = color.rgb;", " if (u_useNature > 0.5) {", // Soft bilinear over 18×18 noise (1-tile halo) so blend crosses chunk edges. " vec2 texel = v_texCoord * 16.0 - 0.5;", " vec2 i0 = floor(texel);", " vec2 f = fract(texel);", " vec2 i1 = i0 + 1.0;", " vec2 c00 = (i0 + 1.5) / 18.0;", " vec2 c10 = (vec2(i1.x, i0.y) + 1.5) / 18.0;", " vec2 c01 = (vec2(i0.x, i1.y) + 1.5) / 18.0;", " vec2 c11 = (i1 + 1.5) / 18.0;", " vec4 s00 = texture2D(u_bump, c00);", " vec4 s10 = texture2D(u_bump, c10);", " vec4 s01 = texture2D(u_bump, c01);", " vec4 s11 = texture2D(u_bump, c11);", " float nRaw = mix(mix(s00.r, s10.r, f.x), mix(s01.r, s11.r, f.x), f.y);", " float a = mix(mix(s00.a, s10.a, f.x), mix(s01.a, s11.a, f.x), f.y);", " if (a > 0.01) {", " float n = clamp((nRaw - 0.5) * max(u_natureContrast, 0.01) + 0.5, 0.0, 1.0);", " float c = (n - 0.5) * 2.0;", " vec3 tinted = rgb * (1.0 - c * u_natureDark);", " vec3 cool = vec3(0.72, 1.14, 1.08);", " vec3 warm = vec3(1.28, 1.06, 0.68);", " vec3 tint = mix(cool, warm, n);", " tinted *= mix(vec3(1.0), tint, clamp(u_natureTint, 0.0, 1.0));", " rgb = mix(rgb, tinted, clamp(a, 0.0, 1.0));", " }", " }", " vec2 lightUV = v_texCoord;", " if (u_lightRow >= 0.0) {", " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;", " }", " float lit = texture2D(u_secondary, lightUV).r;", " float darkness = u_ambientDark * (1.0 - lit);", " rgb = mix(rgb, vec3(0.0), darkness);", " gl_FragColor = vec4(rgb, color.a * u_alpha);", "}" ].join("\n"); /** * Per-tile cliff sprite: high-chroma / authored magenta top → sample this chunk's * ground atlas (u_bump) at the cliff's tile-local UV. Only assigned to * `cliffGroundTop` blocks — never to chunk block-row atlases (those keep normal * lighting so magenta wood tints are not mistaken for cliff tops). */ const SPRITE_CLIFF_GROUND_TOP_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform sampler2D u_bump;", "uniform float u_alpha;", "uniform float u_darkness;", "uniform vec2 u_tileLocal;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " vec3 rgb = color.rgb;", " float rbDiff = abs(rgb.r - rgb.b);", " if (rbDiff < 0.02 && rgb.g < rgb.r) {", " vec2 groundUV = (u_tileLocal + v_texCoord) / 16.0;", " rgb = texture2D(u_bump, groundUV).rgb;", " }", " rgb = mix(rgb, vec3(0.0), u_darkness);", " gl_FragColor = vec4(rgb, color.a * u_alpha);", "}" ].join("\n"); let spriteLightingShader = null; let atlasLightingShader = null; let cliffGroundTopShader = null; let waterGroundShader = null; let lavaGroundShader = null; let lavaBloomShader = null; let tintLitSpriteShader = null; let dualTintLitSpriteShader = null; let tightFitTintLitSpriteShader = null; let tightFitLitSpriteShader = null; function getSpriteLightingShader () { if (!spriteLightingShader) { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); } return spriteLightingShader; } function getAtlasLightingShader () { if (!atlasLightingShader) { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); } return atlasLightingShader; } function getCliffGroundTopShader () { if (!cliffGroundTopShader) { cliffGroundTopShader = Shader.fragment(SPRITE_CLIFF_GROUND_TOP_FRAG); } return cliffGroundTopShader; } function getWaterGroundShader () { if (!waterGroundShader) { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); } return waterGroundShader; } function getLavaGroundShader () { if (!lavaGroundShader) { lavaGroundShader = Shader.fragment(LAVA_GROUND_FRAG); } return lavaGroundShader; } function getLavaBloomShader () { if (!lavaBloomShader) { lavaBloomShader = Shader.fragment(LAVA_BLOOM_FRAG); } return lavaBloomShader; } function getTintLitSpriteShader () { if (!tintLitSpriteShader) { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); } return tintLitSpriteShader; } function getDualTintLitSpriteShader () { if (!dualTintLitSpriteShader) { dualTintLitSpriteShader = Shader.fragment(DUAL_TINT_LIT_SPRITE_FRAG); } return dualTintLitSpriteShader; } function getTightFitTintLitSpriteShader () { if (!tightFitTintLitSpriteShader) { tightFitTintLitSpriteShader = Shader.fragment(TIGHT_FIT_TINT_LIT_SPRITE_FRAG); } return tightFitTintLitSpriteShader; } function getTightFitLitSpriteShader () { if (!tightFitLitSpriteShader) { tightFitLitSpriteShader = Shader.fragment(TIGHT_FIT_LIT_SPRITE_FRAG); } return tightFitLitSpriteShader; } export class WorldView { #chunkRebuildKeys = new Set(); /** Soft-blend / wet-sand neighbor rebakes — deferred so they do not nest inside a primary bake. */ #chunkSoftNeighborKeys = new Set(); #chunkRebuildRaf = 0; #edgesDirty = false; #CHUNK_REBUILD_BATCH = 2; #pendingTextureCanvases = []; #pendingTextureCanvasSet = new Set(); #textureWarmRaf = 0; #TEXTURE_WARM_BATCH = 3; #atlasCache = createChunkAtlasCache(); #idlePrefetchId = 0; #playerChunkX = null; #playerChunkY = null; #playerMoveChunkDx = 0; #playerMoveChunkDy = 0; /** Reused by {@link #placePivoted} to avoid per-call `new vector()`. */ #placeSizeScratch = new vector(0, 0); constructor(game, scene, catalog = { grounds: {}, blocks: {} }) { this.game = game; this.scene = scene; this.catalog = catalog; this.preview = null; this.zoom = 2; /** Chunk-quantised world-Y origin for the depth sort (see {@link #depthLayer}). */ this.ySortOrigin = null; this.chunks = new Map(); this.bakedChunks = new Map(); this.tiles = new Map(); this.entities = new Map(); this.groundItems = new Map(); this.edges = new Map(); this.localEntityId = null; this.localBlind = false; /** @type {string} */ this.dimensionId = OVERWORLD_ID; /** @type {string} */ this.dimensionLightingMode = "dayNight"; /** @type {string} */ this.dimensionSeasonMode = "auto"; /** Calendar season from worldStatus when dimension season is auto. */ this.calendarSeason = seasonIdAt(); /** @type {"soft"|"simple"} */ this.lightingMode = "soft"; /** @type {boolean} */ this.bloomEnabled = true; /** Soft edge blend for blendable grounds (grass, dirt, …). */ this.softTerrain = false; /** * Per-chunk nature Perlin tint. Off in the world editor while painting * (rebakes are frequent); editor enables a one-shot bake on chunk save. */ this.natureTintEnabled = true; this.settings = { ...DEFAULT_WORLD_SETTINGS }; this.worldHour = 12; /** Calendar season for seasonal ground/block visuals (`spring` / `summer` / `fall` / `winter`). */ this.worldSeason = seasonIdAt(); this.nightPreview = null; this.followPlayer = true; this.dynamicLights = []; /** Persistent Light-spell tile lights (server-driven). */ this.spellLights = new Map(); /** Persistent Dark-spell tile darkness (server-driven). */ this.spellDarks = new Map(); this.swipes = []; this.damageFloats = []; this.damageNumbersEl = document.getElementById("damage-numbers"); this.skillLevelFloats = []; this.skillLevelFloatsEl = document.getElementById("skill-level-floats"); /** @type {Map} */ this.editorSpawners = new Map(); this.spawnRangeHighlight = null; this.wanderRangeHighlight = null; this.spellTargetHighlight = null; this.#syncBloomLayer(); } setSettings (settings) { const previous = this.settings; this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings }; this.#syncBloomLayer(); const prevBand = Number(previous?.wetSandBand); const nextBand = Number(this.settings.wetSandBand); if (Number.isFinite(nextBand) && prevBand !== nextBand) { this.#rebakeAllChunks(); } } /** * Client graphics prefs (lighting Soft/Simple, bloom On/Off, soft terrain). * @param {{ lighting?: string, bloom?: string, softTerrain?: string }} prefs */ setGraphicsPrefs (prefs) { if (prefs?.lighting === "simple" || prefs?.lighting === "soft") { this.lightingMode = prefs.lighting; } if (prefs?.bloom === "off" || prefs?.bloom === "on") { const enabled = prefs.bloom !== "off"; if (enabled !== this.bloomEnabled) { this.bloomEnabled = enabled; this.#syncBloomLayer(); } else { this.bloomEnabled = enabled; } } if (prefs?.softTerrain === "on" || prefs?.softTerrain === "off") { const enabled = prefs.softTerrain === "on"; if (enabled !== this.softTerrain) { this.softTerrain = enabled; this.#rebakeAllChunks(); } } } /** Apply server (or local) calendar season; rebakes chunks when it changes. */ setWorldSeason (season) { const calendar = season === SeasonId.spring || season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer ? season : seasonIdAt(); this.calendarSeason = calendar; const forced = resolveDimensionSeasonId(this.dimensionSeasonMode); const next = forced ?? calendar; if (next === this.worldSeason) { return; } this.worldSeason = next; this.#rebakeAllChunks(); } setDimensionId (dimensionId) { this.dimensionId = normalizeDimensionId(dimensionId); } setDimensionModes (lightingMode, seasonMode) { this.dimensionLightingMode = normalizeLightingMode(lightingMode); this.dimensionSeasonMode = normalizeSeasonMode(seasonMode); const forced = resolveDimensionSeasonId(this.dimensionSeasonMode); const next = forced ?? this.calendarSeason ?? seasonIdAt(); if (next !== this.worldSeason) { this.worldSeason = next; this.#rebakeAllChunks(); } } clearAllChunks () { for (const key of [...this.chunks.keys()]) { const [chunkX, chunkY] = key.split(",").map(Number); this.removeChunk(chunkX, chunkY); } for (const [id] of [...this.entities.entries()]) { if (id === this.localEntityId) { continue; } this.despawnEntity(id, { immediate: true }); } for (const [id] of [...this.groundItems.entries()]) { this.despawnGroundItem(id); } } /** Full client wipe when leaving the world (menu / disconnect). Includes the local player. */ clearPlaySession () { this.#cancelIdlePrefetch(); this.#chunkRebuildKeys.clear(); this.#chunkSoftNeighborKeys.clear(); this.#playerChunkX = null; this.#playerChunkY = null; this.#playerMoveChunkDx = 0; this.#playerMoveChunkDy = 0; this.localEntityId = null; for (const key of [...this.chunks.keys()]) { const [chunkX, chunkY] = key.split(",").map(Number); this.removeChunk(chunkX, chunkY); } for (const [id] of [...this.entities.entries()]) { this.despawnEntity(id, { immediate: true }); } for (const [id] of [...this.groundItems.entries()]) { this.despawnGroundItem(id); } } applySnapshot (snapshot) { const snapDim = normalizeDimensionId(snapshot.dimensionId ?? OVERWORLD_ID); if (normalizeDimensionId(this.dimensionId) !== snapDim) { return; } const key = `${snapshot.chunkX},${snapshot.chunkY}`; snapshot.occlusion = bakeChunkOcclusion(snapshot); this.chunks.set(key, snapshot); this.#scheduleChunkRebuild(snapshot); this.#redrawPreview(); this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY); if (snapshot.staticOnly) { this.#stripChunkDynamic(snapshot.chunkX, snapshot.chunkY); this.#scheduleEdgeRebuild(); return; } for (const entity of snapshot.entities ?? []) { this.#upsertEntity(entity); } for (const [id, item] of [...this.groundItems.entries()]) { if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY) { this.despawnGroundItem(id); } } for (const item of snapshot.groundItems ?? []) { this.upsertGroundItem(item); } this.#scheduleEdgeRebuild(); } setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null, skullValue = 0) { this.localEntityId = entityId; this.#upsertEntity({ entityId, characterId, tileX, tileY, gait, sex, firstName, lastName, layers: layers ?? undefined, skullValue: skullValue | 0, ...(health != null ? { health } : {}), ...(maxHealth != null ? { maxHealth } : {}) }); this.#notePlayerTile(tileX, tileY); } #stripChunkDynamic (chunkX, chunkY) { for (const [id, item] of [...this.groundItems.entries()]) { if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) { this.despawnGroundItem(id); } } for (const [id, entity] of [...this.entities.entries()]) { if (id === this.localEntityId) { continue; } if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY) { this.despawnEntity(id, { immediate: true }); } } } removeChunk (chunkX, chunkY) { const key = `${chunkX},${chunkY}`; this.chunks.delete(key); this.#destroyBakedChunk(key); this.#destroyEdges(key); const prefix = `${chunkX},${chunkY}:`; for (const [spawnerKey, entry] of [...this.editorSpawners.entries()]) { if (!spawnerKey.startsWith(prefix)) { continue; } this.#destroyEditorSpawnerEntry(entry); this.editorSpawners.delete(spawnerKey); } for (const [tileKey, objects] of [...this.tiles.entries()]) { if (objects.chunkX === chunkX && objects.chunkY === chunkY) { objects.ground?.destroy(); objects.groundBloom?.destroy(); objects.lavaBloom?.destroy(); objects.block?.destroy(); objects.blockBloom?.destroy(); this.tiles.delete(tileKey); } } for (const [id, item] of [...this.groundItems.entries()]) { if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) { this.despawnGroundItem(id); } } // Server sends unsubscribeChunk when a chunk leaves the static 5×5 ring. // Entity replication is limited to the inner 3×3; static-only chunks strip dynamics via staticOnly snapshots. for (const [id, entity] of [...this.entities.entries()]) { if (id === this.localEntityId) { continue; } if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY) { this.despawnEntity(id, { immediate: true }); } } this.#rebuildAllEdges(); } setChunkOpen (chunkX, chunkY, open) { const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return; } snapshot.open = !!open; this.#rebuildAllEdges(); } spawnEntity (payload) { // Fresh spawn is authoritative; do not let an older deferred hit overwrite HP. this.cancelDeferredCombatHits(payload?.entityId); this.#upsertEntity(payload); } moveEntity (payload) { const existing = this.entities.get(payload.entityId); // Move payloads lack appearance/mobTypeId — never invent a stub entity // (that looked like a nameless humanoid "target"). Wait for entity-spawn. if (!existing) { return; } // Fading corpses stay put; respawn restores via reviveAfterDeath / spawn. if (existing.dying) { return; } const size = this.tileSize(); existing.fromX = existing.visualX; existing.fromY = existing.visualY; existing.shadeFromTileX = existing.tileX; existing.shadeFromTileY = existing.tileY; if (existing.tileX !== payload.tileX || existing.tileY !== payload.tileY) { existing.previousTileX = existing.tileX; existing.previousTileY = existing.tileY; } existing.tileX = payload.tileX; existing.tileY = payload.tileY; existing.gait = payload.gait; existing.freeFlight = !!payload.freeFlight || existing.freeFlight; if (payload.worldX != null && payload.worldY != null) { existing.worldX = payload.worldX; existing.worldY = payload.worldY; existing.targetX = payload.worldX * size; existing.targetY = payload.worldY * size; } else { const pivot = tilePivot(payload.tileX, payload.tileY, size); existing.targetX = pivot.x; existing.targetY = pivot.y; } existing.lerpStarted = performance.now(); existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait); if (payload.entityId === this.localEntityId) { this.#notePlayerTile(payload.tileX, payload.tileY); } } despawnEntity (entityId, { immediate = false, combatDeath = false } = {}) { const existing = this.entities.get(entityId); if (!existing) { return; } if (existing.dying) { if (immediate) { this.#finishEntityFade(entityId); } else if (combatDeath) { this.#upgradeToDeathDissolve(existing); } return; } // Chunk unload / session wipe: drop instantly. if (immediate) { this.cancelDeferredCombatHits(entityId); this.#destroyEntityVisuals(existing); this.entities.delete(entityId); return; } // Combat death → red silhouette. Leaving 3×3 / summons / etc. → plain fade. if (combatDeath) { this.#beginDeathDissolve(existing); } else { this.#beginDespawnFade(existing); } } /** * Start the red silhouette fade without requiring a despawn message * (e.g. local playerDied arrives before entityDespawn). */ beginDeathDissolve (entityId) { const existing = this.entities.get(entityId); if (!existing) { return; } if (existing.dying) { this.#upgradeToDeathDissolve(existing); return; } this.#beginDeathDissolve(existing); } /** * Abort an in-progress (or finished) death fade and snap the sprite back. * Local players are never entity-despawned, so respawn must restore — not * destroy — the visual. Remotes get a fresh entity-spawn instead. */ reviveAfterDeath (entityId, { tileX, tileY, health, maxHealth, skullValue } = {}) { const entity = this.entities.get(entityId); if (!entity) { return false; } this.#abortEntityFade(entity); if (tileX != null && tileY != null) { this.#snapEntityToTile(entity, tileX, tileY); } if (health != null) { entity.health = health; } if (maxHealth != null) { entity.maxHealth = maxHealth; } if (skullValue != null) { entity.skullValue = Math.max(0, skullValue | 0); } this.#syncHpBar(entity); this.#syncSkullMarker(entity); this.#placeEntity(entity, performance.now()); return true; } #destroyEntityVisuals (existing) { existing.object?.destroy(); existing.hpBar?.destroy(); existing.skullMarker?.destroy(); for (const overlay of existing.overlays ?? []) { overlay.destroy(); } for (const overlay of existing.bloomOverlays ?? []) { overlay.destroy(); } } #stripEntityChrome (entity) { entity.hpBar?.destroy(); entity.hpBar = null; entity.skullMarker?.destroy(); entity.skullMarker = null; } #beginDespawnFade (entity) { const now = performance.now(); entity.dying = true; entity.deathDissolve = false; entity.untargetable = true; entity.deathFadeStarted = now; entity.deathFadeMs = DESPAWN_FADE_MS; this.#stripEntityChrome(entity); } #beginDeathDissolve (entity) { const now = performance.now(); entity.dying = true; entity.deathDissolve = true; entity.untargetable = true; entity.deathFadeStarted = now; entity.deathFadeMs = DEATH_FADE_MS; // Keep a full red silhouette for the whole fade (hit flash may already be running). entity.damageFlashUntil = now + DEATH_FADE_MS; entity.damageFlashColor = FLASH_COLOR_DAMAGE; this.#stripEntityChrome(entity); // Leave deferred projectile impacts queued so knockback / float still play on arrival. } /** Promote an in-progress plain despawn fade to the red combat dissolve. */ #upgradeToDeathDissolve (entity) { if (entity.deathDissolve) { return; } const now = performance.now(); const elapsed = Math.max(0, now - (entity.deathFadeStarted ?? now)); const remaining = Math.max(1, (entity.deathFadeMs ?? DESPAWN_FADE_MS) - elapsed); entity.deathDissolve = true; entity.deathFadeStarted = now; entity.deathFadeMs = Math.min(DEATH_FADE_MS, remaining); entity.damageFlashUntil = now + entity.deathFadeMs; entity.damageFlashColor = FLASH_COLOR_DAMAGE; } #abortEntityFade (entity) { entity.dying = false; entity.deathDissolve = false; entity.untargetable = false; entity.deathFadeStarted = null; entity.deathFadeMs = null; entity.damageFlashUntil = 0; entity.damageFlashColor = null; if (entity.object?.renderer) { entity.object.renderer.alpha = 1; } for (const overlay of entity.overlays ?? []) { if (overlay.renderer) { overlay.renderer.alpha = 1; } } for (const overlay of entity.bloomOverlays ?? []) { if (overlay.renderer) { overlay.renderer.alpha = 1; } } } #snapEntityToTile (entity, tileX, tileY) { const size = this.tileSize(); const pivot = tilePivot(tileX, tileY, size); entity.tileX = tileX; entity.tileY = tileY; entity.visualX = pivot.x; entity.visualY = pivot.y; entity.targetX = pivot.x; entity.targetY = pivot.y; entity.fromX = pivot.x; entity.fromY = pivot.y; entity.lerpStarted = null; entity.previousTileX = null; entity.previousTileY = null; entity.shadeFromTileX = null; entity.shadeFromTileY = null; entity.shoveOffsetX = 0; entity.shoveOffsetY = 0; if (entity.entityId === this.localEntityId) { this.#notePlayerTile(tileX, tileY); } } #finishEntityFade (entityId) { this.cancelDeferredCombatHits(entityId); const existing = this.entities.get(entityId); if (!existing) { return; } this.#destroyEntityVisuals(existing); this.entities.delete(entityId); } /** * Drop queued combat-hit/block presentation for a target. * Killing blows often defer health=0 until a projectile lands; if the * target already finished dissolving or respawned, that stale apply must not run. */ cancelDeferredCombatHits (targetId) { if (targetId == null) { return; } for (const swipe of this.swipes) { if (swipe.targetId !== targetId) { continue; } swipe.onImpact = null; swipe.trackTarget = false; } } updateEntitySkull (entityId, skullValue) { const entity = this.entities.get(entityId); if (!entity) { return; } entity.skullValue = Math.max(0, skullValue | 0); const pivotX = (entity.visualX ?? 0) + (entity.shoveOffsetX ?? 0) + (entity.stackOffsetX ?? 0); const pivotY = (entity.visualY ?? 0) + (entity.shoveOffsetY ?? 0) + (entity.stackOffsetY ?? 0); const tileShade = this.#entityShadeAlpha?.(entity, performance.now()) ?? this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0; this.#placeSkullMarker(entity, pivotX, pivotY, tileShade); } updateEntityHealth (entityId, health, maxHealth) { const entity = this.entities.get(entityId); if (!entity || entity.dying) { return; } entity.health = health; entity.maxHealth = maxHealth; this.#syncHpBar(entity); } flashDamage (entityId) { this.#flashEntity(entityId, FLASH_COLOR_DAMAGE); } flashBlock (entityId) { this.#flashEntity(entityId, FLASH_COLOR_BLOCK); } #flashEntity (entityId, color) { const entity = this.entities.get(entityId); if (!entity) { return; } entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS; entity.damageFlashColor = color ?? FLASH_COLOR_DAMAGE; } /** Target knocks back away from attacker (hit). */ spawnCombatKnockback (payload) { const attacker = this.entities.get(payload?.attackerId); const target = this.entities.get(payload?.targetId); if (!attacker || !target) { return; } const ax = attacker.visualX + (attacker.stackOffsetX ?? 0); const ay = attacker.visualY + (attacker.stackOffsetY ?? 0); const tx = target.visualX + (target.stackOffsetX ?? 0); const ty = target.visualY + (target.stackOffsetY ?? 0); this.#applyShoveInDirection(target, tx - ax, ty - ay); } /** Target sidesteps perpendicular to the attack (dodge / miss). */ spawnCombatDodge (payload) { const attacker = this.entities.get(payload?.attackerId); const target = this.entities.get(payload?.targetId); if (!attacker || !target) { return; } const ax = attacker.visualX + (attacker.stackOffsetX ?? 0); const ay = attacker.visualY + (attacker.stackOffsetY ?? 0); const tx = target.visualX + (target.stackOffsetX ?? 0); const ty = target.visualY + (target.stackOffsetY ?? 0); const dx = tx - ax; const dy = ty - ay; const side = Math.random() < 0.5 ? 1 : -1; this.#applyShoveInDirection(target, -dy * side, dx * side); } spawnDamageNumber (entityId, damage) { const amount = damage | 0; if (amount <= 0) { return; } this.damageFloats.push({ entityId, damage: amount, started: performance.now() }); } /** * Queue combat-hit presentation until a matching in-flight projectile lands. * Returns true when deferred; caller should apply immediately when false. */ deferCombatHit (message, apply) { if (typeof apply !== "function" || message?.targetId == null) { return false; } const attackerId = message.attackerId ?? null; const targetId = message.targetId; const swipe = this.swipes.find((entry) => entry.lerp && entry.onImpact == null && entry.targetId === targetId && (attackerId == null || entry.attackerId === attackerId) && (entry.until ?? 0) > performance.now()); if (!swipe) { return false; } swipe.onImpact = apply; swipe.trackTarget = true; return true; } /** Stop tracking a living target (misses fly to a fixed tile). */ markProjectileMiss (message) { const attackerId = message?.attackerId ?? null; const targetId = message?.targetId ?? null; for (const swipe of this.swipes) { if (!swipe.lerp || swipe.onImpact != null) { continue; } if (targetId != null && swipe.targetId !== targetId) { continue; } if (attackerId != null && swipe.attackerId !== attackerId) { continue; } swipe.trackTarget = false; if (message.tileX != null) { swipe.tileX = message.tileX; } if (message.tileY != null) { swipe.tileY = message.tileY; } } } spawnSkillLevelUp (entityId, payload) { const level = payload?.level | 0; if (level <= 0 || !payload?.icon) { return; } this.skillLevelFloats.push({ entityId, level, icon: payload.icon, displayName: payload.displayName ?? payload.skillId ?? "", started: performance.now() }); } setAppearance (payload) { const existing = this.entities.get(payload.entityId); if (!existing) { return; } existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0; if (payload.lightIntensity != null) { existing.lightIntensity = Number(payload.lightIntensity) || 1; } if (payload.visualScale != null) { existing.visualScale = Number(payload.visualScale) || 1; } this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]); this.#placeEntity(existing); } /** * Render the live entity (body + overlays, same tint/tight-fit shaders as the * world, unlit) into an offscreen FBO, crop the top square, and return a * pixel-scaled canvas for UI (e.g. dialogue speaker icons). * @param {number} entityId * @param {{ size?: number }} [options] * @returns {HTMLCanvasElement | null} */ captureEntityPortrait (entityId, { size = 64 } = {}) { const entity = this.entities.get(entityId); const body = entity?.object?.renderer?.sprite; const glCtx = this.scene?.glContext; const gl = glCtx?.gl; if (!entity || !body || !gl) { return null; } const frameW = Math.max(1, body.width | 0 || SPRITE_SIZE_PX); const frameH = Math.max(1, body.height | 0 || SPRITE_SIZE_PX); if (!this.#ensurePortraitTarget(gl, frameW, frameH)) { return null; } const prevFb = gl.getParameter(gl.FRAMEBUFFER_BINDING); const prevViewport = gl.getParameter(gl.VIEWPORT); const prevW = glCtx._lastWidth; const prevH = glCtx._lastHeight; const prevBlend = gl.isEnabled(gl.BLEND); try { // drawSprite projects with _lastWidth/_lastHeight — match the FBO. glCtx._lastWidth = frameW; glCtx._lastHeight = frameH; gl.bindFramebuffer(gl.FRAMEBUFFER, this._portrait.fb); gl.viewport(0, 0, frameW, frameH); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); const pivotX = frameW * 0.5; const pivotY = frameH - PIVOT_FROM_BOTTOM_PX; this._portraitBodyMap = body.g_image ?? null; this._portraitTightFitEntity = entity; this.#drawPortraitLayer(glCtx, entity.object, pivotX, pivotY, null, false); const overlays = entity.overlays ?? []; const tints = entity.overlayTints ?? []; const dualTints = entity.overlayDualTints ?? []; const tight = entity.overlayTightFit ?? []; for (let index = 0; index < overlays.length; index++) { this.#drawPortraitLayer( glCtx, overlays[index], pivotX, pivotY, tints[index] ?? null, !!tight[index], dualTints[index] ?? null ); } this._portraitBodyMap = null; this._portraitTightFitEntity = null; const pixels = this._portrait.pixels; gl.readPixels(0, 0, frameW, frameH, gl.RGBA, gl.UNSIGNED_BYTE, pixels); } finally { glCtx._lastWidth = prevW; glCtx._lastHeight = prevH; gl.bindFramebuffer(gl.FRAMEBUFFER, prevFb); gl.viewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]); if (!prevBlend) { gl.disable(gl.BLEND); } gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); } return this.#portraitPixelsToCanvas(frameW, frameH, size); } #ensurePortraitTarget (gl, width, height) { const prev = this._portrait; if (prev && prev.w === width && prev.h === height && prev.fb && prev.tex) { return true; } if (prev?.fb) { gl.deleteFramebuffer(prev.fb); } if (prev?.tex) { gl.deleteTexture(prev.tex); } const tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0); const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); gl.bindFramebuffer(gl.FRAMEBUFFER, null); if (status !== gl.FRAMEBUFFER_COMPLETE) { gl.deleteFramebuffer(fb); gl.deleteTexture(tex); this._portrait = null; return false; } this._portrait = { fb, tex, w: width, h: height, pixels: new Uint8Array(width * height * 4), scratch: document.createElement("canvas") }; return true; } #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit, dualTint = null) { const sprite = object?.renderer?.sprite; if (!sprite?.g_image) { return; } const subImage = object.renderer.subImage | 0; const height = sprite.height || SPRITE_SIZE_PX; const draw = spriteDrawSize(sprite.width, sprite.height, 1); const center = spriteCenterFromPivot(pivotX, pivotY, height, 1); const tint = tintColor ? normalizeRgb(tintColor) : null; let shader = glCtx.defaultShader; let uniforms = null; let secondaryHtml = null; const bodyHtml = this._portraitBodyMap; const portraitEntity = this._portraitTightFitEntity; const maskUniforms = tightFit && portraitEntity ? this.#tightFitMaskUniforms(object, portraitEntity) : null; if (dualTint) { const shaft = normalizeRgb(dualTint.shaft); const tip = normalizeRgb(dualTint.tip); const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null; shader = getDualTintLitSpriteShader(); uniforms = { u_darkness: 0, u_strength: 0, u_flashColor: FLASH_COLOR_DAMAGE, u_wade: 0, u_spriteHeight: height, u_shaftTint: [shaft.r, shaft.g, shaft.b], u_tipTint: [tip.r, tip.g, tip.b], u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0], u_hasCoat: coat ? 1 : 0 }; } else if (tightFit && bodyHtml && maskUniforms) { secondaryHtml = bodyHtml; if (tint) { shader = getTightFitTintLitSpriteShader(); uniforms = { u_darkness: 0, u_strength: 0, u_flashColor: FLASH_COLOR_DAMAGE, u_wade: 0, u_spriteHeight: height, u_useTint: 1, u_tintColor: [tint.r, tint.g, tint.b], ...maskUniforms }; } else { shader = getTightFitLitSpriteShader(); uniforms = { u_darkness: 0, u_strength: 0, u_flashColor: FLASH_COLOR_DAMAGE, u_wade: 0, u_spriteHeight: height, ...maskUniforms }; } } else if (tint) { shader = getTintLitSpriteShader(); uniforms = { u_darkness: 0, u_strength: 0, u_flashColor: FLASH_COLOR_DAMAGE, u_wade: 0, u_spriteHeight: height, u_useTint: 1, u_tintColor: [tint.r, tint.g, tint.b] }; } else { shader = getSpriteLightingShader(); uniforms = { u_darkness: 0, u_strength: 0, u_flashColor: FLASH_COLOR_DAMAGE, u_wade: 0, u_spriteHeight: height }; } glCtx.drawSprite({ texture: glCtx.getTexture(sprite.g_image), x: center.x, y: center.y, w: draw.w, h: draw.h, rotationDeg: 0, mirrorX: false, mirrorY: false, alpha: 1, uvRect: sprite.getUvRect(subImage), shader, uniforms, textures: secondaryHtml ? { u_secondary: glCtx.getTexture(secondaryHtml) } : null, lights: null }); } #portraitPixelsToCanvas (frameW, frameH, size) { const pixels = this._portrait?.pixels; if (!pixels) { return null; } const scratch = this._portrait.scratch; scratch.width = frameW; scratch.height = frameH; const sctx = scratch.getContext("2d"); const imageData = sctx.createImageData(frameW, frameH); // WebGL y=0 is bottom — flip to top-down image order. for (let y = 0; y < frameH; y++) { const src = (frameH - 1 - y) * frameW * 4; const dst = y * frameW * 4; imageData.data.set(pixels.subarray(src, src + frameW * 4), dst); } sctx.putImageData(imageData, 0, 0); const crop = Math.min(frameW, frameH); const out = document.createElement("canvas"); out.width = size; out.height = size; const octx = out.getContext("2d"); octx.imageSmoothingEnabled = false; octx.clearRect(0, 0, size, size); octx.drawImage(scratch, 0, 0, crop, crop, 0, 0, size, size); return out; } upsertGroundItem (payload) { const size = this.tileSize(); const pivot = tilePivot(payload.tileX, payload.tileY, size); const potion = payload.instance?.kind === "potion" ? payload.instance : null; const spriteName = potion ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`) : (payload.sprite ?? itemSpriteNameForStack({ itemId: payload.itemId, instance: payload.instance, quantity: payload.quantity })); let item = this.groundItems.get(payload.groundItemId); if (!item) { const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK); this.scene.addObject(object); item = { object }; this.groundItems.set(payload.groundItemId, item); } else if (item.object?.renderer && this.game.images[spriteName]) { item.object.renderer.sprite = this.game.images[spriteName]; } item.groundItemId = payload.groundItemId; item.tileX = payload.tileX; item.tileY = payload.tileY; item.itemId = payload.itemId; item.quantity = payload.quantity; item.displayName = payload.displayName; item.sprite = spriteName; item.instance = payload.instance ?? null; const stack = { itemId: payload.itemId, instance: payload.instance ?? null }; const def = itemDefinition(payload.itemId); item.dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def); item.tintColor = item.dualTint ? null : resolveItemTint(stack, def); if (item.object?.renderer && itemMaxCharges(def) != null) { item.object.renderer.setSubImage?.(chargeSpriteFrameIndex(stack)); } this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0); } despawnGroundItem (groundItemId) { const item = this.groundItems.get(groundItemId); if (!item) { return; } item.object?.destroy(); this.groundItems.delete(groundItemId); } groundItemAtTile (tileX, tileY) { return this.groundItemsAtTile(tileX, tileY)[0] ?? null; } groundItemsAtTile (tileX, tileY) { const items = []; for (const item of this.groundItems.values()) { if (item.tileX === tileX && item.tileY === tileY) { items.push(item); } } return items; } entitiesAtTile (tileX, tileY, options = {}) { const includePrevious = !!options.includePrevious; const matches = []; for (const entity of this.entities.values()) { if (entity.tileX === tileX && entity.tileY === tileY) { matches.push(entity); continue; } if ( includePrevious && entity.lerpStarted != null && entity.previousTileX === tileX && entity.previousTileY === tileY ) { matches.push(entity); } } matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0)); return matches; } setZoom (zoom, limits = { min: 2, max: 4 }) { const min = limits.min ?? 1; const max = limits.max ?? 4; this.zoom = Math.min(max, Math.max(min, zoom)); for (const snapshot of this.chunks.values()) { this.#relayoutChunk(snapshot); } const size = this.tileSize(); for (const entity of this.entities.values()) { entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x; entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y; entity.fromX = entity.visualX; entity.fromY = entity.visualY; entity.targetX = entity.visualX; entity.targetY = entity.visualY; entity.lerpStarted = null; this.#placeEntity(entity); } for (const item of this.groundItems.values()) { const pivot = tilePivot(item.tileX, item.tileY, size); this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); } this.#rebuildAllEdges(); this.#relayoutEditorSpawners(); this.#relayoutSpawnRangeHighlight(); this.#relayoutSpellTargetHighlight(); // Play: recenter + refresh cull flags with the new tile size immediately. // Editor sets the camera via frameNeighborhood after setZoom — call refreshViewport there. if (this.followPlayer) { this.refreshViewport(); } } /** Recenter (when following) and refresh off-screen cull flags after zoom/layout. */ refreshViewport () { this.#centerCamera(); this.#syncYSortOrigin(); this.#refreshDepthLayers(); this.#cullOffscreenDrawables(); } tileSize () { return SPRITE_SIZE_PX * this.zoom; } screenToTile (mouseX, mouseY) { const size = this.tileSize(); const worldX = mouseX - this.scene.cameraPosition.x; const worldY = mouseY - this.scene.cameraPosition.y; return { tileX: Math.floor(worldX / size), tileY: Math.floor(worldY / size) }; } entityAtScreen (mouseX, mouseY) { let best = null; let bestLayer = -Infinity; for (const entity of this.entities.values()) { const box = this.#entityScreenBox(entity); if (!box) { continue; } if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom) { const layer = entity.object?.layer ?? 0; if (layer >= bestLayer) { best = entity; bestLayer = layer; } } } return best; } nametagAnchor (entity) { const box = this.#entityScreenBox(entity); if (!box) { return null; } return { x: (box.left + box.right) / 2, y: box.top }; } #entityScreenBox (entity) { const object = entity?.object; if (!object) { return null; } const size = object.transform.size; const x = object.transform.position.x + this.scene.cameraPosition.x; const y = object.transform.position.y + this.scene.cameraPosition.y; return { left: x - size.x / 2, right: x + size.x / 2, top: y - size.y / 2, bottom: y + size.y / 2 }; } update (deltaTime) { const now = performance.now(); const size = this.tileSize(); this.#refreshStackTargets(); for (const entity of this.entities.values()) { const target = entity.targetX != null && entity.targetY != null ? { x: entity.targetX, y: entity.targetY } : tilePivot(entity.tileX, entity.tileY, size); if (entity.lerpStarted != null) { const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs)); entity.visualX = entity.fromX + (target.x - entity.fromX) * t; entity.visualY = entity.fromY + (target.y - entity.fromY) * t; if (t >= 1) { entity.lerpStarted = null; entity.previousTileX = null; entity.previousTileY = null; } } else { entity.visualX = target.x; entity.visualY = target.y; } this.#updateStackOffset(entity, now); this.#updateShove(entity, now, size); this.#expireGatherToolOverlay(entity, now); } // The y-sort origin must settle before any layer is computed this frame, // otherwise entities and blocks end up sorted against different origins. // It only moves when the view crosses a chunk row; the static world then // needs one re-layer pass, and nothing at all on every other frame. this.#centerCamera(); if (this.#syncYSortOrigin()) { this.#refreshDepthLayers(); } for (const entity of this.entities.values()) { this.#placeEntity(entity, now); } this.#updateSwipes(now); this.#updateDamageNumbers(now); this.#updateSkillLevelFloats(now); this.#relayoutSpellTargetHighlight(); this.#cullOffscreenDrawables(); this.#updateShade(deltaTime); } /** * Desired circle offsets for stacked entities (applied via {@link #updateStackOffset}). * Stable assignment by entityId; free-flight entities stay unshifted. */ #refreshStackTargets () { const byTile = new Map(); for (const entity of this.entities.values()) { if (entity.freeFlight || entity.dying) { entity.stackTargetX = 0; entity.stackTargetY = 0; continue; } const key = `${entity.tileX},${entity.tileY}`; let list = byTile.get(key); if (!list) { list = []; byTile.set(key, list); } list.push(entity); } const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2; for (const list of byTile.values()) { if (list.length <= 1) { for (const entity of list) { entity.stackTargetX = 0; entity.stackTargetY = 0; } continue; } list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId))); const n = list.length; for (let i = 0; i < n; i++) { const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n; list[i].stackTargetX = Math.cos(angle) * radius; list[i].stackTargetY = Math.sin(angle) * radius; } } } #updateStackOffset (entity, now) { const tx = entity.stackTargetX ?? 0; const ty = entity.stackTargetY ?? 0; const cx = entity.stackOffsetX ?? 0; const cy = entity.stackOffsetY ?? 0; if (entity.stackLerpToX !== tx || entity.stackLerpToY !== ty) { entity.stackFromX = cx; entity.stackFromY = cy; entity.stackLerpToX = tx; entity.stackLerpToY = ty; entity.stackLerpStarted = now; } if (entity.stackLerpStarted == null) { entity.stackOffsetX = tx; entity.stackOffsetY = ty; return; } const t = Math.min(1, (now - entity.stackLerpStarted) / STACK_SPREAD_LERP_MS); entity.stackOffsetX = entity.stackFromX + (tx - entity.stackFromX) * t; entity.stackOffsetY = entity.stackFromY + (ty - entity.stackFromY) * t; if (t >= 1) { entity.stackOffsetX = tx; entity.stackOffsetY = ty; entity.stackLerpStarted = null; } } #updateShove (entity, now, tileSize) { if (!entity.shove) { entity.shoveOffsetX = 0; entity.shoveOffsetY = 0; return; } const elapsed = now - entity.shove.started; const t = Math.min(1, elapsed / entity.shove.durationMs); const maxDist = tileSize * SHOVE_TILE_FRACTION; const dx = entity.shove.targetVisualX - entity.shove.startVisualX; const dy = entity.shove.targetVisualY - entity.shove.startVisualY; const dist = Math.hypot(dx, dy) || 1; const ux = dx / dist; const uy = dy / dist; let phase; if (t < 0.45) { phase = t / 0.45; } else { phase = 1 - (t - 0.45) / 0.55; } entity.shoveOffsetX = ux * maxDist * phase; entity.shoveOffsetY = uy * maxDist * phase; if (t >= 1) { entity.shove = null; } } spawnCombatSwing (payload) { const attacker = this.entities.get(payload.attackerId); const target = this.entities.get(payload.targetId); if (!attacker || !target) { return; } const ax = attacker.visualX + (attacker.stackOffsetX ?? 0); const ay = attacker.visualY + (attacker.stackOffsetY ?? 0); const tx = target.visualX + (target.stackOffsetX ?? 0); const ty = target.visualY + (target.stackOffsetY ?? 0); this.#applyShove(attacker, tx, ty); const midX = (ax + tx) / 2; const midY = (ay + ty) / 2; const sortY = Math.max(ay, ty) + 0.02; const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI); const jitter = (Math.random() * 2 - 1) * MELEE_SWIPE_JITTER_DEG; const spriteName = "fx:melee-swipe:melee-swipe"; const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX); if (object.transform) { object.transform.rotation = angle + jitter; } if (object.renderer) { object.renderer.alpha = 1; } this.scene.addObject(object); this.#placePivoted(object, midX, midY, sortY, SORT_FX); this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY); const started = performance.now(); this.swipes.push({ object, until: started + MELEE_SWIPE_MS, started, durationMs: MELEE_SWIPE_MS, sortY, fadeOpacity: true, fromTileX: payload.fromTileX, fromTileY: payload.fromTileY, tileX: payload.tileX, tileY: payload.tileY }); } /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */ spawnGatherSwing (payload) { const attacker = this.entities.get(payload.attackerId); if (!attacker) { return; } const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize()); this.#applyShove(attacker, pivot.x, pivot.y); if (payload.toolItemId != null) { this.#setGatherToolOverlay(attacker, payload.toolItemId); } } #applyShove (entity, targetVisualX, targetVisualY) { entity.shove = { startVisualX: entity.visualX, startVisualY: entity.visualY, targetVisualX, targetVisualY, started: performance.now(), durationMs: SHOVE_MS }; } #applyShoveInDirection (entity, dirX, dirY) { const len = Math.hypot(dirX, dirY); if (len < 1e-4) { return; } const tileSize = this.tileSize(); const ux = dirX / len; const uy = dirY / len; this.#applyShove( entity, entity.visualX + ux * tileSize, entity.visualY + uy * tileSize ); } /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */ spawnPhysicalProjectileFx (payload) { const spriteName = payload.sprite ?? "fx:projectile:arrow"; const image = this.game.images[spriteName]; if (!image) { return; } const dualTint = this.#dualTintFromPayload(payload); const fromPivot = this.#projectileLaunchPoint( payload.attackerId ?? null, payload.fromTileX, payload.fromTileY ); const toPivot = this.#projectileAimPoint( payload.targetId ?? null, payload.tileX, payload.tileY ); const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02; const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI); const object = new GameObject(0, 0, image, SORT_FX); if (object.transform) { object.transform.rotation = angle; } this.scene.addObject(object); this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX); this.#applyPhysicalCombatFxDarkness( object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY, dualTint ); const started = performance.now(); const durationMs = payload.durationMs ?? 400; const trackTarget = payload.trackTarget !== false && payload.targetId != null; this.swipes.push({ object, until: started + durationMs, started, durationMs, lerp: true, dualTint, fromTileX: payload.fromTileX, fromTileY: payload.fromTileY, tileX: payload.tileX, tileY: payload.tileY, attackerId: payload.attackerId ?? null, targetId: payload.targetId ?? null, trackTarget, onImpact: null }); } /** Bloom-layer spell projectiles — magenta-tinted, unique art per spell. */ spawnSpellProjectileFx (payload) { const spellId = payload.spellId ?? null; const def = spellId != null ? spellDefinition(spellId) : null; const spriteName = payload.sprite ?? def?.projectileSprite ?? "fx:projectile:spell-none-1-mana-bullet"; const image = this.game.images[spriteName]; if (!image) { return; } const tint = spellProjectileTint(def?.element); const fromPivot = this.#projectileLaunchPoint( payload.casterId ?? null, payload.fromTileX, payload.fromTileY ); const toPivot = this.#projectileAimPoint( payload.targetId ?? null, payload.tileX, payload.tileY ); // Spell casts push the caster visually toward the spell's target. // (Presentation only; server authority remains combat-resolution.) const caster = payload.casterId != null ? this.entities.get(payload.casterId) : null; if (caster && !caster.dying) { const casterPivotX = caster.visualX + (caster.stackOffsetX ?? 0); const casterPivotY = caster.visualY + (caster.stackOffsetY ?? 0); this.#applyShoveInDirection(caster, toPivot.x - casterPivotX, toPivot.y - casterPivotY); } const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02; const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI); const object = new GameObject(0, 0, image, SORT_FX); object.renderer.layer = RENDER_LAYER_BLOOM; this.#markUnlit(object); this.#syncUnlitTintSprite(object, tint); if (object.transform) { object.transform.rotation = angle; } this.scene.addObject(object); this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX); const started = performance.now(); const durationMs = payload.durationMs ?? 2000; this.swipes.push({ object, until: started + durationMs, started, durationMs, lerp: true, spellProjectile: true, tint, fromTileX: payload.fromTileX, fromTileY: payload.fromTileY, tileX: payload.tileX, tileY: payload.tileY, attackerId: payload.casterId ?? null, targetId: payload.targetId ?? null, trackTarget: payload.targetId != null, onImpact: null }); } spawnSpellFizzleFx (_payload) { // Visual-only fizzle; no dynamic light (cast flashes skip lightmap rebakes). } /** * Authoritative Light-spell tile light from the server. * Kept out of short-lived `dynamicLights` so duration follows `remainingMs` updates. */ setSpellLight (payload) { const key = `${payload.tileX},${payload.tileY}`; this.spellLights.set(key, { tileX: payload.tileX, tileY: payload.tileY, until: performance.now() + Math.max(0, payload.remainingMs ?? 0), range: payload.rangeTiles ?? 6, intensity: payload.intensity ?? 0.88 }); this.#invalidateNeighborLightmapCaches( Math.floor(payload.tileX / CHUNK_SIZE), Math.floor(payload.tileY / CHUNK_SIZE) ); } removeSpellLight (payload) { this.spellLights.delete(`${payload.tileX},${payload.tileY}`); this.#invalidateNeighborLightmapCaches( Math.floor(payload.tileX / CHUNK_SIZE), Math.floor(payload.tileY / CHUNK_SIZE) ); } setSpellDark (payload) { const key = `${payload.tileX},${payload.tileY}`; this.spellDarks.set(key, { tileX: payload.tileX, tileY: payload.tileY, until: performance.now() + Math.max(0, payload.remainingMs ?? 0), range: payload.rangeTiles ?? 6, intensity: payload.intensity ?? 0.88 }); this.#invalidateNeighborLightmapCaches( Math.floor(payload.tileX / CHUNK_SIZE), Math.floor(payload.tileY / CHUNK_SIZE) ); } removeSpellDark (payload) { this.spellDarks.delete(`${payload.tileX},${payload.tileY}`); this.#invalidateNeighborLightmapCaches( Math.floor(payload.tileX / CHUNK_SIZE), Math.floor(payload.tileY / CHUNK_SIZE) ); } addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 }) { this.dynamicLights.push({ tileX: Math.floor(worldX), tileY: Math.floor(worldY), range: radiusTiles, intensity, until: performance.now() + durationMs }); } updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {}) { const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return; } const index = localY * CHUNK_SIZE + localX; if (ground !== undefined) { snapshot.grounds[index] = ground; } if (block !== undefined) { snapshot.blocks[index] = block; } if (light !== undefined) { snapshot.light[index] = light; } if (ground !== undefined || block !== undefined) { if (!Array.isArray(snapshot.occlusion) || snapshot.occlusion.length < CHUNK_SIZE * CHUNK_SIZE) { snapshot.occlusion = bakeChunkOcclusion(snapshot); } else { snapshot.occlusion[index] = tileLightOcclusionAt(snapshot.grounds, snapshot.blocks, localX, localY); } } const tileX = chunkX * CHUNK_SIZE + localX; const tileY = chunkY * CHUNK_SIZE + localY; if (block !== undefined) { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); this.#drawTile(tileX, tileY); return; } this.#scheduleChunkRebuild(snapshot); if (ground !== undefined) { this.#drawTile(tileX, tileY); } } /** * Editor-only mob markers for authored spawners (invisible during play). * Humanoid / town guard / CE show body + equipment overlays. * @param {number} chunkX * @param {number} chunkY * @param {Array<{ localX: number, localY: number, config?: object }>} spawners * @param {(mobTypeId: number) => string} resolveSprite */ setEditorSpawners (chunkX, chunkY, spawners, resolveSprite) { const prefix = `${chunkX},${chunkY}:`; for (const [key, entry] of [...this.editorSpawners.entries()]) { if (!key.startsWith(prefix)) { continue; } this.#destroyEditorSpawnerEntry(entry); this.editorSpawners.delete(key); } const size = this.tileSize(); for (const spawner of spawners ?? []) { const tileX = chunkX * CHUNK_SIZE + spawner.localX; const tileY = chunkY * CHUNK_SIZE + spawner.localY; const layers = layersFromSpawnerConfig(spawner.config); const bodySpriteName = layers?.[0]?.sprite ?? resolveSprite?.(spawner.config?.mobTypeId) ?? null; if (!bodySpriteName) { continue; } const key = `${prefix}${spawner.localX},${spawner.localY}`; const object = this.#ensureSprite(null, bodySpriteName, SORT_ENTITY); if (!object) { continue; } object.renderer.alpha = 0.85; const bodyTint = layers?.[0]?.tint ? normalizeRgb(layers[0].tint) : null; if (bodyTint) { this.#syncUnlitTintSprite(object, bodyTint); } else { this.#markUnlit(object); } const overlays = []; for (const layer of layers?.slice(1) ?? []) { const overlay = this.#ensureSprite(null, layer.sprite, SORT_ENTITY); if (!overlay) { continue; } overlay.renderer.alpha = 0.85; this.#applyEditorSpawnerOverlayLook(overlay, layer); overlays.push(overlay); } const pivot = tilePivot(tileX, tileY, size); this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY); for (let i = 0; i < overlays.length; i++) { this.#placePivoted( overlays[i], pivot.x, pivot.y, pivot.y + 0.05 + 0.001 * (i + 1), SORT_ENTITY ); } this.editorSpawners.set(key, { object, overlays, tileX, tileY, spriteName: bodySpriteName }); } } #destroyEditorSpawnerEntry (entry) { entry?.object?.destroy(); for (const overlay of entry?.overlays ?? []) { overlay?.destroy(); } } #applyEditorSpawnerOverlayLook (overlay, layer) { const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null; const dualTint = layerDef?.iconTintFromTier ? null : (layer.itemId != null ? resolveEquipDualTint({ itemId: layer.itemId }, layerDef) : null); const tint = layer.tint ? normalizeRgb(layer.tint) : (dualTint ? null : (layerDef?.iconTintFromTier ? resolveItemTint({ itemId: layer.itemId }, layerDef) : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null))); if (dualTint) { overlay._lit = true; this.#syncDualTintLitSprite(overlay, 0, dualTint, 0, false); return; } if (tint) { this.#syncUnlitTintSprite(overlay, tint); return; } this.#markUnlit(overlay); } clearEditorSpawners () { for (const entry of this.editorSpawners.values()) { this.#destroyEditorSpawnerEntry(entry); } this.editorSpawners.clear(); } #relayoutEditorSpawners () { const size = this.tileSize(); for (const entry of this.editorSpawners.values()) { if (!entry.object) { continue; } const pivot = tilePivot(entry.tileX, entry.tileY, size); this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY); const overlays = entry.overlays ?? []; for (let i = 0; i < overlays.length; i++) { this.#placePivoted( overlays[i], pivot.x, pivot.y, pivot.y + 0.05 + 0.001 * (i + 1), SORT_ENTITY ); } } } /** * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares). */ setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null) { const spawnRadius = Math.max(0, spawnRange | 0); const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0)); if (this.spawnRangeHighlight && this.wanderRangeHighlight && this.spawnRangeHighlight.tileX === tileX && this.spawnRangeHighlight.tileY === tileY && this.spawnRangeHighlight.range === spawnRadius && this.wanderRangeHighlight.range === wanderRadius) { this.#relayoutSpawnRangeHighlight(); return; } this.clearSpawnRangeHighlight(); const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE); const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE); if (wanderObject) { this.#markUnlit(wanderObject); wanderObject.renderer.alpha = 1; this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius }; } if (spawnObject) { this.#markUnlit(spawnObject); spawnObject.renderer.alpha = 1; this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius }; } this.#relayoutSpawnRangeHighlight(); } clearSpawnRangeHighlight () { this.spawnRangeHighlight?.object?.destroy(); this.wanderRangeHighlight?.object?.destroy(); this.spawnRangeHighlight = null; this.wanderRangeHighlight = null; } setSpellTargetHighlight (tileX, tileY, inRange = true) { if ( this.spellTargetHighlight && this.spellTargetHighlight.mode === "tile" && this.spellTargetHighlight.tileX === tileX && this.spellTargetHighlight.tileY === tileY && this.spellTargetHighlight.inRange === inRange ) { this.#relayoutSpellTargetHighlight(); return; } this.clearSpellTargetHighlight(); const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid"; const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1); if (!object) { return; } this.#markUnlit(object); object.renderer.alpha = 1; this.spellTargetHighlight = { mode: "tile", object, tileX, tileY, entityId: null, inRange, spriteName }; this.#relayoutSpellTargetHighlight(); } /** Outline box around a living entity (mob / player) for entity-target spells. */ setSpellEntityTargetHighlight (entityId, inRange = true) { const id = entityId | 0; if ( this.spellTargetHighlight && this.spellTargetHighlight.mode === "entity" && this.spellTargetHighlight.entityId === id && this.spellTargetHighlight.inRange === inRange ) { this.#relayoutSpellTargetHighlight(); return; } this.clearSpellTargetHighlight(); if (!this.entities.has(id)) { return; } const spriteName = inRange ? "spell-target-entity" : "spell-target-entity-invalid"; const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1); if (!object) { return; } this.#markUnlit(object); object.renderer.alpha = 1; this.spellTargetHighlight = { mode: "entity", object, tileX: 0, tileY: 0, entityId: id, inRange, spriteName }; this.#relayoutSpellTargetHighlight(); } clearSpellTargetHighlight () { this.spellTargetHighlight?.object?.destroy(); this.spellTargetHighlight = null; } #relayoutSpellTargetHighlight () { const highlight = this.spellTargetHighlight; if (!highlight?.object) { return; } if (highlight.mode === "entity") { const entity = this.entities.get(highlight.entityId); if (!entity?.object) { this.clearSpellTargetHighlight(); return; } const pad = this.tileSize() * 0.12; const src = entity.object.transform; highlight.object.transform.position.x = src.position.x; highlight.object.transform.position.y = src.position.y; highlight.object.transform.size = new vector(src.size.x + pad, src.size.y + pad); this.#setLayer(highlight.object, LAYER_EDGE - 1); highlight.tileX = entity.tileX; highlight.tileY = entity.tileY; return; } const size = this.tileSize(); const left = highlight.tileX * size; const top = highlight.tileY * size; highlight.object.transform.position.x = left + size / 2; highlight.object.transform.position.y = top + size / 2; highlight.object.transform.size = new vector(size, size); this.#setLayer(highlight.object, LAYER_EDGE - 1); } #relayoutSpawnRangeHighlight () { this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2); this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1); } #layoutRangeOverlay (highlight, layer) { if (!highlight?.object) { return; } const size = this.tileSize(); const side = (2 * highlight.range + 1) * size; const left = (highlight.tileX - highlight.range) * size; const top = (highlight.tileY - highlight.range) * size; highlight.object.transform.position.x = left + side / 2; highlight.object.transform.position.y = top + side / 2; highlight.object.transform.size = new vector(side, side); this.#setLayer(highlight.object, layer); } setTilePreview (tileX, tileY, override) { const next = { tileX, tileY, ...override }; if (this.#previewEqual(this.preview, next)) { return; } const previous = this.preview; this.preview = next; const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); this.#scheduleChunkRebuild(this.chunks.get(`${chunkX},${chunkY}`)); if (previous && (previous.tileX !== tileX || previous.tileY !== tileY)) { const prevKey = `${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`; if (prevKey !== `${chunkX},${chunkY}`) { this.#scheduleChunkRebuild(this.chunks.get(prevKey)); } // Per-tile blocks (doors, campfires, …) are not in the atlas — refresh sprites. this.#drawTile(previous.tileX, previous.tileY); } this.#drawTile(tileX, tileY); } clearTilePreview () { if (!this.preview) { return; } const previous = this.preview; this.preview = null; const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`); this.#scheduleChunkRebuild(snapshot); this.#drawTile(previous.tileX, previous.tileY); } #lerpMs (gait) { const walk = this.settings.walkTilesPerSecond || 2; const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk; return seconds * 1000; } #centerCamera () { if (!this.followPlayer) { return; } const local = this.entities.get(this.localEntityId); if (!local) { return; } const x = local.visualX + (local.stackOffsetX ?? 0); const y = local.visualY + (local.stackOffsetY ?? 0); this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x; this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y; } /** * World Y the depth sort is measured against, so layers stay bounded * (absolute tileY×zoom otherwise overflows past LAYER_EDGE). * * Quantised to the chunk row under the viewport centre: every sprite's layer * is relative to this, so an origin that moved with the camera would mean * re-layering the whole world every frame. Chunks only span the static 5×5 * ring, so relative sortY stays far inside LAYER_EDGE. * * @returns {boolean} whether the origin moved, i.e. callers must re-layer. */ #syncYSortOrigin () { const camY = this.scene.cameraPosition.y; const screenH = this.scene.real_size.y; const chunkPx = CHUNK_SIZE * this.tileSize(); const origin = Math.floor((-camY + screenH / 2) / chunkPx) * chunkPx; if (origin === this.ySortOrigin) { return false; } this.ySortOrigin = origin; return true; } /** Viewport-relative y-sort layer for world sprites. */ #depthLayer (sortY, subOrder, flight = false) { const relative = sortY - (this.ySortOrigin ?? 0); return flight ? flightSortLayer(relative, subOrder) : ySortLayer(relative, subOrder); } /** * Re-apply depth for every world sprite that is not repositioned each frame. * Their layer is relative to the y-sort origin, so a layer assigned once at * draw time goes stale as soon as that origin moves. * * Only run when {@link #syncYSortOrigin} reports a move (or after a zoom / * layout change) — entities carry their own per-frame layer via #placeEntity. */ #refreshDepthLayers () { const size = this.tileSize(); for (const baked of this.bakedChunks.values()) { const top = baked.chunkY * CHUNK_SIZE * size; const chunkPx = CHUNK_SIZE * size; for (let row = 0; row < CHUNK_SIZE; row++) { const rowY = top + row * size + size / 2; this.#setLayer(baked.blockObjects?.[row], this.#depthLayer(rowY, SORT_BLOCK)); } this.#setLayer(baked.bloomObject, this.#depthLayer(top + chunkPx, SORT_BLOCK)); } // Unbaked tile sprites: tall blocks, doors and animated grounds. for (const objects of this.tiles.values()) { if (!objects.block && !objects.blockBloom && !objects.groundBloom) { continue; } const pivotY = objects.tileY * size + size / 2; this.#setLayer(objects.block, this.#depthLayer(pivotY, objects.blockSort ?? SORT_ENTITY)); this.#setLayer(objects.blockBloom, this.#depthLayer(pivotY, SORT_ENTITY)); this.#setLayer(objects.groundBloom, this.#depthLayer(pivotY, LAYER_GROUND)); } for (const item of this.groundItems.values()) { this.#setLayer( item.object, this.#depthLayer(item.tileY * size + size / 2 - 0.01, SORT_BLOCK) ); } // Lerping FX are re-placed in #updateSwipes; static ones need the refresh. for (const swipe of this.swipes) { if (swipe.lerp || swipe.sortY == null) { continue; } this.#setLayer(swipe.object, this.#depthLayer(swipe.sortY, SORT_FX)); } for (const entry of this.editorSpawners.values()) { const pivotY = entry.tileY * size + size / 2; this.#setLayer(entry.object, this.#depthLayer(pivotY + 0.05, SORT_ENTITY)); const overlays = entry.overlays ?? []; for (let i = 0; i < overlays.length; i++) { this.#setLayer( overlays[i], this.#depthLayer(pivotY + 0.05 + 0.001 * (i + 1), SORT_ENTITY) ); } } } /** * World-pixel AABB of the screen, expanded for tall block sprites (zoom-aware). * Tiles fully outside this rect are not drawn. */ #drawBounds () { const pad = this.tileSize() * 2; const camX = this.scene.cameraPosition.x; const camY = this.scene.cameraPosition.y; const w = this.scene.real_size.x; const h = this.scene.real_size.y; return { left: -camX - pad, right: -camX + w + pad, top: -camY - pad, bottom: -camY + h + pad }; } #rectIntersects (left, top, right, bottom, bounds) { return right >= bounds.left && left <= bounds.right && bottom >= bounds.top && top <= bounds.bottom; } #setRendererVisible (object, visible) { if (object?.renderer) { object.renderer.visible = !!visible; } } /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */ #cullOffscreenDrawables () { const bounds = this.#drawBounds(); const size = this.tileSize(); for (const baked of this.bakedChunks.values()) { const left = baked.chunkX * CHUNK_SIZE * size; const top = baked.chunkY * CHUNK_SIZE * size; const chunkPx = CHUNK_SIZE * size; const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds); this.#setRendererVisible(baked.groundObject, chunkVisible); this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled); baked._inViewport = chunkVisible; for (let row = 0; row < CHUNK_SIZE; row++) { const rowTop = top + row * size; const rowVisible = chunkVisible && this.#rectIntersects( left, rowTop, left + chunkPx, rowTop + size, bounds ); this.#setRendererVisible(baked.blockObjects?.[row], rowVisible); } } for (const objects of this.tiles.values()) { const left = objects.tileX * size; const top = objects.tileY * size; const visible = this.#rectIntersects(left, top, left + size, top + size, bounds); objects._inViewport = visible; this.#setRendererVisible(objects.ground, visible); this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled); this.#setRendererVisible(objects.block, visible); this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled); this.#setRendererVisible(objects.lavaBloom, visible && this.bloomEnabled); } } #upsertEntity (payload) { const size = this.tileSize(); const pivot = tilePivot(payload.tileX, payload.tileY, size); let entity = this.entities.get(payload.entityId); if (entity?.dying) { if (entity.entityId === this.localEntityId) { this.#abortEntityFade(entity); } else { this.#finishEntityFade(payload.entityId); entity = null; } } if (!entity) { const spriteName = payload.layers?.[0]?.sprite ?? payload.sprite ?? bodySpriteName(payload.sex); const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY); this.scene.addObject(object); this.#startIdleAnimation(object); entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y }; this.entities.set(payload.entityId, entity); } entity.entityId = payload.entityId; entity.tileX = payload.tileX; entity.tileY = payload.tileY; entity.gait = payload.gait; entity.sex = payload.sex ?? entity.sex; entity.characterId = payload.characterId ?? entity.characterId ?? null; entity.accountId = payload.accountId ?? entity.accountId ?? null; entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null; if (payload.level != null) { entity.level = payload.level | 0; } entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile; entity.aggressive = payload.aggressive != null ? !!payload.aggressive : (payload.hostile != null ? !!payload.hostile : !!entity.aggressive); entity.canFight = payload.canFight != null ? !!payload.canFight : !!(entity.canFight || (payload.mobTypeId && !payload.talkable)); entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable; entity.hasDialogue = payload.hasDialogue != null ? !!payload.hasDialogue : !!entity.hasDialogue; entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop; entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable; entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight; entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0; if (payload.lightIntensity != null) { entity.lightIntensity = Number(payload.lightIntensity) || 1; } else if (entity.lightIntensity == null) { entity.lightIntensity = 1; } if (payload.visualScale != null) { entity.visualScale = Number(payload.visualScale) || 1; } else if (entity.visualScale == null) { entity.visualScale = 1; } if (payload.health != null) { entity.health = payload.health; } if (payload.maxHealth != null) { entity.maxHealth = payload.maxHealth; } if (payload.skullValue != null) { entity.skullValue = Math.max(0, payload.skullValue | 0); } else if (entity.skullValue == null) { entity.skullValue = 0; } if (payload.firstName) { entity.firstName = payload.firstName; } if (payload.lastName) { entity.lastName = payload.lastName; } entity.firstName = entity.firstName ?? ""; entity.lastName = entity.lastName ?? ""; if (payload.worldX != null && payload.worldY != null) { entity.worldX = payload.worldX; entity.worldY = payload.worldY; entity.visualX = payload.worldX * size; entity.visualY = payload.worldY * size; entity.targetX = entity.visualX; entity.targetY = entity.visualY; } else { entity.visualX = pivot.x; entity.visualY = pivot.y; entity.targetX = pivot.x; entity.targetY = pivot.y; } entity.fromX = entity.visualX; entity.fromY = entity.visualY; if (payload.layers) { this.#applyLayers(entity, payload.layers); } this.#syncHpBar(entity); this.#syncSkullMarker(entity); this.#placeEntity(entity, performance.now()); } #applyLayers (entity, layers) { entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }]; this.#rebuildOverlays(entity); } #setGatherToolOverlay (entity, toolItemId) { entity.gatherToolItemId = toolItemId; entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS; this.#rebuildOverlays(entity); this.#placeEntity(entity, performance.now()); } #expireGatherToolOverlay (entity, now) { if (entity.gatherToolItemId == null) { return; } if ((entity.gatherToolUntil ?? 0) > now) { return; } entity.gatherToolItemId = null; entity.gatherToolUntil = 0; this.#rebuildOverlays(entity); } /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */ #layersForDisplay (entity) { const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer })); const toolId = entity.gatherToolItemId; if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now()) { return layers; } const equip = itemEquipSprite(toolId); if (!equip || !this.game.images[equip]) { return layers; } const replacement = { sprite: equip, itemId: toolId, tint: resolveEquipTint(toolId) }; for (let index = layers.length - 1; index >= 1; index--) { const def = itemDefinition(layers[index].itemId); if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon) { layers[index] = replacement; return layers; } } layers.push(replacement); return layers; } #rebuildOverlays (entity) { const layers = this.#layersForDisplay(entity); const base = layers[0]?.sprite ?? bodySpriteName(entity.sex); if (this.game.images[base]) { entity.object.renderer.sprite = this.game.images[base]; this.#startIdleAnimation(entity.object); } entity.bodyTint = layers[0]?.tint ? normalizeRgb(layers[0].tint) : null; entity.bodyDualTint = layers[0]?.dualTint ? { shaft: normalizeRgb(layers[0].dualTint.shaft), tip: normalizeRgb(layers[0].dualTint.tip), ...(layers[0].dualTint.coat ? { coat: normalizeRgb(layers[0].dualTint.coat) } : {}) } : null; entity.bloomBody = !!layers[0]?.bloomBody; for (const overlay of entity.overlays ?? []) { overlay.destroy(); } for (const overlay of entity.bloomOverlays ?? []) { overlay.destroy(); } entity.overlays = []; entity.overlayTints = []; entity.overlayDualTints = []; entity.overlayTightFit = []; entity.bloomOverlays = []; entity.bloomOverlayTints = []; entity.bloomOverlayDualTints = []; if (entity.bloomBody && this.game.images[base]) { const bloomName = bloomCompanionName(base); const bloomImage = this.game.images[bloomName] ?? this.game.images[base]; if (bloomImage) { const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY); bloom.renderer.layer = RENDER_LAYER_BLOOM; this.#markUnlit(bloom); this.#startIdleAnimation(bloom); this.scene.addObject(bloom); entity.bloomOverlays.push(bloom); entity.bloomOverlayTints.push(entity.bodyTint); entity.bloomOverlayDualTints.push(entity.bodyDualTint); } } for (const layer of layers.slice(1)) { const image = this.game.images[layer.sprite]; if (!image) { continue; } const object = new GameObject(0, 0, image, SORT_ENTITY); this.scene.addObject(object); entity.overlays.push(object); const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null; entity.overlayTightFit.push(!!layerDef?.tightFit); const dualTint = layer.dualTint ? { shaft: normalizeRgb(layer.dualTint.shaft), tip: normalizeRgb(layer.dualTint.tip), ...(layer.dualTint.coat ? { coat: normalizeRgb(layer.dualTint.coat) } : {}) } : (layer.itemId != null ? resolveEquipDualTint({ itemId: layer.itemId }, layerDef) : null); entity.overlayDualTints.push(dualTint); entity.overlayTints.push( dualTint ? null : (layer.tint ? normalizeRgb(layer.tint) : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)) ); const bloomName = bloomCompanionName(layer.sprite); const bloomImage = this.game.images[bloomName]; if (!bloomImage) { continue; } const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY); bloom.renderer.layer = RENDER_LAYER_BLOOM; this.#markUnlit(bloom); this.scene.addObject(bloom); entity.bloomOverlays.push(bloom); entity.bloomOverlayTints.push( layer.tint ? normalizeRgb(layer.tint) : null ); } } #placeEntity (entity, now = performance.now()) { const zoom = this.zoom; const offsetX = entity.shoveOffsetX ?? 0; const offsetY = entity.shoveOffsetY ?? 0; const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0); const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0); let walkTilt = 0; if (entity.lerpStarted != null) { const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait)); const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2; const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG; walkTilt = Math.sin(cycles) * tilt; } let flashStrength = (entity.damageFlashUntil ?? 0) > now ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS : 0; let deathAlpha = 1; if (entity.dying) { const fadeMs = Math.max(1, entity.deathFadeMs ?? DEATH_FADE_MS); const fadeT = (now - (entity.deathFadeStarted ?? now)) / fadeMs; if (fadeT >= 1 && entity.entityId !== this.localEntityId) { this.#finishEntityFade(entity.entityId); return; } deathAlpha = Math.max(0, 1 - fadeT); // Red silhouette only for combat death; plain despawn keeps lit colours + darkness. if (entity.deathDissolve) { flashStrength = 1; } } const flashColor = entity.damageFlashColor ?? FLASH_COLOR_DAMAGE; const tileShade = this.#entityShadeAlpha(entity, now); const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason); entity.object.transform.rotation = walkTilt; if (entity.object.renderer) { entity.object.renderer.alpha = deathAlpha; } if (entity.bodyDualTint) { this.#syncDualTintLitSprite( entity.object, tileShade, entity.bodyDualTint, flashStrength, wade, flashColor ); } else { this.#syncLitSprite(entity.object, tileShade, flashStrength, wade, entity.bodyTint ?? null, flashColor); } const flight = !!entity.freeFlight; this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1, flight); for (let index = 0; index < (entity.overlays ?? []).length; index++) { const overlay = entity.overlays[index]; const overlaySort = Math.min(SORT_HP_BAR - 2, SORT_ENTITY + 1 + index); overlay.transform.rotation = walkTilt; if (overlay.renderer) { overlay.renderer.alpha = deathAlpha; } const dualTint = entity.overlayDualTints?.[index] ?? null; if (dualTint) { this.#syncDualTintLitSprite(overlay, tileShade, dualTint, flashStrength, wade, flashColor); } else if (entity.overlayTightFit?.[index]) { this.#syncTightFitLitSprite( overlay, entity, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null, flashColor ); } else { this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null, flashColor); } this.#placePivoted(overlay, pivotX, pivotY, pivotY, overlaySort, entity.visualScale ?? 1, flight); } for (let index = 0; index < (entity.bloomOverlays ?? []).length; index++) { const overlay = entity.bloomOverlays[index]; this.#setRendererVisible(overlay, this.bloomEnabled && deathAlpha > 0.02); if (!this.bloomEnabled) { continue; } /** Multi-frame body bloom locks to the base sprite; static bodies leave bloom free to animate. */ if (entity.bloomBody && index === 0 && entity.object?.renderer) { const bodySprite = entity.object.renderer.sprite; const bloomSprite = overlay.renderer.sprite; const bodyFrames = Number(bodySprite?.subImages) || Number(bodySprite?.subImgTotal) || 1; const bloomFrames = Number(bloomSprite?.subImages) || Number(bloomSprite?.subImgTotal) || 1; if (bodyFrames > 1 && bloomFrames === bodyFrames) { overlay.renderer.cycle = null; overlay.renderer.subImage = entity.object.renderer.subImage | 0; } } overlay.transform.rotation = walkTilt; if (overlay.renderer) { overlay.renderer.alpha = deathAlpha; } const bloomDual = entity.bloomOverlayDualTints?.[index] ?? null; const bloomTint = entity.bloomOverlayTints?.[index] ?? entity.bodyTint ?? null; if (bloomDual) { this.#syncDualTintLitSprite(overlay, 0, bloomDual); } else if (bloomTint) { this.#syncUnlitTintSprite(overlay, bloomTint); } else { this.#markUnlit(overlay); } this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1, flight); } if (!entity.dying) { this.#placeHpBar(entity, pivotX, pivotY); this.#placeSkullMarker(entity, pivotX, pivotY, tileShade); } } #markUnlit (object) { if (!object?.renderer) { return; } object._lit = false; object.renderer.shader = null; object.renderer.shaderUniforms = null; object.renderer._shaderUniformKind = null; object.renderer.secondaryMap = null; } #ensureUniformBag (renderer, shader, kind) { renderer.shader = shader; if (!renderer.shaderUniforms || renderer._shaderUniformKind !== kind) { renderer.shaderUniforms = {}; renderer._shaderUniformKind = kind; } return renderer.shaderUniforms; } #writeUniformVec3 (uniforms, key, src) { let arr = uniforms[key]; if (!Array.isArray(arr) || arr.length !== 3) { arr = [0, 0, 0]; uniforms[key] = arr; } if (Array.isArray(src)) { arr[0] = src[0]; arr[1] = src[1]; arr[2] = src[2]; } else { arr[0] = src.r; arr[1] = src.g; arr[2] = src.b; } } #writeUniformVec2 (uniforms, key, a, b) { let arr = uniforms[key]; if (!Array.isArray(arr) || arr.length !== 2) { arr = [0, 0]; uniforms[key] = arr; } arr[0] = a; arr[1] = b; } #writeUniformVec4 (uniforms, key, a, b, c, d) { let arr = uniforms[key]; if (!Array.isArray(arr) || arr.length !== 4) { arr = [0, 0, 0, 0]; uniforms[key] = arr; } arr[0] = a; arr[1] = b; arr[2] = c; arr[3] = d; } /** Bloom / unlit overlays that still need magenta channel tint (e.g. elemental sprites). */ #syncUnlitTintSprite (object, tintColor) { if (!object?.renderer || !tintColor) { return; } const tint = normalizeRgb(tintColor); const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX; const uniforms = this.#ensureUniformBag(object.renderer, getTintLitSpriteShader(), "unlitTint"); uniforms.u_darkness = 0; uniforms.u_strength = 0; this.#writeUniformVec3(uniforms, "u_flashColor", FLASH_COLOR_DAMAGE); uniforms.u_wade = 0; uniforms.u_spriteHeight = height; uniforms.u_useTint = 1; this.#writeUniformVec3(uniforms, "u_tintColor", tint); object.renderer.secondaryMap = null; } #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null) { if (!object?.renderer || object._lit === false) { return; } object._lit = true; const dark = Math.min(1, Math.max(0, darkness ?? 0)); const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX; const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE; const tint = tintColor ? normalizeRgb(tintColor) : null; if (tint) { const uniforms = this.#ensureUniformBag(object.renderer, getTintLitSpriteShader(), "tintLit"); uniforms.u_darkness = dark; uniforms.u_strength = flash; this.#writeUniformVec3(uniforms, "u_flashColor", flashRgb); uniforms.u_wade = wade ? 1 : 0; uniforms.u_spriteHeight = height; uniforms.u_useTint = 1; this.#writeUniformVec3(uniforms, "u_tintColor", tint); } else { const uniforms = this.#ensureUniformBag(object.renderer, getSpriteLightingShader(), "lit"); uniforms.u_darkness = dark; uniforms.u_strength = flash; this.#writeUniformVec3(uniforms, "u_flashColor", flashRgb); uniforms.u_wade = wade ? 1 : 0; uniforms.u_spriteHeight = height; } object.renderer.secondaryMap = null; } #bodySecondaryMap (entity) { return entity?.object?.renderer?.sprite?.g_image ?? null; } #tightFitMaskUniforms (overlay, entity, into = null) { const bodyRenderer = entity?.object?.renderer; const clothRenderer = overlay?.renderer; const bodySprite = bodyRenderer?.sprite; const clothSprite = clothRenderer?.sprite; if (!bodySprite || !clothSprite) { return null; } const clothUv = clothSprite.getUvRect?.(clothRenderer.subImage | 0) ?? { u0: 0, v0: 0, u1: 1, v1: 1 }; const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0) ?? { u0: 0, v0: 0, u1: 1, v1: 1 }; const uniforms = into ?? {}; this.#writeUniformVec2(uniforms, "u_clothSize", clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX); this.#writeUniformVec2(uniforms, "u_bodySize", bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX); uniforms.u_pivotFromBottom = PIVOT_FROM_BOTTOM_PX; this.#writeUniformVec4(uniforms, "u_clothUvRect", clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1); this.#writeUniformVec4(uniforms, "u_bodyUvRect", bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1); return uniforms; } #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null) { if (!overlay?.renderer || entity?.object?.renderer == null) { return; } const bodyMap = this.#bodySecondaryMap(entity); const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE; if (!bodyMap) { this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb); return; } overlay._lit = true; const dark = Math.min(1, Math.max(0, darkness ?? 0)); const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX; const tint = tintColor ? normalizeRgb(tintColor) : null; overlay.renderer.secondaryMap = bodyMap; const kind = tint ? "tightFitTint" : "tightFit"; const shader = tint ? getTightFitTintLitSpriteShader() : getTightFitLitSpriteShader(); const uniforms = this.#ensureUniformBag(overlay.renderer, shader, kind); if (!this.#tightFitMaskUniforms(overlay, entity, uniforms)) { this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb); return; } uniforms.u_darkness = dark; uniforms.u_strength = flash; this.#writeUniformVec3(uniforms, "u_flashColor", flashRgb); uniforms.u_wade = wade ? 1 : 0; uniforms.u_spriteHeight = height; if (tint) { uniforms.u_useTint = 1; this.#writeUniformVec3(uniforms, "u_tintColor", tint); } } #syncDualTintLitSprite (object, darkness, dualTint, flashStrength = 0, wade = false, flashColor = null) { if (!object?.renderer || !dualTint) { return; } const shaft = normalizeRgb(dualTint.shaft); const tip = normalizeRgb(dualTint.tip); const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null; const dark = object._lit === false ? 0 : Math.min(1, Math.max(0, darkness ?? 0)); if (object._lit !== false) { object._lit = true; } const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX; const uniforms = this.#ensureUniformBag(object.renderer, getDualTintLitSpriteShader(), "dualTint"); uniforms.u_darkness = dark; uniforms.u_strength = flash; this.#writeUniformVec3(uniforms, "u_flashColor", flashColor ?? FLASH_COLOR_DAMAGE); uniforms.u_wade = wade ? 1 : 0; uniforms.u_spriteHeight = height; this.#writeUniformVec3(uniforms, "u_shaftTint", shaft); this.#writeUniformVec3(uniforms, "u_tipTint", tip); this.#writeUniformVec3(uniforms, "u_coatTint", coat ?? { r: 0, g: 0, b: 0 }); uniforms.u_hasCoat = coat ? 1 : 0; object.renderer.secondaryMap = null; } #syncGroundItemSprite (item, darkness) { if (item?.dualTint) { this.#syncDualTintLitSprite(item.object, darkness, item.dualTint); return; } this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null); } #groundTypeAt (tileX, tileY) { const ground = this.#groundAtTile(tileX, tileY); return ground == null ? null : normalizeGround(ground).typeId; } /** Ground entry at a world tile, including editor hover preview when present. */ #groundAtTile (tileX, tileY) { if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY && this.preview.ground !== undefined) { return this.preview.ground; } const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return null; } const localX = tileX - chunkX * CHUNK_SIZE; const localY = tileY - chunkY * CHUNK_SIZE; const index = localY * CHUNK_SIZE + localX; return snapshot.grounds?.[index] ?? null; } #waterCoastEdges (tileX, tileY) { const season = this.worldSeason; const continues = (x, y) => fluidCoastContinues( this.#groundTypeAt(x, y), (typeId) => isLiquidWaterGround(typeId, season) ); const n = continues(tileX, tileY - 1); const e = continues(tileX + 1, tileY); const s = continues(tileX, tileY + 1); const w = continues(tileX - 1, tileY); const ne = continues(tileX + 1, tileY - 1); const nw = continues(tileX - 1, tileY - 1); const se = continues(tileX + 1, tileY + 1); const sw = continues(tileX - 1, tileY + 1); return { n: n ? 0 : 1, e: e ? 0 : 1, s: s ? 0 : 1, w: w ? 0 : 1, // Pure diagonal land pockets (e.g. WWW/WLL) — only when cardinals stay water. ne: (!ne && n && e) ? 1 : 0, nw: (!nw && n && w) ? 1 : 0, se: (!se && s && e) ? 1 : 0, sw: (!sw && s && w) ? 1 : 0 }; } /** * Corner deepness = average of liquid-water tiles meeting that corner. * Bilinear sampling of these corners is continuous across shared edges/corners. */ #waterDeepCorners (tileX, tileY, selfDeep) { const season = this.worldSeason; const fallback = selfDeep ? 1 : 0; const depthAt = (x, y) => { const typeId = this.#groundTypeAt(x, y); if (!isLiquidWaterGround(typeId, season)) { return null; } return typeId === GroundType.deepWater ? 1 : 0; }; const corner = (offsets) => { let sum = 0; let count = 0; for (const [dx, dy] of offsets) { const d = depthAt(tileX + dx, tileY + dy); if (d == null) { continue; } sum += d; count += 1; } return count ? sum / count : fallback; }; return { nw: corner([[0, 0], [-1, 0], [0, -1], [-1, -1]]), ne: corner([[0, 0], [1, 0], [0, -1], [1, -1]]), sw: corner([[0, 0], [-1, 0], [0, 1], [-1, 1]]), se: corner([[0, 0], [1, 0], [0, 1], [1, 1]]) }; } /** * Neighbor ground sprite for coast retreat peeks. * Water prefers wet-shore (sand-wet); lava uses dry land only. */ #fluidCoastShore (tileX, tileY, edges, { preferWet = true } = {}) { const season = this.worldSeason; const candidates = []; if (edges?.n) { candidates.push({ edge: "n", tileX, tileY: tileY - 1 }); } if (edges?.e) { candidates.push({ edge: "e", tileX: tileX + 1, tileY }); } if (edges?.s) { candidates.push({ edge: "s", tileX, tileY: tileY + 1 }); } if (edges?.w) { candidates.push({ edge: "w", tileX: tileX - 1, tileY }); } if (edges?.ne) { candidates.push({ edge: "ne", tileX: tileX + 1, tileY: tileY - 1 }); } if (edges?.nw) { candidates.push({ edge: "nw", tileX: tileX - 1, tileY: tileY - 1 }); } if (edges?.se) { candidates.push({ edge: "se", tileX: tileX + 1, tileY: tileY + 1 }); } if (edges?.sw) { candidates.push({ edge: "sw", tileX: tileX - 1, tileY: tileY + 1 }); } let pick = null; for (const candidate of candidates) { const ground = this.#groundAtTile(candidate.tileX, candidate.tileY); if (ground == null) { continue; } const entry = normalizeGround(ground); const def = GROUND_DEFINITIONS[entry.typeId]; if (!def || def.proceduralWaves || !def.blendable) { continue; } let spriteName = null; if (preferWet && def.wetShore) { const wetState = `${def.key}-wet`; const states = this.catalog?.grounds?.[def.key]?.states ?? []; if (states.includes(wetState)) { spriteName = spriteImageName("ground", def.key, wetState); } } if (!spriteName) { const states = this.catalog?.grounds?.[def.key]?.states ?? []; const state = resolveSeasonalVisualState(states, entry.state, season) ?? def.key; spriteName = spriteImageName("ground", def.key, state); } const sprite = spriteName ? this.game.images[spriteName] : null; if (!sprite) { continue; } const ranked = { ...candidate, sprite, wet: !!(preferWet && def.wetShore) }; if (ranked.wet) { pick = ranked; break; } if (!pick) { pick = ranked; } } const shore = { sprite: pick?.sprite ?? null, edgeN: 0, edgeE: 0, edgeS: 0, edgeW: 0, edgeNE: 0, edgeNW: 0, edgeSE: 0, edgeSW: 0 }; if (pick?.edge === "n") { shore.edgeN = 1; } else if (pick?.edge === "e") { shore.edgeE = 1; } else if (pick?.edge === "s") { shore.edgeS = 1; } else if (pick?.edge === "w") { shore.edgeW = 1; } else if (pick?.edge === "ne") { shore.edgeNE = 1; } else if (pick?.edge === "nw") { shore.edgeNW = 1; } else if (pick?.edge === "se") { shore.edgeSE = 1; } else if (pick?.edge === "sw") { shore.edgeSW = 1; } return shore; } #waterCoastShore (tileX, tileY, edges) { return this.#fluidCoastShore(tileX, tileY, edges, { preferWet: true }); } #syncWaterGroundSprite (object, { corners = null, ambientDark = 0, edges = null, shore = null, timeSec = 0, fallbackLit = 1, tileX = 0, tileY = 0, deepCorners = null } = {}) { if (!object?.renderer) { return; } const lit = corners ?? { nw: fallbackLit, ne: fallbackLit, sw: fallbackLit, se: fallbackLit }; const dark = Math.min(1, Math.max(0, ambientDark ?? 0)); const shoreSprite = shore?.sprite ?? null; const shoreUv = shoreSprite?.getUvRect?.(0) ?? { u0: 0, v0: 0, u1: 1, v1: 1 }; const dNW = deepCorners?.nw ?? 0; const dNE = deepCorners?.ne ?? 0; const dSW = deepCorners?.sw ?? 0; const dSE = deepCorners?.se ?? 0; object._lit = true; // Shallow + deep share one noise atlas so texAmp seams don't hard-cut at depth edges. const sharedNoise = this.game.images[spriteImageName("ground", "water", "water")]; if (sharedNoise) { object.renderer.sprite = sharedNoise; } object.renderer.secondaryMap = shoreSprite?.g_image ?? null; const uniforms = this.#ensureUniformBag(object.renderer, getWaterGroundShader(), "water"); uniforms.u_ambientDark = dark; uniforms.u_litNW = lit.nw; uniforms.u_litNE = lit.ne; uniforms.u_litSW = lit.sw; uniforms.u_litSE = lit.se; uniforms.u_time = timeSec; uniforms.u_tileX = tileX | 0; uniforms.u_tileY = tileY | 0; uniforms.u_deepNW = dNW; uniforms.u_deepNE = dNE; uniforms.u_deepSW = dSW; uniforms.u_deepSE = dSE; uniforms.u_edgeN = edges?.n ?? 0; uniforms.u_edgeE = edges?.e ?? 0; uniforms.u_edgeS = edges?.s ?? 0; uniforms.u_edgeW = edges?.w ?? 0; uniforms.u_edgeNE = edges?.ne ?? 0; uniforms.u_edgeNW = edges?.nw ?? 0; uniforms.u_edgeSE = edges?.se ?? 0; uniforms.u_edgeSW = edges?.sw ?? 0; uniforms.u_hasShore = shoreSprite ? 1 : 0; uniforms.u_shoreEdgeN = shore?.edgeN ?? 0; uniforms.u_shoreEdgeE = shore?.edgeE ?? 0; uniforms.u_shoreEdgeS = shore?.edgeS ?? 0; uniforms.u_shoreEdgeW = shore?.edgeW ?? 0; uniforms.u_shoreEdgeNE = shore?.edgeNE ?? 0; uniforms.u_shoreEdgeNW = shore?.edgeNW ?? 0; uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0; uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0; this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1); Object.assign(uniforms, waterDebugUniforms()); } /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. Lava is procedural heat. */ #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null) { if (!objects?.ground) { return; } if (isLavaGround(objects.groundTypeId)) { objects.waterEdges = null; this.#syncLavaGroundFx(objects, ambientDark, timeSec, baked); return; } this.#clearLavaBloom(objects); if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason)) { objects.waterEdges = null; this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0); return; } const fallbackLit = 1 - (objects.shadeAlpha ?? 0); const chunkX = Math.floor(objects.tileX / CHUNK_SIZE); const chunkY = Math.floor(objects.tileY / CHUNK_SIZE); const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`); const localX = objects.tileX - chunkX * CHUNK_SIZE; const localY = objects.tileY - chunkY * CHUNK_SIZE; let litCorners = null; if (chunkBaked) { if (this.lightingMode === "simple") { const gridW = CHUNK_SIZE + 2; const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit; litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity }; } else { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); } } objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY); const shore = this.#waterCoastShore(objects.tileX, objects.tileY, objects.waterEdges); const deep = objects.groundTypeId === GroundType.deepWater; this.#syncWaterGroundSprite(objects.ground, { corners: litCorners, ambientDark, edges: objects.waterEdges, shore, timeSec, fallbackLit, tileX: objects.tileX, tileY: objects.tileY, deepCorners: this.#waterDeepCorners(objects.tileX, objects.tileY, deep) }); } #lavaCoastEdges (tileX, tileY) { const continues = (x, y) => fluidCoastContinues( this.#groundTypeAt(x, y), (typeId) => isLavaGround(typeId) ); const n = continues(tileX, tileY - 1); const e = continues(tileX + 1, tileY); const s = continues(tileX, tileY + 1); const w = continues(tileX - 1, tileY); const ne = continues(tileX + 1, tileY - 1); const nw = continues(tileX - 1, tileY - 1); const se = continues(tileX + 1, tileY + 1); const sw = continues(tileX - 1, tileY + 1); return { n: n ? 0 : 1, e: e ? 0 : 1, s: s ? 0 : 1, w: w ? 0 : 1, ne: (!ne && n && e) ? 1 : 0, nw: (!nw && n && w) ? 1 : 0, se: (!se && s && e) ? 1 : 0, sw: (!sw && s && w) ? 1 : 0 }; } #clearLavaBloom (objects) { if (!objects) { return; } objects.lavaBloom?.destroy(); objects.lavaBloom = null; } #ensureLavaBloom (objects) { const sprite = objects.ground?.renderer?.sprite; if (!sprite) { return null; } if (!objects.lavaBloom) { const bloom = new GameObject(0, 0, sprite, LAYER_GROUND); bloom.renderer.layer = RENDER_LAYER_BLOOM; this.#markUnlit(bloom); this.scene.addObject(bloom); objects.lavaBloom = bloom; } else if (objects.lavaBloom.renderer) { objects.lavaBloom.renderer.sprite = sprite; } const size = this.tileSize(); objects.lavaBloom.transform.position.x = objects.tileX * size + size / 2; objects.lavaBloom.transform.position.y = objects.tileY * size + size / 2; objects.lavaBloom.transform.size = new vector(size, size); this.#setLayer(objects.lavaBloom, LAYER_GROUND); return objects.lavaBloom; } #syncLavaGroundFx (objects, ambientDark, timeSec, baked = null) { const fallbackLit = 1 - (objects.shadeAlpha ?? 0); const chunkX = Math.floor(objects.tileX / CHUNK_SIZE); const chunkY = Math.floor(objects.tileY / CHUNK_SIZE); const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`); const localX = objects.tileX - chunkX * CHUNK_SIZE; const localY = objects.tileY - chunkY * CHUNK_SIZE; let litCorners = null; if (chunkBaked) { if (this.lightingMode === "simple") { const gridW = CHUNK_SIZE + 2; const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit; litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity }; } else { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); } } const edges = this.#lavaCoastEdges(objects.tileX, objects.tileY); const shore = this.#fluidCoastShore(objects.tileX, objects.tileY, edges, { preferWet: false }); this.#syncLavaGroundSprite(objects.ground, { corners: litCorners, ambientDark, edges, shore, timeSec, fallbackLit, tileX: objects.tileX, tileY: objects.tileY }); const bloom = this.#ensureLavaBloom(objects); if (bloom) { this.#syncLavaBloomSprite(bloom, { edges, timeSec, tileX: objects.tileX, tileY: objects.tileY }); } } #syncLavaGroundSprite (object, { corners = null, ambientDark = 0, edges = null, shore = null, timeSec = 0, fallbackLit = 1, tileX = 0, tileY = 0 } = {}) { if (!object?.renderer) { return; } const lit = corners ?? { nw: fallbackLit, ne: fallbackLit, sw: fallbackLit, se: fallbackLit }; const dark = Math.min(1, Math.max(0, ambientDark ?? 0)); const shoreSprite = shore?.sprite ?? null; const shoreUv = shoreSprite?.getUvRect?.(0) ?? { u0: 0, v0: 0, u1: 1, v1: 1 }; object._lit = true; object.renderer.secondaryMap = shoreSprite?.g_image ?? null; const uniforms = this.#ensureUniformBag(object.renderer, getLavaGroundShader(), "lava"); uniforms.u_ambientDark = dark; uniforms.u_litNW = lit.nw; uniforms.u_litNE = lit.ne; uniforms.u_litSW = lit.sw; uniforms.u_litSE = lit.se; uniforms.u_time = timeSec; uniforms.u_tileX = tileX | 0; uniforms.u_tileY = tileY | 0; uniforms.u_edgeN = edges?.n ?? 0; uniforms.u_edgeE = edges?.e ?? 0; uniforms.u_edgeS = edges?.s ?? 0; uniforms.u_edgeW = edges?.w ?? 0; uniforms.u_edgeNE = edges?.ne ?? 0; uniforms.u_edgeNW = edges?.nw ?? 0; uniforms.u_edgeSE = edges?.se ?? 0; uniforms.u_edgeSW = edges?.sw ?? 0; uniforms.u_hasShore = shoreSprite ? 1 : 0; uniforms.u_shoreEdgeN = shore?.edgeN ?? 0; uniforms.u_shoreEdgeE = shore?.edgeE ?? 0; uniforms.u_shoreEdgeS = shore?.edgeS ?? 0; uniforms.u_shoreEdgeW = shore?.edgeW ?? 0; uniforms.u_shoreEdgeNE = shore?.edgeNE ?? 0; uniforms.u_shoreEdgeNW = shore?.edgeNW ?? 0; uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0; uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0; this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1); Object.assign(uniforms, lavaDebugUniforms()); } #syncLavaBloomSprite (object, { edges = null, timeSec = 0, tileX = 0, tileY = 0 } = {}) { if (!object?.renderer) { return; } const uniforms = this.#ensureUniformBag(object.renderer, getLavaBloomShader(), "lavaBloom"); uniforms.u_time = timeSec; uniforms.u_tileX = tileX | 0; uniforms.u_tileY = tileY | 0; uniforms.u_edgeN = edges?.n ?? 0; uniforms.u_edgeE = edges?.e ?? 0; uniforms.u_edgeS = edges?.s ?? 0; uniforms.u_edgeW = edges?.w ?? 0; uniforms.u_edgeNE = edges?.ne ?? 0; uniforms.u_edgeNW = edges?.nw ?? 0; uniforms.u_edgeSE = edges?.se ?? 0; uniforms.u_edgeSW = edges?.sw ?? 0; Object.assign(uniforms, lavaDebugUniforms()); } #ambientDarkness () { const hour = this.nightPreview ?? this.worldHour; const calendar = nightFactor(hour, this.settings.nightDarkness); let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar); if (dark == null) { dark = calendar; } if (this.localBlind) { dark = Math.min(1, dark + 0.85); } return dark; } setLocalBlind (blind) { this.localBlind = !!blind; } /** Soft vision bubble while blinded (client-only; stacks with ambient). */ #blindVisionLight () { if (!this.localBlind) { return null; } const local = this.entities.get(this.localEntityId); if (!local) { return null; } const tileSize = this.tileSize(); return { tileX: Math.floor(local.visualX / tileSize), tileY: Math.floor(local.visualY / tileSize), range: 2.25, intensity: 1 }; } #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null) { const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0; const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0; const dark = (fromAlpha + toAlpha) / 2; if (dualTint) { this.#syncDualTintLitSprite(object, dark, dualTint); return; } this.#syncLitSprite(object, dark); } #dualTintFromPayload (payload) { if (!payload?.shaftTint || !payload?.tipTint) { return null; } return { shaft: payload.shaftTint, tip: payload.tipTint, ...(payload.coatTint ? { coat: payload.coatTint } : {}) }; } #syncHpBar (entity) { const current = entity.health; const max = entity.maxHealth; const show = current != null && max != null && max > 0 && current < max; if (!show) { entity.hpBar?.destroy(); entity.hpBar = null; entity.hpBarCanvas = null; return; } if (!entity.hpBarCanvas) { entity.hpBarCanvas = document.createElement("canvas"); entity.hpBarCanvas.width = HP_BAR_W; entity.hpBarCanvas.height = HP_BAR_H; const image = frameworkImageFromCanvas(entity.hpBarCanvas); entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR); this.#markUnlit(entity.hpBar); this.scene.addObject(entity.hpBar); } drawHpBar(entity.hpBarCanvas, current, max); invalidateCanvasTexture(this.scene, entity.hpBarCanvas); } #placeHpBar (entity, pivotX, pivotY) { if (!entity.hpBar) { return; } const sprite = entity.object?.renderer?.sprite; if (!sprite) { return; } const zoom = this.zoom; const drawH = sprite.height * zoom; const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom); const spriteTop = centerY - drawH / 2; const barW = HP_BAR_W * zoom; const barH = HP_BAR_H * zoom; entity.hpBar.transform.position.x = pivotX; entity.hpBar.transform.position.y = spriteTop - barH / 2; entity.hpBar.transform.size = new vector(barW, barH); this.#setLayer(entity.hpBar, this.#depthLayer(pivotY, SORT_HP_BAR)); } #syncSkullMarker (entity) { if (!entity?.characterId) { entity.skullMarker?.destroy(); entity.skullMarker = null; return; } const tint = skullTintColor(entity.skullValue | 0, this.settings); if (!tint) { entity.skullMarker?.destroy(); entity.skullMarker = null; return; } const image = this.game.images[SKULL_SPRITE] ?? this.game.images["item:skull:skull"]; if (!image) { return; } if (!entity.skullMarker) { entity.skullMarker = new GameObject(0, 0, image, SORT_HP_BAR); this.scene.addObject(entity.skullMarker); } entity.skullTint = tint; entity.skullMarker.renderer.sprite = image; } /** * Bottom edge of the skull sprite sits exactly on the character sprite's top edge. */ #placeSkullMarker (entity, pivotX, pivotY, darkness) { this.#syncSkullMarker(entity); if (!entity.skullMarker) { return; } const body = entity.object?.renderer?.sprite; const skull = entity.skullMarker.renderer?.sprite; if (!body || !skull) { return; } const zoom = this.zoom; const scale = entity.visualScale ?? 1; const bodyH = body.height * zoom * scale; const skullH = skull.height * zoom; const skullW = skull.width * zoom; const bodyCenterY = pivotY - (bodyH / 2 - PIVOT_FROM_BOTTOM_PX * zoom * scale); const bodyTop = bodyCenterY - bodyH / 2; // GameObject position is sprite center; bottom of skull at bodyTop ⇒ center at bodyTop - skullH/2 entity.skullMarker.transform.position.x = pivotX; entity.skullMarker.transform.position.y = bodyTop - skullH / 2; entity.skullMarker.transform.size = new vector(skullW, skullH); this.#setLayer(entity.skullMarker, this.#depthLayer(pivotY, SORT_HP_BAR)); this.#syncLitSprite(entity.skullMarker, darkness, 0, false, entity.skullTint); } #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {}) { this.#bakeAndPlaceChunk(snapshot); this.#relayoutChunkTiles(snapshot); // Soft terrain and wet-sand shorelines both sample cross-chunk neighbors. if (refreshSoftNeighbors && this.#needsSoftTerrainNeighborRefresh()) { this.#rebuildSoftTerrainNeighborChunks(snapshot); } } /** Soft blend / wet-sand atlas borders need a rebake when an adjacent chunk arrives. */ #needsSoftTerrainNeighborRefresh () { if (this.softTerrain) { return true; } return Math.max(0, Number(this.settings?.wetSandBand) || 0) > 0; } #relayoutChunk (snapshot) { this.#layoutBakedChunk(snapshot); this.#relayoutChunkTiles(snapshot); } #relayoutChunkTiles (snapshot) { for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const tileX = snapshot.chunkX * CHUNK_SIZE + localX; const tileY = snapshot.chunkY * CHUNK_SIZE + localY; this.#drawTile(tileX, tileY); } } } #scheduleChunkRebuild (snapshot) { if (!snapshot) { return; } const key = `${snapshot.chunkX},${snapshot.chunkY}`; this.#chunkRebuildKeys.add(key); this.#chunkSoftNeighborKeys.delete(key); this.#cancelIdlePrefetch(); this.#ensureChunkFlushScheduled(); } /** Queue a neighbor atlas rebake without cascading further soft-neighbor work. */ #scheduleSoftNeighborChunkRebuild (snapshot) { if (!snapshot) { return; } const key = `${snapshot.chunkX},${snapshot.chunkY}`; if (this.#chunkRebuildKeys.has(key)) { return; } this.#chunkSoftNeighborKeys.add(key); this.#cancelIdlePrefetch(); this.#ensureChunkFlushScheduled(); } #scheduleEdgeRebuild () { this.#edgesDirty = true; this.#cancelIdlePrefetch(); this.#ensureChunkFlushScheduled(); } #pendingChunkRebuildCount () { return this.#chunkRebuildKeys.size + this.#chunkSoftNeighborKeys.size; } #ensureChunkFlushScheduled () { if (this.#chunkRebuildRaf) { return; } this.#cancelIdlePrefetch(); this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork()); } #notePlayerTile (tileX, tileY) { const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const prevX = this.#playerChunkX; const prevY = this.#playerChunkY; if (prevX != null && (chunkX !== prevX || chunkY !== prevY)) { const dx = chunkX - prevX; const dy = chunkY - prevY; if (dx !== 0) { this.#playerMoveChunkDx = Math.sign(dx); } if (dy !== 0) { this.#playerMoveChunkDy = Math.sign(dy); } this.#onActiveLightingCenterChanged(prevX, prevY, chunkX, chunkY); } this.#playerChunkX = chunkX; this.#playerChunkY = chunkY; } /** When the 3×3 lighting center moves: refresh door sprites (resting vs live) and lightmaps. */ #onActiveLightingCenterChanged (prevChunkX, prevChunkY, chunkX, chunkY) { this.#invalidateActiveLightingMoveCaches(prevChunkX, prevChunkY, chunkX, chunkY); const doorChunks = new Set(); for (const [cx, cy] of [[prevChunkX, prevChunkY], [chunkX, chunkY]]) { for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { doorChunks.add(`${cx + dx},${cy + dy}`); } } } for (const key of doorChunks) { const [cx, cy] = key.split(",").map(Number); this.#redrawDoorTilesInChunk(cx, cy); } } /** * Only bust lightmaps for chunks whose active-3×3 membership (or ±1 halo) changed. * Cache keys already track light positions; a full ±2 wipe around both centers was redundant. */ #invalidateActiveLightingMoveCaches (prevChunkX, prevChunkY, nextChunkX, nextChunkY) { const prev = new Set(); const next = new Set(); for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { prev.add(`${prevChunkX + dx},${prevChunkY + dy}`); next.add(`${nextChunkX + dx},${nextChunkY + dy}`); } } const changed = []; for (const key of prev) { if (!next.has(key)) { changed.push(key); } } for (const key of next) { if (!prev.has(key)) { changed.push(key); } } const bust = new Set(); for (const key of changed) { const [cx, cy] = key.split(",").map(Number); for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { bust.add(`${cx + dx},${cy + dy}`); } } } for (const key of bust) { const baked = this.bakedChunks.get(key); if (baked) { baked.lightmapCacheKey = null; } } } #redrawDoorTilesInChunk (chunkX, chunkY) { const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot?.blocks) { return; } for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const block = snapshot.blocks[localY * CHUNK_SIZE + localX]; if (!blockDefinition(block?.typeId)?.door) { continue; } this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY); } } } #playerChunkCoords () { const local = this.entities.get(this.localEntityId); if (local) { return { chunkX: Math.floor(local.tileX / CHUNK_SIZE), chunkY: Math.floor(local.tileY / CHUNK_SIZE) }; } if (this.#playerChunkX != null && this.#playerChunkY != null) { return { chunkX: this.#playerChunkX, chunkY: this.#playerChunkY }; } return null; } /** Lower score = bake sooner in urgent mode; idle mode inverts distance. */ #chunkRebuildScore (key, mode = "urgent") { const [chunkX, chunkY] = key.split(",").map(Number); const player = this.#playerChunkCoords(); if (!player) { return 0; } const dx = chunkX - player.chunkX; const dy = chunkY - player.chunkY; const dist = Math.abs(dx) + Math.abs(dy); let ahead = 0; if (this.#playerMoveChunkDx !== 0 || this.#playerMoveChunkDy !== 0) { ahead = dx * this.#playerMoveChunkDx + dy * this.#playerMoveChunkDy; } if (mode === "idle") { return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0)); } return dist * 10 - Math.max(0, ahead) * 3; } #sortedChunkRebuildKeys (keySet, mode = "urgent") { return [...keySet].sort((a, b) => this.#chunkRebuildScore(a, mode) - this.#chunkRebuildScore(b, mode)); } #discoverUnbakedChunks () { for (const key of this.chunks.keys()) { if (!this.bakedChunks.has(key)) { this.#chunkRebuildKeys.add(key); } } } #hasUnbakedChunks () { for (const key of this.chunks.keys()) { if (!this.bakedChunks.has(key)) { return true; } } return false; } #pickIdlePrefetchSnapshot () { let best = null; let bestScore = Infinity; for (const snapshot of this.chunks.values()) { const key = `${snapshot.chunkX},${snapshot.chunkY}`; if (this.bakedChunks.has(key) || this.#chunkRebuildKeys.has(key) || this.#chunkSoftNeighborKeys.has(key)) { continue; } const score = this.#chunkRebuildScore(key, "idle"); if (score < bestScore) { bestScore = score; best = snapshot; } } return best; } #cancelIdlePrefetch () { if (this.#idlePrefetchId && typeof cancelIdleCallback === "function") { cancelIdleCallback(this.#idlePrefetchId); } this.#idlePrefetchId = 0; } #scheduleIdleChunkPrefetch () { if (this.#idlePrefetchId || this.#chunkRebuildRaf || this.#pendingChunkRebuildCount()) { return; } if (typeof requestIdleCallback !== "function") { return; } if (!this.#hasUnbakedChunks()) { return; } this.#idlePrefetchId = requestIdleCallback( (deadline) => this.#runIdleChunkPrefetch(deadline), { timeout: 2500 } ); } #runIdleChunkPrefetch (deadline) { this.#idlePrefetchId = 0; if (this.#chunkRebuildRaf || this.#pendingChunkRebuildCount()) { return; } this.#discoverUnbakedChunks(); if (this.#pendingChunkRebuildCount()) { this.#ensureChunkFlushScheduled(); return; } const snapshot = this.#pickIdlePrefetchSnapshot(); if (!snapshot) { return; } if (deadline.timeRemaining() <= 4 && !deadline.didTimeout) { this.#scheduleIdleChunkPrefetch(); return; } this.#rebuildChunk(snapshot, { refreshSoftNeighbors: true }); if (this.#hasUnbakedChunks()) { this.#scheduleIdleChunkPrefetch(); } } #flushChunkWork () { this.#chunkRebuildRaf = 0; const primary = this.#sortedChunkRebuildKeys(this.#chunkRebuildKeys, "urgent"); const soft = this.#sortedChunkRebuildKeys(this.#chunkSoftNeighborKeys, "urgent"); let budget = this.#CHUNK_REBUILD_BATCH; const primaryBatch = primary.slice(0, budget); budget -= primaryBatch.length; const softBatch = soft.slice(0, Math.max(0, budget)); for (const key of primaryBatch) { this.#chunkRebuildKeys.delete(key); } for (const key of softBatch) { this.#chunkSoftNeighborKeys.delete(key); } for (const key of primaryBatch) { const snap = this.chunks.get(key); if (snap) { this.#rebuildChunk(snap, { refreshSoftNeighbors: true }); } } for (const key of softBatch) { const snap = this.chunks.get(key); if (snap) { this.#rebuildChunk(snap, { refreshSoftNeighbors: false }); } } if (this.#pendingChunkRebuildCount()) { this.#ensureChunkFlushScheduled(); return; } if (this.#edgesDirty) { this.#rebuildAllEdges(); this.#edgesDirty = false; } this.#scheduleIdleChunkPrefetch(); } #previewEqual (a, b) { if (a === b) { return true; } if (!a || !b) { return false; } return a.tileX === b.tileX && a.tileY === b.tileY && this.#previewPart(a.ground) === this.#previewPart(b.ground) && this.#previewPart(a.block) === this.#previewPart(b.block); } #previewPart (value) { return value === undefined ? undefined : JSON.stringify(value); } #rebuildSoftTerrainNeighborChunks (snapshot) { for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { if (dx === 0 && dy === 0) { continue; } const neighbor = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`); if (neighbor) { this.#scheduleSoftNeighborChunkRebuild(neighbor); } } } } #rebakeAllChunks () { for (const snapshot of this.chunks.values()) { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); } } #bakeAndPlaceChunk (snapshot) { const key = `${snapshot.chunkX},${snapshot.chunkY}`; const atlases = bakeChunkAtlases({ snapshot, catalog: this.catalog, images: this.game.images, preview: this.preview, season: this.worldSeason, softTerrain: this.softTerrain, wetSandBandFraction: Math.max(0, Math.min(1, Number(this.settings?.wetSandBand) || 0)), resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY), cache: this.#atlasCache }); const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX; let baked = this.bakedChunks.get(key); this.#releaseBakedAtlasRefs(baked); const groundImage = this.#atlasCache.getImage(atlases.cacheRefs?.ground); const blockImages = atlases.cacheRefs?.blockRows.map((entry) => this.#atlasCache.getImage(entry)) ?? atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)); const bloomImage = this.#atlasCache.getImage(atlases.cacheRefs?.bloom) ?? frameworkImageFromCanvas(atlases.bloom); if (!baked) { const lightmapCanvas = makeLightmapCanvas(atlasPx); const natureCanvas = makeNatureNoiseCanvas(); baked = { groundCanvas: atlases.ground, blockCanvases: atlases.blockRows, bloomCanvas: atlases.bloom, lightmapCanvas, natureCanvas, groundImage, blockImages, bloomImage, lightmapImage: frameworkImageFromCanvas(lightmapCanvas), natureImage: frameworkImageFromCanvas(natureCanvas), groundObject: null, blockObjects: [], bloomObject: null, tallBlocks: atlases.tallBlocks, animatedGrounds: atlases.animatedGrounds, lightmapPixels: null, atlasCacheRefs: atlases.cacheRefs, chunkX: snapshot.chunkX, chunkY: snapshot.chunkY }; baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND); this.#applyAtlasLighting( baked.groundObject, baked.lightmapImage, -1, this.#groundNatureImage(baked) ); this.scene.addObject(baked.groundObject); for (let row = 0; row < CHUNK_SIZE; row++) { const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK); this.#applyAtlasLighting(object, baked.lightmapImage, row, null); this.scene.addObject(object); baked.blockObjects.push(object); } baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK); baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; this.#markUnlit(baked.bloomObject); this.scene.addObject(baked.bloomObject); this.bakedChunks.set(key, baked); } else { baked.chunkX = snapshot.chunkX; baked.chunkY = snapshot.chunkY; if (!baked.natureCanvas) { baked.natureCanvas = makeNatureNoiseCanvas(); baked.natureImage = frameworkImageFromCanvas(baked.natureCanvas); } if (baked.groundCanvas !== atlases.ground) { baked.groundCanvas = atlases.ground; baked.groundImage = groundImage; baked.groundObject.renderer.sprite = groundImage; } this.#applyAtlasLighting( baked.groundObject, baked.lightmapImage, -1, this.#groundNatureImage(baked) ); for (let row = 0; row < CHUNK_SIZE; row++) { if (baked.blockCanvases[row] !== atlases.blockRows[row]) { baked.blockCanvases[row] = atlases.blockRows[row]; baked.blockImages[row] = blockImages[row]; baked.blockObjects[row].renderer.sprite = blockImages[row]; } this.#applyAtlasLighting( baked.blockObjects[row], baked.lightmapImage, row, null ); } if (baked.bloomCanvas !== atlases.bloom) { baked.bloomCanvas = atlases.bloom; baked.bloomImage = bloomImage; baked.bloomObject.renderer.sprite = bloomImage; } baked.tallBlocks = atlases.tallBlocks; baked.animatedGrounds = atlases.animatedGrounds; baked.atlasCacheRefs = atlases.cacheRefs; } baked.chunkX = snapshot.chunkX; baked.chunkY = snapshot.chunkY; if (this.natureTintEnabled) { this.#refreshNatureNoiseAround(snapshot.chunkX, snapshot.chunkY); } baked.lightmapCacheKey = null; this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY); this.#layoutBakedChunk(snapshot); this.#queueBakedChunkTextures(baked, snapshot.chunkX, snapshot.chunkY); } #groundNatureImage (baked) { if (!baked?.natureImage) { return null; } if (this.natureTintEnabled || baked.natureTintReady) { return baked.natureImage; } return null; } #releaseBakedAtlasRefs (baked) { if (!baked?.atlasCacheRefs) { return; } this.#atlasCache.release(baked.atlasCacheRefs.ground); for (const entry of baked.atlasCacheRefs.blockRows ?? []) { this.#atlasCache.release(entry); } this.#atlasCache.release(baked.atlasCacheRefs.bloom); baked.atlasCacheRefs = null; } #chunkTextureWarmPriority (chunkX, chunkY) { const local = this.entities.get(this.localEntityId); if (!local) { return 999; } const playerChunkX = Math.floor(local.tileX / CHUNK_SIZE); const playerChunkY = Math.floor(local.tileY / CHUNK_SIZE); return Math.abs(chunkX - playerChunkX) + Math.abs(chunkY - playerChunkY); } #queueCanvasTextureWarm (canvas, chunkX, chunkY) { if (!canvas || this.#pendingTextureCanvasSet.has(canvas)) { return; } this.#pendingTextureCanvasSet.add(canvas); this.#pendingTextureCanvases.push({ canvas, priority: this.#chunkTextureWarmPriority(chunkX, chunkY) }); this.#scheduleTextureWarm(); } #queueBakedChunkTextures (baked, chunkX, chunkY) { if (!baked) { return; } const refs = baked.atlasCacheRefs; const maybeWarm = (canvas, entry) => { if (!canvas) { return; } if (entry && this.#atlasCache.isWarmed(canvas)) { return; } this.#queueCanvasTextureWarm(canvas, chunkX, chunkY); }; maybeWarm(baked.groundCanvas, refs?.ground); for (let row = 0; row < (baked.blockCanvases ?? []).length; row++) { maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); } maybeWarm(baked.bloomCanvas, refs?.bloom); this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY); this.#queueCanvasTextureWarm(baked.natureCanvas, chunkX, chunkY); } #scheduleTextureWarm () { if (this.#textureWarmRaf) { return; } this.#textureWarmRaf = requestAnimationFrame(() => this.#flushTextureWarm()); } #flushTextureWarm () { this.#textureWarmRaf = 0; if (!this.#pendingTextureCanvases.length) { return; } this.#pendingTextureCanvases.sort((a, b) => a.priority - b.priority); const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH); for (const entry of batch) { this.#pendingTextureCanvasSet.delete(entry.canvas); setNearestFilter(this.scene, entry.canvas); this.#atlasCache.markWarmed(entry.canvas); } if (this.#pendingTextureCanvases.length) { this.#scheduleTextureWarm(); } } #applyAtlasLighting (object, lightmapImage, lightRow, natureImage = null) { if (!object?.renderer) { return; } object._lit = true; object.renderer.shader = getAtlasLightingShader(); const useNature = natureImage != null && lightRow < 0; object.renderer.bumpMap = useNature ? natureImage : null; object.renderer.secondaryMap = lightmapImage; object.renderer.shaderUniforms = { u_ambientDark: 0, u_lightRow: lightRow, u_useNature: useNature ? 1 : 0, u_natureTint: 0, u_natureDark: 0, u_natureContrast: 1, ...(useNature ? natureTintUniforms() : {}) }; } /** * One-shot nature tint bake (editor chunk-save). Fills noise for each chunk * and its halo neighbors, and enables tint on the ground atlas. * @param {Iterable<{ chunkX: number, chunkY: number }>} chunks */ bakeNatureTintForChunks (chunks) { const seen = new Set(); for (const entry of chunks ?? []) { const chunkX = entry?.chunkX; const chunkY = entry?.chunkY; if (!Number.isFinite(chunkX) || !Number.isFinite(chunkY)) { continue; } for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { const key = `${chunkX + dx},${chunkY + dy}`; if (seen.has(key)) { continue; } seen.add(key); const baked = this.bakedChunks.get(key); const snapshot = this.chunks.get(key); if (!baked?.natureCanvas || !snapshot) { continue; } if (this.#fillNatureNoise(baked, snapshot) || baked.natureTintReady) { if (baked.groundObject) { this.#applyAtlasLighting( baked.groundObject, baked.lightmapImage, -1, baked.natureImage ); } } } } } } /** Rebuild nature noise for a chunk and neighbors (halo needs adjacent grounds). */ #refreshNatureNoiseAround (chunkX, chunkY) { if (!this.natureTintEnabled) { return; } for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { const cx = chunkX + dx; const cy = chunkY + dy; const baked = this.bakedChunks.get(`${cx},${cy}`); const snapshot = this.chunks.get(`${cx},${cy}`); if (!baked?.natureCanvas || !snapshot) { continue; } if (this.#fillNatureNoise(baked, snapshot) && baked.groundObject) { this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1, baked.natureImage); } } } } /** * Hash of grounds sampled by the nature canvas (chunk + pad halo). * Used to skip Perlin refill when nothing under the noise map changed. */ #natureSourceHash (snapshot) { let hash = 2166136261; const baseX = snapshot.chunkX * CHUNK_SIZE; const baseY = snapshot.chunkY * CHUNK_SIZE; const pad = NATURE_NOISE_PAD; for (let ly = -pad; ly < CHUNK_SIZE + pad; ly++) { for (let lx = -pad; lx < CHUNK_SIZE + pad; lx++) { const ground = this.#groundAtTile(baseX + lx, baseY + ly); const typeId = ground == null ? -1 : (normalizeGround(ground).typeId ?? -1); hash ^= (typeId + 1) >>> 0; hash = Math.imul(hash, 16777619); } } return hash >>> 0; } /** * @returns {boolean} true when the nature canvas was rewritten */ #fillNatureNoise (baked, snapshot) { if (!baked?.natureCanvas || !snapshot) { return false; } const sourceHash = this.#natureSourceHash(snapshot); if (baked.natureSourceHash === sourceHash && baked.natureTintReady && baked.natureImage) { return false; } const canvas = baked.natureCanvas; if (canvas.width !== NATURE_NOISE_SIZE || canvas.height !== NATURE_NOISE_SIZE) { canvas.width = NATURE_NOISE_SIZE; canvas.height = NATURE_NOISE_SIZE; } const scale = NATURE_TINT.scale; const ctx = canvas.getContext("2d"); const pixelCount = NATURE_NOISE_SIZE * NATURE_NOISE_SIZE * 4; if (!baked.naturePixels || baked.naturePixels.length !== pixelCount) { baked.naturePixels = new Uint8ClampedArray(pixelCount); } const pixels = baked.naturePixels; if (!baked.natureImageData || baked.natureImageData.data !== pixels) { baked.natureImageData = new ImageData(pixels, NATURE_NOISE_SIZE, NATURE_NOISE_SIZE); } const baseX = snapshot.chunkX * CHUNK_SIZE; const baseY = snapshot.chunkY * CHUNK_SIZE; const pad = NATURE_NOISE_PAD; for (let py = 0; py < NATURE_NOISE_SIZE; py++) { for (let px = 0; px < NATURE_NOISE_SIZE; px++) { const lx = px - pad; const ly = py - pad; const worldX = baseX + lx; const worldY = baseY + ly; const ground = this.#groundAtTile(worldX, worldY); const typeId = ground == null ? null : normalizeGround(ground).typeId; const blendable = typeId != null && !!GROUND_DEFINITIONS[typeId]?.blendable; const n = natureNoise01(worldX, worldY, scale); const i = (py * NATURE_NOISE_SIZE + px) * 4; const v = Math.round(n * 255); pixels[i] = v; pixels[i + 1] = v; pixels[i + 2] = v; pixels[i + 3] = blendable ? 255 : 0; } } ctx.putImageData(baked.natureImageData, 0, 0); invalidateCanvasTexture(this.scene, baked.natureCanvas); this.#queueCanvasTextureWarm(baked.natureCanvas, snapshot.chunkX, snapshot.chunkY); if (!baked.natureImage) { baked.natureImage = frameworkImageFromCanvas(baked.natureCanvas); } baked.natureSourceHash = sourceHash; baked.natureTintReady = true; return true; } #syncCliffGroundTopSprite (object, darkness, groundImage, localX, localY) { if (!object?.renderer) { return; } object._lit = true; const dark = Math.min(1, Math.max(0, darkness ?? 0)); object.renderer.bumpMap = groundImage ?? null; object.renderer.secondaryMap = null; const uniforms = this.#ensureUniformBag(object.renderer, getCliffGroundTopShader(), "cliffTop"); uniforms.u_darkness = dark; this.#writeUniformVec2(uniforms, "u_tileLocal", localX, localY); } #layoutBakedChunk (snapshot) { const key = `${snapshot.chunkX},${snapshot.chunkY}`; const baked = this.bakedChunks.get(key); if (!baked) { return; } const size = this.tileSize(); const left = snapshot.chunkX * CHUNK_SIZE * size; const top = snapshot.chunkY * CHUNK_SIZE * size; const chunkPx = CHUNK_SIZE * size; baked.groundObject.transform.position.x = left + chunkPx / 2; baked.groundObject.transform.position.y = top + chunkPx / 2; baked.groundObject.transform.size = new vector(chunkPx, chunkPx); this.#setLayer(baked.groundObject, LAYER_GROUND); for (let row = 0; row < CHUNK_SIZE; row++) { const object = baked.blockObjects[row]; const rowY = top + row * size + size / 2; object.transform.position.x = left + chunkPx / 2; object.transform.position.y = rowY; object.transform.size = new vector(chunkPx, size); this.#setLayer(object, this.#depthLayer(rowY, SORT_BLOCK)); } baked.bloomObject.transform.position.x = left + chunkPx / 2; baked.bloomObject.transform.position.y = top + chunkPx / 2; baked.bloomObject.transform.size = new vector(chunkPx, chunkPx); this.#setLayer(baked.bloomObject, this.#depthLayer(top + chunkPx, SORT_BLOCK)); baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; } #destroyBakedChunk (key) { const baked = this.bakedChunks.get(key); if (!baked) { return; } this.#releaseBakedAtlasRefs(baked); baked.groundObject?.destroy(); for (const object of baked.blockObjects ?? []) { object.destroy(); } baked.bloomObject?.destroy(); invalidateCanvasTexture(this.scene, baked.lightmapCanvas); invalidateCanvasTexture(this.scene, baked.natureCanvas); this.bakedChunks.delete(key); } #redrawPreview () { if (!this.preview) { return; } const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`); if (snapshot) { this.#rebuildChunk(snapshot); } } #refreshWaterCoastsNear (chunkX, chunkY) { const timeSec = performance.now() / 1000; for (const objects of this.tiles.values()) { if (!objects.ground) { continue; } const fluid = isWaterGround(objects.groundTypeId) || isLavaGround(objects.groundTypeId); if (!fluid) { continue; } if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1) { continue; } // Light intensity grid is visible light (1 − shade); fluid shaders use ambient=1. this.#syncGroundWaterFx(objects, 1, timeSec); } } #drawTile (tileX, tileY) { const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return; } const localX = tileX - chunkX * CHUNK_SIZE; const localY = tileY - chunkY * CHUNK_SIZE; const index = localY * CHUNK_SIZE + localX; const key = `${tileX},${tileY}`; let objects = this.tiles.get(key); if (!objects) { objects = { chunkX, chunkY, tileX, tileY }; this.tiles.set(key, objects); } objects.tileX = tileX; objects.tileY = tileY; objects.chunkX = chunkX; objects.chunkY = chunkY; objects.light = snapshot.light[index] ?? 0; const baked = this.bakedChunks.get(`${chunkX},${chunkY}`); const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY); if (animatedGround) { objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND); if (objects.ground) { const size = this.tileSize(); objects.ground.transform.position.x = tileX * size + size / 2; objects.ground.transform.position.y = tileY * size + size / 2; objects.ground.transform.size = new vector(size, size); this.#setLayer(objects.ground, LAYER_GROUND); objects.groundTypeId = animatedGround.typeId; this.#syncGroundWaterFx(objects, 1, performance.now() / 1000); } if (animatedGround.bloom) { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); } else if (!isLavaGround(animatedGround.typeId)) { objects.groundBloom?.destroy(); objects.groundBloom = null; } } else { objects.ground?.destroy(); objects.ground = null; objects.groundBloom?.destroy(); objects.groundBloom = null; this.#clearLavaBloom(objects); objects.groundTypeId = null; objects.waterEdges = null; } let blockSource = snapshot.blocks[index]; if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY && this.preview.block !== undefined) { blockSource = this.preview.block; } // Outer map ring: always show doors at resting (matches baked light; no entities there). if ( blockSource && blockDefinition(blockSource.typeId)?.door && !this.#isActiveLightingChunk(chunkX, chunkY) ) { const resting = doorRestingState(blockSource); if (resting && resting !== blockSource.state) { blockSource = { ...blockSource, state: resting }; } } const tileBlock = tileBlockSpriteEntry( this.catalog, this.game.images, blockSource, this.worldSeason ); if (tileBlock) { const pivot = tilePivot(tileX, tileY, this.tileSize()); const blockEntry = normalizeBlock(blockSource); const blockDef = blockDefinition(blockEntry?.typeId); const blockSort = blockDef?.door ? doorSortSubOrder(blockEntry?.state, SORT_ENTITY) : SORT_BLOCK; objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, blockSort); objects.blockSort = blockSort; objects.cliffGroundTop = !!blockDef?.cliffGroundTop; if (objects.block) { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, blockSort); if (objects.cliffGroundTop) { const localX = ((tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; const localY = ((tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; this.#syncCliffGroundTopSprite( objects.block, objects.shadeAlpha ?? 0, baked?.groundImage ?? null, localX, localY ); } else { this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0); } } objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tileBlock.bloom, pivot, SORT_ENTITY); } else { objects.block?.destroy(); objects.block = null; objects.blockSort = null; objects.blockBloom?.destroy(); objects.blockBloom = null; objects.cliffGroundTop = false; } } #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK) { if (!name) { existing?.destroy(); return null; } const object = this.#ensureSprite(existing, name, sortOrder); if (!object) { return null; } object.renderer.layer = RENDER_LAYER_BLOOM; this.#markUnlit(object); this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder); return object; } #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1, flight = false) { const sprite = object?.renderer?.sprite; if (!sprite) { return; } const zoom = this.zoom; const draw = spriteDrawSize(sprite.width, sprite.height, zoom); const factor = Math.max(0.1, Number(scale) || 1); const w = draw.w * factor; const h = draw.h * factor; const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom); const layer = this.#depthLayer(sortY, subOrder, flight); if ( object._placeX === center.x && object._placeY === center.y && object._placeW === w && object._placeH === h && object.layer === layer ) { return; } object._placeX = center.x; object._placeY = center.y; object._placeW = w; object._placeH = h; object.transform.position.x = center.x; object.transform.position.y = center.y; const size = this.#placeSizeScratch; size.x = w; size.y = h; object.transform.size = size; this.#setLayer(object, layer); } #ensureSprite (existing, name, layer) { const sprite = this.game.images[name]; if (!sprite) { existing?.destroy(); return null; } if (!existing || existing.renderer.sprite !== sprite) { existing?.destroy(); existing = new GameObject(0, 0, sprite, layer); this.#syncLitSprite(existing, 0); this.scene.addObject(existing); this.#startIdleAnimation(existing); } return existing; } #startIdleAnimation (object) { const sprite = object?.renderer?.sprite; if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0) { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); } } #neighborClosed (snapshot, dir, dx, dy) { const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`); if (other) { return !other.open; } return !!snapshot.closedEdges?.[dir]; } #rebuildAllEdges () { const seen = new Set(); for (const snapshot of this.chunks.values()) { const key = `${snapshot.chunkX},${snapshot.chunkY}`; seen.add(key); this.#rebuildChunkEdges(snapshot); } for (const key of [...this.edges.keys()]) { if (!seen.has(key)) { this.#destroyEdges(key); } } } #rebuildChunkEdges (snapshot) { const key = `${snapshot.chunkX},${snapshot.chunkY}`; let bars = this.edges.get(key); if (!bars) { bars = {}; this.edges.set(key, bars); } const size = this.tileSize(); const chunkPx = CHUNK_SIZE * size; const left = snapshot.chunkX * CHUNK_SIZE * size; const top = snapshot.chunkY * CHUNK_SIZE * size; const centerX = left + chunkPx / 2; const centerY = top + chunkPx / 2; const thickness = Math.max(2, Math.round(2 * this.zoom)); const draw = snapshot.open === true; bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1), centerX, top, chunkPx, thickness, true); bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1), centerX, top + chunkPx, chunkPx, thickness, true); bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0), left, centerY, chunkPx, thickness, false); bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0), left + chunkPx, centerY, chunkPx, thickness, false); } #edgeBar (existing, visible, x, y, length, thickness, horizontal) { if (!visible) { if (existing) { existing.renderer.visible = false; } return existing; } existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE); this.#markUnlit(existing); existing.renderer.visible = true; existing.transform.position.x = x; existing.transform.position.y = y; existing.transform.size = horizontal ? new vector(length, thickness) : new vector(thickness, length); this.#setLayer(existing, LAYER_EDGE); return existing; } #destroyEdges (key) { const bars = this.edges.get(key); if (!bars) { return; } bars.north?.destroy(); bars.east?.destroy(); bars.south?.destroy(); bars.west?.destroy(); this.edges.delete(key); } #entityShadeAlpha (entity, now) { const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0; if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null) { return toAlpha; } const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0; const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1)); return fromAlpha + (toAlpha - fromAlpha) * t; } /** Layer writes notify the scene; avoid redundant full-sort flags. */ #setLayer (object, layer) { if (!object || object.layer === layer) { return; } object.layer = layer; } #markSortDirty () { if (typeof this.scene?.markSortDirty === "function") { this.scene.markSortDirty(); } else { this.scene._sortDirty = true; } } /** Player chunk for dynamic lighting; null in editor / before spawn → no 3×3 limit. */ #activeLightingCenterChunk () { const local = this.entities.get(this.localEntityId); if (!local) { return null; } return { chunkX: Math.floor(local.tileX / CHUNK_SIZE), chunkY: Math.floor(local.tileY / CHUNK_SIZE) }; } #isActiveLightingChunk (chunkX, chunkY) { const center = this.#activeLightingCenterChunk(); if (!center) { return true; } return Math.abs(chunkX - center.chunkX) <= 1 && Math.abs(chunkY - center.chunkY) <= 1; } #isActiveLightingTile (tileX, tileY) { return this.#isActiveLightingChunk( Math.floor(tileX / CHUNK_SIZE), Math.floor(tileY / CHUNK_SIZE) ); } /** Dynamic light sources that originate inside the player 3×3 (never from the outer ring). */ #innerDynamicLights (activeLights) { return activeLights.filter((light) => this.#isActiveLightingTile(light.tileX, light.tileY)); } /** * Lights to simulate for one chunk. * Inner 3×3: mobile lights from the inner region + authored block lights that reach the chunk. * Outer ring: baked base + spill from any dynamic source that originates inside the 3×3 * (lanterns, spells, and torches) so the boundary stays seamless. */ #dynamicLightsForChunk (chunkX, chunkY, mobileLights, blockLights = []) { const center = this.#activeLightingCenterChunk(); if (!center) { return [...mobileLights, ...blockLights]; } if (this.#isActiveLightingChunk(chunkX, chunkY)) { const inner = this.#innerDynamicLights(mobileLights); const blocks = blockLights.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY)); return [...inner, ...blocks]; } const spill = this.#innerDynamicLights([...mobileLights, ...blockLights]); return spill.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY)); } #dynamicLightsForTile (tileX, tileY, mobileLights, blockLights = []) { return this.#dynamicLightsForChunk( Math.floor(tileX / CHUNK_SIZE), Math.floor(tileY / CHUNK_SIZE), mobileLights, blockLights ); } /** Authored torches/furnaces/lava in chunks that can light the active 3×3 (or all chunks in editor). */ #collectBlockLightsForShading () { const center = this.#activeLightingCenterChunk(); const maxRange = maxBlockLightRangeTiles(); const halo = Math.ceil(maxRange / CHUNK_SIZE) + 1; const sources = []; const pushChunk = (snapshot) => { if (!snapshot) { return; } if (snapshot.blocks) { sources.push(...collectBlockLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.blocks)); } if (snapshot.grounds) { sources.push(...collectGroundLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.grounds)); } }; if (!center) { for (const snapshot of this.chunks.values()) { pushChunk(snapshot); } return sources; } for (let dy = -1 - halo; dy <= 1 + halo; dy++) { for (let dx = -1 - halo; dx <= 1 + halo; dx++) { pushChunk(this.chunks.get(`${center.chunkX + dx},${center.chunkY + dy}`)); } } return sources; } /** * Lights for one chunk, memoized for a single shade pass. * Halo tiles in {@link #fillChunkLightGrids} often share the same chunk key. */ #cachedLightsForChunk (chunkX, chunkY, mobileLights, blockLights, cache) { const key = `${chunkX},${chunkY}`; let lights = cache.get(key); if (!lights) { lights = this.#dynamicLightsForChunk(chunkX, chunkY, mobileLights, blockLights); cache.set(key, lights); } return lights; } /** * Shade 0–1 from the chunk intensity grid (1 − lit). Same quantity * {@link #intensityAtTile} writes during lightmap fills — avoids a second * per-tile raycast pass after the grids are current. * @returns {number|null} */ #shadeAlphaFromLightGrid (tileX, tileY) { const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const baked = this.bakedChunks.get(`${chunkX},${chunkY}`); const grid = baked?.lightIntensityGrid; if (!grid?.length) { return null; } const localX = tileX - chunkX * CHUNK_SIZE; const localY = tileY - chunkY * CHUNK_SIZE; if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE) { return null; } const gridW = CHUNK_SIZE + 2; const lit = grid[(localY + 1) * gridW + (localX + 1)] ?? 0; return Math.min(1, Math.max(0, 1 - lit)); } #updateShade () { const ambientDark = this.#ambientDarkness(); const now = performance.now(); this.dynamicLights = this.dynamicLights.filter((light) => light.until > now); const mobileLights = [...this.dynamicLights]; for (const light of this.spellLights.values()) { if (light.until <= now) { continue; } mobileLights.push({ tileX: light.tileX, tileY: light.tileY, range: light.range, intensity: light.intensity }); } for (const key of [...this.spellLights.keys()]) { if (this.spellLights.get(key).until <= now) { const expired = this.spellLights.get(key); this.spellLights.delete(key); this.#invalidateNeighborLightmapCaches( Math.floor(expired.tileX / CHUNK_SIZE), Math.floor(expired.tileY / CHUNK_SIZE) ); } } const activeDarks = []; for (const dark of this.spellDarks.values()) { if (dark.until <= now) { continue; } activeDarks.push({ tileX: dark.tileX, tileY: dark.tileY, range: dark.range, intensity: dark.intensity }); } for (const key of [...this.spellDarks.keys()]) { if (this.spellDarks.get(key).until <= now) { const expired = this.spellDarks.get(key); this.spellDarks.delete(key); this.#invalidateNeighborLightmapCaches( Math.floor(expired.tileX / CHUNK_SIZE), Math.floor(expired.tileY / CHUNK_SIZE) ); } } this._activeSpellDarks = activeDarks; const tileSize = this.tileSize(); const blindLight = this.#blindVisionLight(); if (blindLight) { mobileLights.push(blindLight); } for (const entity of this.entities.values()) { const range = entity.lightRadiusTiles ?? 0; if (range <= 0) { continue; } mobileLights.push({ tileX: Math.floor(entity.visualX / tileSize), tileY: Math.floor(entity.visualY / tileSize), range, intensity: entity.lightIntensity ?? 1 }); } const blockLights = this.#collectBlockLightsForShading(); const lightOcclusion = makeSnapshotLightOcclusion(this.chunks); const lightsByChunk = new Map(); // Lightmaps first so intensity grids are filled (or kept on cache hit). for (const baked of this.bakedChunks.values()) { if (baked._inViewport === false) { continue; } const lights = this.#cachedLightsForChunk( baked.chunkX, baked.chunkY, mobileLights, blockLights, lightsByChunk ); this.#writeChunkLightmap( baked, lights, mobileLights, blockLights, lightOcclusion, ambientDark, lightsByChunk ); // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit. if (baked.groundObject?.renderer?.shaderUniforms) { const natureOn = this.#groundNatureImage(baked) != null; Object.assign(baked.groundObject.renderer.shaderUniforms, { u_ambientDark: 1, ...(natureOn ? natureTintUniforms() : { u_useNature: 0 }) }); } for (const object of baked.blockObjects ?? []) { if (object?.renderer?.shaderUniforms) { object.renderer.shaderUniforms.u_ambientDark = 1; } } } // Per-tile shade from the same grids the lightmap used — no second raycast sweep. for (const objects of this.tiles.values()) { if (objects._inViewport === false) { continue; } const fromGrid = this.#shadeAlphaFromLightGrid(objects.tileX, objects.tileY); if (fromGrid != null) { objects.shadeAlpha = fromGrid; } else { const lights = this.#cachedLightsForChunk( objects.chunkX, objects.chunkY, mobileLights, blockLights, lightsByChunk ); objects.shadeAlpha = this.#tileShadeAlpha(objects, lights, lightOcclusion, ambientDark); } } const timeSec = now / 1000; for (const objects of this.tiles.values()) { if (objects._inViewport === false) { continue; } if (objects.block) { if (objects.cliffGroundTop) { const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`); const localX = ((objects.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; const localY = ((objects.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; this.#syncCliffGroundTopSprite( objects.block, objects.shadeAlpha, baked?.groundImage ?? null, localX, localY ); } else { this.#syncLitSprite(objects.block, objects.shadeAlpha); } } if (objects.ground && (isWaterGround(objects.groundTypeId) || isLavaGround(objects.groundTypeId))) { const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`); // Light intensity grid is visible light (1 − shade); fluid shaders use ambient=1. this.#syncGroundWaterFx(objects, 1, timeSec, baked); } else if (objects.ground) { this.#clearLavaBloom(objects); this.#syncLitSprite(objects.ground, objects.shadeAlpha); } } for (const item of this.groundItems.values()) { const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0; this.#syncGroundItemSprite(item, alpha); } } #tileLightSources (objects, activeLights, lightOcclusion) { // Inner 3×3: ignore baked (stale behind doors); outer ring keeps authored lightmaps. const useBaked = !this.#isActiveLightingTile(objects.tileX, objects.tileY); const baked = useBaked ? lightIntensity(objects.light ?? 0) : 0; const dynamic = dynamicLightAtTile( objects.tileX, objects.tileY, activeLights, lightOcclusion ); const dark = dynamicDarknessAtTile( objects.tileX, objects.tileY, this._activeSpellDarks ?? [], lightOcclusion ); return { lights: Math.max(baked, dynamic), dark }; } /** Shade 0–1: night ambient over unlit tiles, plus Dark spell dimming daylight/torches. */ #tileShadeAlpha (objects, activeLights, lightOcclusion, ambientDark) { const { lights, dark } = this.#tileLightSources(objects, activeLights, lightOcclusion); return Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark); } #tileLightIntensity (objects, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness()) { return 1 - this.#tileShadeAlpha(objects, activeLights, lightOcclusion, ambientDark); } /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */ #intensityAtTile (tileX, tileY, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness()) { const tileObjects = this.tiles.get(`${tileX},${tileY}`); if (tileObjects) { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion, ambientDark); } const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return 1 - Math.min(1, Math.max(0, ambientDark)); } const localX = tileX - chunkX * CHUNK_SIZE; const localY = tileY - chunkY * CHUNK_SIZE; const index = localY * CHUNK_SIZE + localX; const useBaked = !this.#isActiveLightingTile(tileX, tileY); const bakedLit = useBaked ? lightIntensity(snapshot.light[index] ?? 0) : 0; const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion); const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion); const lights = Math.max(bakedLit, dynamic); const shade = Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark); return 1 - shade; } /** True when ground or block on this tile occludes light rays (same rules as bake). */ #tileOccludesLight (tileX, tileY) { const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return false; } const localX = tileX - chunkX * CHUNK_SIZE; const localY = tileY - chunkY * CHUNK_SIZE; if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE) { return false; } const index = localY * CHUNK_SIZE + localX; const ground = normalizeGround(snapshot.grounds?.[index]); if (groundLightOcclusion(ground.typeId) === LightOcclusion.solid) { return true; } return blockLightOcclusionForBlock(snapshot.blocks?.[index]) === LightOcclusion.solid; } #fillChunkLightGrids (baked, mobileLights, blockLights, lightOcclusion, ambientDark, lightsByChunk = null) { const gridW = CHUNK_SIZE + 2; const gridSize = gridW * gridW; if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize) { baked.lightIntensityGrid = new Float32Array(gridSize); } if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize) { baked.lightOccludeGrid = new Uint8Array(gridSize); } const grid = baked.lightIntensityGrid; const occlude = baked.lightOccludeGrid; const cache = lightsByChunk ?? new Map(); for (let ly = -1; ly <= CHUNK_SIZE; ly++) { for (let lx = -1; lx <= CHUNK_SIZE; lx++) { const tileX = baked.chunkX * CHUNK_SIZE + lx; const tileY = baked.chunkY * CHUNK_SIZE + ly; const gi = (ly + 1) * gridW + (lx + 1); // Halo tiles may sit in the other lighting region (3×3 vs outer). Resolve // sources per tile so corner blends match the neighbour chunk's shading. const lights = this.#cachedLightsForChunk( Math.floor(tileX / CHUNK_SIZE), Math.floor(tileY / CHUNK_SIZE), mobileLights, blockLights, cache ); grid[gi] = this.#intensityAtTile(tileX, tileY, lights, lightOcclusion, ambientDark); occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0; } } return { grid, occlude, gridW }; } #makeLightCornerSampler (grid, occlude, gridW) { const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)]; const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0; const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) => smoothLitCorner({ homeLit: sample(homeLx, homeLy), homeBlocks: blocks(homeLx, homeLy), aLit: sample(aLx, aLy), aBlocks: blocks(aLx, aLy), bLit: sample(bLx, bLy), bBlocks: blocks(bLx, bLy), dLit: sample(dLx, dLy), dBlocks: blocks(dLx, dLy) }); return { smoothCorner }; } /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */ #tileLitCorners (baked, localX, localY) { const grid = baked?.lightIntensityGrid; const occlude = baked?.lightOccludeGrid; if (!grid?.length || !occlude?.length) { return null; } const gridW = CHUNK_SIZE + 2; const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW); return { nw: smoothCorner( localX, localY, localX - 1, localY, localX, localY - 1, localX - 1, localY - 1 ), ne: smoothCorner( localX, localY, localX + 1, localY, localX, localY - 1, localX + 1, localY - 1 ), sw: smoothCorner( localX, localY, localX - 1, localY, localX, localY + 1, localX - 1, localY + 1 ), se: smoothCorner( localX, localY, localX + 1, localY, localX, localY + 1, localX + 1, localY + 1 ) }; } #hashUint8Array (values) { let hash = 2166136261; for (let i = 0; i < values.length; i++) { hash ^= values[i]; hash = Math.imul(hash, 16777619); } return hash >>> 0; } #lightAffectsChunkBounds (light, chunkX, chunkY) { const minX = chunkX * CHUNK_SIZE - 1; const minY = chunkY * CHUNK_SIZE - 1; const maxX = chunkX * CHUNK_SIZE + CHUNK_SIZE; const maxY = chunkY * CHUNK_SIZE + CHUNK_SIZE; const closestX = Math.max(minX, Math.min(light.tileX, maxX)); const closestY = Math.max(minY, Math.min(light.tileY, maxY)); return Math.hypot(light.tileX - closestX, light.tileY - closestY) <= light.range; } #chunkLightmapCacheKey (baked, activeLights, ambientDark = this.#ambientDarkness()) { const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`); if (!snapshot?.light) { return null; } const bakedHash = this.#hashUint8Array(snapshot.light); // Caller already scoped lights for this chunk (incl. 3×3 spill onto the outer ring). const lights = activeLights; const darks = this._activeSpellDarks ?? []; const mode = this.lightingMode === "simple" ? "s" : "f"; const ambientKey = Math.round(Math.max(0, ambientDark) * 1000); let lightsKey = ""; for (const light of lights) { if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY)) { continue; } lightsKey += `l${light.tileX},${light.tileY},${light.range},${light.intensity ?? 1};`; } let darksKey = ""; for (const dark of darks) { if (!this.#lightAffectsChunkBounds(dark, baked.chunkX, baked.chunkY)) { continue; } darksKey += `d${dark.tileX},${dark.tileY},${dark.range},${dark.intensity ?? 1};`; } return `a:${mode}:${ambientKey}:${bakedHash}:${lightsKey}|${darksKey}`; } #invalidateNeighborLightmapCaches (chunkX, chunkY) { // Halo grid is ±1 tile; outer map ring is ±2 chunks from the player. for (let dy = -2; dy <= 2; dy++) { for (let dx = -2; dx <= 2; dx++) { const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`); if (baked) { baked.lightmapCacheKey = null; } } } } /** * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours; * occluding tiles stay flat and contribute 0 into others so light does not bleed * through a wall to the far side. Diagonals only when both cardinals are clear. * @param chunkLights Sources that affect this chunk (cache key + in-chunk samples). * @param mobileLights / blockLights Full lists so the ±1 halo can sample across the 3×3 boundary. * @param lightsByChunk Optional per-pass memo of chunk → light list. */ #writeChunkLightmap ( baked, chunkLights, mobileLights, blockLights, lightOcclusion, ambientDark = this.#ambientDarkness(), lightsByChunk = null ) { const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`); if (!snapshot) { return; } const cacheKey = this.#chunkLightmapCacheKey(baked, chunkLights, ambientDark); if (cacheKey && baked.lightmapCacheKey === cacheKey) { return; } const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX; const pixelCount = atlasPx * atlasPx * 4; if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount) { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); } const pixels = baked.lightmapPixels; this.#fillChunkLightGrids( baked, mobileLights, blockLights, lightOcclusion, ambientDark, lightsByChunk ); const simple = this.lightingMode === "simple"; for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const baseX = localX * SPRITE_SIZE_PX; const baseY = localY * SPRITE_SIZE_PX; if (simple) { const gridW = CHUNK_SIZE + 2; const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0; const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255); for (let py = 0; py < SPRITE_SIZE_PX; py++) { for (let px = 0; px < SPRITE_SIZE_PX; px++) { const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4; pixels[offset] = value; pixels[offset + 1] = value; pixels[offset + 2] = value; pixels[offset + 3] = 255; } } continue; } const corners = this.#tileLitCorners(baked, localX, localY); const nw = corners.nw; const ne = corners.ne; const sw = corners.sw; const se = corners.se; for (let py = 0; py < SPRITE_SIZE_PX; py++) { const v = (py + 0.5) / SPRITE_SIZE_PX; const left = nw + (sw - nw) * v; const right = ne + (se - ne) * v; for (let px = 0; px < SPRITE_SIZE_PX; px++) { const u = (px + 0.5) / SPRITE_SIZE_PX; const intensity = left + (right - left) * u; const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255); const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4; pixels[offset] = value; pixels[offset + 1] = value; pixels[offset + 2] = value; pixels[offset + 3] = 255; } } } } // Keep canvas pixels in sync for Framework getTexture fallbacks, but upload // to GL via texSubImage2D when the texture already exists (no delete/recreate). if (!baked.lightmapImageData || baked.lightmapImageData.data !== pixels) { baked.lightmapImageData = new ImageData(pixels, atlasPx, atlasPx); } if (baked.lightmapUploadSize !== atlasPx) { invalidateCanvasTexture(this.scene, baked.lightmapCanvas); baked.lightmapUploadSize = atlasPx; } const gl = this.scene?.glContext?.gl; const created = uploadCanvasTextureRgba( this.scene, baked.lightmapCanvas, pixels, atlasPx, atlasPx, gl?.NEAREST ?? null ); if (created) { const ctx = baked.lightmapCanvas.getContext("2d"); ctx.putImageData(baked.lightmapImageData, 0, 0); } baked.lightmapCacheKey = cacheKey; } #updateSwipes (now) { this.swipes = this.swipes.filter((swipe) => { if (swipe.lerp && swipe.started != null) { const durationMs = swipe.durationMs ?? 400; const t = Math.min(1, (now - swipe.started) / durationMs); const fromPivot = this.#projectileLaunchPoint( swipe.attackerId ?? null, swipe.fromTileX, swipe.fromTileY ); const toPivot = this.#projectileEndPivot(swipe); const x = fromPivot.x + (toPivot.x - fromPivot.x) * t; const y = fromPivot.y + (toPivot.y - fromPivot.y) * t; const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02; if (swipe.object?.transform) { swipe.object.transform.rotation = Math.atan2( toPivot.y - fromPivot.y, toPivot.x - fromPivot.x ) * (180 / Math.PI); } if (swipe.spellProjectile && swipe.tint) { this.#syncUnlitTintSprite(swipe.object, swipe.tint); } this.#placePivoted(swipe.object, x, y, sortY, SORT_FX); if (!swipe.spellProjectile) { this.#applyPhysicalCombatFxDarkness( swipe.object, swipe.fromTileX, swipe.fromTileY, swipe.tileX, swipe.tileY, swipe.dualTint ?? null ); } } else if (swipe.fromTileX != null && !swipe.spellProjectile) { this.#applyPhysicalCombatFxDarkness( swipe.object, swipe.fromTileX, swipe.fromTileY, swipe.tileX, swipe.tileY, swipe.dualTint ?? null ); } if (swipe.fadeOpacity && swipe.started != null && swipe.object?.renderer) { const durationMs = swipe.durationMs ?? MELEE_SWIPE_MS; const t = Math.min(1, Math.max(0, (now - swipe.started) / durationMs)); swipe.object.renderer.alpha = 1 - t; } if (swipe.until > now) { return true; } const onImpact = swipe.onImpact; swipe.onImpact = null; swipe.object?.destroy(); if (typeof onImpact === "function") { try { onImpact(); } catch (_) { /* presentation only */ } } return false; }); } #projectileEndPivot (swipe) { if (swipe.trackTarget && swipe.targetId != null) { return this.#projectileAimPoint(swipe.targetId, swipe.tileX, swipe.tileY); } return this.#projectileAimPoint(null, swipe.tileX, swipe.tileY); } /** * Launch point: 4px below the top of the caster sprite (falls back to tile centre). */ #projectileLaunchPoint (entityId, tileX, tileY) { const entity = entityId != null ? this.entities.get(entityId) : null; if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY)) { const zoom = this.zoom; const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX; const pivotX = entity.visualX + (entity.stackOffsetX ?? 0); const pivotY = entity.visualY + (entity.stackOffsetY ?? 0); const topY = pivotY - (spriteH - PIVOT_FROM_BOTTOM_PX) * zoom; return { x: pivotX, y: topY + PROJECTILE_LAUNCH_FROM_TOP_PX * zoom }; } return tilePivot(tileX, tileY, this.tileSize()); } /** * Aim point: sprite centre for creatures, tile centre for tile targets. */ #projectileAimPoint (entityId, tileX, tileY) { const entity = entityId != null ? this.entities.get(entityId) : null; if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY)) { const zoom = this.zoom; const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX; const pivotX = entity.visualX + (entity.stackOffsetX ?? 0); const pivotY = entity.visualY + (entity.stackOffsetY ?? 0); return spriteCenterFromPivot(pivotX, pivotY, spriteH, zoom); } return tilePivot(tileX, tileY, this.tileSize()); } #updateDamageNumbers (now) { const layer = this.damageNumbersEl; if (!layer) { return; } this.damageFloats = this.damageFloats.filter((entry) => { const elapsed = now - entry.started; if (elapsed >= DAMAGE_FLOAT_MS) { entry.element?.remove(); return false; } const entity = this.entities.get(entry.entityId); if (!entity) { entry.element?.remove(); return false; } if (!entry.element) { entry.element = document.createElement("span"); entry.element.className = "damage-number"; entry.element.textContent = String(entry.damage); layer.append(entry.element); } const anchor = this.nametagAnchor(entity); if (!anchor) { return true; } const t = elapsed / DAMAGE_FLOAT_MS; entry.element.style.left = `${anchor.x}px`; entry.element.style.top = `${anchor.y - 6 - t * 28}px`; entry.element.style.opacity = String(1 - t); return true; }); } #updateSkillLevelFloats (now) { const layer = this.skillLevelFloatsEl; if (!layer) { return; } this.skillLevelFloats = this.skillLevelFloats.filter((entry) => { const elapsed = now - entry.started; if (elapsed >= SKILL_LEVEL_FLOAT_MS) { entry.element?.remove(); return false; } const entity = this.entities.get(entry.entityId); if (!entity) { entry.element?.remove(); return false; } if (!entry.element) { const root = document.createElement("div"); root.className = "skill-level-float"; const levelEl = document.createElement("div"); levelEl.className = "skill-level-float-level"; levelEl.textContent = `↑${entry.level}↑`; const icon = document.createElement("img"); icon.className = "skill-level-float-icon"; icon.src = entry.icon; icon.alt = entry.displayName || ""; root.append(levelEl, icon); entry.element = root; layer.append(entry.element); } const anchor = this.nametagAnchor(entity); if (!anchor) { return true; } const t = elapsed / SKILL_LEVEL_FLOAT_MS; entry.element.style.left = `${anchor.x}px`; entry.element.style.top = `${anchor.y - 10 - t * 18}px`; entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85)); return true; }); } #syncBloomLayer () { if (!this.bloomEnabled) { this.scene.setLayers([{ name: "default" }]); return; } const settings = this.settings ?? DEFAULT_WORLD_SETTINGS; this.scene.setLayers([ { name: "default" }, { name: RENDER_LAYER_BLOOM, composite: "add", postShaders: Shader.getBloomPostChain({ threshold: settings.bloomThreshold, softKnee: settings.bloomSoftKnee, intensity: settings.bloomIntensity, blurSize: settings.bloomBlurSize, saturation: settings.bloomSaturation, colorPreserve: settings.bloomColorPreserve, dilate: settings.bloomDilate, scales: Math.max(1, Math.round(settings.bloomScales ?? 1)), halfRes: (settings.bloomHalfRes ?? 1) >= 0.5 }) } ]); } } export function nightFactor (hour, nightDarkness = 0.72) { const peak = Math.min(1, Math.max(0, nightDarkness)); if (hour >= 8 && hour <= 16) { return 0; } if (hour >= 22 || hour <= 5) { return peak; } if (hour < 8) { return lerp(peak, 0, (hour - 5) / 3); } return lerp(0, peak, (hour - 16) / 6); } function bodySpriteName (sex) { const key = sex === "female" ? "player-body-female" : "player-body-male"; return spriteImageName("character", key, key); } function lerp (a, b, t) { return a + (b - a) * Math.min(1, Math.max(0, t)); } function makeLightmapCanvas (size) { const canvas = document.createElement("canvas"); canvas.width = size; canvas.height = size; return canvas; } function makeNatureNoiseCanvas () { const canvas = document.createElement("canvas"); canvas.width = NATURE_NOISE_SIZE; canvas.height = NATURE_NOISE_SIZE; return canvas; } function copyCanvas (source, dest) { const ctx = dest.getContext("2d"); ctx.imageSmoothingEnabled = false; ctx.clearRect(0, 0, dest.width, dest.height); ctx.drawImage(source, 0, 0); } function drawHpBar (canvas, current, max) { const ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H); ctx.fillStyle = "#000000"; ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H); const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0; const fillW = Math.round(12 * ratio); if (fillW > 0) { ctx.fillStyle = "#ff0000"; ctx.fillRect(1, 1, fillW, 2); } }