Codrops 원본
Building a Dual-Scene Fluid X-Ray Reveal Effect in Three.js
배경 · MIT
갤러리 안에서는 화면을 벗어나거나 움직임을 멈추면 예제도 닫힙니다. 다시 재생할 때는 처음부터 시작해요.
SOURCE FILES
원본 코드 읽기
수집한 원본 소스와 실행 안내를 함께 제공합니다.
index.html
<!doctype html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Skeleton Fluid Reveal | Codrops</title>
<meta
name="description"
content="WebGPU dual-scene fluid reveal with TSL post-processing" />
<meta name="keywords" content="" />
<meta name="author" content="Codrops" />
<link
rel="icon"
type="image/svg+xml"
href="https://tympanus.net/favicon/favicon.svg" />
<link rel="shortcut icon" href="https://tympanus.net/favicon/favicon.ico" />
<script>
document.documentElement.className = "js";
</script>
</head>
<body class="loading">
<main>
<header class="frame">
<h1 class="frame__title">Skeleton Fluid Reveal</h1>
<a class="frame__back" href="https://tympanus.net/codrops/?p=112796">Tutorial</a>
<a class="frame__archive" href="https://tympanus.net/codrops/hub/">All demos</a>
<a
class="frame__github"
href="https://github.com/cullenwebber/three-skull">GitHub</a>
<nav class="frame__tags">
<a href="https://tympanus.net/codrops/hub/tag/three-js">#three.js</a>
<a href="https://tympanus.net/codrops/hub/tag/webgpu">#webgpu</a>
</nav>
</header>
<div id="app"></div>
</main>
<script type="module" src="./src/main.js"></script>
</body>
</html>src/core/Three.js
import * as THREE from "three/webgpu";
import WebGPUContext from "./WebGPUContext";
import Scene from "../scenes/Scene";
import MouseTrail from "../utils/MouseTrail";
import FluidSim from "../postprocessing/FluidSim";
import PostProcessing from "../postprocessing/PostProcessing";
class Three {
constructor(container) {
this.container = container;
this.clock = new THREE.Clock();
}
async run() {
this.context = new WebGPUContext(this.container);
await this.context.init();
this.#setup();
this.#animate();
this.#addResizeListener();
}
#setup() {
const { width, height } = this.context.getFullScreenDimensions();
const pr = this.context.pixelRatio;
this.scene = new Scene();
this.mouseTrail = new MouseTrail(width * pr, height * pr);
this.fluidSim = new FluidSim(width * pr, height * pr);
this.postProcessing = new PostProcessing(
this.context.renderer,
this.scene.solidScene,
this.scene.wireScene,
this.scene.camera,
this.fluidSim.texture,
);
}
#animate() {
const delta = this.clock.getDelta();
this.scene.animate(delta, this.clock.elapsedTime);
// Update mouse trail → fluid sim
this.mouseTrail.update(
this.scene.cameraRig.mouseNormalized.x,
this.scene.cameraRig.mouseNormalized.y,
);
this.fluidSim.update(this.context.renderer, this.mouseTrail.texture);
// Render everything (scene passes + effects)
this.postProcessing.render();
requestAnimationFrame(() => this.#animate());
}
#addResizeListener() {
window.addEventListener("resize", () => this.#onResize());
}
#onResize() {
const { width, height } = this.context.getFullScreenDimensions();
const pr = this.context.pixelRatio;
this.context.onResize(width, height);
this.scene.onResize(width, height);
this.fluidSim.onResize(width * pr, height * pr);
}
}
export default Three;
함께 쓰는 파일 17개 보기
src/core/WebGPUContext.js
import * as THREE from "three/webgpu";
class WebGPUContext {
constructor(container) {
if (!!WebGPUContext.instance) {
return WebGPUContext.instance;
}
this.container = container;
this.renderer = null;
this.canvas = null;
this.pixelRatio = Math.min(window.devicePixelRatio, 2.0);
WebGPUContext.instance = this;
}
async init() {
this.canvas = this.#createCanvas();
this.renderer = new THREE.WebGPURenderer({
canvas: this.canvas,
antialias: false,
});
await this.renderer.init();
const { width, height } = this.getFullScreenDimensions();
this.renderer.setSize(width, height);
this.renderer.setPixelRatio(this.pixelRatio);
this.renderer.shadowMap.enabled = false;
this.renderer.autoClear = false;
this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
}
getFullScreenDimensions() {
const el = document.createElement("div");
Object.assign(el.style, {
height: "100lvh",
width: "100lvw",
position: "absolute",
visibility: "hidden",
});
document.body.appendChild(el);
const width = el.offsetWidth;
const height = el.offsetHeight;
document.body.removeChild(el);
return { width, height };
}
#createCanvas() {
const canvas = document.createElement("canvas");
canvas.style.position = "fixed";
canvas.style.left = 0;
canvas.style.top = 0;
canvas.style.zIndex = 35;
canvas.style.pointerEvents = "auto";
document.body.appendChild(canvas);
return canvas;
}
onResize(width, height) {
this.pixelRatio = Math.min(window.devicePixelRatio, 2);
this.renderer.setSize(width, height);
this.renderer.setPixelRatio(this.pixelRatio);
}
}
export default WebGPUContext;
src/main.js
import Three from "./core/Three";
import "./style.css";
document.addEventListener("DOMContentLoaded", async () => {
const container = document.querySelector("#app");
const three = new Three(container);
await three.run();
await three.scene.ready;
document.body.classList.remove("loading");
});
src/materials/fresnelMaterial.js
import { MeshStandardNodeMaterial } from "three/webgpu";
import {
positionLocal,
mix,
vec3,
smoothstep,
float,
normalView,
positionViewDirection,
pow,
sub,
} from "three/tsl";
export function createFresnelMaterial({
heightMax = 1.0,
roughness = 1.0,
color = vec3(0.2, 0.6, 1.0),
emissiveIntensity = 0.75,
}) {
const material = new MeshStandardNodeMaterial({
metalness: 0,
roughness,
});
// Fresnel: bright at silhouette edges, dark facing camera
const fresnel = pow(
sub(float(1.0), normalView.dot(positionViewDirection.negate())),
float(1.0),
);
const coreColor = vec3(0.0, 0.05, 0.1);
const fresnelColor = mix(coreColor, color, fresnel);
// Fade out below heightMax
const heightFade = smoothstep(0.5, heightMax, positionLocal.y);
const finalColor = fresnelColor.mul(heightFade);
material.colorNode = finalColor;
material.emissiveNode = finalColor.mul(emissiveIntensity);
return material;
}
src/postprocessing/FluidSim.js
import * as THREE from "three/webgpu";
import { MeshBasicNodeMaterial } from "three/webgpu";
import {
vec2,
vec3,
float,
sub,
mul,
add,
min,
uv,
texture,
Fn,
} from "three/tsl";
import { fbm } from "../utils/fbm";
export default class FluidSim {
constructor(width, height) {
this.width = width;
this.height = height;
this.#createRenderTargets();
this.#createFBOScene();
}
#createRenderTargets() {
const opts = {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
depthBuffer: false,
stencilBuffer: false,
};
this.targetA = new THREE.RenderTarget(this.width, this.height, opts);
this.targetB = new THREE.RenderTarget(this.width, this.height, opts);
this.prevNode = texture(this.targetA.texture);
this.maskNode = texture(this.targetA.texture);
}
#createFBOScene() {
this.fboScene = new THREE.Scene();
this.fboCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, -1, 1);
this.inputNode = texture(new THREE.Texture());
const material = new MeshBasicNodeMaterial();
material.colorNode = this.#createFluidShader();
const geo = new THREE.PlaneGeometry(2, 2);
// Flip geometry UVs Y so render target read-back is self-consistent in WebGPU
const uvAttr = geo.attributes.uv;
for (let i = 0; i < uvAttr.count; i++) {
uvAttr.setY(i, 1.0 - uvAttr.getY(i));
}
this.fboQuad = new THREE.Mesh(geo, material);
this.fboScene.add(this.fboQuad);
}
#createFluidShader() {
const blendDarken = Fn(([base, blend]) => min(blend, base));
const aspect = this.height / this.width;
const aspectVec =
this.width < this.height
? vec2(1.0, 1.0 / aspect)
: vec2(aspect, 1.0);
return Fn(() => {
const uvCoord = uv();
const disp = mul(mul(fbm(mul(uvCoord, 20.0), float(4)), aspectVec), 0.01);
// Sample previous frame with noise displacement (fluid spreading)
const texel = this.prevNode.sample(uvCoord);
const texel2 = this.prevNode.sample(vec2(add(uvCoord.x, disp.x), uvCoord.y));
const texel3 = this.prevNode.sample(vec2(sub(uvCoord.x, disp.x), uvCoord.y));
const texel4 = this.prevNode.sample(vec2(uvCoord.x, add(uvCoord.y, disp.y)));
const texel5 = this.prevNode.sample(vec2(uvCoord.x, sub(uvCoord.y, disp.y)));
// Take darkest of neighborhood
const floodcolor = texel.rgb.toVar();
floodcolor.assign(blendDarken(floodcolor, texel2.rgb));
floodcolor.assign(blendDarken(floodcolor, texel3.rgb));
floodcolor.assign(blendDarken(floodcolor, texel4.rgb));
floodcolor.assign(blendDarken(floodcolor, texel5.rgb));
// Blend with new trail input (flip Y — canvas texture has opposite Y to render targets in WebGPU)
const flippedUV = vec2(uvCoord.x, sub(float(1.0), uvCoord.y));
const input = this.inputNode.sample(flippedUV);
const combined = blendDarken(floodcolor, input.rgb);
// Fade back to white
return min(vec3(1.0), add(combined, vec3(0.015)));
})();
}
get texture() {
return this.maskNode;
}
update(renderer, trailTexture) {
this.prevNode.value = this.targetA.texture;
this.inputNode.value = trailTexture;
renderer.setRenderTarget(this.targetB);
renderer.render(this.fboScene, this.fboCamera);
renderer.setRenderTarget(null);
// Update mask to read from the just-rendered target
this.maskNode.value = this.targetB.texture;
// Swap
const temp = this.targetA;
this.targetA = this.targetB;
this.targetB = temp;
}
onResize(width, height) {
this.width = width;
this.height = height;
this.targetA.setSize(width, height);
this.targetB.setSize(width, height);
}
dispose() {
this.targetA.dispose();
this.targetB.dispose();
this.fboQuad.material.dispose();
this.fboQuad.geometry.dispose();
}
}
src/postprocessing/PostProcessing.js
import * as THREE from "three/webgpu";
import {
pass,
vec3,
screenUV,
time,
float,
sub,
sin,
mul,
add,
mix,
dot,
clamp,
Fn,
} from "three/tsl";
import { mx_noise_float } from "three/tsl";
import { bloom } from "three/addons/tsl/display/BloomNode.js";
export default class PostProcessing {
constructor(renderer, solidScene, wireScene, camera, fluidMaskNode) {
this.pipeline = new THREE.RenderPipeline(renderer);
this.solidScene = solidScene;
this.wireScene = wireScene;
this.camera = camera;
this.fluidMaskNode = fluidMaskNode;
this.#compose();
}
#compose() {
// Render both scenes
const solidPass = pass(this.solidScene, this.camera);
const solidColor = solidPass.getTextureNode("output");
const wirePass = pass(this.wireScene, this.camera);
const wireColor = wirePass.getTextureNode("output");
// Bloom on solid scene
const bloomPass = bloom(solidColor.sample(screenUV), 0.4, 0.05);
// Scan lines on bloom only (darken only)
const scanRaw = sin(mul(screenUV.y, float(1250.0)));
const scanDarken = clamp(scanRaw, -1.0, 0.0).mul(-0.15);
const scanLines = sub(float(1.0), scanDarken);
const bloomWithScanLines = bloomPass.mul(scanLines);
// Fluid mask composites solid ↔ wire
const fluidMask = sub(float(1.0), this.fluidMaskNode.sample(screenUV).r);
const blended = mix(
bloomWithScanLines,
wireColor.sample(screenUV),
fluidMask,
);
// Film grain
const noise = mx_noise_float(
vec3(screenUV.mul(2000.0), time.mul(20.0)),
).mul(0.015);
// Combine effects
const withEffects = blended.sub(noise);
// Slight desaturation
const luminance = dot(withEffects, vec3(0.299, 0.587, 0.114));
const desaturated = mix(
vec3(luminance, luminance, luminance),
withEffects,
float(0.985),
);
const lowContrast = mix(vec3(0.0, 0.0, 0.2), desaturated, float(0.9));
this.pipeline.outputNode = lowContrast;
}
render() {
this.pipeline.render();
}
dispose() {
this.pipeline.dispose();
}
}
src/scenes/Scene.js
import * as THREE from "three/webgpu";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
import WebGPUContext from "../core/WebGPUContext";
import { CameraRig } from "../utils/CameraRig";
import InstancedModel from "../utils/InstancedModel";
export default class Scene {
constructor() {
this.context = new WebGPUContext();
const { width, height } = this.context.getFullScreenDimensions();
this.width = width;
this.height = height;
this.envMap = this.#createEnvironment();
this.solidScene = this.#createScene();
this.wireScene = this.#createScene();
this.#createInstancedModels();
this.#createCamera();
}
#createInstancedModels() {
const solid = new InstancedModel(this.solidScene, {
url: `${import.meta.env.BASE_URL}man_comp-transformed.glb`,
meshName: "body",
heightMax: 1.0,
roughness: 1.0,
});
const wire = new InstancedModel(this.wireScene, {
url: `${import.meta.env.BASE_URL}skeleton_comp-transformed.glb`,
meshName: "skeleton",
heightMax: 0.9,
roughness: 0.9,
});
this.ready = Promise.all([solid.ready, wire.ready]);
}
#createEnvironment() {
const pmremGenerator = new THREE.PMREMGenerator(this.context.renderer);
const envMap = pmremGenerator.fromScene(new RoomEnvironment()).texture;
pmremGenerator.dispose();
return envMap;
}
#createScene() {
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x000000, 1, 3);
scene.background = new THREE.Color(0x000000);
scene.environment = this.envMap;
scene.environmentIntensity = 0.1;
const light = new THREE.PointLight(0xffffff, 0.75);
light.position.set(1, 2, 1);
scene.add(light);
return scene;
}
#createCamera() {
this.camera = new THREE.PerspectiveCamera(
17,
this.width / this.height,
0.1,
100,
);
this.cameraRig = new CameraRig(this.camera);
}
animate(delta, elapsed) {
this.cameraRig?.update(delta, elapsed);
}
onResize(width, height) {
this.width = width;
this.height = height;
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
}
}
src/style.css
@import "tailwindcss";
*,
*::after,
*::before {
box-sizing: border-box;
}
:root {
font-size: 12px;
--color-text: #fff;
--color-bg: #000;
--color-link: #fff;
--color-link-hover: #fff;
--page-padding: 1.5rem;
}
body {
margin: 0;
color: var(--color-text);
background-color: var(--color-bg);
font-family: ui-monospace, monospace;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
@media (scripting: enabled) {
.loading {
&::before,
&::after {
content: "";
position: fixed;
z-index: 10000;
}
&::before {
top: 0;
left: 0;
width: 100%;
height: 100%;
background: var(--color-bg);
}
&::after {
top: 50%;
left: 50%;
width: 100px;
height: 1px;
margin: 0 0 0 -50px;
background: var(--color-link);
animation: loaderAnim 1.5s ease-in-out infinite alternate forwards;
}
}
}
@keyframes loaderAnim {
0% {
transform: scaleX(0);
transform-origin: 0% 50%;
}
50% {
transform: scaleX(1);
transform-origin: 0% 50%;
}
50.1% {
transform: scaleX(1);
transform-origin: 100% 50%;
}
100% {
transform: scaleX(0);
transform-origin: 100% 50%;
}
}
a {
text-decoration: none;
color: var(--color-link);
outline: none;
cursor: pointer;
&:hover {
text-decoration: underline;
color: var(--color-link-hover);
}
&:focus {
outline: none;
background: lightgrey;
&:not(:focus-visible) {
background: transparent;
}
&:focus-visible {
outline: 2px solid red;
background: transparent;
}
}
}
.frame {
padding: 3rem var(--page-padding) 0;
display: grid;
z-index: 1000;
position: relative;
grid-row-gap: 1rem;
grid-column-gap: 2rem;
pointer-events: none;
justify-items: start;
grid-template-columns: auto auto auto 1fr;
grid-template-areas:
"title title title title"
"back archive github ..."
"tags tags tags tags";
a {
pointer-events: auto;
}
.frame__title {
grid-area: title;
font-size: inherit;
margin: 0;
}
.frame__back {
grid-area: back;
justify-self: start;
}
.frame__archive {
grid-area: archive;
justify-self: start;
}
.frame__github {
grid-area: github;
}
.frame__tags {
grid-area: tags;
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
@media screen and (min-width: 53em) {
padding: var(--page-padding);
height: 100%;
position: fixed;
top: 0;
left: 0;
width: 100%;
grid-template-columns: auto auto auto auto 1fr;
grid-template-rows: auto auto;
align-content: space-between;
grid-template-areas:
"title back github archive ..."
"tags tags tags tags tags";
.frame__tags {
align-self: end;
}
}
}
src/utils/CameraRig.js
import * as THREE from "three/webgpu";
import { easing } from "maath";
export class CameraRig {
constructor(camera) {
this.camera = camera;
this.basePos = new THREE.Vector3(1.5, 1.5, 0.55);
this.lookAt = new THREE.Vector3(-0.52, 0.45, -0.45);
this.camera.position.copy(this.basePos);
this.camera.lookAt(this.lookAt);
// Normalized mouse (0-1), exposed for MouseTrail
this.mouseNormalized = { x: 0.5, y: 0.5 };
// Pointer for camera (-1..1)
this.pointer = { x: 0, y: 0 };
this.smoothTime = 0.25;
this.touchTime = 0;
this.isTouch =
window.matchMedia("(pointer: coarse)").matches || "ontouchstart" in window;
this.isMobile = window.innerWidth < 768;
this._targetPos = [0, 0, 0];
if (!this.isTouch) {
window.addEventListener("mousemove", (e) => {
this.mouseNormalized.x = e.clientX / window.innerWidth;
this.mouseNormalized.y = 1 - e.clientY / window.innerHeight;
this.pointer.x = (e.clientX / window.innerWidth) * 2 - 1;
this.pointer.y = -(e.clientY / window.innerHeight) * 2 + 1;
});
}
}
update(delta, elapsed) {
let pointerX, pointerY;
if (this.isTouch) {
// Figure-8 animation for camera
this.touchTime += delta * 0.5;
pointerX = Math.sin(this.touchTime);
pointerY = Math.sin(this.touchTime * 0.7) * 0.5;
// Figure-8 for trail (faster)
const trailT = elapsed * 1.3;
const tx = Math.sin(trailT);
const ty = Math.sin(trailT * 2.0);
this.mouseNormalized.x = 0.5 + tx * 0.5;
this.mouseNormalized.y = 0.5 + ty * 0.5;
} else {
pointerX = this.pointer.x;
pointerY = this.pointer.y;
}
const zoom = this.isMobile ? 1.2 : 1;
this._targetPos[0] =
this.lookAt.x + (this.basePos.x - this.lookAt.x) * zoom + pointerX * 0.125;
this._targetPos[1] =
this.lookAt.y + (this.basePos.y - this.lookAt.y) * zoom + pointerY * 0.075;
this._targetPos[2] =
this.lookAt.z + (this.basePos.z - this.lookAt.z) * zoom;
easing.damp3(this.camera.position, this._targetPos, this.smoothTime, delta);
this.camera.lookAt(this.lookAt);
}
}
src/utils/ImportGltf.js
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath("https://www.gstatic.com/draco/v1/decoders/");
loader.setDRACOLoader(dracoLoader);
export default class ImportGltf {
constructor(url, { onLoad }) {
this.ready = new Promise((resolve, reject) => {
loader.load(
url,
(gltf) => {
onLoad?.(gltf.scene);
resolve();
},
undefined,
(error) => {
console.error("GLTF load error:", error);
reject(error);
},
);
});
}
}
src/utils/InstancedModel.js
import * as THREE from "three/webgpu";
import ImportGltf from "./ImportGltf";
import { createFresnelMaterial } from "../materials/fresnelMaterial";
export default class InstancedModel {
constructor(
scene,
{
url,
meshName,
heightMax = 1.0,
roughness = 1.0,
color,
emissiveIntensity,
count = 12,
spacing = 0.65,
},
) {
this.scene = scene;
this.count = count;
this.spacing = spacing;
const gltf = new ImportGltf(url, {
onLoad: (model) => {
let geometry = null;
model.traverse((child) => {
if (child.isMesh && (!meshName || child.name === meshName)) {
if (!geometry) geometry = child.geometry;
}
});
const material = createFresnelMaterial({
heightMax,
roughness,
color,
emissiveIntensity,
});
const mesh = new THREE.InstancedMesh(geometry, material, this.count);
this.#setPositions(mesh);
this.scene.add(mesh);
},
});
this.ready = gltf.ready;
}
#setPositions(mesh) {
const { count, spacing } = this;
const gridSize = Math.ceil(Math.sqrt(count));
const halfSize = ((gridSize - 1) * spacing) / 2;
const spacingZ = spacing * 0.65;
const halfSizeZ = ((gridSize - 1) * spacingZ) / 2;
const dummy = new THREE.Object3D();
for (let i = 0; i < count; i++) {
const x = i % gridSize;
const z = Math.floor(i / gridSize);
const xOffset = z % 2 === 1 ? spacing / 2 : 0;
dummy.position.set(
x * spacing - halfSize + xOffset,
0,
z * spacingZ - halfSizeZ,
);
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
}
mesh.instanceMatrix.needsUpdate = true;
}
}
src/utils/MouseTrail.js
import * as THREE from "three";
export default class MouseTrail {
constructor(width, height) {
this.currentX = null;
this.currentY = null;
this.lastX = null;
this.lastY = null;
this.opacity = 0;
this.lerpSpeed = 0.075;
this.fadeInSpeed = 0.1;
this.fadeOutSpeed = 0.1;
this.moveThreshold = 0.5;
this.#createCanvas(width, height);
this.#createTexture();
}
#createCanvas(width, height) {
this.canvas = document.createElement("canvas");
this.canvas.width = width;
this.canvas.height = height;
this.ctx = this.canvas.getContext("2d");
this.lineWidth = Math.max(width * 0.2, 100);
this.ctx.fillStyle = "white";
this.ctx.fillRect(0, 0, width, height);
}
#createTexture() {
this.texture = new THREE.CanvasTexture(this.canvas);
this.texture.minFilter = THREE.LinearFilter;
this.texture.magFilter = THREE.LinearFilter;
this.texture.generateMipmaps = false;
}
update(mouseX, mouseY) {
const targetX = mouseX * this.canvas.width;
const targetY = (1 - mouseY) * this.canvas.height;
if (this.currentX === null) {
this.currentX = targetX;
this.currentY = targetY;
this.lastX = targetX;
this.lastY = targetY;
return;
}
this.#lerp(targetX, targetY);
this.#updateOpacity();
this.#draw();
this.lastX = this.currentX;
this.lastY = this.currentY;
this.texture.needsUpdate = true;
}
#lerp(targetX, targetY) {
this.currentX += (targetX - this.currentX) * this.lerpSpeed;
this.currentY += (targetY - this.currentY) * this.lerpSpeed;
}
#updateOpacity() {
const dx = this.currentX - this.lastX;
const dy = this.currentY - this.lastY;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist > this.moveThreshold) {
this.opacity = Math.min(1, this.opacity + this.fadeInSpeed);
} else {
this.opacity = Math.max(0, this.opacity - this.fadeOutSpeed);
}
}
#draw() {
const { canvas, ctx, lineWidth } = this;
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
if (this.opacity > 0.01) {
ctx.beginPath();
ctx.moveTo(this.lastX, this.lastY);
ctx.lineTo(this.currentX, this.currentY);
ctx.lineCap = "round";
ctx.lineWidth = lineWidth;
ctx.strokeStyle = `rgba(0, 0, 0, ${this.opacity})`;
ctx.stroke();
}
}
dispose() {
this.texture.dispose();
}
}
src/utils/fbm.js
import {
vec2,
float,
sub,
sin,
cos,
mul,
add,
mix,
dot,
Fn,
fract,
floor,
} from "three/tsl";
const rand = Fn(([n]) => {
const dp = dot(n, vec2(12.9898, 4.1414));
return fract(mul(sin(dp), 43758.5453));
});
const noise = Fn(([p]) => {
const ip = floor(p);
const u = fract(p);
const uu = mul(mul(u, u), sub(float(3.0), mul(u, 2.0)));
const res = mix(
mix(rand(ip), rand(add(ip, vec2(1.0, 0.0))), uu.x),
mix(rand(add(ip, vec2(0.0, 1.0))), rand(add(ip, vec2(1.0, 1.0))), uu.x),
uu.y,
);
return mul(res, res);
});
export const fbm = Fn(([x, numOctaves]) => {
const v = float(0.0).toVar();
const a = float(0.5).toVar();
const shift = vec2(100);
const angle = float(0.5);
const c = cos(angle);
const s = sin(angle);
const xx = x.toVar();
// 4 octaves (unrolled — TSL has no loops)
v.assign(add(v, mul(a, noise(xx))));
xx.assign(add(mul(vec2(sub(mul(xx.x, c), mul(xx.y, s)), add(mul(xx.x, s), mul(xx.y, c))), 2.0), shift));
a.assign(mul(a, 0.5));
v.assign(add(v, mul(a, noise(xx))));
xx.assign(add(mul(vec2(sub(mul(xx.x, c), mul(xx.y, s)), add(mul(xx.x, s), mul(xx.y, c))), 2.0), shift));
a.assign(mul(a, 0.5));
v.assign(add(v, mul(a, noise(xx))));
xx.assign(add(mul(vec2(sub(mul(xx.x, c), mul(xx.y, s)), add(mul(xx.x, s), mul(xx.y, c))), 2.0), shift));
a.assign(mul(a, 0.5));
v.assign(add(v, mul(a, noise(xx))));
return v;
});
vite.config.js
import { defineConfig } from 'vite'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
plugins: [tailwindcss()],
base: './',
})
Original author attribution실행 안내·자료
Building a Dual-Scene Fluid X-Ray Reveal Effect in Three.js
Original author: Cullen Webber
Published by Codrops. Copyright (c) 2026 Codrops.
License: MIT, pursuant to the publisher's downloadable-demo grant.
Keep CODROPS-MIT-2026.txt and the original project notices with copies.
Third-party media exceptions and credits are recorded separately in the source inventory.
Google Draco decoder notices실행 안내·자료
Google Draco 1.5.5 license and bundled notices
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------------------
Files: docs/assets/js/ASCIIMathML.js
Copyright (c) 2014 Peter Jipsen and other ASCIIMathML.js contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
--------------------------------------------------------------------------------
Files: docs/assets/css/pygments/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org>
Media credits and license evidence실행 안내·자료
README.md
## Credits
- [Three.js](https://threejs.org/)
- [maath](https://github.com/pmndrs/maath) for easing utilities
## License
[MIT](LICENSE)
Bundled dependency licenses실행 안내·자료
three@0.183.2 — LICENSE
The MIT License
Copyright © 2010-2026 three.js authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
BEHIND THE EXAMPLE
이 장면을 만드는 원리
직전 마스크를 읽고 다른 대상으로 쓰기
화면 크기·입력·동시 작업을 고정하고 실제 렌더링 실패와 비용을 관찰합니다.
- 이 예제에서는
- FluidSim.update는 targetA를 이전 프레임으로 읽고 targetB에 새 마스크를 그린 뒤 두 대상을 바꿉니다. 셰이더는 이웃의 어두운 값을 합치고 프레임마다 0.015씩 흰색으로 돌립니다.
코드와 함께 확인하기
코드에서 찾기
update(renderer, trailTexture)FluidSim.js읽기와 쓰기 대상을 분리하고 새 결과를 외부 maskNode에 연결합니다.
직접 해보기
같은 포인터 궤적을 서로 다른 프레임 속도와 resize 전후에 재현합니다.
살펴볼 변화잔상이 사라지는 시간이 프레임 수에 얼마나 좌우되는지와 새 크기에서 마스크가 맞는지 확인해야 합니다.
