07酸の腐食 — 出会った素材を消す反応規則
酸のマスの下・横の隣接が土や石ならそのマスを空け、自身も確率で消費すると、床を突き抜けて地下へ染み込み通路を掘る腐食が生まれます。
使いどころゲームパズルの地形破壊、先鋭的なインタラクティブデモ
ImageDataputImageDatarequestAnimationFrame

<main class="stage">
<div class="cd is-demo" id="cdRoot">
<p class="cd__hint"><span>酸が土と石を溶かし、通路を掘ります</span></p>
<div class="cd__field" id="cdField" role="application" aria-label="酸の腐食 セル・オートマトン デモ" tabindex="0">
<canvas class="cd__cv" id="cdCv"></canvas>
</div>
<div class="cd__bar">
<span class="cd__meta"><b class="cd__val" id="cdN">30</b>% 腐食確率・酸-土-石 反応</span>
<span class="cd__meta cd__meta--dim">canvas · ImageData putImageData · requestAnimationFrame</span>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 산 부식(07). @keyframes 을 아예 두지 않는다 —
// 움직임은 전부 캔버스 rAF 루프(산 스포너 → 부식 → 낙하 → 잔광)가 만든다.
// 무대는 어스름 잉크. 파스텔 고정 팔레트를 --sand-* 로 편 공통 규격(01~09 동일).
$duration: $dur-loop;
$easing: $ease-spring;
$color: $subject-lilac;
@include stage($stage-ink);
// ── 편 공통 파스텔 팔레트(BD26 vivid 0 실측 통과값 — 다른 색 금지) ──
$sand-night: #201c17; // 밤 지하 배경
$sand-mist: #d8d2c6; // 먼지 — 힌트 글자
$sand-glow: #f2e2c4; // 산 하이라이트
$sand-grain: #d9b98a; // 모래 셰이드 A
$sand-gold: #ecd9b0; // 모래 셰이드 B
$sand-water: #a9c8dd; // (공용) 물
$sand-ice: #cfe3ee; // (공용) 얼음
$sand-fire: #ffc9ad; // (공용) 불
$sand-flame: #ffe0c4; // (공용) 불꽃 코어
$sand-ash: #b9b2a6; // (공용) 재
$sand-smoke: #8e8879; // (공용) 연기
$sand-plant: #9fd6ad; // (공용) 풀
$sand-leaf: #c4e6c9; // (공용) 잎
$sand-acid: #c7dd8f; // 산 — 라임 파스텔
$sand-stone: #8a8578; // 돌
$sand-wood: #b98a63; // 흙(목톤)
.cd {
// 렌더러가 읽는 색 — JS 는 getComputedStyle 로 --sand-* 를 받아 쓴다
--sand-night: #{$sand-night};
--sand-mist: #{$sand-mist};
--sand-glow: #{$sand-glow};
--sand-grain: #{$sand-grain};
--sand-gold: #{$sand-gold};
--sand-water: #{$sand-water};
--sand-ice: #{$sand-ice};
--sand-fire: #{$sand-fire};
--sand-flame: #{$sand-flame};
--sand-ash: #{$sand-ash};
--sand-smoke: #{$sand-smoke};
--sand-plant: #{$sand-plant};
--sand-leaf: #{$sand-leaf};
--sand-acid: #{$sand-acid};
--sand-stone: #{$sand-stone};
--sand-wood: #{$sand-wood};
display: flex; flex-direction: column; gap: $sp-2;
width: 100%; max-width: 424px;
}
.cd__hint {
display: flex; align-items: center; gap: $sp-1; margin: 0;
font-weight: 700; font-size: clamp(10px, 2.8vw, 12px); line-height: 1.35;
color: $sand-mist;
}
.cd__field {
position: relative; height: 200px;
border-radius: $r-card; overflow: hidden;
background: $sand-night;
box-shadow: inset 0 0 0 1px rgba($sand-mist, .18);
}
.cd__field:focus-visible { outline: 2px solid $subject-lilac; outline-offset: 2px; }
.cd__cv { display: block; width: 100%; height: 100%; }
.cd__bar { display: flex; align-items: baseline; justify-content: space-between; gap: $sp-2; }
.cd__meta { font-size: 10px; font-weight: 500; color: rgba($sand-mist, .72); }
.cd__val { color: $subject-lilac; font-weight: 700; }
.cd__meta--dim { font-size: 10px; }
@media (max-width: 340px) {
.cd { gap: $sp-1; }
.cd__field { height: 110px; }
.cd__meta--dim { display: none; }
}
// reduce — rAF 를 돌리지 않고 부식이 한참 진행된 한 장만 남는다.
@media (prefers-reduced-motion: reduce) {
.cd.is-still .cd__field { cursor: default !important; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #17141a;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.cd {
--sand-night: #201c17;
--sand-mist: #d8d2c6;
--sand-glow: #f2e2c4;
--sand-grain: #d9b98a;
--sand-gold: #ecd9b0;
--sand-water: #a9c8dd;
--sand-ice: #cfe3ee;
--sand-fire: #ffc9ad;
--sand-flame: #ffe0c4;
--sand-ash: #b9b2a6;
--sand-smoke: #8e8879;
--sand-plant: #9fd6ad;
--sand-leaf: #c4e6c9;
--sand-acid: #c7dd8f;
--sand-stone: #8a8578;
--sand-wood: #b98a63;
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
max-width: 424px;
}
.cd__hint {
display: flex;
align-items: center;
gap: 4px;
margin: 0;
font-weight: 700;
font-size: clamp(10px, 2.8vw, 12px);
line-height: 1.35;
color: #d8d2c6;
}
.cd__field {
position: relative;
height: 200px;
border-radius: 16px;
overflow: hidden;
background: #201c17;
box-shadow: inset 0 0 0 1px rgba(216, 210, 198, 0.18);
}
.cd__field:focus-visible {
outline: 2px solid #b9a0ff;
outline-offset: 2px;
}
.cd__cv {
display: block;
width: 100%;
height: 100%;
}
.cd__bar {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
}
.cd__meta {
font-size: 10px;
font-weight: 500;
color: rgba(216, 210, 198, 0.72);
}
.cd__val {
color: #b9a0ff;
font-weight: 700;
}
.cd__meta--dim {
font-size: 10px;
}
@media (max-width: 340px) {
.cd {
gap: 4px;
}
.cd__field {
height: 110px;
}
.cd__meta--dim {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
.cd.is-still .cd__field {
cursor: default !important;
}
}// 산 부식(07). 재료 코드: 0 빈칸 1 모래 10 흙 11 돌 12 산.
// 산 칸은 물처럼 아래→대각→좌우로 이동하되, 이동 전 아래·좌·우 이웃이 흙/돌/모래면 그 이웃을 지우고(부식)
// 확률 EAT_P 로 산 자신도 소모돼 사라진다. 3~4 단 계단형 지형(흙+돌) 위 얇은 모래층을 상단 좌·우
// 스포너에서 떨어지는 산이 뚫고 내려가며 지하 통로를 판다.
(function () {
// ── 변형 상수 블록 ──
var EAT_P = 0.3; // 부식 성공 시 산이 소모될 확률 — 낮추면 산이 오래 남아 통로가 굵어진다
var SPAWN_EVERY = 7; // 산 스포너 간격(틱) — 줄이면 산이 더 자주 떨어진다
// ────────────────────────────
var EMPTY = 0, SAND = 1, DIRT = 10, STONE = 11, ACID = 12;
var root = document.getElementById('cdRoot');
var field = document.getElementById('cdField');
var cv = document.getElementById('cdCv');
var ctx = cv.getContext('2d');
function makeRand(seed) {
var st = seed >>> 0;
return function () {
st = (st + 0x6D2B79F5) >>> 0;
var t = st;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
var rand = makeRand(0x318A07);
function hexToRgb(hex) {
hex = hex.trim();
if (hex.length === 4) hex = '#' + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];
var n = parseInt(hex.slice(1), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var CELL = 4;
var cols = 0, rows = 0, grid = null;
var COL = {};
// 지형 연출 — 프레임0 은 빈 무대에서 시작해 TERRAIN_TICKS 틱에 걸쳐 계단 지형이 위에서부터 굳는다.
// 채워지는 지형 자체가 누적면적을 만들고(장면의 절반 이상), 굳는 동안 모래가 흘러내리는 낙하도 겹친다.
var TERRAIN_TICKS = 115;
function readColors() {
var css = getComputedStyle(root);
COL.night = hexToRgb(css.getPropertyValue('--sand-night'));
COL.dirt = hexToRgb(css.getPropertyValue('--sand-wood'));
COL.stone = hexToRgb(css.getPropertyValue('--sand-stone'));
COL.sandA = hexToRgb(css.getPropertyValue('--sand-grain'));
COL.sandB = hexToRgb(css.getPropertyValue('--sand-gold'));
COL.acidA = hexToRgb(css.getPropertyValue('--sand-acid'));
COL.acidB = hexToRgb(css.getPropertyValue('--sand-glow'));
COL.mist = hexToRgb(css.getPropertyValue('--sand-mist'));
}
function idx(x, y) { return y * cols + x; }
function get(x, y) {
if (x < 0 || x >= cols || y < 0 || y >= rows) return STONE;
return grid[idx(x, y)];
}
function set(x, y, v) {
if (x < 0 || x >= cols || y < 0 || y >= rows) return;
grid[idx(x, y)] = v;
}
function buildTerrainFull() {
// 3~4 단 계단형 흙+돌 선반 — x 를 4 구간으로 나눠 단마다 깊이를 다르게
var seg = Math.max(1, Math.floor(cols / 4));
for (var x = 0; x < cols; x++) {
var tier = Math.min(3, Math.floor(x / seg));
var top = Math.floor(rows * (0.32 + tier * 0.15));
for (var y = top; y < rows; y++) {
var depth = y - top;
set(x, y, depth < 2 ? DIRT : STONE);
}
// 선반 위 얇은 모래층 1~2 칸
var sandDepth = 1 + (rand() < 0.4 ? 1 : 0);
for (var sy = 0; sy < sandDepth; sy++) {
var ty = top - 1 - sy;
if (ty >= 0) set(x, ty, SAND);
}
}
}
// 지형 낙하 연출 — 각 칸에 '굳는 시각' 을 배정하고 update 마다 그 시각이 지난 칸만 채운다.
// 위쪽 행부터 먼저 굳고 x 는 좌우에서 안쪽으로(협곡이 벌어지듯) 차오른다.
var solidAt = null;
function buildTerrainStagger() {
solidAt = new Float32Array(cols * rows);
var seg = Math.max(1, Math.floor(cols / 4));
for (var x = 0; x < cols; x++) {
var tier = Math.min(3, Math.floor(x / seg));
var top = Math.floor(rows * (0.32 + tier * 0.15));
var edgeDist = Math.min(x, cols - 1 - x) / (cols / 2); // 0(가장자리) → 1(중앙)
for (var y = top; y < rows; y++) {
var depthFrac = (y - top) / Math.max(1, rows - top);
// 가장자리·얕은 쪽 먼저, 중앙 심부가 마지막에 굳는다
solidAt[idx(x, y)] = TERRAIN_TICKS * (0.15 + 0.85 * edgeDist * 0.55 + 0.45 * depthFrac) * (0.85 + 0.3 * rand());
}
var sandDepth = 1 + (rand() < 0.4 ? 1 : 0);
for (var sy = 0; sy < sandDepth; sy++) {
var ty = top - 1 - sy;
if (ty >= 0) solidAt[idx(x, ty)] = TERRAIN_TICKS * (0.7 + 0.5 * rand()) * (0.4 + 0.6 * edgeDist);
}
}
}
function resolveSolid(tick) {
if (!solidAt) return;
for (var y = 0; y < rows; y++) {
for (var x = 0; x < cols; x++) {
var i = idx(x, y);
if (solidAt[i] > 0 && solidAt[i] <= tick && grid[i] === EMPTY) {
// 굳는 시각에 도달한 칸 — 흙 표층(위 2칸) / 돌 심부 / 모래 얇은 층
var seg = Math.max(1, Math.floor(cols / 4));
var tier = Math.min(3, Math.floor(x / seg));
var top = Math.floor(rows * (0.32 + tier * 0.15));
if (y < top) grid[i] = SAND;
else if (y - top < 2) grid[i] = DIRT;
else grid[i] = STONE;
}
}
}
}
function resetGrid() {
grid = new Uint8Array(cols * rows);
buildTerrainStagger();
}
function spawnAcid(tick) {
if (tick % SPAWN_EVERY !== 0) return;
var leftX = 1 + Math.floor(rand() * 3);
var rightX = cols - 2 - Math.floor(rand() * 3);
if (get(leftX, 0) === EMPTY) set(leftX, 0, ACID);
if (get(rightX, 0) === EMPTY) set(rightX, 0, ACID);
}
function isErodible(m) { return m === DIRT || m === STONE || m === SAND; }
function moveInto(x, y, nx, ny, m) {
if (get(nx, ny) !== EMPTY) return false;
set(x, y, EMPTY);
set(nx, ny, m);
return true;
}
function updateAcid(x, y, dir) {
var m = get(x, y);
if (m !== ACID) return;
var spots = [[x, y + 1], [x - 1, y], [x + 1, y]];
var melted = false;
for (var i = 0; i < spots.length; i++) {
var nx = spots[i][0], ny = spots[i][1];
if (isErodible(get(nx, ny))) { set(nx, ny, EMPTY); melted = true; }
}
if (melted && rand() < EAT_P) { set(x, y, EMPTY); return; }
if (moveInto(x, y, x, y + 1, ACID)) return;
var first = dir > 0 ? -1 : 1;
if (moveInto(x, y, x + first, y + 1, ACID)) return;
if (moveInto(x, y, x - first, y + 1, ACID)) return;
if (moveInto(x, y, x + first, y, ACID)) return;
moveInto(x, y, x - first, y, ACID);
}
function updateSand(x, y, dir) {
var m = get(x, y);
if (m !== SAND) return;
if (moveInto(x, y, x, y + 1, SAND)) return;
var first = dir > 0 ? -1 : 1;
if (moveInto(x, y, x + first, y + 1, SAND)) return;
moveInto(x, y, x - first, y + 1, SAND);
}
var tick = 0;
function update() {
tick++;
resolveSolid(tick);
spawnAcid(tick);
var dir = (tick % 2 === 0) ? 1 : -1;
for (var y = rows - 1; y >= 0; y--) {
if (dir > 0) {
for (var x = 0; x < cols; x++) {
var m = get(x, y);
if (m === ACID) updateAcid(x, y, dir);
else if (m === SAND) updateSand(x, y, dir);
}
} else {
for (var x2 = cols - 1; x2 >= 0; x2--) {
var m2 = get(x2, y);
if (m2 === ACID) updateAcid(x2, y, dir);
else if (m2 === SAND) updateSand(x2, y, dir);
}
}
}
}
var buf = null, imgData = null;
function ensureBuf() {
imgData = ctx.createImageData(cv.width, cv.height);
buf = imgData.data;
}
function shade(c, amt) {
return [
Math.max(0, Math.min(255, c[0] + amt)),
Math.max(0, Math.min(255, c[1] + amt)),
Math.max(0, Math.min(255, c[2] + amt))
];
}
function draw(t) {
if (!buf) ensureBuf();
var W = cv.width, H = cv.height;
var wave = Math.sin(t * 0.00055) * 0.5 + 0.5;
var cx = W * (0.5 + 0.34 * Math.sin(t * 0.00042));
var cy = H * (0.5 + 0.34 * Math.cos(t * 0.00036));
var maxD = Math.hypot(W, H) * 0.6;
for (var y = 0; y < rows; y++) {
for (var x = 0; x < cols; x++) {
var m = grid[idx(x, y)];
var px0 = x * CELL, py0 = y * CELL;
var d = Math.hypot(px0 - cx, py0 - cy) / maxD;
var glow = Math.max(0, 1 - d) * (0.08 + 0.05 * wave);
var col;
if (m === EMPTY) {
col = shade(COL.night, Math.round(glow * 40));
} else if (m === DIRT) {
col = shade(COL.dirt, ((x * 7 + y * 13) % 5) - 2 + Math.round(glow * 14));
} else if (m === STONE) {
col = shade(COL.stone, ((x * 11 + y * 5) % 5) - 2 + Math.round(glow * 10));
} else if (m === SAND) {
col = ((x + y) % 3 === 0) ? shade(COL.sandA, Math.round(glow * 18)) : shade(COL.sandB, Math.round(glow * 18));
} else if (m === ACID) {
var flick = Math.sin(t * 0.02 + x * 0.7 + y * 0.5) * 0.5 + 0.5;
col = shade(flick > 0.5 ? COL.acidB : COL.acidA, Math.round(glow * 20));
} else {
col = COL.night;
}
for (var cyi = 0; cyi < CELL; cyi++) {
var rowOff = ((py0 + cyi) * W + px0) * 4;
for (var cxi = 0; cxi < CELL; cxi++) {
var o = rowOff + cxi * 4;
buf[o] = col[0]; buf[o + 1] = col[1]; buf[o + 2] = col[2]; buf[o + 3] = 255;
}
}
}
}
ctx.putImageData(imgData, 0, 0);
}
function fit() {
readColors();
var r = field.getBoundingClientRect();
cv.width = Math.max(1, Math.round(r.width));
cv.height = Math.max(1, Math.round(r.height));
cols = Math.max(1, Math.floor(cv.width / CELL));
rows = Math.max(1, Math.floor(cv.height / CELL));
buf = null;
resetGrid();
}
function stillFrame() {
buildTerrainFull();
solidAt = null;
for (var i = 0; i < 90; i++) update();
draw(1500);
root.classList.add('is-still');
}
var last = 0, acc = 0;
var STEP = 1000 / 60;
function frame(now) {
if (!last) last = now;
acc += now - last;
last = now;
var guard = 0;
while (acc >= STEP && guard < 6) { update(); acc -= STEP; guard++; }
draw(now);
requestAnimationFrame(frame);
}
window.addEventListener('resize', fit);
fit();
if (reduce) { stillFrame(); } else { requestAnimationFrame(frame); }
})();// AcidDissolve — vanilla 판(run/318/demo/07-sand-acid-dissolve-react/index.html) 의 React 포트.
// 산 칸이 아래·양옆 이웃을 지우고(부식) 확률로 자신도 소모되며, 물처럼 아래→대각→좌우로 이동한다.
// 계단형 흙·돌 선반 위 얇은 모래층을 상단 좌·우 스포너의 산이 뚫고 지하 통로를 파는 장면.
import { useEffect, useRef, useState } from "react";
import type { CSSProperties } from "react";
import styles from "./AcidDissolve.module.scss";
export type AcidDissolveProps = {
duration?: string;
easing?: string;
color?: string;
eatP?: number; // 부식 성공 시 산이 소모될 확률(0~1)
spawnEvery?: number; // 산 스포너 간격(틱)
cellPx?: number; // 셀 크기(px)
};
type Vars = CSSProperties & { "--duration"?: string; "--easing"?: string; "--color"?: string };
type Box<T> = { current: T };
type RGB = [number, number, number];
type Colors = {
night: RGB; dirt: RGB; stone: RGB; sandA: RGB; sandB: RGB;
acidA: RGB; acidB: RGB; mist: RGB;
};
const FIELD_LABEL = "산 부식 셀 오토마타 데모";
const EMPTY = 0, SAND = 1, DIRT = 10, STONE = 11, ACID = 12;
function makePRNG(seed: number): () => number {
let s = seed >>> 0;
return function () {
s = (s + 0x6d2b79f5) >>> 0;
let t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export default function AcidDissolve({
duration = "2s",
easing = "cubic-bezier(.2, .8, .2, 1)",
color = "#b9a0ff",
eatP = 0.3,
spawnEvery = 7,
cellPx = 4,
}: AcidDissolveProps) {
const rootRef = useRef<HTMLDivElement | null>(null);
const fieldRef = useRef<HTMLDivElement | null>(null);
const cvRef = useRef<HTMLCanvasElement | null>(null);
const ctxRef = useRef<CanvasRenderingContext2D | null>(null);
const sizeRef = useRef({ w: 0, h: 0 }) as Box<{ w: number; h: number }>;
const colRef = useRef<Colors | null>(null);
const gridRef = useRef(new Uint8Array(0)) as Box<Uint8Array>;
const dimRef = useRef({ cols: 0, rows: 0 }) as Box<{ cols: number; rows: number }>;
const cellRef = useRef(cellPx) as Box<number>;
const eatRef = useRef(eatP) as Box<number>;
const spawnRef = useRef(spawnEvery) as Box<number>;
const randRef = useRef(makePRNG(0x318a07)) as Box<() => number>;
const tickRef = useRef(0) as Box<number>;
const imgRef = useRef<ImageData | null>(null) as Box<ImageData | null>;
const rafRef = useRef(0) as Box<number>;
const [still, setStill] = useState(false);
const vars: Vars = { "--duration": duration, "--easing": easing, "--color": color };
function reduced(): boolean {
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
function tokRGB(root: HTMLDivElement, name: string): RGB {
const s = getComputedStyle(root).getPropertyValue(name).trim();
const hx = s.length === 4
? s.charAt(1) + s.charAt(1) + s.charAt(2) + s.charAt(2) + s.charAt(3) + s.charAt(3)
: s.slice(1);
return [parseInt(hx.slice(0, 2), 16), parseInt(hx.slice(2, 4), 16), parseInt(hx.slice(4, 6), 16)];
}
function get(x: number, y: number): number {
const { cols, rows } = dimRef.current;
if (x < 0 || x >= cols || y < 0 || y >= rows) return STONE;
return gridRef.current[y * cols + x];
}
function set(x: number, y: number, v: number): void {
const { cols, rows } = dimRef.current;
if (x < 0 || x >= cols || y < 0 || y >= rows) return;
gridRef.current[y * cols + x] = v;
}
function buildTerrain(): void {
const rand = randRef.current;
const { cols, rows } = dimRef.current;
const seg = Math.max(1, Math.floor(cols / 4));
for (let x = 0; x < cols; x++) {
const tier = Math.min(3, Math.floor(x / seg));
const top = Math.floor(rows * (0.32 + tier * 0.15));
for (let y = top; y < rows; y++) {
const depth = y - top;
set(x, y, depth < 2 ? DIRT : STONE);
}
const sandDepth = 1 + (rand() < 0.4 ? 1 : 0);
for (let sy = 0; sy < sandDepth; sy++) {
const ty = top - 1 - sy;
if (ty >= 0) set(x, ty, SAND);
}
}
}
function isErodible(m: number): boolean { return m === DIRT || m === STONE || m === SAND; }
function moveInto(x: number, y: number, nx: number, ny: number, m: number): boolean {
if (get(nx, ny) !== EMPTY) return false;
set(x, y, EMPTY);
set(nx, ny, m);
return true;
}
function updateAcid(x: number, y: number, dir: number): void {
const rand = randRef.current;
const spots: [number, number][] = [[x, y + 1], [x - 1, y], [x + 1, y]];
let melted = false;
for (let i = 0; i < spots.length; i++) {
if (isErodible(get(spots[i][0], spots[i][1]))) { set(spots[i][0], spots[i][1], EMPTY); melted = true; }
}
if (melted && rand() < eatRef.current) { set(x, y, EMPTY); return; }
if (moveInto(x, y, x, y + 1, ACID)) return;
const first = dir > 0 ? -1 : 1;
if (moveInto(x, y, x + first, y + 1, ACID)) return;
if (moveInto(x, y, x - first, y + 1, ACID)) return;
if (moveInto(x, y, x + first, y, ACID)) return;
moveInto(x, y, x - first, y, ACID);
}
function updateSand(x: number, y: number, dir: number): void {
if (moveInto(x, y, x, y + 1, SAND)) return;
const first = dir > 0 ? -1 : 1;
if (moveInto(x, y, x + first, y + 1, SAND)) return;
moveInto(x, y, x - first, y + 1, SAND);
}
function update(): void {
const rand = randRef.current;
const { cols, rows } = dimRef.current;
tickRef.current++;
const tick = tickRef.current;
if (tick % spawnRef.current === 0) {
const leftX = 1 + Math.floor(rand() * 3);
const rightX = cols - 2 - Math.floor(rand() * 3);
if (get(leftX, 0) === EMPTY) set(leftX, 0, ACID);
if (get(rightX, 0) === EMPTY) set(rightX, 0, ACID);
}
const dir = tick % 2 === 0 ? 1 : -1;
for (let y = rows - 1; y >= 0; y--) {
if (dir > 0) {
for (let x = 0; x < cols; x++) {
const m = get(x, y);
if (m === ACID) updateAcid(x, y, dir);
else if (m === SAND) updateSand(x, y, dir);
}
} else {
for (let x = cols - 1; x >= 0; x--) {
const m = get(x, y);
if (m === ACID) updateAcid(x, y, dir);
else if (m === SAND) updateSand(x, y, dir);
}
}
}
}
function shade(c: RGB, amt: number): RGB {
return [
Math.max(0, Math.min(255, c[0] + amt)),
Math.max(0, Math.min(255, c[1] + amt)),
Math.max(0, Math.min(255, c[2] + amt)),
];
}
function draw(t: number): void {
const ctx = ctxRef.current;
const col = colRef.current;
if (!ctx || !col) return;
const W = sizeRef.current.w, H = sizeRef.current.h;
const CELL = cellRef.current;
const { cols, rows } = dimRef.current;
let img = imgRef.current;
if (!img || img.width !== W || img.height !== H) {
img = ctx.createImageData(W, H);
imgRef.current = img;
}
const buf = img.data;
const grid = gridRef.current;
const wave = Math.sin(t * 0.00055) * 0.5 + 0.5;
const cx = W * (0.5 + 0.34 * Math.sin(t * 0.00042));
const cy = H * (0.5 + 0.34 * Math.cos(t * 0.00036));
const maxD = Math.hypot(W, H) * 0.6;
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
const m = grid[y * cols + x];
const px0 = x * CELL, py0 = y * CELL;
const d = Math.hypot(px0 - cx, py0 - cy) / maxD;
const glow = Math.max(0, 1 - d) * (0.08 + 0.05 * wave);
let c: RGB;
if (m === EMPTY) {
c = shade(col.night, Math.round(glow * 40));
} else if (m === DIRT) {
c = shade(col.dirt, ((x * 7 + y * 13) % 5) - 2 + Math.round(glow * 14));
} else if (m === STONE) {
c = shade(col.stone, ((x * 11 + y * 5) % 5) - 2 + Math.round(glow * 10));
} else if (m === SAND) {
c = ((x + y) % 3 === 0)
? shade(col.sandA, Math.round(glow * 18))
: shade(col.sandB, Math.round(glow * 18));
} else {
const flick = Math.sin(t * 0.02 + x * 0.7 + y * 0.5) * 0.5 + 0.5;
c = shade(flick > 0.5 ? col.acidB : col.acidA, Math.round(glow * 20));
}
for (let cyi = 0; cyi < CELL; cyi++) {
const rowOff = ((py0 + cyi) * W + px0) * 4;
for (let cxi = 0; cxi < CELL; cxi++) {
const o = rowOff + cxi * 4;
buf[o] = c[0]; buf[o + 1] = c[1]; buf[o + 2] = c[2]; buf[o + 3] = 255;
}
}
}
}
ctx.putImageData(img, 0, 0);
}
function fit(): void {
const field = fieldRef.current;
const cv = cvRef.current;
if (!field || !cv) return;
const ctx = cv.getContext("2d");
if (!ctx) return;
const r = field.getBoundingClientRect();
sizeRef.current.w = Math.max(1, Math.round(r.width));
sizeRef.current.h = Math.max(1, Math.round(r.height));
cv.width = sizeRef.current.w;
cv.height = sizeRef.current.h;
ctxRef.current = ctx;
const CELL = cellRef.current;
dimRef.current.cols = Math.max(1, Math.floor(sizeRef.current.w / CELL));
dimRef.current.rows = Math.max(1, Math.floor(sizeRef.current.h / CELL));
gridRef.current = new Uint8Array(dimRef.current.cols * dimRef.current.rows);
imgRef.current = null;
buildTerrain();
}
let last = 0, acc = 0;
const STEP = 1000 / 60;
function frame(now: number): void {
if (!last) last = now;
acc += now - last;
last = now;
let guard = 0;
while (acc >= STEP && guard < 6) { update(); acc -= STEP; guard++; }
draw(now);
rafRef.current = requestAnimationFrame(frame);
}
useEffect(() => {
const root = rootRef.current;
if (!root) return;
cellRef.current = cellPx;
eatRef.current = eatP;
spawnRef.current = spawnEvery;
randRef.current = makePRNG(0x318a07);
tickRef.current = 0;
colRef.current = {
night: tokRGB(root, "--sand-night"),
dirt: tokRGB(root, "--sand-wood"),
stone: tokRGB(root, "--sand-stone"),
sandA: tokRGB(root, "--sand-grain"),
sandB: tokRGB(root, "--sand-gold"),
acidA: tokRGB(root, "--sand-acid"),
acidB: tokRGB(root, "--sand-glow"),
mist: tokRGB(root, "--sand-mist"),
};
fit();
function onResize(): void { last = 0; acc = 0; fit(); }
window.addEventListener("resize", onResize);
if (reduced()) {
for (let i = 0; i < 90; i++) update();
draw(1500);
setStill(true);
} else {
rafRef.current = requestAnimationFrame(frame);
}
return () => {
window.removeEventListener("resize", onResize);
cancelAnimationFrame(rafRef.current);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [eatP, spawnEvery, cellPx]);
const rootCls = still ? `${styles.root} ${styles.isStill}` : styles.root;
return (
<main className={styles.stage}>
<div className={rootCls} ref={rootRef} style={vars}>
<p className={styles.hint}>
<span>산이 흙과 돌을 지우며 통로를 팝니다</span>
</p>
<div className={styles.field} ref={fieldRef} role="application" aria-label={FIELD_LABEL} tabIndex={0}>
<canvas className={styles.cv} ref={cvRef}></canvas>
</div>
<div className={styles.bar}>
<span className={styles.meta}><b className={styles.val}>{Math.round(eatP * 100)}</b>% 부식 확률 · 산-흙-돌 반응</span>
<span className={styles.metaDim}>canvas · ImageData putImageData · requestAnimationFrame</span>
</div>
</div>
</main>
);
}07 酸の腐食 — 出会った素材を消す反応規則 — 計測 累積面積 30.269% · 動いたフレーム 23/23GODRICH オリジナル · SCSS と React は zip に同梱 · フォーリングサンド(falling sand simulator) 9種の作り方
このデモが属する記事
フォーリングサンド(falling sand simulator) 9種の作り方フォーリングサンド(falling sand simulator)とは、画面上部から落ちる粒を演出ではなく計算で積もらせる仕組みです。ライブラリ·WebGL なしでセル1つの規則4つ(下・左下・右下・横)で砂が積み、水が流れ、火が広がります この記事のデモをすべて見る


