import { CanvasSource, Container, Sprite, Texture } from 'pixi.js'; import { CHUNK_SIZE, MATERIAL_EMPTY, OUTLINE_PX, RENDER_MARGIN } from '../../shared/constants'; import { parseHexColor, type MaterialRegistry } from '../../shared/materials'; import type { TerrainBitmap } from '../../shared/terrain/bitmap'; import type { TerrainEvent } from '../../shared/terrain/events'; import { rleDecode } from '../../shared/terrain/rle'; import { CAVITY_DARKEN, CAVITY_SHADOW_DEPTH, DROP_SHADOW_ALPHA, DROP_SHADOW_DX, DROP_SHADOW_DY, DROP_SHADOW_SOFTNESS, OUTLINE_COLOR, RIM_LIGHT_DEPTH, RIM_LIGHT_WHITE, TERRAIN_AA, TERRAIN_SUPERSAMPLE, UNDERSIDE_DARKEN, UNDERSIDE_DEPTH, } from '../config'; import { sampleBilinear, signedDistance } from './distance'; import { hash2, makeThicknessTile, makeTile, scaledTileIndex, tileIndex } from './textures'; interface ChunkSprite { ctx: CanvasRenderingContext2D; image: ImageData; texture: Texture; sprite: Sprite; } const S = TERRAIN_SUPERSAMPLE; /** Texture side of one terrain chunk. */ const TEX = CHUNK_SIZE * S; /** The distance field window around a chunk: enough for the outline, the shading and the drop shadow. */ const M = RENDER_MARGIN; const WIN = CHUNK_SIZE + 2 * M; /** Column scan margin: how far above/below the chunk the lighting looks. */ const SCAN = Math.max(RIM_LIGHT_DEPTH, UNDERSIDE_DEPTH, CAVITY_SHADOW_DEPTH) + OUTLINE_PX + 1; const OR = OUTLINE_COLOR >> 16; const OG = (OUTLINE_COLOR >> 8) & 0xff; const OB = OUTLINE_COLOR & 0xff; /** 0..1 coverage of a signed distance (positive inside), antialiased over TERRAIN_AA pixels. */ function coverage(sd: number): number { const c = sd / TERRAIN_AA + 0.5; return c <= 0 ? 0 : c >= 1 ? 1 : c; } /** * Renders the terrain bitmap as one canvas-backed sprite per 64 px chunk, supersampled * (TERRAIN_SUPERSAMPLE texels per pixel). Edges come from a signed distance field, so they are * smooth and antialiased whatever the zoom: textured materials, an irregular felt-pen outline, * rim light on top faces, darker undersides, a soft drop shadow, and holes that show the inside * of the cake. */ export class TerrainView { readonly container = new Container(); private readonly chunks = new Map(); private readonly tiles: (Uint32Array | undefined)[] = []; private readonly thickness = makeThicknessTile(OUTLINE_PX); /** The map as loaded: pixels solid here but empty now are cavities. */ private readonly original: Uint8Array; // Per-column scratch: distance to the nearest empty pixel above / below, and to solid above. private readonly solidUp = new Int16Array(CHUNK_SIZE); private readonly solidDown = new Int16Array(CHUNK_SIZE); private readonly emptyUp = new Int16Array(CHUNK_SIZE); /** Signed distance of the current terrain, and coverage of the original one, around the chunk being drawn. */ private readonly sd = new Float32Array(WIN * WIN); private readonly orig = new Float32Array(WIN * WIN); // Per-pixel shading of the chunk being drawn: brightness, tint toward white, cavity darkening. private readonly shadeK = new Float32Array(CHUNK_SIZE * CHUNK_SIZE); private readonly shadeW = new Float32Array(CHUNK_SIZE * CHUNK_SIZE); private readonly cavityK = new Float32Array(CHUNK_SIZE * CHUNK_SIZE); constructor( private readonly bitmap: TerrainBitmap, materials: MaterialRegistry, ) { this.original = bitmap.data.slice(); materials.byId.forEach((m, id) => { if (m && id !== MATERIAL_EMPTY) this.tiles[id] = makeTile(parseHexColor(m.color), m.texture, S); }); } /** * Keeps the "as loaded" copy in sync with pieces that move: a detached chunk takes its * pixels away (the gap shows the background, not the inside of the cake), and a merged * chunk brings them back. Call after applying the event to the bitmap. */ onEvent(ev: TerrainEvent): void { if (ev.kind === 'op') return; const cells = rleDecode(ev.kind === 'detach' ? ev.mask : ev.patch, ev.w * ev.h); const { width, height } = this.bitmap; for (let ly = 0; ly < ev.h; ly++) { for (let lx = 0; lx < ev.w; lx++) { const v = cells[ly * ev.w + lx]; const x = ev.x + lx; const y = ev.y + ly; if (v === MATERIAL_EMPTY || x < 0 || y < 0 || x >= width || y >= height) continue; const i = y * width + x; this.original[i] = ev.kind === 'detach' ? MATERIAL_EMPTY : this.bitmap.data[i]; } } } /** * Draws a falling chunk's mask with the same textures (sampled at its original map * position, so it looks unchanged at the moment it breaks off) and a felt outline. * The texture is 1 px larger than the mask on each side (see ChunkView's pivot). */ makeChunkTexture(mask: Uint8Array, w: number, h: number, ox: number, oy: number): Texture { const pad = 1; const m = OUTLINE_PX + 2; const ww = w + 2 * m; const wh = h + 2 * m; const sd = new Float32Array(ww * wh); signedDistance( (i) => { const x = (i % ww) - m; const y = ((i / ww) | 0) - m; return x >= 0 && y >= 0 && x < w && y < h && mask[y * w + x] !== MATERIAL_EMPTY; }, ww, wh, sd, m, ); const cw = (w + pad * 2) * S; const ch = (h + pad * 2) * S; const canvas = document.createElement('canvas'); canvas.width = cw; canvas.height = ch; const ctx = canvas.getContext('2d')!; const image = ctx.createImageData(cw, ch); const out = image.data; for (let ty = 0; ty < ch; ty++) { for (let tx = 0; tx < cw; tx++) { // Local mask coordinates of this texel's center. const lx = (tx + 0.5) / S - pad; const ly = (ty + 0.5) / S - pad; const d = sampleBilinear(sd, ww, wh, lx + m, ly + m); const a = coverage(d); if (a === 0) continue; const px = Math.max(0, Math.min(w - 1, Math.floor(lx))); const py = Math.max(0, Math.min(h - 1, Math.floor(ly))); const t = this.thickness[tileIndex(ox + px, oy + py)]; const ink = 1 - coverage(d - t); let r = OR; let g = OG; let b = OB; const mat = mask[py * w + px]; if (ink < 1 && mat !== MATERIAL_EMPTY) { const c = this.tiles[mat]![scaledTileIndex((ox + px) * S + (tx % S), (oy + py) * S + (ty % S), S)]; r = (c >> 16) * (1 - ink) + OR * ink; g = ((c >> 8) & 0xff) * (1 - ink) + OG * ink; b = (c & 0xff) * (1 - ink) + OB * ink; } const o = (ty * cw + tx) * 4; out[o] = r; out[o + 1] = g; out[o + 2] = b; out[o + 3] = a * 255; } } ctx.putImageData(image, 0, 0); return new Texture({ source: new CanvasSource({ resource: canvas, resolution: S, scaleMode: 'linear' }) }); } /** Redraws every chunk flagged dirty in the bitmap. */ update(): void { for (const index of this.bitmap.takeDirtyChunks()) this.redraw(index); } private redraw(index: number): void { const { x0, y0, x1, y1 } = this.bitmap.chunkRect(index); const { width, height, data } = this.bitmap; const original = this.original; let any = false; for (let y = y0; y < y1 && !any; y++) { for (let x = x0; x < x1; x++) { const i = y * width + x; // Anything solid, any cavity, or any solid casting a shadow into this chunk needs drawing. if (data[i] !== MATERIAL_EMPTY || original[i] !== MATERIAL_EMPTY) { any = true; break; } } } if (!any) any = this.receivesShadow(x0, y0, x1, y1); let chunk = this.chunks.get(index); if (!any) { if (chunk) chunk.sprite.visible = false; return; } chunk ??= this.createChunk(index, x0, y0); chunk.sprite.visible = true; // Distance fields over the window around the chunk (clamped to the map: no outline on the map border). const wx0 = x0 - M; const wy0 = y0 - M; const at = (i: number): number => { const x = Math.max(0, Math.min(width - 1, wx0 + (i % WIN))); const y = Math.max(0, Math.min(height - 1, wy0 + ((i / WIN) | 0))); return y * width + x; }; signedDistance((i) => data[at(i)] !== MATERIAL_EMPTY, WIN, WIN, this.sd, M); for (let i = 0; i < WIN * WIN; i++) this.orig[i] = original[at(i)] !== MATERIAL_EMPTY ? 1 : 0; // Per-pixel lighting from column scans: rim light on top faces, darker undersides, cavity shade. const { solidUp, solidDown, emptyUp, shadeK, shadeW, cavityK } = this; const cw = x1 - x0; for (let x = x0; x < x1; x++) { this.scanColumn(x, y0, y1); for (let y = y0; y < y1; y++) { const p = (y - y0) * CHUNK_SIZE + (x - x0); const t = this.thickness[tileIndex(x, y)]; const up = solidUp[y - y0]; const down = solidDown[y - y0]; let k = 1; let white = 0; if (up <= t + RIM_LIGHT_DEPTH) white = Math.max(0, RIM_LIGHT_WHITE * (1 - (up - t) / (RIM_LIGHT_DEPTH + 1))); else if (down <= t + UNDERSIDE_DEPTH) k = UNDERSIDE_DARKEN; shadeK[p] = k; shadeW[p] = Math.min(RIM_LIGHT_WHITE, white); let ck = CAVITY_DARKEN; const e = emptyUp[y - y0]; if (e < CAVITY_SHADOW_DEPTH) ck *= 0.6 + (0.4 * e) / CAVITY_SHADOW_DEPTH; cavityK[p] = ck; } } const out = chunk.image.data; out.fill(0); const sd = this.sd; const origCov = this.orig; const shadowA = DROP_SHADOW_ALPHA / 255; const texW = cw * S; const texH = (y1 - y0) * S; for (let ty = 0; ty < texH; ty++) { const py = ty / S; const y = y0 + Math.floor(py); // Window coordinates of the texel center. const v = py + 0.5 / S + M; for (let tx = 0; tx < texW; tx++) { const px = tx / S; const x = x0 + Math.floor(px); const u = px + 0.5 / S + M; const p = (y - y0) * CHUNK_SIZE + (x - x0); const o = (ty * TEX + tx) * 4; const i = y * width + x; // Background layer: the inside of the cake where it was dug, and the drop shadow. let bgR = 0; let bgG = 0; let bgB = 0; let bgA = 0; const cav = Math.min(1, Math.max(0, (sampleBilinear(origCov, WIN, WIN, u, v) - 0.5) / TERRAIN_AA + 0.5)); const sh = shadowA * Math.min(1, Math.max(0, sampleBilinear(sd, WIN, WIN, u - DROP_SHADOW_DX, v - DROP_SHADOW_DY) / DROP_SHADOW_SOFTNESS + 0.5)); if (cav > 0) { let om = original[i]; if (om === MATERIAL_EMPTY) om = this.nearbyMaterial(original, x, y); if (om !== MATERIAL_EMPTY) { const c = this.tiles[om]![scaledTileIndex(x0 * S + tx, y0 * S + ty, S)]; const k = cavityK[p] * (1 - sh * 0.55); bgR = (c >> 16) * k; bgG = ((c >> 8) & 0xff) * k * 0.95; bgB = (c & 0xff) * k * 0.9; bgA = cav; } } if (sh > 0 && bgA < 1) { const a = sh * (1 - bgA); const na = bgA + a; bgR = (bgR * bgA + OR * a) / na; bgG = (bgG * bgA + OG * a) / na; bgB = (bgB * bgA + OB * a) / na; bgA = na; } // Terrain layer: textured fill inside a felt-pen outline. const d = sampleBilinear(sd, WIN, WIN, u, v); const fa = coverage(d); let fr = 0; let fg = 0; let fb = 0; if (fa > 0) { const t = this.thickness[tileIndex(x, y)]; const ink = 1 - coverage(d - t); // Felt pen: slightly uneven ink. const inkK = 1 + (hash2(x >> 1, y >> 1, 99) - 0.5) * 0.35; fr = OR * inkK; fg = OG * inkK; fb = OB * inkK; const mat = data[i]; if (ink < 1 && mat !== MATERIAL_EMPTY) { const c = this.tiles[mat]![scaledTileIndex(x0 * S + tx, y0 * S + ty, S)]; const k = shadeK[p]; const w = shadeW[p]; const r = (c >> 16) * k; const g = ((c >> 8) & 0xff) * k; const b = (c & 0xff) * k; fr = (r + (255 - r) * w) * (1 - ink) + fr * ink; fg = (g + (255 - g) * w) * (1 - ink) + fg * ink; fb = (b + (255 - b) * w) * (1 - ink) + fb * ink; } } // Terrain over background. const a = fa + bgA * (1 - fa); if (a <= 0) continue; out[o] = (fr * fa + bgR * bgA * (1 - fa)) / a; out[o + 1] = (fg * fa + bgG * bgA * (1 - fa)) / a; out[o + 2] = (fb * fa + bgB * bgA * (1 - fa)) / a; out[o + 3] = a * 255; } } chunk.ctx.putImageData(chunk.image, 0, 0); chunk.texture.source.update(); } /** A material of the original map next to (x, y), for antialiased cavity edges. */ private nearbyMaterial(original: Uint8Array, x: number, y: number): number { const { width, height } = this.bitmap; for (const [dx, dy] of [ [1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, -1], [1, -1], [-1, 1], ]) { const nx = x + dx; const ny = y + dy; if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue; const m = original[ny * width + nx]; if (m !== MATERIAL_EMPTY) return m; } return MATERIAL_EMPTY; } /** Fills the per-column distance tables for column x over rows [y0, y1). */ private scanColumn(x: number, y0: number, y1: number): void { const { width, height, data } = this.bitmap; const solid = (y: number): boolean => y >= 0 && y < height && data[y * width + x] !== MATERIAL_EMPTY; let runSolid = 0; let sinceSolid = SCAN; for (let y = y0 - SCAN; y < y1; y++) { if (solid(y)) { runSolid++; sinceSolid = 0; } else { runSolid = 0; sinceSolid++; } if (y >= y0) { this.solidUp[y - y0] = runSolid; this.emptyUp[y - y0] = sinceSolid; } } runSolid = 0; for (let y = y1 + SCAN - 1; y >= y0; y--) { runSolid = solid(y) ? runSolid + 1 : 0; if (y < y1) this.solidDown[y - y0] = runSolid; } } private receivesShadow(x0: number, y0: number, x1: number, y1: number): boolean { const bm = this.bitmap; for (let y = y0 - DROP_SHADOW_DY - 2; y < y1 - DROP_SHADOW_DY + 2; y++) { for (let x = x0 - DROP_SHADOW_DX - 2; x < x1 - DROP_SHADOW_DX + 2; x++) if (bm.isSolid(x, y)) return true; } return false; } private createChunk(index: number, x0: number, y0: number): ChunkSprite { const canvas = document.createElement('canvas'); canvas.width = TEX; canvas.height = TEX; const ctx = canvas.getContext('2d')!; const image = ctx.createImageData(TEX, TEX); const texture = new Texture({ source: new CanvasSource({ resource: canvas, resolution: S, scaleMode: 'linear' }) }); const sprite = new Sprite(texture); sprite.position.set(x0, y0); this.container.addChild(sprite); const chunk = { ctx, image, texture, sprite }; this.chunks.set(index, chunk); return chunk; } }