import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } from "/shared/protocol/constants.js"; import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js"; import { itemSpriteName } from "/shared/definitions/items.js"; import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js"; import { bakeChunkAtlases, frameworkImageFromCanvas, invalidateCanvasTexture } from "./chunkBake.js"; const LAYER_GROUND = 0; const LAYER_EDGE = 900000; const SORT_BLOCK = 1; const SORT_SHADE = 2; const SORT_ENTITY = 3; const SORT_SPRITE_SHADE = 4; const SORT_HP_BAR = 5; const RENDER_LAYER_BLOOM = "bloom"; 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; const DAMAGE_FLASH_MS = 180; const SPRITE_SHADE_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform float u_alpha;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " gl_FragColor = vec4(0.0, 0.0, 0.0, color.a * u_alpha);", "}" ].join("\n"); const DAMAGE_FLASH_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform float u_strength;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " vec3 flash = mix(color.rgb, vec3(1.0, 0.12, 0.12), u_strength);", " gl_FragColor = vec4(flash, color.a);", "}" ].join("\n"); let spriteShadeShader = null; let damageFlashShader = null; function getSpriteShadeShader () { if (!spriteShadeShader) { spriteShadeShader = Shader.fragment(SPRITE_SHADE_FRAG); } return spriteShadeShader; } function getDamageFlashShader () { if (!damageFlashShader) { damageFlashShader = Shader.fragment(DAMAGE_FLASH_FRAG); } return damageFlashShader; } export class WorldView { constructor (game, scene, catalog = { grounds: {}, blocks: {} }) { this.game = game; this.scene = scene; this.catalog = catalog; this.preview = null; this.zoom = 2; 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.settings = { ...DEFAULT_WORLD_SETTINGS }; this.worldHour = 12; this.nightPreview = null; this.followPlayer = true; this.dynamicLights = []; this.swipes = []; this.#syncBloomLayer(); } setSettings (settings) { this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings }; this.#syncBloomLayer(); } setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null) { this.localEntityId = entityId; this.#upsertEntity({ entityId, characterId, tileX, tileY, gait, sex, firstName, lastName, layers: layers ?? undefined }); } applySnapshot (snapshot) { const key = `${snapshot.chunkX},${snapshot.chunkY}`; this.chunks.set(key, snapshot); this.#rebuildChunk(snapshot); this.#redrawPreview(); for (const entity of snapshot.entities ?? []) { this.#upsertEntity(entity); } const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`; 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.#rebuildAllEdges(); } removeChunk (chunkX, chunkY) { const key = `${chunkX},${chunkY}`; this.chunks.delete(key); this.#destroyBakedChunk(key); this.#destroyEdges(key); for (const [tileKey, objects] of [...this.tiles.entries()]) { if (objects.chunkX === chunkX && objects.chunkY === chunkY) { objects.block?.destroy(); objects.blockBloom?.destroy(); objects.spriteShade?.destroy(); objects.shade?.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); } } this.#rebuildAllEdges(); } setChunkOpen (chunkX, chunkY, open) { const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return; } snapshot.open = !!open; this.#rebuildAllEdges(); } spawnEntity (payload) { this.#upsertEntity(payload); } moveEntity (payload) { const existing = this.entities.get(payload.entityId); if (!existing) { this.#upsertEntity(payload); return; } const size = this.tileSize(); existing.fromX = existing.visualX; existing.fromY = existing.visualY; 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); } despawnEntity (entityId) { const existing = this.entities.get(entityId); if (!existing) { return; } existing.object?.destroy(); existing.spriteShade?.destroy(); existing.hpBar?.destroy(); for (const shade of existing.overlayShades ?? []) { shade.destroy(); } for (const overlay of existing.overlays ?? []) { overlay.destroy(); } for (const overlay of existing.bloomOverlays ?? []) { overlay.destroy(); } this.entities.delete(entityId); } updateEntityHealth (entityId, health, maxHealth) { const entity = this.entities.get(entityId); if (!entity) { return; } entity.health = health; entity.maxHealth = maxHealth; this.#syncHpBar(entity); } flashDamage (entityId) { const entity = this.entities.get(entityId); if (!entity) { return; } entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS; } setAppearance (payload) { const existing = this.entities.get(payload.entityId); if (!existing) { return; } this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]); this.#placeEntity(existing); } upsertGroundItem (payload) { const size = this.tileSize(); const pivot = tilePivot(payload.tileX, payload.tileY, size); let item = this.groundItems.get(payload.groundItemId); if (!item) { const object = new GameObject(0, 0, this.game.images[payload.sprite] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK); this.scene.addObject(object); item = { object }; this.groundItems.set(payload.groundItemId, item); } 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 = payload.sprite; this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); } 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) { const matches = []; for (const entity of this.entities.values()) { if (entity.tileX === tileX && entity.tileY === tileY) { matches.push(entity); } } matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0)); return matches; } setZoom (zoom, limits = { min: 1, 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.#layoutBakedChunk(snapshot); for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); } } } 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.#redrawPreview(); } 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(); 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; } } else { entity.visualX = target.x; entity.visualY = target.y; } this.#updateShove(entity, now, size); this.#placeEntity(entity, now); } this.#updateSwipes(now); this.#centerCamera(); this.#updateShade(deltaTime); } #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; } attacker.shove = { startVisualX: attacker.visualX, startVisualY: attacker.visualY, targetVisualX: target.visualX, targetVisualY: target.visualY, started: performance.now(), durationMs: SHOVE_MS }; const midX = (attacker.visualX + target.visualX) / 2; const midY = (attacker.visualY + target.visualY) / 2; const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI); const spriteName = "fx:melee-swipe:melee-swipe"; const object = new GameObject(midX, midY, this.game.images[spriteName], SORT_ENTITY + 1); if (object.transform) { object.transform.rotation = angle; } this.scene.addObject(object); this.swipes.push({ object, until: performance.now() + 500 }); this.addDynamicLight({ worldX: (attacker.tileX + target.tileX) / 2 + 0.5, worldY: (attacker.tileY + target.tileY) / 2 + 0.5, radiusTiles: 2.5, intensity: 0.55, durationMs: 220 }); } addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 }) { this.dynamicLights.push({ worldX, worldY, 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; } this.#rebuildChunk(snapshot); } setTilePreview (tileX, tileY, override) { const previous = this.preview; this.preview = { tileX, tileY, ...override }; const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (snapshot) { this.#rebuildChunk(snapshot); } if (previous && (previous.tileX !== tileX || previous.tileY !== tileY)) { const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`); if (prevSnapshot && prevSnapshot !== snapshot) { this.#rebuildChunk(prevSnapshot); } } } clearTilePreview () { const previous = this.preview; this.preview = null; if (previous) { const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`); if (snapshot) { this.#rebuildChunk(snapshot); } } } #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; } this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX; this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY; } #upsertEntity (payload) { const size = this.tileSize(); const pivot = tilePivot(payload.tileX, payload.tileY, size); let entity = this.entities.get(payload.entityId); 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.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null; entity.hostile = !!payload.hostile; entity.canFight = !!payload.canFight; entity.talkable = !!payload.talkable; entity.untargetable = !!payload.untargetable; entity.freeFlight = !!payload.freeFlight; if (payload.health != null) { entity.health = payload.health; } if (payload.maxHealth != null) { entity.maxHealth = payload.maxHealth; } 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.#placeEntity(entity, performance.now()); } #applyLayers (entity, layers) { 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); } for (const overlay of entity.overlays ?? []) { overlay.destroy(); } for (const overlay of entity.bloomOverlays ?? []) { overlay.destroy(); } entity.overlays = []; entity.bloomOverlays = []; 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 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.scene.addObject(bloom); entity.bloomOverlays.push(bloom); } } #placeEntity (entity, now = performance.now()) { const zoom = this.zoom; const offsetX = entity.shoveOffsetX ?? 0; const offsetY = entity.shoveOffsetY ?? 0; const pivotX = entity.visualX + offsetX; const pivotY = entity.visualY + offsetY; 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; } const flashStrength = (entity.damageFlashUntil ?? 0) > now ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS : 0; entity.object.transform.rotation = walkTilt; this.#applyDamageFlash(entity.object, flashStrength); this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY); for (let index = 0; index < (entity.overlays ?? []).length; index++) { const overlay = entity.overlays[index]; overlay.transform.rotation = walkTilt; this.#applyDamageFlash(overlay, flashStrength); this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.001, SORT_ENTITY); } for (const overlay of entity.bloomOverlays ?? []) { overlay.transform.rotation = walkTilt; this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY); } entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, pivotX, pivotY); const nextOverlayShades = []; for (let index = 0; index < (entity.overlays ?? []).length; index++) { nextOverlayShades.push(this.#placeSpriteShade( entity.overlayShades?.[index] ?? null, entity.overlays[index], pivotX, pivotY + 0.001 )); } for (let index = nextOverlayShades.length; index < (entity.overlayShades ?? []).length; index++) { entity.overlayShades[index]?.destroy(); } entity.overlayShades = nextOverlayShades; this.#placeHpBar(entity, pivotX, pivotY); } #applyDamageFlash (object, strength) { if (!object?.renderer) { return; } if (strength > 0) { object.renderer.shader = getDamageFlashShader(); object.renderer.shaderUniforms = { u_strength: strength }; return; } if (object.renderer.shader === getDamageFlashShader()) { object.renderer.shader = null; object.renderer.shaderUniforms = null; } } #syncHpBar (entity) { const current = entity.health; const max = entity.maxHealth; const show = entity.mobTypeId != null && 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.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); entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR); this.#markSortDirty(); } #rebuildChunk (snapshot) { this.#bakeAndPlaceChunk(snapshot); const tall = new Set( (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? []) .map((entry) => `${entry.tileX},${entry.tileY}`) ); 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, tall.has(`${tileX},${tileY}`)); } } } #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); } } #bakeAndPlaceChunk (snapshot) { const key = `${snapshot.chunkX},${snapshot.chunkY}`; const atlases = bakeChunkAtlases({ snapshot, catalog: this.catalog, images: this.game.images, preview: this.preview }); let baked = this.bakedChunks.get(key); if (!baked) { baked = { groundCanvas: atlases.ground, blockCanvases: atlases.blockRows, bloomCanvas: atlases.bloom, groundImage: frameworkImageFromCanvas(atlases.ground), blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)), bloomImage: frameworkImageFromCanvas(atlases.bloom), groundObject: null, blockObjects: [], bloomObject: null, tallBlocks: atlases.tallBlocks }; baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND); 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.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.scene.addObject(baked.bloomObject); this.bakedChunks.set(key, baked); } else { copyCanvas(atlases.ground, baked.groundCanvas); for (let row = 0; row < CHUNK_SIZE; row++) { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); } copyCanvas(atlases.bloom, baked.bloomCanvas); invalidateCanvasTexture(this.scene, baked.groundCanvas); for (const canvas of baked.blockCanvases) { invalidateCanvasTexture(this.scene, canvas); } invalidateCanvasTexture(this.scene, baked.bloomCanvas); baked.tallBlocks = atlases.tallBlocks; } this.#layoutBakedChunk(snapshot); } #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); baked.groundObject.layer = 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); object.layer = ySortLayer(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); baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK); baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; this.#markSortDirty(); setNearestFilter(this.scene, baked.groundCanvas); for (const canvas of baked.blockCanvases) { setNearestFilter(this.scene, canvas); } setNearestFilter(this.scene, baked.bloomCanvas); } #destroyBakedChunk (key) { const baked = this.bakedChunks.get(key); if (!baked) { return; } baked.groundObject?.destroy(); for (const object of baked.blockObjects ?? []) { object.destroy(); } baked.bloomObject?.destroy(); invalidateCanvasTexture(this.scene, baked.groundCanvas); for (const canvas of baked.blockCanvases ?? []) { invalidateCanvasTexture(this.scene, canvas); } invalidateCanvasTexture(this.scene, baked.bloomCanvas); this.bakedChunks.delete(key); } #drawTile (tileX, tileY, forceTall = null) { 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; const size = this.tileSize(); const pivot = tilePivot(tileX, tileY, size); objects.light = snapshot.light[index] ?? 0; const previousShade = objects.shade; objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, ySortLayer(pivot.y, SORT_SHADE)); if (objects.shade && objects.shade !== previousShade) { objects.shade.renderer.alpha = 0; } const baked = this.bakedChunks.get(`${chunkX},${chunkY}`); const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY); const isTall = forceTall === true || !!tallEntry; if (isTall && tallEntry) { objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY); if (objects.block) { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY); } objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY); objects.spriteShade = this.#placeSpriteShade(objects.spriteShade, objects.block, pivot.x, pivot.y); } else { if (objects.block) { objects.block.destroy(); objects.block = null; } if (objects.blockBloom) { objects.blockBloom.destroy(); objects.blockBloom = null; } if (objects.spriteShade) { objects.spriteShade.destroy(); objects.spriteShade = null; } } } #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.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder); return object; } #placeSpriteShade (existing, targetObject, pivotX, pivotY) { if (!targetObject?.renderer?.sprite) { existing?.destroy(); return null; } const sprite = targetObject.renderer.sprite; if (!existing || existing.renderer.sprite !== sprite) { existing?.destroy(); existing = new GameObject(0, 0, sprite, SORT_SPRITE_SHADE); this.scene.addObject(existing); } existing.renderer.sprite = sprite; existing.renderer.shader = getSpriteShadeShader(); existing.renderer.subImage = targetObject.renderer.subImage || 0; existing.renderer.mirrorX = !!targetObject.renderer.mirrorX; existing.renderer.mirrorY = !!targetObject.renderer.mirrorY; const zoom = this.zoom; const draw = spriteDrawSize(sprite.width, sprite.height, zoom); const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom); existing.transform.position.x = center.x; existing.transform.position.y = center.y; existing.transform.size = new vector(draw.w, draw.h); existing.layer = ySortLayer(pivotY, SORT_SPRITE_SHADE); this.#markSortDirty(); return existing; } #tileFill (existing, name, x, y, layer) { existing = this.#ensureSprite(existing, name, layer); if (!existing) { return null; } const size = this.tileSize(); existing.transform.position.x = x; existing.transform.position.y = y; existing.transform.size = new vector(size, size); existing.layer = layer; this.#markSortDirty(); return existing; } #placePivoted (object, pivotX, pivotY, sortY, subOrder) { const sprite = object?.renderer?.sprite; if (!sprite) { return; } const zoom = this.zoom; const draw = spriteDrawSize(sprite.width, sprite.height, zoom); const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom); object.transform.position.x = center.x; object.transform.position.y = center.y; object.transform.size = new vector(draw.w, draw.h); object.layer = ySortLayer(sortY, subOrder); this.#markSortDirty(); } #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.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); 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); existing.layer = LAYER_EDGE; this.#markSortDirty(); 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); } #markSortDirty () { this.scene._sortDirty = true; } #updateShade () { const hour = this.nightPreview ?? this.worldHour; const ambientDark = nightFactor(hour, this.settings.nightDarkness); const now = performance.now(); this.dynamicLights = this.dynamicLights.filter((light) => light.until > now); for (const objects of this.tiles.values()) { const baked = Math.min(1, Math.max(0, (objects.light ?? 0) / 255)); let dynamic = 0; for (const light of this.dynamicLights) { const dx = (objects.tileX + 0.5) - light.worldX; const dy = (objects.tileY + 0.5) - light.worldY; const dist = Math.hypot(dx, dy); if (dist >= light.radiusTiles) { continue; } const falloff = 1 - dist / light.radiusTiles; dynamic = Math.max(dynamic, falloff * light.intensity); } const intensity = Math.max(baked, dynamic); const alpha = ambientDark * (1 - intensity); objects.shadeAlpha = alpha; if (objects.shade) { objects.shade.renderer.alpha = alpha; } if (objects.spriteShade) { objects.spriteShade.renderer.alpha = alpha; } } for (const entity of this.entities.values()) { const alpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0; if (entity.spriteShade) { entity.spriteShade.renderer.alpha = alpha; } for (const shade of entity.overlayShades ?? []) { if (shade) { shade.renderer.alpha = alpha; } } } } #updateSwipes (now) { this.swipes = this.swipes.filter((swipe) => { if (swipe.until > now) { return true; } swipe.object?.destroy(); return false; }); } #syncBloomLayer () { 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 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); } } 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 setNearestFilter (scene, canvas) { const glContext = scene?.glContext; if (!glContext || !canvas) { return; } const texture = glContext.getTexture(canvas); if (!texture) { return; } const gl = glContext.gl; gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); }