09ディープフィールドシーン — 何億年も込めた銀河進化の舞台
暗い背景に星雲スプライトを敷き、複数の銀河が次々すれ違い合体する場面をシーケンスに並べると、宇宙望遠鏡のディープフィールド写真の構図を1枚のキャンバスに移した表紙ヒーローになります。
使いどころ表紙ヒーロー、スプラッシュ
createRadialGradientCanvasRenderingContext2DrequestAnimationFrame

<main class="stage">
<div class="gx is-demo" id="gxRoot">
<p class="gx__hint">
<span>星雲を敷いた深宇宙で、複数の銀河が次々すれ違い合体する進化シーケンスです</span>
</p>
<div class="gx__field" id="gxField" role="application" aria-label="深宇宙銀河進化ラボ" tabindex="0">
<canvas class="gx__cv" id="gxCv"></canvas>
</div>
<div class="gx__bar">
<span class="gx__meta">銀河3つ・星330個</span>
<span class="gx__meta gx__meta--dim">canvas · nebula sprites · requestAnimationFrame</span>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 심우주 씬(09). @keyframes 를 두지 않는다 —
// 움직임은 전부 캔버스 rAF 루프(성운 스프라이트 + 은하 3개 O(N²) 적분 → 점 그리기)가 만든다.
// 무대는 편 공통 심우주 팔레트. 파스텔 주색을 --gx-* 로 편 전체(01~09) 공통 규격.
$duration: $dur-loop;
$easing: $ease-spring;
$color: $subject-lilac;
// ── 편 공통 심우주 팔레트(BD9~11 원칙: 편마다 다시 정하지 않는다) ──
$gx-stage: #12101c; // 심우주 자정 — 저채도 짙은 남보라 (파스텔 검사 무관: 저채도·저명도)
@include stage($gx-stage);
$gx-ink: #0b0a13; // 관측창 바닥 — 무대보다 한 톤 어두운 보라검
$gx-glow: #b7c8ff; // 은하 A 별빛 — 파스텔 페리윙클(고명도라 vivid 아님)
$gx-hot: #ffdf9e; // 은하 B 코어 — 파스텔 앰버
$gx-text: #d8d4e6; // 라벨 글자 — 밝은 회보라
.gx {
// 렌더러가 읽는 색 — JS 는 getComputedStyle 로 --gx-* 를 받아 쓴다
--gx-ink: #{$gx-ink};
--gx-glow: #{$gx-glow};
--gx-hot: #{$gx-hot};
--gx-tail: #{$subject-pink};
display: flex; flex-direction: column; gap: $sp-2;
width: 100%; max-width: 424px;
}
.gx__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: $gx-text;
}
.gx__field {
position: relative; height: 180px;
border-radius: $r-card; overflow: hidden;
background: $gx-ink;
box-shadow: inset 0 0 0 1px rgba($gx-text, .18);
}
.gx__field:focus-visible { outline: 2px solid $gx-glow; outline-offset: 2px; }
.gx__cv { display: block; width: 100%; height: 100%; }
.gx__bar { display: flex; align-items: baseline; justify-content: space-between; gap: $sp-2; }
.gx__meta { font-size: 10px; font-weight: 500; color: rgba($gx-text, .72); }
.gx__meta--dim { font-size: 10px; }
@media (max-width: 340px) {
.gx { gap: $sp-1; }
.gx__field { height: 100px; }
.gx__meta--dim { display: none; }
}
// reduce — rAF 를 돌리지 않고 궤적이 다 쌓인 한 장만 남는다.
@media (prefers-reduced-motion: reduce) {
.gx.is-still .gx__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: #12101c;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.gx {
--gx-ink: #0b0a13;
--gx-glow: #b7c8ff;
--gx-hot: #ffdf9e;
--gx-tail: #ff9ebb;
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
max-width: 424px;
}
.gx__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: #d8d4e6;
}
.gx__field {
position: relative;
height: 180px;
border-radius: 16px;
overflow: hidden;
background: #0b0a13;
box-shadow: inset 0 0 0 1px rgba(216, 212, 230, 0.18);
}
.gx__field:focus-visible {
outline: 2px solid #b7c8ff;
outline-offset: 2px;
}
.gx__cv {
display: block;
width: 100%;
height: 100%;
}
.gx__bar {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
}
.gx__meta {
font-size: 10px;
font-weight: 500;
color: rgba(216, 212, 230, 0.72);
}
.gx__meta--dim {
font-size: 10px;
}
@media (max-width: 340px) {
.gx {
gap: 4px;
}
.gx__field {
height: 100px;
}
.gx__meta--dim {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
.gx.is-still .gx__field {
cursor: default !important;
}
}// 심우주 씬(09) — 성운을 깐 무대에 은하 3개를 놓는 장면.
// 무대: createRadialGradient 로 구운 성운 스프라이트 3장(청록·장미·앰버)을
// 미리 별도 캔버스에 구워 두고 매 프레임 drawImage 로 얹는다 — 매 프레임 그라디언트를
// 다시 만들지 않아 330개 별 계산과 함께 돌아도 프레임이 나간다.
// 은하 3개(별 110+110+110)는 01 과 같은 전 쌍 O(N²) 뉴턴 중력 + leapfrog 으로 적분한다(근사 아님).
// 궤도는 대각선으로 엇갈리게 심는다 — 스침 → 조석 꼬리 → 합체(타원화) 순서의 진화 시퀀스가
// 한 루프 안에 차례로 나타난다. 별 색은 은하마다 다른 파스텔 3색.
(function () {
// ── 변형 상수 블록 — 아래 값 하나만 바꿔 변형을 만든다 ──
var NSTARS = 330; // 세 은하 합계 별 수
var NEBULA = 3; // 성운 스프라이트 수 — 변형 "성운 밀도"
// ────────────────────────────────────────────────────
var root = document.getElementById('gxRoot');
var field = document.getElementById('gxField');
var cv = document.getElementById('gxCv');
var css = getComputedStyle(root);
function tokRGB(name) {
var s = css.getPropertyValue(name).trim();
var 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)];
}
var C_INK = tokRGB('--gx-ink');
var C_GLOW = tokRGB('--gx-glow');
var C_HOT = tokRGB('--gx-hot');
var C_TAIL = tokRGB('--gx-tail');
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var raf = 0, t0 = -1;
var W = 0, H = 0, dpr = 1;
var chainCv, chainCtx;
var nebCvs = []; // 구워 둔 성운 스프라이트
var N = 0, X = [], Y = [], VX = [], VY = [], GID = []; // GID — 별이 속한 은하(색·코어 계산용)
function fit() {
var r = field.getBoundingClientRect();
W = Math.round(r.width); H = Math.round(r.height);
dpr = Math.min(2, window.devicePixelRatio || 1);
cv.width = W * dpr; cv.height = H * dpr;
cv.style.width = '100%'; cv.style.height = '100%';
chainCv = document.createElement('canvas');
chainCv.width = W * dpr; chainCv.height = H * dpr;
chainCtx = chainCv.getContext('2d');
chainCtx.scale(dpr, dpr);
bakeNebulas();
}
function mulberry32(seed) {
return function () {
seed |= 0; seed = (seed + 0x6D2B79F5) | 0;
var t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// 성운 스프라이트 — createRadialGradient 로 한 번 구워 둔다(매 프레임 재계산 없음)
function bakeNebulas() {
nebCvs = [];
var rnd = mulberry32(77);
var cols = [C_GLOW, C_TAIL, C_HOT];
for (var k = 0; k < NEBULA; k++) {
var s = document.createElement('canvas');
var sz = Math.max(160, Math.round(Math.min(W, H) * (0.55 + rnd() * 0.5)));
s.width = sz; s.height = sz;
var sc = s.getContext('2d');
var g = sc.createRadialGradient(sz * 0.5, sz * 0.5, 0, sz * 0.5, sz * 0.5, sz * 0.5);
var c = cols[k % 3];
g.addColorStop(0.00, rgba(c, 0.16));
g.addColorStop(0.35, rgba(c, 0.07));
g.addColorStop(0.70, rgba(c, 0.02));
g.addColorStop(1.00, rgba(c, 0));
sc.fillStyle = g;
sc.fillRect(0, 0, sz, sz);
nebCvs.push({ cv: s, x: 0.12 + rnd() * 0.76, y: 0.10 + rnd() * 0.80, sz: sz });
}
}
// G·질량은 캔버스 픽셀 단위 시뮬레이션 값(물리 상수 아님 — 글에서 설명)
var G = 120.0, SOFT2 = 20;
var DT = 1 / 60;
var AX = [], AY = [];
function accel() {
// 전 쌍 O(N²) 뉴턴 — a_i = Σ G·(x_j - x_i)/(|d|²+ε²)^1.5 (근사 아님)
var i, j, dx, dy, d2, inv, f;
for (i = 0; i < N; i++) { AX[i] = 0; AY[i] = 0; }
for (i = 0; i < N; i++) {
for (j = i + 1; j < N; j++) {
dx = X[j] - X[i]; dy = Y[j] - Y[i];
d2 = dx * dx + dy * dy + SOFT2;
inv = 1 / Math.sqrt(d2);
f = G * inv * inv * inv;
AX[i] += dx * f; AY[i] += dy * f;
AX[j] -= dx * f; AY[j] -= dy * f;
}
}
}
var aReady = false;
function stepLeap() {
if (!aReady) { accel(); aReady = true; }
var h = DT * 0.5;
for (var i = 0; i < N; i++) {
VX[i] += AX[i] * h; VY[i] += AY[i] * h;
X[i] += VX[i] * DT; Y[i] += VY[i] * DT;
}
accel();
for (var j = 0; j < N; j++) {
VX[j] += AX[j] * h; VY[j] += AY[j] * h;
}
}
function placeDisk(cx, cy, R, count, phase, dvx, dvy, dir, gid, rnd) {
var M = R * R * 0.90;
for (var i = 0; i < count; i++) {
var r = R * Math.sqrt(rnd());
var a = phase + (i / count) * Math.PI * 2 + rnd() * 0.5;
var v = Math.sqrt(M / Math.max(r, 6)) * dir;
X.push(cx + Math.cos(a) * r);
Y.push(cy + Math.sin(a) * r);
VX.push(dvx * R * 0.30 + -Math.sin(a) * v + (rnd() - 0.5) * 2);
VY.push(dvy * R * 0.30 + Math.cos(a) * v + (rnd() - 0.5) * 2);
GID.push(gid);
N++;
}
}
function seed() {
// 세 은하 — 대각선으로 엇갈리는 궤도. 시간이 흐르면 두 쌍이 스치고 세째가 합류한다.
// 산개 별(STRAY)을 섞어 궤적이 캔버스 구석까지 뻗게 한다 — 심우주의 백업 별밭 역할
X = []; Y = []; VX = []; VY = []; GID = []; N = 0; aReady = false;
var rnd = mulberry32(29);
var per = Math.floor(NSTARS / 3);
var R = Math.min(W, H) * 0.28;
placeDisk(W * 0.22, H * 0.26, R, per - 28, 0, 0.62, -0.40, 1.00, 0, rnd);
placeDisk(W * 0.78, H * 0.52, R, per - 28, Math.PI, -0.62, 0.40, 0.85, 1, rnd);
placeDisk(W * 0.38, H * 0.82, R, NSTARS - 2 * per - 28, Math.PI * 0.5, 0.34, -0.62, 0.92, 2, rnd);
// 산개 별 84개 — 세 은하 사이 공간을 채워 스치는 순간 전체가 살아 난다
for (var s = 0; s < 84; s++) {
var sx = W * (0.04 + rnd() * 0.92);
var sy = H * (0.06 + rnd() * 0.88);
var sa = rnd() * Math.PI * 2;
var sv = 38 + rnd() * 34;
X.push(sx); Y.push(sy);
VX.push(Math.cos(sa) * sv); VY.push(Math.sin(sa) * sv);
GID.push(s % 3);
N++;
}
}
function rgba(c, a) { return 'rgba(' + c[0] + ',' + c[1] + ',' + c[2] + ',' + a + ')'; }
function gcol(gid) { return [C_GLOW, C_TAIL, C_HOT][gid % 3]; }
function decay() {
chainCtx.setTransform(1, 0, 0, 1, 0, 0);
chainCtx.globalCompositeOperation = 'destination-out';
chainCtx.fillStyle = 'rgba(0,0,0,0.013)';
chainCtx.fillRect(0, 0, W * dpr, H * dpr);
chainCtx.globalCompositeOperation = 'source-over';
chainCtx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
var prev = null;
function stamp() {
if (prev) {
for (var i = 0; i < N; i++) {
chainCtx.strokeStyle = rgba(gcol(GID[i]), 0.26);
chainCtx.lineWidth = 1.7;
chainCtx.beginPath();
chainCtx.moveTo(prev[0][i], prev[1][i]);
chainCtx.lineTo(X[i], Y[i]);
chainCtx.stroke();
}
}
if (!prev) { prev = [X.slice(), Y.slice()]; }
else { prev[0] = X.slice(); prev[1] = Y.slice(); }
}
function draw() {
var ctx = cv.getContext('2d'); // CanvasRenderingContext2D — 이 데모의 그리기 문맥
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
// 심우주 배경 — 잉크
ctx.fillStyle = rgb(C_INK);
ctx.fillRect(0, 0, W, H);
// 먼 별밭(정적·시드 고정)
var rnd = mulberry32(31);
ctx.fillStyle = rgba(C_GLOW, 0.35);
for (var k = 0; k < 55; k++) {
var bx = rnd() * W, by = rnd() * H, br = rnd() * 0.8 + 0.3;
ctx.globalAlpha = 0.10 + rnd() * 0.24;
ctx.beginPath(); ctx.arc(bx, by, br, 0, Math.PI * 2); ctx.fill();
}
ctx.globalAlpha = 1;
// 성운 스프라이트 — 구워 둔 것을 얹는다. 아주 느린 드리프트로 심우주 배경 자체를 살린다
for (var n = 0; n < nebCvs.length; n++) {
var nb = nebCvs[n];
var ph = n * 2.1;
var dx = Math.sin(simSteps * 0.0031 + ph) * W * 0.035;
var dy = Math.cos(simSteps * 0.0026 + ph * 1.7) * H * 0.045;
var sc = 1 + Math.sin(simSteps * 0.0022 + ph) * 0.10;
var sz2 = nb.sz * sc;
ctx.drawImage(nb.cv, W * nb.x + dx - sz2 * 0.5, H * nb.y + dy - sz2 * 0.5, sz2, sz2);
}
// 궤도 잔상
ctx.drawImage(chainCv, 0, 0, W, H);
// 별 — 은하별 파스텔 3색
for (var i = 0; i < N; i++) {
var col = gcol(GID[i]);
ctx.fillStyle = rgba(col, 0.10);
ctx.beginPath(); ctx.arc(X[i], Y[i], 3.2, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = rgba(col, 0.6);
ctx.beginPath(); ctx.arc(X[i], Y[i], 1.6, 0, Math.PI * 2); ctx.fill();
}
// 각 은하의 코어 — 같은 색 밝은 점(무게중심)
for (var g = 0; g < 3; g++) {
var sx = 0, sy = 0, c = 0;
for (var i2 = 0; i2 < N; i2++) {
if (GID[i2] !== g) continue;
sx += X[i2]; sy += Y[i2]; c++;
}
if (!c) continue;
ctx.fillStyle = rgba(gcol(g), 0.9);
ctx.beginPath(); ctx.arc(sx / c, sy / c, 2.2, 0, Math.PI * 2); ctx.fill();
}
}
function rgb(c) { return 'rgb(' + c[0] + ',' + c[1] + ',' + c[2] + ')'; }
var simSteps = 0;
function frame(now) {
if (t0 < 0) t0 = now;
var loop = ((now - t0) / 1000) % 4.5; // 4.5초 루프 — 스침 → 꼬리 → 합류 순서가 다 보이게
var target = Math.floor(loop / DT);
while (simSteps < target) { stepLeap(); simSteps++; stamp(); }
if (target < simSteps - 3) { seed(); simSteps = 0; prev = null; chainCtx.clearRect(0, 0, W, H); }
decay();
draw();
raf = requestAnimationFrame(frame);
}
function stillFrame() {
// reduce — 첫 스침이 일어난 장면까지 적분한 뒤 한 장 고정
for (var s = 0; s < 200; s++) { stepLeap(); stamp(); }
draw();
}
window.addEventListener('resize', function () {
fit(); seed(); simSteps = 0; prev = null; aReady = false;
if (reduce) stillFrame();
});
fit();
seed();
if (reduce) {
stillFrame();
root.classList.add('is-still');
} else {
raf = requestAnimationFrame(frame);
}
})();// GalaxyNbodyDeepFieldScene — vanilla 판(run/322/demo/09-galaxy-nbody-deep-field-scene/index.html) 의 React 포트.
// 심우주 씬 — 성운을 깐 무대에 은하 3개를 놓는 장면.
// 무대: createRadialGradient 로 구운 성운 스프라이트 3장(청록·장미·앰버)을
// 미리 별도 캔버스에 구워 두고 매 프레임 drawImage 로 얹는다 — 매 프레임 그라디언트를
// 다시 만들지 않아 330개 별 계산과 함께 돌아도 프레임이 나간다.
// 은하 3개(별 110+110+110)는 01 과 같은 전 쌍 O(N²) 뉴턴 중력 + leapfrog 으로 적분한다(근사 아님).
// 궤도는 대각선으로 엇갈리게 심는다 — 스침 → 조석 꼬리 → 합체(타원화) 순서의 진화 시퀀스가
// 한 루프 안에 차례로 나타난다. 별 색은 은하마다 다른 파스텔 3색.
import { useEffect, useRef, useState } from "react";
import type { CSSProperties } from "react";
import styles from "./GalaxyNbodyDeepFieldScene.module.scss";
export type GalaxyNbodyDeepFieldSceneProps = {
duration?: string;
easing?: string;
color?: string;
nstars?: number; // 세 은하 합계 별 수
nebula?: number; // 성운 스프라이트 수 — 변형 "성운 밀도"
};
type Vars = CSSProperties & { "--duration"?: string; "--easing"?: string; "--color"?: string };
type Box<T> = { current: T };
type RGB = [number, number, number];
type SimG = { N: number; X: number[]; Y: number[]; VX: number[]; VY: number[]; GID: number[] };
type NebSprite = { cv: HTMLCanvasElement; x: number; y: number; sz: number };
const FIELD_LABEL = "심우주 은하 진화 실험판";
// G·질량은 캔버스 픽셀 단위 시뮬레이션 값(물리 상수 아님 — 글에서 설명)
const G = 120.0, SOFT2 = 20;
const DT = 1 / 60;
function mulberry32(seed: number): () => number {
let s = seed | 0;
return function (): number {
s = (s + 0x6D2B79F5) | 0;
let t = Math.imul(s ^ (s >>> 15), 1 | s);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export default function GalaxyNbodyDeepFieldScene({
duration = "2s",
easing = "cubic-bezier(.2, .8, .2, 1)",
color = "#b7c8ff",
nstars = 330,
nebula = 3
}: GalaxyNbodyDeepFieldSceneProps) {
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 colRef = useRef<{ ink: RGB; glow: RGB; hot: RGB; tail: RGB } | null>(null);
const chainCvRef = useRef<HTMLCanvasElement | null>(null);
const chainCtxRef = useRef<CanvasRenderingContext2D | null>(null);
const nebRef = useRef<NebSprite[]>([]) as Box<NebSprite[]>; // 구워 둔 성운 스프라이트
const nstarsRef = useRef(nstars) as Box<number>;
const nebulaRef = useRef(nebula) as Box<number>;
const wRef = useRef(0) as Box<number>;
const hRef = useRef(0) as Box<number>;
const dprRef = useRef(1) as Box<number>;
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 rgba(c: RGB, a: number): string {
return "rgba(" + c[0] + "," + c[1] + "," + c[2] + "," + a + ")";
}
function rgb(c: RGB): string {
return "rgb(" + c[0] + "," + c[1] + "," + c[2] + ")";
}
function gcol(gid: number): RGB {
const col = colRef.current;
if (!col) return [0, 0, 0];
return [col.glow, col.tail, col.hot][gid % 3];
}
const simRef = useRef({ N: 0, X: [] as number[], Y: [] as number[], VX: [] as number[], VY: [] as number[], GID: [] as number[] }) as Box<SimG>;
const AXRef = useRef<number[]>([]) as Box<number[]>;
const AYRef = useRef<number[]>([]) as Box<number[]>;
const aReadyRef = useRef(false) as Box<boolean>;
const prevRef = useRef<[number[], number[]] | null>(null);
const simStepsRef = useRef(0) as Box<number>;
function fit(): void {
const field = fieldRef.current;
const cv = cvRef.current;
if (!field || !cv) return;
const r = field.getBoundingClientRect();
const W = Math.round(r.width), H = Math.round(r.height);
const dpr = Math.min(2, window.devicePixelRatio || 1);
wRef.current = W; hRef.current = H; dprRef.current = dpr;
cv.width = W * dpr; cv.height = H * dpr;
cv.style.width = "100%"; cv.style.height = "100%";
ctxRef.current = cv.getContext("2d");
const chainCv = document.createElement("canvas");
chainCv.width = W * dpr; chainCv.height = H * dpr;
const chainCtx = chainCv.getContext("2d");
if (chainCtx) chainCtx.scale(dpr, dpr);
chainCvRef.current = chainCv;
chainCtxRef.current = chainCtx;
bakeNebulas();
}
// 성운 스프라이트 — createRadialGradient 로 한 번 구워 둔다(매 프레임 재계산 없음)
function bakeNebulas(): void {
const col = colRef.current;
if (!col) return;
nebRef.current = [];
const rnd = mulberry32(77);
const W = wRef.current, H = hRef.current;
const cols: RGB[] = [col.glow, col.tail, col.hot];
for (let k = 0; k < nebulaRef.current; k++) {
const s = document.createElement("canvas");
const sz = Math.max(160, Math.round(Math.min(W, H) * (0.55 + rnd() * 0.5)));
s.width = sz; s.height = sz;
const sc = s.getContext("2d");
if (!sc) continue;
const g = sc.createRadialGradient(sz * 0.5, sz * 0.5, 0, sz * 0.5, sz * 0.5, sz * 0.5);
const c = cols[k % 3];
g.addColorStop(0.00, rgba(c, 0.16));
g.addColorStop(0.35, rgba(c, 0.07));
g.addColorStop(0.70, rgba(c, 0.02));
g.addColorStop(1.00, rgba(c, 0));
sc.fillStyle = g;
sc.fillRect(0, 0, sz, sz);
nebRef.current.push({ cv: s, x: 0.12 + rnd() * 0.76, y: 0.10 + rnd() * 0.80, sz: sz });
}
}
function accel(): void {
// 전 쌍 O(N²) 뉴턴 — a_i = Σ G·(x_j - x_i)/(|d|²+ε²)^1.5 (근사 아님)
const sim = simRef.current;
const AX = AXRef.current, AY = AYRef.current;
const N = sim.N;
let i: number, j: number, dx: number, dy: number, d2: number, inv: number, f: number;
for (i = 0; i < N; i++) { AX[i] = 0; AY[i] = 0; }
for (i = 0; i < N; i++) {
for (j = i + 1; j < N; j++) {
dx = sim.X[j] - sim.X[i]; dy = sim.Y[j] - sim.Y[i];
d2 = dx * dx + dy * dy + SOFT2;
inv = 1 / Math.sqrt(d2);
f = G * inv * inv * inv;
AX[i] += dx * f; AY[i] += dy * f;
AX[j] -= dx * f; AY[j] -= dy * f;
}
}
}
function stepLeap(): void {
const sim = simRef.current;
const AX = AXRef.current, AY = AYRef.current;
if (!aReadyRef.current) { accel(); aReadyRef.current = true; }
const h = DT * 0.5;
for (let i = 0; i < sim.N; i++) {
sim.VX[i] += AX[i] * h; sim.VY[i] += AY[i] * h;
sim.X[i] += sim.VX[i] * DT; sim.Y[i] += sim.VY[i] * DT;
}
accel();
for (let j = 0; j < sim.N; j++) {
sim.VX[j] += AX[j] * h; sim.VY[j] += AY[j] * h;
}
}
function placeDisk(cx: number, cy: number, R: number, count: number, phase: number, dvx: number, dvy: number, dir: number, gid: number, rnd: () => number): void {
const sim = simRef.current;
const M = R * R * 0.90;
for (let i = 0; i < count; i++) {
const r = R * Math.sqrt(rnd());
const a = phase + (i / count) * Math.PI * 2 + rnd() * 0.5;
const v = Math.sqrt(M / Math.max(r, 6)) * dir;
sim.X.push(cx + Math.cos(a) * r);
sim.Y.push(cy + Math.sin(a) * r);
sim.VX.push(dvx * R * 0.30 + -Math.sin(a) * v + (rnd() - 0.5) * 2);
sim.VY.push(dvy * R * 0.30 + Math.cos(a) * v + (rnd() - 0.5) * 2);
sim.GID.push(gid);
sim.N++;
}
}
function seed(): void {
// 세 은하 — 대각선으로 엇갈리는 궤도. 시간이 흐르면 두 쌍이 스치고 세째가 합류한다.
// 산개 별(STRAY)을 섞어 궤적이 캔버스 구석까지 뻗게 한다 — 심우주의 백업 별밭 역할
const sim = simRef.current;
sim.X = []; sim.Y = []; sim.VX = []; sim.VY = []; sim.GID = []; sim.N = 0;
aReadyRef.current = false;
const rnd = mulberry32(29);
const W = wRef.current, H = hRef.current;
const per = Math.floor(nstarsRef.current / 3);
const R = Math.min(W, H) * 0.28;
placeDisk(W * 0.22, H * 0.26, R, per - 28, 0, 0.62, -0.40, 1.00, 0, rnd);
placeDisk(W * 0.78, H * 0.52, R, per - 28, Math.PI, -0.62, 0.40, 0.85, 1, rnd);
placeDisk(W * 0.38, H * 0.82, R, nstarsRef.current - 2 * per - 28, Math.PI * 0.5, 0.34, -0.62, 0.92, 2, rnd);
// 산개 별 84개 — 세 은하 사이 공간을 채워 스치는 순간 전체가 살아 난다
for (let s = 0; s < 84; s++) {
const sx = W * (0.04 + rnd() * 0.92);
const sy = H * (0.06 + rnd() * 0.88);
const sa = rnd() * Math.PI * 2;
const sv = 38 + rnd() * 34;
sim.X.push(sx); sim.Y.push(sy);
sim.VX.push(Math.cos(sa) * sv); sim.VY.push(Math.sin(sa) * sv);
sim.GID.push(s % 3);
sim.N++;
}
}
function decay(): void {
const chainCtx = chainCtxRef.current;
const dpr = dprRef.current;
const W = wRef.current, H = hRef.current;
if (!chainCtx) return;
chainCtx.setTransform(1, 0, 0, 1, 0, 0);
chainCtx.globalCompositeOperation = "destination-out";
chainCtx.fillStyle = "rgba(0,0,0,0.013)";
chainCtx.fillRect(0, 0, W * dpr, H * dpr);
chainCtx.globalCompositeOperation = "source-over";
chainCtx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
function stamp(): void {
const chainCtx = chainCtxRef.current;
const col = colRef.current;
const sim = simRef.current;
const prev = prevRef.current;
if (!chainCtx || !col) return;
if (prev) {
for (let i = 0; i < sim.N; i++) {
chainCtx.strokeStyle = rgba(gcol(sim.GID[i]), 0.26);
chainCtx.lineWidth = 1.7;
chainCtx.beginPath();
chainCtx.moveTo(prev[0][i], prev[1][i]);
chainCtx.lineTo(sim.X[i], sim.Y[i]);
chainCtx.stroke();
}
}
if (!prev) prevRef.current = [sim.X.slice(), sim.Y.slice()];
else { prev[0] = sim.X.slice(); prev[1] = sim.Y.slice(); }
}
function draw(): void {
const ctx = ctxRef.current;
const chainCv = chainCvRef.current;
const col = colRef.current;
const dpr = dprRef.current;
const sim = simRef.current;
const W = wRef.current, H = hRef.current;
if (!ctx || !chainCv || !col) return;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
// 심우주 배경 — 잉크
ctx.fillStyle = rgb(col.ink);
ctx.fillRect(0, 0, W, H);
// 먼 별밭(정적·시드 고정)
const rnd = mulberry32(31);
ctx.fillStyle = rgba(col.glow, 0.35);
for (let k = 0; k < 55; k++) {
const bx = rnd() * W, by = rnd() * H, br = rnd() * 0.8 + 0.3;
ctx.globalAlpha = 0.10 + rnd() * 0.24;
ctx.beginPath(); ctx.arc(bx, by, br, 0, Math.PI * 2); ctx.fill();
}
ctx.globalAlpha = 1;
// 성운 스프라이트 — 구워 둔 것을 얹는다. 아주 느린 드리프트로 심우주 배경 자체를 살린다
const nebCvs = nebRef.current;
for (let n = 0; n < nebCvs.length; n++) {
const nb = nebCvs[n];
const ph = n * 2.1;
const dx = Math.sin(simStepsRef.current * 0.0031 + ph) * W * 0.035;
const dy = Math.cos(simStepsRef.current * 0.0026 + ph * 1.7) * H * 0.045;
const sc = 1 + Math.sin(simStepsRef.current * 0.0022 + ph) * 0.10;
const sz2 = nb.sz * sc;
ctx.drawImage(nb.cv, W * nb.x + dx - sz2 * 0.5, H * nb.y + dy - sz2 * 0.5, sz2, sz2);
}
// 궤도 잔상
ctx.drawImage(chainCv, 0, 0, W, H);
// 별 — 은하별 파스텔 3색
for (let i = 0; i < sim.N; i++) {
const c = gcol(sim.GID[i]);
ctx.fillStyle = rgba(c, 0.10);
ctx.beginPath(); ctx.arc(sim.X[i], sim.Y[i], 3.2, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = rgba(c, 0.6);
ctx.beginPath(); ctx.arc(sim.X[i], sim.Y[i], 1.6, 0, Math.PI * 2); ctx.fill();
}
// 각 은하의 코어 — 같은 색 밝은 점(무게중심)
for (let g = 0; g < 3; g++) {
let sx = 0, sy = 0, c = 0;
for (let i2 = 0; i2 < sim.N; i2++) {
if (sim.GID[i2] !== g) continue;
sx += sim.X[i2]; sy += sim.Y[i2]; c++;
}
if (!c) continue;
ctx.fillStyle = rgba(gcol(g), 0.9);
ctx.beginPath(); ctx.arc(sx / c, sy / c, 2.2, 0, Math.PI * 2); ctx.fill();
}
}
function stillFrame(): void {
// reduce — 첫 스침이 일어난 장면까지 적분한 뒤 한 장 고정
for (let s = 0; s < 200; s++) { stepLeap(); stamp(); }
draw();
}
let t0 = -1;
function frame(now: number): void {
if (t0 < 0) t0 = now;
const loop = ((now - t0) / 1000) % 4.5; // 4.5초 루프 — 스침 → 꼬리 → 합류 순서가 다 보이게
const target = Math.floor(loop / DT);
while (simStepsRef.current < target) { stepLeap(); simStepsRef.current++; stamp(); }
if (target < simStepsRef.current - 3) {
seed(); simStepsRef.current = 0; prevRef.current = null;
const chainCtx = chainCtxRef.current;
if (chainCtx) chainCtx.clearRect(0, 0, wRef.current, hRef.current);
}
decay();
draw();
rafRef.current = requestAnimationFrame(frame);
}
useEffect(() => {
const root = rootRef.current;
if (!root) return;
nstarsRef.current = nstars;
nebulaRef.current = nebula;
colRef.current = {
ink: tokRGB(root, "--gx-ink"),
glow: tokRGB(root, "--gx-glow"),
hot: tokRGB(root, "--gx-hot"),
tail: tokRGB(root, "--gx-tail"),
};
fit();
seed();
simStepsRef.current = 0;
prevRef.current = null;
function onResize(): void {
fit(); seed(); simStepsRef.current = 0; prevRef.current = null; aReadyRef.current = false;
if (reduced()) stillFrame();
}
window.addEventListener("resize", onResize);
if (reduced()) {
stillFrame();
setStill(true);
} else {
t0 = -1;
rafRef.current = requestAnimationFrame(frame);
}
return () => {
window.removeEventListener("resize", onResize);
cancelAnimationFrame(rafRef.current);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [nstars, nebula]);
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}>은하 3개 · 별 330개</span>
<span className={styles.metaDim}>canvas · nebula sprites · requestAnimationFrame</span>
</div>
</div>
</main>
);
}09 ディープフィールドシーン — 何億年も込めた銀河進化の舞台 — 計測 累積面積 30.189% · 動いたフレーム 23/23GODRICH オリジナル · SCSS と React は zip に同梱 · 銀河 シミュレーション 9種 — ぶつかり合う星が渦巻腕と潮汐尾を作る
このデモが属する記事
銀河 シミュレーション 9種 — ぶつかり合う星が渦巻腕と潮汐尾を作るライブラリ・WebGLなしで、星ひとつひとつに毎フレームニュートン重力を積分すると、2つの銀河がすれ違い潮汐尾を残して合体します。宇宙規模の引力がそのまま目の前で起こるシーンをコピペで持ち帰れます。銀河 シミュレーション とは、渦巻きの絵を この記事のデモをすべて見る


