TerrainView.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. import { CanvasSource, Container, Sprite, Texture } from 'pixi.js';
  2. import { CHUNK_SIZE, MATERIAL_EMPTY, OUTLINE_PX, RENDER_MARGIN } from '../../shared/constants';
  3. import { parseHexColor, type MaterialRegistry } from '../../shared/materials';
  4. import type { TerrainBitmap } from '../../shared/terrain/bitmap';
  5. import type { TerrainEvent } from '../../shared/terrain/events';
  6. import { rleDecode } from '../../shared/terrain/rle';
  7. import {
  8. CAVITY_DARKEN,
  9. CAVITY_SHADOW_DEPTH,
  10. DROP_SHADOW_ALPHA,
  11. DROP_SHADOW_DX,
  12. DROP_SHADOW_DY,
  13. DROP_SHADOW_SOFTNESS,
  14. OUTLINE_COLOR,
  15. RIM_LIGHT_DEPTH,
  16. RIM_LIGHT_WHITE,
  17. TERRAIN_AA,
  18. TERRAIN_SUPERSAMPLE,
  19. UNDERSIDE_DARKEN,
  20. UNDERSIDE_DEPTH,
  21. } from '../config';
  22. import { sampleBilinear, signedDistance } from './distance';
  23. import { hash2, makeThicknessTile, makeTile, scaledTileIndex, tileIndex } from './textures';
  24. interface ChunkSprite {
  25. ctx: CanvasRenderingContext2D;
  26. image: ImageData;
  27. texture: Texture;
  28. sprite: Sprite;
  29. }
  30. const S = TERRAIN_SUPERSAMPLE;
  31. /** Texture side of one terrain chunk. */
  32. const TEX = CHUNK_SIZE * S;
  33. /** The distance field window around a chunk: enough for the outline, the shading and the drop shadow. */
  34. const M = RENDER_MARGIN;
  35. const WIN = CHUNK_SIZE + 2 * M;
  36. /** Column scan margin: how far above/below the chunk the lighting looks. */
  37. const SCAN = Math.max(RIM_LIGHT_DEPTH, UNDERSIDE_DEPTH, CAVITY_SHADOW_DEPTH) + OUTLINE_PX + 1;
  38. const OR = OUTLINE_COLOR >> 16;
  39. const OG = (OUTLINE_COLOR >> 8) & 0xff;
  40. const OB = OUTLINE_COLOR & 0xff;
  41. /** 0..1 coverage of a signed distance (positive inside), antialiased over TERRAIN_AA pixels. */
  42. function coverage(sd: number): number {
  43. const c = sd / TERRAIN_AA + 0.5;
  44. return c <= 0 ? 0 : c >= 1 ? 1 : c;
  45. }
  46. /**
  47. * Renders the terrain bitmap as one canvas-backed sprite per 64 px chunk, supersampled
  48. * (TERRAIN_SUPERSAMPLE texels per pixel). Edges come from a signed distance field, so they are
  49. * smooth and antialiased whatever the zoom: textured materials, an irregular felt-pen outline,
  50. * rim light on top faces, darker undersides, a soft drop shadow, and holes that show the inside
  51. * of the cake.
  52. */
  53. export class TerrainView {
  54. readonly container = new Container();
  55. private readonly chunks = new Map<number, ChunkSprite>();
  56. private readonly tiles: (Uint32Array | undefined)[] = [];
  57. private readonly thickness = makeThicknessTile(OUTLINE_PX);
  58. /** The map as loaded: pixels solid here but empty now are cavities. */
  59. private readonly original: Uint8Array;
  60. // Per-column scratch: distance to the nearest empty pixel above / below, and to solid above.
  61. private readonly solidUp = new Int16Array(CHUNK_SIZE);
  62. private readonly solidDown = new Int16Array(CHUNK_SIZE);
  63. private readonly emptyUp = new Int16Array(CHUNK_SIZE);
  64. /** Signed distance of the current terrain, and coverage of the original one, around the chunk being drawn. */
  65. private readonly sd = new Float32Array(WIN * WIN);
  66. private readonly orig = new Float32Array(WIN * WIN);
  67. // Per-pixel shading of the chunk being drawn: brightness, tint toward white, cavity darkening.
  68. private readonly shadeK = new Float32Array(CHUNK_SIZE * CHUNK_SIZE);
  69. private readonly shadeW = new Float32Array(CHUNK_SIZE * CHUNK_SIZE);
  70. private readonly cavityK = new Float32Array(CHUNK_SIZE * CHUNK_SIZE);
  71. constructor(
  72. private readonly bitmap: TerrainBitmap,
  73. materials: MaterialRegistry,
  74. ) {
  75. this.original = bitmap.data.slice();
  76. materials.byId.forEach((m, id) => {
  77. if (m && id !== MATERIAL_EMPTY) this.tiles[id] = makeTile(parseHexColor(m.color), m.texture, S);
  78. });
  79. }
  80. /**
  81. * Keeps the "as loaded" copy in sync with pieces that move: a detached chunk takes its
  82. * pixels away (the gap shows the background, not the inside of the cake), and a merged
  83. * chunk brings them back. Call after applying the event to the bitmap.
  84. */
  85. onEvent(ev: TerrainEvent): void {
  86. if (ev.kind === 'op') return;
  87. const cells = rleDecode(ev.kind === 'detach' ? ev.mask : ev.patch, ev.w * ev.h);
  88. const { width, height } = this.bitmap;
  89. for (let ly = 0; ly < ev.h; ly++) {
  90. for (let lx = 0; lx < ev.w; lx++) {
  91. const v = cells[ly * ev.w + lx];
  92. const x = ev.x + lx;
  93. const y = ev.y + ly;
  94. if (v === MATERIAL_EMPTY || x < 0 || y < 0 || x >= width || y >= height) continue;
  95. const i = y * width + x;
  96. this.original[i] = ev.kind === 'detach' ? MATERIAL_EMPTY : this.bitmap.data[i];
  97. }
  98. }
  99. }
  100. /**
  101. * Draws a falling chunk's mask with the same textures (sampled at its original map
  102. * position, so it looks unchanged at the moment it breaks off) and a felt outline.
  103. * The texture is 1 px larger than the mask on each side (see ChunkView's pivot).
  104. */
  105. makeChunkTexture(mask: Uint8Array, w: number, h: number, ox: number, oy: number): Texture {
  106. const pad = 1;
  107. const m = OUTLINE_PX + 2;
  108. const ww = w + 2 * m;
  109. const wh = h + 2 * m;
  110. const sd = new Float32Array(ww * wh);
  111. signedDistance(
  112. (i) => {
  113. const x = (i % ww) - m;
  114. const y = ((i / ww) | 0) - m;
  115. return x >= 0 && y >= 0 && x < w && y < h && mask[y * w + x] !== MATERIAL_EMPTY;
  116. },
  117. ww,
  118. wh,
  119. sd,
  120. m,
  121. );
  122. const cw = (w + pad * 2) * S;
  123. const ch = (h + pad * 2) * S;
  124. const canvas = document.createElement('canvas');
  125. canvas.width = cw;
  126. canvas.height = ch;
  127. const ctx = canvas.getContext('2d')!;
  128. const image = ctx.createImageData(cw, ch);
  129. const out = image.data;
  130. for (let ty = 0; ty < ch; ty++) {
  131. for (let tx = 0; tx < cw; tx++) {
  132. // Local mask coordinates of this texel's center.
  133. const lx = (tx + 0.5) / S - pad;
  134. const ly = (ty + 0.5) / S - pad;
  135. const d = sampleBilinear(sd, ww, wh, lx + m, ly + m);
  136. const a = coverage(d);
  137. if (a === 0) continue;
  138. const px = Math.max(0, Math.min(w - 1, Math.floor(lx)));
  139. const py = Math.max(0, Math.min(h - 1, Math.floor(ly)));
  140. const t = this.thickness[tileIndex(ox + px, oy + py)];
  141. const ink = 1 - coverage(d - t);
  142. let r = OR;
  143. let g = OG;
  144. let b = OB;
  145. const mat = mask[py * w + px];
  146. if (ink < 1 && mat !== MATERIAL_EMPTY) {
  147. const c = this.tiles[mat]![scaledTileIndex((ox + px) * S + (tx % S), (oy + py) * S + (ty % S), S)];
  148. r = (c >> 16) * (1 - ink) + OR * ink;
  149. g = ((c >> 8) & 0xff) * (1 - ink) + OG * ink;
  150. b = (c & 0xff) * (1 - ink) + OB * ink;
  151. }
  152. const o = (ty * cw + tx) * 4;
  153. out[o] = r;
  154. out[o + 1] = g;
  155. out[o + 2] = b;
  156. out[o + 3] = a * 255;
  157. }
  158. }
  159. ctx.putImageData(image, 0, 0);
  160. return new Texture({ source: new CanvasSource({ resource: canvas, resolution: S, scaleMode: 'linear' }) });
  161. }
  162. /** Redraws every chunk flagged dirty in the bitmap. */
  163. update(): void {
  164. for (const index of this.bitmap.takeDirtyChunks()) this.redraw(index);
  165. }
  166. private redraw(index: number): void {
  167. const { x0, y0, x1, y1 } = this.bitmap.chunkRect(index);
  168. const { width, height, data } = this.bitmap;
  169. const original = this.original;
  170. let any = false;
  171. for (let y = y0; y < y1 && !any; y++) {
  172. for (let x = x0; x < x1; x++) {
  173. const i = y * width + x;
  174. // Anything solid, any cavity, or any solid casting a shadow into this chunk needs drawing.
  175. if (data[i] !== MATERIAL_EMPTY || original[i] !== MATERIAL_EMPTY) {
  176. any = true;
  177. break;
  178. }
  179. }
  180. }
  181. if (!any) any = this.receivesShadow(x0, y0, x1, y1);
  182. let chunk = this.chunks.get(index);
  183. if (!any) {
  184. if (chunk) chunk.sprite.visible = false;
  185. return;
  186. }
  187. chunk ??= this.createChunk(index, x0, y0);
  188. chunk.sprite.visible = true;
  189. // Distance fields over the window around the chunk (clamped to the map: no outline on the map border).
  190. const wx0 = x0 - M;
  191. const wy0 = y0 - M;
  192. const at = (i: number): number => {
  193. const x = Math.max(0, Math.min(width - 1, wx0 + (i % WIN)));
  194. const y = Math.max(0, Math.min(height - 1, wy0 + ((i / WIN) | 0)));
  195. return y * width + x;
  196. };
  197. signedDistance((i) => data[at(i)] !== MATERIAL_EMPTY, WIN, WIN, this.sd, M);
  198. for (let i = 0; i < WIN * WIN; i++) this.orig[i] = original[at(i)] !== MATERIAL_EMPTY ? 1 : 0;
  199. // Per-pixel lighting from column scans: rim light on top faces, darker undersides, cavity shade.
  200. const { solidUp, solidDown, emptyUp, shadeK, shadeW, cavityK } = this;
  201. const cw = x1 - x0;
  202. for (let x = x0; x < x1; x++) {
  203. this.scanColumn(x, y0, y1);
  204. for (let y = y0; y < y1; y++) {
  205. const p = (y - y0) * CHUNK_SIZE + (x - x0);
  206. const t = this.thickness[tileIndex(x, y)];
  207. const up = solidUp[y - y0];
  208. const down = solidDown[y - y0];
  209. let k = 1;
  210. let white = 0;
  211. if (up <= t + RIM_LIGHT_DEPTH) white = Math.max(0, RIM_LIGHT_WHITE * (1 - (up - t) / (RIM_LIGHT_DEPTH + 1)));
  212. else if (down <= t + UNDERSIDE_DEPTH) k = UNDERSIDE_DARKEN;
  213. shadeK[p] = k;
  214. shadeW[p] = Math.min(RIM_LIGHT_WHITE, white);
  215. let ck = CAVITY_DARKEN;
  216. const e = emptyUp[y - y0];
  217. if (e < CAVITY_SHADOW_DEPTH) ck *= 0.6 + (0.4 * e) / CAVITY_SHADOW_DEPTH;
  218. cavityK[p] = ck;
  219. }
  220. }
  221. const out = chunk.image.data;
  222. out.fill(0);
  223. const sd = this.sd;
  224. const origCov = this.orig;
  225. const shadowA = DROP_SHADOW_ALPHA / 255;
  226. const texW = cw * S;
  227. const texH = (y1 - y0) * S;
  228. for (let ty = 0; ty < texH; ty++) {
  229. const py = ty / S;
  230. const y = y0 + Math.floor(py);
  231. // Window coordinates of the texel center.
  232. const v = py + 0.5 / S + M;
  233. for (let tx = 0; tx < texW; tx++) {
  234. const px = tx / S;
  235. const x = x0 + Math.floor(px);
  236. const u = px + 0.5 / S + M;
  237. const p = (y - y0) * CHUNK_SIZE + (x - x0);
  238. const o = (ty * TEX + tx) * 4;
  239. const i = y * width + x;
  240. // Background layer: the inside of the cake where it was dug, and the drop shadow.
  241. let bgR = 0;
  242. let bgG = 0;
  243. let bgB = 0;
  244. let bgA = 0;
  245. const cav = Math.min(1, Math.max(0, (sampleBilinear(origCov, WIN, WIN, u, v) - 0.5) / TERRAIN_AA + 0.5));
  246. 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));
  247. if (cav > 0) {
  248. let om = original[i];
  249. if (om === MATERIAL_EMPTY) om = this.nearbyMaterial(original, x, y);
  250. if (om !== MATERIAL_EMPTY) {
  251. const c = this.tiles[om]![scaledTileIndex(x0 * S + tx, y0 * S + ty, S)];
  252. const k = cavityK[p] * (1 - sh * 0.55);
  253. bgR = (c >> 16) * k;
  254. bgG = ((c >> 8) & 0xff) * k * 0.95;
  255. bgB = (c & 0xff) * k * 0.9;
  256. bgA = cav;
  257. }
  258. }
  259. if (sh > 0 && bgA < 1) {
  260. const a = sh * (1 - bgA);
  261. const na = bgA + a;
  262. bgR = (bgR * bgA + OR * a) / na;
  263. bgG = (bgG * bgA + OG * a) / na;
  264. bgB = (bgB * bgA + OB * a) / na;
  265. bgA = na;
  266. }
  267. // Terrain layer: textured fill inside a felt-pen outline.
  268. const d = sampleBilinear(sd, WIN, WIN, u, v);
  269. const fa = coverage(d);
  270. let fr = 0;
  271. let fg = 0;
  272. let fb = 0;
  273. if (fa > 0) {
  274. const t = this.thickness[tileIndex(x, y)];
  275. const ink = 1 - coverage(d - t);
  276. // Felt pen: slightly uneven ink.
  277. const inkK = 1 + (hash2(x >> 1, y >> 1, 99) - 0.5) * 0.35;
  278. fr = OR * inkK;
  279. fg = OG * inkK;
  280. fb = OB * inkK;
  281. const mat = data[i];
  282. if (ink < 1 && mat !== MATERIAL_EMPTY) {
  283. const c = this.tiles[mat]![scaledTileIndex(x0 * S + tx, y0 * S + ty, S)];
  284. const k = shadeK[p];
  285. const w = shadeW[p];
  286. const r = (c >> 16) * k;
  287. const g = ((c >> 8) & 0xff) * k;
  288. const b = (c & 0xff) * k;
  289. fr = (r + (255 - r) * w) * (1 - ink) + fr * ink;
  290. fg = (g + (255 - g) * w) * (1 - ink) + fg * ink;
  291. fb = (b + (255 - b) * w) * (1 - ink) + fb * ink;
  292. }
  293. }
  294. // Terrain over background.
  295. const a = fa + bgA * (1 - fa);
  296. if (a <= 0) continue;
  297. out[o] = (fr * fa + bgR * bgA * (1 - fa)) / a;
  298. out[o + 1] = (fg * fa + bgG * bgA * (1 - fa)) / a;
  299. out[o + 2] = (fb * fa + bgB * bgA * (1 - fa)) / a;
  300. out[o + 3] = a * 255;
  301. }
  302. }
  303. chunk.ctx.putImageData(chunk.image, 0, 0);
  304. chunk.texture.source.update();
  305. }
  306. /** A material of the original map next to (x, y), for antialiased cavity edges. */
  307. private nearbyMaterial(original: Uint8Array, x: number, y: number): number {
  308. const { width, height } = this.bitmap;
  309. for (const [dx, dy] of [
  310. [1, 0],
  311. [-1, 0],
  312. [0, 1],
  313. [0, -1],
  314. [1, 1],
  315. [-1, -1],
  316. [1, -1],
  317. [-1, 1],
  318. ]) {
  319. const nx = x + dx;
  320. const ny = y + dy;
  321. if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;
  322. const m = original[ny * width + nx];
  323. if (m !== MATERIAL_EMPTY) return m;
  324. }
  325. return MATERIAL_EMPTY;
  326. }
  327. /** Fills the per-column distance tables for column x over rows [y0, y1). */
  328. private scanColumn(x: number, y0: number, y1: number): void {
  329. const { width, height, data } = this.bitmap;
  330. const solid = (y: number): boolean => y >= 0 && y < height && data[y * width + x] !== MATERIAL_EMPTY;
  331. let runSolid = 0;
  332. let sinceSolid = SCAN;
  333. for (let y = y0 - SCAN; y < y1; y++) {
  334. if (solid(y)) {
  335. runSolid++;
  336. sinceSolid = 0;
  337. } else {
  338. runSolid = 0;
  339. sinceSolid++;
  340. }
  341. if (y >= y0) {
  342. this.solidUp[y - y0] = runSolid;
  343. this.emptyUp[y - y0] = sinceSolid;
  344. }
  345. }
  346. runSolid = 0;
  347. for (let y = y1 + SCAN - 1; y >= y0; y--) {
  348. runSolid = solid(y) ? runSolid + 1 : 0;
  349. if (y < y1) this.solidDown[y - y0] = runSolid;
  350. }
  351. }
  352. private receivesShadow(x0: number, y0: number, x1: number, y1: number): boolean {
  353. const bm = this.bitmap;
  354. for (let y = y0 - DROP_SHADOW_DY - 2; y < y1 - DROP_SHADOW_DY + 2; y++) {
  355. for (let x = x0 - DROP_SHADOW_DX - 2; x < x1 - DROP_SHADOW_DX + 2; x++) if (bm.isSolid(x, y)) return true;
  356. }
  357. return false;
  358. }
  359. private createChunk(index: number, x0: number, y0: number): ChunkSprite {
  360. const canvas = document.createElement('canvas');
  361. canvas.width = TEX;
  362. canvas.height = TEX;
  363. const ctx = canvas.getContext('2d')!;
  364. const image = ctx.createImageData(TEX, TEX);
  365. const texture = new Texture({ source: new CanvasSource({ resource: canvas, resolution: S, scaleMode: 'linear' }) });
  366. const sprite = new Sprite(texture);
  367. sprite.position.set(x0, y0);
  368. this.container.addChild(sprite);
  369. const chunk = { ctx, image, texture, sprite };
  370. this.chunks.set(index, chunk);
  371. return chunk;
  372. }
  373. }