03トーラスリング — ドーナツの距離式と縁の光
トーラスの距離式は2つの半径の差という短い式ひとつなのに、マーチすると穴の開いた立体がカメラ軌道に合わせて回ります。
使いどころロゴリング、ローディング場面の回転ドーナツ
ImageDataputImageDatarequestAnimationFrame

<main class="stage">
<div class="tg is-demo" id="tgRoot">
<p class="tg__hint">
<svg class="tg__ico" viewBox="0 0 256 256" aria-hidden="true"><g fill="currentColor"><path d="M128 24a104 104 0 0 0-38.6 201.3a8 8 0 0 0 11-6.9a8 8 0 0 1 5.8-6.9c1.7-.5 3.4-.9 5.1-1.4a8 8 0 0 0 5.4-10.2c-.2-.7-.5-1.5-.7-2.2a8 8 0 0 0-9.3-5.1c-1.3.3-2.7.6-4 .8a8 8 0 0 1-8.9-5.2a76.9 76.9 0 0 1-4.5-25.5c0-31.4 21.4-53.7 46.7-53.7s46.7 22.3 46.7 53.7a76.9 76.9 0 0 1-4.5 25.5a8 8 0 0 1-8.9 5.2c-1.3-.2-2.7-.5-4-.8a8 8 0 0 0-9.3 5.1c-.2.7-.5 1.5-.7 2.2a8 8 0 0 0 5.4 10.2c1.7.5 3.4.9 5.1 1.4a8 8 0 0 1 5.8 6.9a8 8 0 0 0 11 6.9A104 104 0 0 0 128 24" opacity=".2"/><path d="M176 156c0 15.5-12.4 23.7-24.4 23.7c-13.4 0-25.9-10.9-25.9-25.3s11.9-23.5 24.5-23.5c16.9 0 25.8 13.6 25.8 25.1m56-28a104 104 0 1 1-104 104a104 104 0 0 1 104-104m0 16a88 88 0 1 0 88 88a88 88 0 0 0-88-88m-56 12c0-17.2-13.5-33.1-33.4-33.1C120.9 106.9 104 124 104 146s15.5 37.7 36.9 37.7c21.4 0 35.1-19.7 35.1-37.7"/></g></svg>
<span>ドーナツの距離式は2つの半径の差 — 縁に光が付き、カメラが周回します</span>
</p>
<div class="tg__field" id="tgField" role="application" aria-label="トーラスリング実験盤" tabindex="0">
<canvas class="tg__cv" id="tgCv"></canvas>
</div>
<div class="tg__bar">
<span class="tg__meta">レンダーターゲット
<button class="tg__res" id="tgRes48" type="button" aria-pressed="false">48px</button>
<button class="tg__res is-on" id="tgRes96" type="button" aria-pressed="true">96px</button>
</span>
<span class="tg__meta">72ステップ・リムライト</span>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 토러스 링(03) — @keyframes 를 아예 두지 않는다(움직임은 rAF 캔버스 루프).
// 무대는 밝은 크림 톤. 링은 라일락 파스텔 + rim 빛 핑크 — 어두운 우주 톤 금지(파스텔 라인).
$duration: $dur-loop;
$easing: $ease-spring;
$color: $subject-lilac;
@include stage($stage-paper);
.tg {
--tg-ring: #{mix($subject-lilac, $stage-paper, 72%)}; // 링 본체 — 라일락 진한 파스텔
--tg-rim: #{$subject-pink}; // 가장자리 rim 빛 — 핑크
--tg-hilite: #{$subject-cream}; // 하이라이트·스펙큘 — 크림
--tg-sky: #{mix($subject-sky, $stage-paper, 30%)}; // 하늘 — 옅은 하늘색
display: flex; flex-direction: column; gap: $sp-2;
width: 100%; max-width: 424px;
}
.tg__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: $subject-ink;
}
.tg__ico { width: 16px; height: 16px; flex: 0 0 auto; color: $subject-ink; }
.tg__field {
position: relative; height: 180px;
border-radius: $r-card; overflow: hidden;
background: $stage-paper;
box-shadow: inset 0 0 0 1px rgba($subject-ink, .16);
cursor: crosshair; touch-action: none;
}
.tg__field:focus-visible { outline: 2px solid $subject-blue; outline-offset: 2px; }
.tg__cv { display: block; width: 100%; height: 100%; }
.tg__bar { display: flex; align-items: center; justify-content: space-between; gap: $sp-2; }
.tg__meta { font-size: 10px; font-weight: 500; color: rgba($subject-ink, .72); }
.tg__res {
margin: 0 0 0 $sp-1; padding: 0 $sp-2;
border: 0; border-radius: $r-pill;
font-family: inherit; font-weight: 700; font-size: 10px; line-height: 1.6;
color: $subject-ink; background: rgba($subject-ink, .08);
cursor: pointer;
}
.tg__res + .tg__res { margin-left: $sp-1; }
.tg__res.is-on { color: $subject-cream; background: $subject-blue-deep; }
.tg__res:focus-visible { outline: 2px solid $subject-blue; outline-offset: 2px; }
@media (max-width: 340px) {
.tg { gap: $sp-1; }
.tg__field { height: 100px; }
}
// reduce — rAF 없이 한 장. 커서 신호만 거둔다.
@media (prefers-reduced-motion: reduce) {
.tg.is-still .tg__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: #ffffff;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.tg {
--tg-ring: rgb(80.2352941176%, 73.1764705882%, 100%);
--tg-rim: #ff9ebb;
--tg-hilite: #fff7e6;
--tg-sky: rgb(82.9411764706%, 93.5294117647%, 100%);
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
max-width: 424px;
}
.tg__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: #17141a;
}
.tg__ico {
width: 16px;
height: 16px;
flex: 0 0 auto;
color: #17141a;
}
.tg__field {
position: relative;
height: 180px;
border-radius: 16px;
overflow: hidden;
background: #ffffff;
box-shadow: inset 0 0 0 1px rgba(23, 20, 26, 0.16);
cursor: crosshair;
touch-action: none;
}
.tg__field:focus-visible {
outline: 2px solid #2f6df6;
outline-offset: 2px;
}
.tg__cv {
display: block;
width: 100%;
height: 100%;
}
.tg__bar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.tg__meta {
font-size: 10px;
font-weight: 500;
color: rgba(23, 20, 26, 0.72);
}
.tg__res {
margin: 0 0 0 4px;
padding: 0 8px;
border: 0;
border-radius: 999px;
font-family: inherit;
font-weight: 700;
font-size: 10px;
line-height: 1.6;
color: #17141a;
background: rgba(23, 20, 26, 0.08);
cursor: pointer;
}
.tg__res + .tg__res {
margin-left: 4px;
}
.tg__res.is-on {
color: #fff7e6;
background: #0a4fe8;
}
.tg__res:focus-visible {
outline: 2px solid #2f6df6;
outline-offset: 2px;
}
@media (max-width: 340px) {
.tg {
gap: 4px;
}
.tg__field {
height: 100px;
}
}
@media (prefers-reduced-motion: reduce) {
.tg.is-still .tg__field {
cursor: default !important;
}
}// 토러스 링(03) — 도넛의 부호 거리는 두 반지름(큰 R·작은 r) 의 길이 차 공식 하나다.
// 가운데 축을 도는 점까지의 거리를 재고 r 을 빼면 구멍이 뚫린 입체가 나온다.
// rim light 근사: 법선과 시선의 내적이 0 에 가까운(가장자리를 스치는) 픽셀에 빛을 얹는다.
// レンダーターゲット 48/96 전환 — 변형 "해상도" 축. 같은 장면의 계산량 차이를 눈으로 본다.
(function () {
// ── 변형 상수 블록 — 아래 값 하나만 바꿔 변형 3종을 만든다 ──
var RT_W = 48; // レンダーターゲット 폭(기본) — 컨트롤로 48/96 전환된다
var STEPS = 72; // 최대 전진 스텝 수 — 구멍 안쪽 골을 파고들 때 스텝이 더 든다
var HIT_EPS = 0.004; // 표면 도달 판정 거리(월드 단위)
var LOOP_MS = 2000; // 미리보기 가상 포인터 주기
// ────────────────────────────────────────────────────
var root = document.getElementById('tgRoot');
var field = document.getElementById('tgField');
var cv = document.getElementById('tgCv');
var ctx = cv.getContext('2d');
var res48 = document.getElementById('tgRes48');
var res96 = document.getElementById('tgRes96');
var css = getComputedStyle(root);
function tokRGB(name) {
var s = css.getPropertyValue(name).trim();
if (s.charAt(0) === '#') {
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 p = s.replace(/[^\d,.]/g, '').split(',');
return [Number(p[0]) || 0, Number(p[1]) || 0, Number(p[2]) || 0];
}
var C_RING = tokRGB('--tg-ring');
var C_RIM = tokRGB('--tg-rim');
var C_HILITE = tokRGB('--tg-hilite');
var C_SKY = tokRGB('--tg-sky');
var TAU = Math.PI * 2;
var TOR_R = 1.05, TOR_r = 0.42; // 큰 반지름 R · 튜브 반지름 r
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var W = 0, H = 0;
var rtW = RT_W; // 현재 レンダーターゲット 폭
var buf, bctx, img;
var heading = 0.55;
var pitch = 0.27;
var px01 = 0.5, py01 = 0.5;
var manual = false;
var raf = 0, t0 = -1;
// 도넛(토러스) 거리 — XY 평면에 눕혔다. 두 반지름의 차가 전부다
function sdTorus(px, py, pz) {
var q = Math.sqrt(px * px + pz * pz) - TOR_R; // 가운데 축까지 거리 - R
return Math.sqrt(q * q + py * py) - TOR_r; // 튜브 중심에서 r 만큼 안쪽
}
function map(px, py, pz) { return sdTorus(px, py, pz); }
// 법선(전방 차분)
function normalAt(px, py, pz) {
var e = 0.0015;
var nx = map(px + e, py, pz) - map(px - e, py, pz);
var ny = map(px, py + e, pz) - map(px, py - e, pz);
var nz = map(px, py, pz + e) - map(px, py, pz - e);
var l = Math.sqrt(nx * nx + ny * ny + nz * nz) || 1;
return [nx / l, ny / l, nz / l];
}
function clamp255(v) { return v > 255 ? 255 : (v < 0 ? 0 : v); }
function draw(tSec) {
if (!img) return;
var data = img.data;
var bw = buf.width, bh = buf.height;
// 카메라 공전 — 자동 모드에서 토러스를 돈다
var ch = Math.cos(heading), sh = Math.sin(heading);
var cp = Math.cos(pitch), sp = Math.sin(pitch);
var D = 3.6;
var ex = sh * cp * D, ey = sp * D, ez = ch * cp * D;
var fx = -sh * cp, fy = -sp, fz = -ch * cp;
var rx = -fz, rz = fx;
var rl = Math.sqrt(rx * rx + rz * rz) || 1;
rx /= rl; rz /= rl;
var ux = -rz * fy, uy = rz * fx - rx * fz, uz = rx * fy;
// 광원 방향 — 위·왼쪽 앞
var lx = -0.44, ly = 0.72, lz = 0.54;
// rim 빛 방향 — 뒤·오른쪽 위(가장자리를 스치는 빛)
var rbx = 0.6, rby = 0.28, rbz = -0.75;
var i = 0;
for (var y = 0; y < bh; y++) {
var vy = (1 - 2 * (y + 0.5) / bh) * 0.5;
for (var x = 0; x < bw; x++) {
var vx = (2 * (x + 0.5) / bw - 1) * 0.8;
var dx = fx + rx * vx + ux * vy;
var dy = fy + uy * vy;
var dz = fz + rz * vx + uz * vy;
var dl = Math.sqrt(dx * dx + dy * dy + dz * dz);
dx /= dl; dy /= dl; dz /= dl;
// ── march 루프 — 토러스 표면까지 전진 ──
var t = 0.0, hit = 0, px = ex, py = ey, pz = ez;
for (var s = 0; s < STEPS; s++) {
var d = map(px, py, pz);
if (d < HIT_EPS) { hit = 1; break; }
if (t > 9.0) break;
t += d;
px = ex + dx * t; py = ey + dy * t; pz = ez + dz * t;
}
var r, g, b;
if (hit) {
var n = normalAt(px, py, pz);
var lam = Math.max(0, n[0] * lx + n[1] * ly + n[2] * lz);
// rim — 법선이 시선과 수직에 가까울수록(가장자리) 1 에 가까워진다
var facing = Math.max(0, n[0] * -dx + n[1] * -dy + n[2] * -dz);
var rimK = Math.pow(1 - facing, 2.2);
var rimLit = Math.max(0, n[0] * rbx + n[1] * rby + n[2] * rbz);
var rim = rimK * (0.35 + 0.65 * rimLit);
// 시간 위상 — 링 표면을 도는 옅은 광점(살아 있음 한 겹)
var ang = Math.atan2(pz, px) - tSec * 1.1;
var sweep = 0.5 + 0.5 * Math.cos(ang * 2);
var dif = 0.3 + 0.62 * lam + 0.08 * sweep;
r = C_RING[0] * dif + C_RIM[0] * rim * 0.85 + C_HILITE[0] * Math.pow(lam, 9) * 0.28;
g = C_RING[1] * dif + C_RIM[1] * rim * 0.85 + C_HILITE[1] * Math.pow(lam, 9) * 0.28;
b = C_RING[2] * dif + C_RIM[2] * rim * 0.85 + C_HILITE[2] * Math.pow(lam, 9) * 0.28;
} else {
var sky = dy > 0 ? dy : 0;
r = C_SKY[0] + (C_HILITE[0] - C_SKY[0]) * sky * 0.3;
g = C_SKY[1] + (C_HILITE[1] - C_SKY[1]) * sky * 0.3;
b = C_SKY[2] + (C_HILITE[2] - C_SKY[2]) * sky * 0.3;
}
data[i] = clamp255(r);
data[i + 1] = clamp255(g);
data[i + 2] = clamp255(b);
data[i + 3] = 255;
i += 4;
}
}
bctx.putImageData(img, 0, 0);
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.clearRect(0, 0, W, H);
ctx.drawImage(buf, 0, 0, W, H);
}
function fit() {
var r = field.getBoundingClientRect();
W = r.width; H = r.height;
cv.width = Math.round(W); cv.height = Math.round(H);
var bh = Math.max(12, Math.round(rtW * H / W));
buf = document.createElement('canvas');
buf.width = rtW; buf.height = bh;
bctx = buf.getContext('2d');
img = bctx.createImageData(rtW, bh);
}
function setRes(w) {
rtW = w;
var is96 = w >= 96;
res48.classList.toggle('is-on', !is96);
res96.classList.toggle('is-on', is96);
res48.setAttribute('aria-pressed', is96 ? 'false' : 'true');
res96.setAttribute('aria-pressed', is96 ? 'true' : 'false');
fit();
if (reduce) draw(0.6);
}
res48.addEventListener('click', function () { setRes(48); });
res96.addEventListener('click', function () { setRes(96); });
function aim() {
return [(px01 - 0.5) * 2.2, 0.24 + (py01 - 0.5) * 0.42];
}
function frame(now) {
if (t0 < 0) t0 = now;
var t = (now - t0) / 1000;
if (!manual) {
var ph = ((now - t0) % LOOP_MS) / LOOP_MS * TAU;
px01 = 0.5 + 0.4 * Math.sin(ph);
py01 = 0.5 + 0.34 * Math.sin(2 * ph + 0.7);
}
var a = aim();
heading += (a[0] - heading) * 0.1;
pitch += (a[1] - pitch) * 0.1;
draw(t);
raf = requestAnimationFrame(frame);
}
field.addEventListener('pointermove', function (e) {
var r = field.getBoundingClientRect();
px01 = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
py01 = Math.min(1, Math.max(0, (e.clientY - r.top) / r.height));
if (!manual) { manual = true; root.classList.remove('is-demo'); }
if (reduce) { var a1 = aim(); heading = a1[0]; pitch = a1[1]; draw(0.6); }
});
field.addEventListener('pointerleave', function () {
if (manual) { px01 = 0.5; py01 = 0.5; }
});
field.addEventListener('keydown', function (e) {
var d = { ArrowLeft: [-0.07, 0], ArrowRight: [0.07, 0], ArrowUp: [0, -0.06], ArrowDown: [0, 0.06] }[e.key];
if (!d) return;
e.preventDefault();
if (!manual) { manual = true; root.classList.remove('is-demo'); }
px01 = Math.max(0, Math.min(1, px01 + d[0]));
py01 = Math.max(0, Math.min(1, py01 + d[1]));
if (reduce) { var a2 = aim(); heading = a2[0]; pitch = a2[1]; draw(0.6); }
});
window.addEventListener('resize', function () { fit(); if (reduce) draw(0.6); });
fit();
// 초기 타깃은 48px — 스펙 기본값. 버튼 표시를 맞춘다
setRes(48);
if (reduce) {
// reduce — rim 이 읽히는 각도의 한 장만
heading = 0.62; pitch = 0.28;
draw(0.6);
root.classList.add('is-still');
} else {
raf = requestAnimationFrame(frame);
}
})();// TorusGlowRing — vanilla 판(run/312/demo/03-rm-torus-glow-ring/index.html) 의 React 포트.
// 도넛의 부호 거리는 두 반지름(큰 R·작은 r) 의 길이 차 공식 하나다. rim light 근사:
// 법선과 시선의 내적이 0 에 가까운(가장자리를 스치는) 픽셀에 빛을 얹는다.
// 렌더 타깃 48/96 전환 — 변형 "해상도" 축. 같은 장면의 계산량 차이를 눈으로 본다.
import { useEffect, useRef, useState } from "react";
import type { CSSProperties } from "react";
import styles from "./TorusGlowRing.module.scss";
export type TorusGlowRingProps = {
duration?: string;
easing?: string;
color?: string;
renderWidth?: number; // 렌더 타깃 폭(버퍼 픽셀) — 48/96 변형 축
};
type Vars = CSSProperties & { "--duration"?: string; "--easing"?: string; "--color"?: string };
type Box<T> = { current: T };
type PointerEvt = { clientX: number; clientY: number };
type KeyEvt = { key: string; preventDefault(): void };
type MouseEvt = { currentTarget: HTMLButtonElement };
type RGB = [number, number, number];
type Size = { w: number; h: number };
const TAU = Math.PI * 2;
const FIELD_LABEL = "토러스 링 렌더 실험판";
const STILL_T = 0.6;
const TOR_R = 1.05, TOR_r = 0.42; // 큰 반지름 R · 튜브 반지름 r
// 도넛(토러스) 거리 — XY 평면에 눕혔다. 두 반지름의 차가 전부다
function sdTorus(px: number, py: number, pz: number): number {
const q = Math.sqrt(px * px + pz * pz) - TOR_R; // 가운데 축까지 거리 - R
return Math.sqrt(q * q + py * py) - TOR_r; // 튜브 중심에서 r 만큼 안쪽
}
function map(px: number, py: number, pz: number): number { return sdTorus(px, py, pz); }
// 법선(전방 차분)
function normalAt(px: number, py: number, pz: number): RGB {
const e = 0.0015;
const nx = map(px + e, py, pz) - map(px - e, py, pz);
const ny = map(px, py + e, pz) - map(px, py - e, pz);
const nz = map(px, py, pz + e) - map(px, py, pz - e);
const l = Math.sqrt(nx * nx + ny * ny + nz * nz) || 1;
return [nx / l, ny / l, nz / l];
}
function clamp255(v: number): number { return v > 255 ? 255 : (v < 0 ? 0 : v); }
export default function TorusGlowRing({
duration = "2s",
easing = "cubic-bezier(.2, .8, .2, 1)",
color = "#b9a0ff",
renderWidth = 48,
}: TorusGlowRingProps) {
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 bufRef = useRef<HTMLCanvasElement | null>(null);
const bctxRef = useRef<CanvasRenderingContext2D | null>(null);
const imgRef = useRef<ImageData | null>(null);
const sizeRef = useRef({ w: 0, h: 0 }) as Box<Size>;
const colRef = useRef<{ ring: RGB; rim: RGB; hilite: RGB; sky: RGB } | null>(null);
const rtRef = useRef(renderWidth) as Box<number>;
const headingRef = useRef(0.55) as Box<number>;
const pitchRef = useRef(0.27) as Box<number>;
const pxRef = useRef(0.5) as Box<number>;
const pyRef = useRef(0.5) as Box<number>;
const manualRef = useRef(false) as Box<boolean>;
const rafRef = useRef(0) as Box<number>;
const t0Ref = useRef(-1) as Box<number>;
const [hiRes, setHiRes] = useState(false);
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();
if (s.charAt(0) === "#") {
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)];
}
const p = s.replace(/[^\d,.]/g, "").split(",");
return [Number(p[0]) || 0, Number(p[1]) || 0, Number(p[2]) || 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 size = sizeRef.current;
const r = field.getBoundingClientRect();
size.w = r.width; size.h = r.height;
cv.width = Math.round(size.w); cv.height = Math.round(size.h);
ctxRef.current = ctx;
const bh = Math.max(12, Math.round(rtRef.current * size.h / size.w));
const buf = document.createElement("canvas");
buf.width = rtRef.current; buf.height = bh;
const bctx = buf.getContext("2d");
if (!bctx) return;
bufRef.current = buf; bctxRef.current = bctx;
imgRef.current = bctx.createImageData(rtRef.current, bh);
}
function draw(tSec: number): void {
const img = imgRef.current, bctx = bctxRef.current, buf = bufRef.current, ctx = ctxRef.current;
const col = colRef.current;
if (!img || !bctx || !buf || !ctx || !col) return;
const data = img.data;
const size = sizeRef.current;
const bw = buf.width, bh = buf.height;
const STEPS = 72, HIT_EPS = 0.004;
// 카메라 공전 — 자동 모드에서 토러스를 돈다
const heading = headingRef.current, pitch = pitchRef.current;
const ch = Math.cos(heading), sh = Math.sin(heading);
const cp = Math.cos(pitch), sp = Math.sin(pitch);
const D = 3.6;
const ex = sh * cp * D, ey = sp * D, ez = ch * cp * D;
const fx = -sh * cp, fy = -sp, fz = -ch * cp;
let rx = -fz, rz = fx;
const rl = Math.sqrt(rx * rx + rz * rz) || 1;
rx /= rl; rz /= rl;
const ux = -rz * fy, uy = rz * fx - rx * fz, uz = rx * fy;
// 광원 방향 — 위·왼쪽 앞. rim 빛은 뒤·오른쪽 위
const lx = -0.44, ly = 0.72, lz = 0.54;
const rbx = 0.6, rby = 0.28, rbz = -0.75;
let i = 0;
for (let y = 0; y < bh; y++) {
const vy = (1 - 2 * (y + 0.5) / bh) * 0.5;
for (let x = 0; x < bw; x++) {
const vx = (2 * (x + 0.5) / bw - 1) * 0.8;
let dx = fx + rx * vx + ux * vy;
let dy = fy + uy * vy;
let dz = fz + rz * vx + uz * vy;
const dl = Math.sqrt(dx * dx + dy * dy + dz * dz);
dx /= dl; dy /= dl; dz /= dl;
// ── march 루프 — 토러스 표면까지 전진 ──
let t = 0.0, hit = 0, px = ex, py = ey, pz = ez;
for (let s = 0; s < STEPS; s++) {
const d = map(px, py, pz);
if (d < HIT_EPS) { hit = 1; break; }
if (t > 9.0) break;
t += d;
px = ex + dx * t; py = ey + dy * t; pz = ez + dz * t;
}
let r: number, g: number, b: number;
if (hit) {
const n = normalAt(px, py, pz);
const lam = Math.max(0, n[0] * lx + n[1] * ly + n[2] * lz);
// rim — 법선이 시선과 수직에 가까울수록(가장자리) 1 에 가까워진다
const facing = Math.max(0, n[0] * -dx + n[1] * -dy + n[2] * -dz);
const rimK = Math.pow(1 - facing, 2.2);
const rimLit = Math.max(0, n[0] * rbx + n[1] * rby + n[2] * rbz);
const rim = rimK * (0.35 + 0.65 * rimLit);
// 시간 위상 — 링 표면을 도는 옅은 광점(살아 있음 한 겹)
const ang = Math.atan2(pz, px) - tSec * 1.1;
const sweep = 0.5 + 0.5 * Math.cos(ang * 2);
const dif = 0.3 + 0.62 * lam + 0.08 * sweep;
const spec = Math.pow(lam, 9) * 0.28;
r = col.ring[0] * dif + col.rim[0] * rim * 0.85 + col.hilite[0] * spec;
g = col.ring[1] * dif + col.rim[1] * rim * 0.85 + col.hilite[1] * spec;
b = col.ring[2] * dif + col.rim[2] * rim * 0.85 + col.hilite[2] * spec;
} else {
const sky = dy > 0 ? dy : 0;
r = col.sky[0] + (col.hilite[0] - col.sky[0]) * sky * 0.3;
g = col.sky[1] + (col.hilite[1] - col.sky[1]) * sky * 0.3;
b = col.sky[2] + (col.hilite[2] - col.sky[2]) * sky * 0.3;
}
data[i] = clamp255(r);
data[i + 1] = clamp255(g);
data[i + 2] = clamp255(b);
data[i + 3] = 255;
i += 4;
}
}
bctx.putImageData(img, 0, 0);
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = "high";
ctx.clearRect(0, 0, size.w, size.h);
ctx.drawImage(buf, 0, 0, size.w, size.h);
}
function aim(): [number, number] {
return [(pxRef.current - 0.5) * 2.2, 0.24 + (pyRef.current - 0.5) * 0.42];
}
function frame(now: number): void {
if (t0Ref.current < 0) t0Ref.current = now;
const t = (now - t0Ref.current) / 1000;
if (!manualRef.current) {
const ph = (((now - t0Ref.current) % 2000) / 2000) * TAU;
pxRef.current = 0.5 + 0.4 * Math.sin(ph);
pyRef.current = 0.5 + 0.34 * Math.sin(2 * ph + 0.7);
}
const a = aim();
headingRef.current += (a[0] - headingRef.current) * 0.1;
pitchRef.current += (a[1] - pitchRef.current) * 0.1;
draw(t);
rafRef.current = requestAnimationFrame(frame);
}
function onPoint(e: PointerEvt): void {
const field = fieldRef.current;
if (!field) return;
const r = field.getBoundingClientRect();
pxRef.current = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
pyRef.current = Math.min(1, Math.max(0, (e.clientY - r.top) / r.height));
if (!manualRef.current) manualRef.current = true;
if (reduced()) {
const a = aim();
headingRef.current = a[0]; pitchRef.current = a[1];
draw(STILL_T);
}
}
function onLeave(): void {
if (manualRef.current) { pxRef.current = 0.5; pyRef.current = 0.5; }
}
function onKeyDown(e: KeyEvt): void {
const deltas: Record<string, [number, number]> = {
ArrowLeft: [-0.07, 0], ArrowRight: [0.07, 0], ArrowUp: [0, -0.06], ArrowDown: [0, 0.06],
};
const d = deltas[e.key];
if (!d) return;
e.preventDefault();
if (!manualRef.current) manualRef.current = true;
pxRef.current = Math.max(0, Math.min(1, pxRef.current + d[0]));
pyRef.current = Math.max(0, Math.min(1, pyRef.current + d[1]));
if (reduced()) {
const a = aim();
headingRef.current = a[0]; pitchRef.current = a[1];
draw(STILL_T);
}
}
function onRes(e: MouseEvt): void {
const hi = e.currentTarget.getAttribute("data-hi") === "1";
rtRef.current = hi ? 96 : 48;
setHiRes(hi);
fit();
if (reduced()) draw(STILL_T);
}
useEffect(() => {
const root = rootRef.current;
if (!root) return;
colRef.current = {
ring: tokRGB(root, "--tg-ring"),
rim: tokRGB(root, "--tg-rim"),
hilite: tokRGB(root, "--tg-hilite"),
sky: tokRGB(root, "--tg-sky"),
};
fit();
function onResize(): void {
fit();
if (reduced()) draw(STILL_T);
}
window.addEventListener("resize", onResize);
if (reduced()) {
// reduce — rim 이 읽히는 각도의 한 장만
headingRef.current = 0.62; pitchRef.current = 0.28;
draw(STILL_T);
setStill(true);
} else {
rafRef.current = requestAnimationFrame(frame);
}
return () => {
window.removeEventListener("resize", onResize);
cancelAnimationFrame(rafRef.current);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
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}>
<svg className={styles.ico} viewBox="0 0 256 256" aria-hidden="true"><g fill="currentColor"><path d="M128 24a104 104 0 0 0-38.6 201.3a8 8 0 0 0 11-6.9a8 8 0 0 1 5.8-6.9c1.7-.5 3.4-.9 5.1-1.4a8 8 0 0 0 5.4-10.2c-.2-.7-.5-1.5-.7-2.2a8 8 0 0 0-9.3-5.1c-1.3.3-2.7.6-4 .8a8 8 0 0 1-8.9-5.2a76.9 76.9 0 0 1-4.5-25.5c0-31.4 21.4-53.7 46.7-53.7s46.7 22.3 46.7 53.7a76.9 76.9 0 0 1-4.5 25.5a8 8 0 0 1-8.9 5.2c-1.3-.2-2.7-.5-4-.8a8 8 0 0 0-9.3 5.1c-.2.7-.5 1.5-.7 2.2a8 8 0 0 0 5.4 10.2c1.7.5 3.4.9 5.1 1.4a8 8 0 0 1 5.8 6.9a8 8 0 0 0 11 6.9A104 104 0 0 0 128 24" opacity=".2"/><path d="M176 156c0 15.5-12.4 23.7-24.4 23.7c-13.4 0-25.9-10.9-25.9-25.3s11.9-23.5 24.5-23.5c16.9 0 25.8 13.6 25.8 25.1m56-28a104 104 0 1 1-104 104a104 104 0 0 1 104-104m0 16a88 88 0 1 0 88 88a88 88 0 0 0-88-88m-56 12c0-17.2-13.5-33.1-33.4-33.1C120.9 106.9 104 124 104 146s15.5 37.7 36.9 37.7c21.4 0 35.1-19.7 35.1-37.7"/></g></svg>
<span>도넛의 거리식은 두 반지름의 차 — 가장자리에 빛이 붙고 카메라가 공전합니다</span>
</p>
<div
className={styles.field}
ref={fieldRef}
role="application"
aria-label={FIELD_LABEL}
tabIndex={0}
onPointerMove={onPoint}
onPointerLeave={onLeave}
onKeyDown={onKeyDown}
>
<canvas className={styles.cv} ref={cvRef}></canvas>
</div>
<div className={styles.bar}>
<span className={styles.meta}>렌더 타깃
<button className={hiRes ? styles.res : styles.resOn} type="button" aria-pressed={!hiRes} data-hi="0" onClick={onRes}>48px</button>
<button className={hiRes ? styles.resOn : styles.res} type="button" aria-pressed={hiRes} data-hi="1" onClick={onRes}>96px</button>
</span>
<span className={styles.meta2}>스텝 72 · rim light</span>
</div>
</div>
</main>
);
}03 トーラスリング — ドーナツの距離式と縁の光 — 計測 累積面積 11.927% · 動いたフレーム 23/23GODRICH オリジナル · SCSS と React は zip に同梱 · レイマーチング9選 — WebGLなし、キャンバスのピクセル計算で描く3Dシーン
このデモが属する記事
レイマーチング9選 — WebGLなし、キャンバスのピクセル計算で描く3Dシーンレイマーチングとは、画面のピクセルごとに視線を1本ずつ前へ進め、数式で定義した距離関数に初めて触れる点の色を決める3Dレンダリングの手法です。WebGLなし、キャンバスのピクセル計算だけで、球からフラクタル、雲まで9つの場面をこのページで動 この記事のデモをすべて見る


