176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.
HTML ai-promptsanimationcss-animationsfrontendgithub-pagesjavascriptmicrointeractionsmotion-designno-dependenciesreferencescroll-animationui-animationweb-animationweb-developmentwebgl
feat(3d): add 16 READMEs + category index for 06-3d-advanced; refresh home to 88 animations
matin826425e6a1d2
diff --git a/animations/06-3d-advanced/2-5d-pseudo-3d/README.md b/animations/06-3d-advanced/2-5d-pseudo-3d/README.mdnew file mode 100644index 00000000..9e7fa1ff--- /dev/null+++ b/animations/06-3d-advanced/2-5d-pseudo-3d/README.md@@ -0,0 +1,67 @@+# 2.5D / Pseudo-3D++## What it is+2.5D (pseudo-3D) arranges flat 2D layers at different virtual depths using CSS `perspective` and `translateZ`, then moves a virtual "camera" to create a parallax depth illusion. Layers closest to the camera move the most in response to mouse or scroll; distant layers barely move. The technique was used in classic video games (Doom, old platformers) and animated films (Disney's multiplane camera, 1937), and translates directly to CSS with no additional libraries.++## When to use it+- Hero sections with illustrated scenes that should feel dimensional+- Portfolio headers and landing page environments+- Game UI overlays where depth reinforces the game world+- Interactive maps or environments where camera movement reveals depth++## How it works+Each layer has a CSS `transform: translateX(offset)` where offset = `mouseNormalizedX * strength * depth`. Layers at depth 0 don't move; depth 1 moves the maximum amount:++```js+const LAYERS = [+ { el: document.getElementById('sky'), depth: 0.05 },+ { el: document.getElementById('mtns'), depth: 0.2 },+ { el: document.getElementById('hills'), depth: 0.4 },+ { el: document.getElementById('trees'), depth: 0.7 },+ { el: document.getElementById('ground'), depth: 1.0 },+];++stage.addEventListener('mousemove', e => {+ const normX = (e.clientX / stage.clientWidth) - 0.5; // -0.5 to 0.5+ const normY = (e.clientY / stage.clientHeight) - 0.5;+ LAYERS.forEach(({ el, depth }) => {+ el.style.transform = `translate(+ ${-normX * STRENGTH * depth}px,+ ${-normY * STRENGTH * depth * 0.4}px+ )`;+ });+});+```++For an **auto-pan** camera, drive the norm values with sine:++```js+function autoLoop(t) {+ const normX = Math.sin(t * 0.0003) * 0.5;+ const normY = Math.sin(t * 0.0002) * 0.3;+ LAYERS.forEach(({ el, depth }) => {+ el.style.transform = `translate(${-normX * STRENGTH * depth}px, ${-normY * STRENGTH * depth * 0.4}px)`;+ });+ requestAnimationFrame(autoLoop);+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Strength | 40px | Maximum displacement of the nearest (depth 1) layer |+| Layer count | 7 | More layers = smoother depth gradient; fewer = staircase effect |+| Depth values | 0.05–1.0 | The distribution determines how pronounced the depth gap feels |+| Y multiplier | 0.4 | Vertical parallax is usually less than horizontal for landscape scenes |++## Production notes+- **Each layer must be wider than the stage**: when the camera pans, layers must extend beyond the visible frame so empty edges don't show. Add 10–20% horizontal overflow per layer.+- **CSS `perspective` vs `translateZ`**: CSS 3D perspective gives the same result with less JavaScript — put `perspective: 800px` on the container and use `translateZ(depth)` on each layer. Mouse rotation of the entire container then creates the parallax effect with a single transform.+- **Scroll-driven variant**: replace `mousemove` with `scroll` and map scroll position to the camera offset. Combine with sticky positioning to pin the scene while the user scrolls through it.+- **Game engines**: this is the native technique in 2D game engines (Phaser, PixiJS, Godot) with "parallax scrolling" built in as a first-class feature. Each layer specifies a scroll factor (0 to 1).+- **Optimization**: layers that extend beyond the viewport trigger paint. Use `overflow: hidden` on the parent and `transform: translateZ(0)` on each layer to promote them to GPU compositing layers.++## See also+- [Parallax Depth-of-Field](../../01-scroll-based/parallax-depth-of-field/) — the same layered parallax concept for scroll-based scenes+- [Parallax 3D Tilt](../parallax-3d-tilt/) — mouse-driven 3D tilt of a single card+- [Scroll-Driven 3D Rotation](../scroll-driven-3d-rotation/) — scroll as the camera driverdiff --git a/animations/06-3d-advanced/2-5d-pseudo-3d/index.html b/animations/06-3d-advanced/2-5d-pseudo-3d/index.htmlnew file mode 100644index 00000000..cdc65e0b--- /dev/null+++ b/animations/06-3d-advanced/2-5d-pseudo-3d/index.html@@ -0,0 +1,216 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>2.5D / Pseudo-3D</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative;cursor:none}+ /* 3D scene container */+ .scene{width:100%;height:100%;position:relative;perspective:800px;perspective-origin:50% 50%;overflow:hidden}+ .scene-inner{width:100%;height:100%;position:relative;transform-style:preserve-3d;transform:translateZ(0);transition:transform 0ms linear}+ /* Layers */+ .layer{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;transform-style:preserve-3d;will-change:transform}+ /* Sky */+ .sky{background:linear-gradient(180deg,#05101e 0%,#0a1f3a 50%,#0d2545 100%)}+ /* Stars */+ .stars{background:transparent}+ .star{position:absolute;border-radius:50%;background:#fff;opacity:.6}+ /* Mountains far */+ .mtns-far{display:flex;align-items:flex-end;justify-content:center;padding-bottom:0}+ .mtn{position:absolute;bottom:35%;border-style:solid;border-color:transparent;border-bottom-color:#0d2040}+ /* Hills */+ .hills-wrap{position:absolute;bottom:30%;left:0;right:0;height:180px;overflow:hidden}+ .hills{width:120%;height:100%;border-radius:50% 50% 0 0;margin-left:-10%}+ /* Ground */+ .ground{position:absolute;bottom:0;left:-20%;right:-20%;height:35%}+ /* Trees */+ .trees-wrap{position:absolute;bottom:30%;left:0;right:0}+ .tree-el{position:absolute;bottom:0;display:flex;flex-direction:column;align-items:center}+ .tree-top{border-style:solid;border-color:transparent}+ .tree-trunk{background:#3a2510}+ /* Fog */+ .fog{position:absolute;bottom:28%;left:0;right:0;height:80px;background:linear-gradient(transparent,rgba(10,30,60,.4) 60%,rgba(10,30,60,.6))}+ /* Moon */+ .moon{position:absolute;top:15%;right:20%;width:50px;height:50px;border-radius:50%;background:#d8e8f8;box-shadow:0 0 20px rgba(200,220,255,.4)}+ /* Cursor */+ #cursor{position:absolute;width:20px;height:20px;border-radius:50%;border:2px solid var(--ui-accent);pointer-events:none;transform:translate(-50%,-50%);z-index:100;display:none}+ /* Depth label */+ .depth-label{position:absolute;top:4px;right:4px;font-size:8px;letter-spacing:1px;text-transform:uppercase;color:rgba(255,255,255,.2);pointer-events:none;z-index:10}+ /* Panel */+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .kv{display:flex;justify-content:space-between;font-size:10px;color:var(--ui-muted)}+ .kv .v{color:var(--ui-text)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:40px;text-align:right;color:var(--ui-text)}+ select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:8px 6px;border-radius:4px;width:100%;min-height:44px}+ .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:420px}}+ @media(prefers-reduced-motion:reduce){.scene-inner{transition:none!important}}+ </style>+</head>+<body>+<header>+ <h1>2.5D / Pseudo-3D</h1>+ <p>Flat 2D layers at different CSS translateZ depths — mouse movement parallaxes each at a different rate.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <div class="scene" id="scene">+ <div class="scene-inner" id="scene-inner">+ <!-- Layer 0: sky (slowest) -->+ <div class="layer sky" id="L0"><div class="depth-label" id="dl0">depth 0.05</div></div>+ <!-- Stars -->+ <div class="layer stars" id="L1"><div class="depth-label" id="dl1">depth 0.1</div><div class="moon"></div></div>+ <!-- Far mountains -->+ <div class="layer" id="L2" style="background:transparent">+ <div class="depth-label" id="dl2">depth 0.2</div>+ <div class="mtns-far" style="position:absolute;bottom:30%;left:0;right:0;height:200px">+ <div class="mtn" style="border-width:0 100px 160px;left:5%"></div>+ <div class="mtn" style="border-width:0 80px 120px;left:18%"></div>+ <div class="mtn" style="border-width:0 120px 180px;left:30%"></div>+ <div class="mtn" style="border-width:0 90px 140px;left:55%"></div>+ <div class="mtn" style="border-width:0 110px 160px;left:70%"></div>+ <div class="mtn" style="border-width:0 70px 100px;left:85%"></div>+ </div>+ </div>+ <!-- Mid hills -->+ <div class="layer" id="L3" style="background:transparent">+ <div class="depth-label" id="dl3">depth 0.4</div>+ <div class="hills-wrap"><div class="hills" style="background:#0a2035;width:110%;margin-left:-5%"></div></div>+ <div class="hills-wrap" style="bottom:32%;height:130px"><div class="hills" style="background:#091c30"></div></div>+ </div>+ <!-- Trees far -->+ <div class="layer" id="L4" style="background:transparent">+ <div class="depth-label" id="dl4">depth 0.6</div>+ <div class="trees-wrap" id="trees-far"></div>+ </div>+ <!-- Trees near -->+ <div class="layer" id="L5" style="background:transparent">+ <div class="depth-label" id="dl5">depth 0.85</div>+ <div class="trees-wrap" id="trees-near" style="bottom:28%"></div>+ <div class="fog"></div>+ </div>+ <!-- Ground (fastest) -->+ <div class="layer" id="L6" style="background:transparent">+ <div class="depth-label" id="dl6">depth 1.0</div>+ <div class="ground" style="background:linear-gradient(180deg,#050f1a,#030c15);border-top:1px solid rgba(88,166,255,.1)"></div>+ </div>+ </div>+ </div>+ <div id="cursor"></div>+ </div>+ <aside>+ <p class="note">Each layer gets a depth multiplier (0–1). Mouse displacement × depth = translateX offset. Layers at depth 0 don't move; depth 1 moves the most.</p>+ <div class="lbl">Mode</div>+ <select id="mode-sel">+ <option value="mouse" selected>Mouse-driven</option>+ <option value="auto">Auto-pan</option>+ </select>+ <div class="lbl">Camera Strength</div>+ <div class="sr"><input type="range" id="str-sl" min="10" max="100" value="40" step="5"><span class="sv" id="str-v">40px</span></div>+ <label class="tog"><input type="checkbox" id="labels-tog"><span>Show depth labels</span></label>+ <div class="div"></div>+ <div class="kv"><span>Mouse X</span><span class="v" id="mx-v">—</span></div>+ <div class="kv"><span>Layers</span><span class="v">7</span></div>+ <button class="rst" id="reset-btn">↺ Reset camera</button>+ </aside>+</div>+<script>+const stage=document.getElementById('stage');+const cursor=document.getElementById('cursor');+const mxV=document.getElementById('mx-v');+const LAYERS=[+ {id:'L0',depth:.05},{id:'L1',depth:.1},{id:'L2',depth:.2},+ {id:'L3',depth:.4},{id:'L4',depth:.6},{id:'L5',depth:.85},{id:'L6',depth:1}+];+let mx=0,my=0,strength=40,mode='mouse',raf=null,autoT=0,paused=false;+const motionOk=!window.matchMedia('(prefers-reduced-motion:reduce)').matches;++// Add stars+const starLayer=document.getElementById('L1');+for(let i=0;i<80;i++){+ const s=document.createElement('div');s.className='star';+ s.style.cssText=`width:${Math.random()*2+1}px;height:${Math.random()*2+1}px;top:${Math.random()*60}%;left:${Math.random()*100}%;opacity:${.3+Math.random()*.7}`;+ starLayer.appendChild(s);+}++// Add trees+function addTrees(containerId,count,size,color){+ const wrap=document.getElementById(containerId);+ for(let i=0;i<count;i++){+ const x=5+i*(95/count)+Math.random()*5;+ const h=size*(0.7+Math.random()*.6);const w=h*.55;+ const el=document.createElement('div');el.className='tree-el';+ el.style.left=x+'%';+ el.innerHTML=`<div class="tree-top" style="border-width:0 ${w/2}px ${h*.7}px;border-bottom-color:${color}"></div><div class="tree-trunk" style="width:${w*.12}px;height:${h*.3}px"></div>`;+ wrap.appendChild(el);+ }+}+addTrees('trees-far',14,36,'#061520');+addTrees('trees-near',8,56,'#040e18');++function applyParallax(normX,normY){+ LAYERS.forEach(l=>{+ const el=document.getElementById(l.id);+ if(!el)return;+ const tx=(-normX*strength*l.depth).toFixed(1);+ const ty=(-normY*strength*l.depth*.4).toFixed(1);+ el.style.transform=`translate(${tx}px,${ty}px)`;+ });+}++stage.addEventListener('mousemove',e=>{+ const r=stage.getBoundingClientRect();+ mx=(e.clientX-r.left)/r.width-.5;+ my=(e.clientY-r.top)/r.height-.5;+ cursor.style.display='block';cursor.style.left=(e.clientX-r.left)+'px';cursor.style.top=(e.clientY-r.top)+'px';+ mxV.textContent=(mx*100).toFixed(0)+'%';+ if(mode==='mouse')applyParallax(mx,my);+});+stage.addEventListener('mouseleave',()=>{cursor.style.display='none'});+stage.addEventListener('touchmove',e=>{+ const r=stage.getBoundingClientRect();+ mx=(e.touches[0].clientX-r.left)/r.width-.5;+ my=(e.touches[0].clientY-r.top)/r.height-.5;+ if(mode==='mouse')applyParallax(mx,my);+},{passive:true});++function autoLoop(t){+ raf=requestAnimationFrame(autoLoop);+ autoT=t*.0003;+ applyParallax(Math.sin(autoT)*.5,Math.sin(autoT*.7)*.3);+}++document.getElementById('mode-sel').addEventListener('change',e=>{+ mode=e.target.value;+ if(mode==='auto'){if(!raf)raf=requestAnimationFrame(autoLoop);}+ else{if(raf){cancelAnimationFrame(raf);raf=null;}}+});+document.getElementById('str-sl').addEventListener('input',e=>{+ strength=+e.target.value;document.getElementById('str-v').textContent=strength+'px';+});+document.getElementById('labels-tog').addEventListener('change',e=>{+ document.querySelectorAll('.depth-label').forEach(d=>d.style.display=e.target.checked?'block':'none');+});+document.getElementById('reset-btn').addEventListener('click',()=>{applyParallax(0,0)});++// Hide labels by default+document.querySelectorAll('.depth-label').forEach(d=>d.style.display='none');+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/3d-model-orbit/README.md b/animations/06-3d-advanced/3d-model-orbit/README.mdnew file mode 100644index 00000000..62cf994c--- /dev/null+++ b/animations/06-3d-advanced/3d-model-orbit/README.md@@ -0,0 +1,71 @@+# 3D Model Orbit++## What it is+3D model orbit renders a Phong-shaded 3D object in a WebGL canvas and continuously rotates it around one or more axes. It is the foundational WebGL demo: a vertex buffer, a shader program, a model-view-projection matrix, and a render loop. Everything in WebGL-based 3D descends from this pattern.++## When to use it+- Product configurators where a 3D object must rotate on hover or on scroll+- Hero sections that display an animated 3D logo or abstract shape+- Mouse-follow effects where an object tilts to track the cursor+- Educational contexts for showing the structure of 3D coordinate systems++## How it works+A WebGL program needs three components: geometry (vertex data), shaders (GPU programs), and a transformation matrix.++**Vertex shader** receives each vertex position and normal, and outputs the clipped position plus interpolated data for the fragment shader:++```glsl+attribute vec3 aPos, aNorm;+uniform mat4 uMVP, uM; /* model-view-projection, model */+varying vec3 vN, vP;++void main() {+ gl_Position = uMVP * vec4(aPos, 1.0);+ vP = (uM * vec4(aPos, 1.0)).xyz;+ vN = normalize(mat3(uM) * aNorm);+}+```++**Fragment shader** applies Phong lighting — ambient + diffuse + specular:++```glsl+precision mediump float;+varying vec3 vN, vP;+uniform vec3 uCol, uLight;++void main() {+ vec3 L = normalize(uLight - vP);+ vec3 V = normalize(vec3(0., 0., 4.) - vP);+ float d = max(dot(vN, L), 0.0);+ float s = pow(max(dot(reflect(-L, vN), V), 0.0), 48.0);+ gl_FragColor = vec4(0.15 * uCol + d * uCol + 0.7 * s, 1.0);+}+```++**Transformation pipeline** — the MVP matrix chain:++```js+const P = perspective(Math.PI/4, width/height, 0.1, 20);+const T = translate(0, 0, -dist);+const M = multiply(multiply(T, rotateY(ry)), rotateX(rx));+const MVP = multiply(P, M);+```++## Key parameters+| Parameter | Typical value | Effect |+|-----------|--------------|--------|+| Camera distance | 2.5–4 | Controls perceived object size without changing field of view |+| Field of view | 45° | Wider FOV = more distortion (fisheye); narrower = more orthographic |+| Specular exponent | 16–128 | Higher = tighter, shinier highlight; lower = broad matte glow |+| Rotation speed | 0.5–2 rad/s | Match to the energy of the surrounding content |++## Production notes+- **Three.js in production**: Three.js's `PerspectiveCamera`, `MeshPhongMaterial`, and `OrbitControls` replace everything in this demo in ~20 lines. Use Three.js for anything more complex than a single object — raw WebGL becomes unmanageable fast.+- **Normal matrix**: strictly, normals should be transformed by the inverse-transpose of the model matrix, not the model matrix itself. For uniform scaling (no non-uniform squash/stretch), the model matrix works fine. For non-uniform scale, use `mat3(transpose(inverse(uM)))`.+- **`prefers-reduced-motion`**: stop the animation loop and show the object in its default orientation. The object should remain visible and interactive for camera control.+- **Touch/pointer interaction**: use `pointerdown` / `pointermove` / `pointerup` for drag-to-rotate, not `mousedown` — this covers touch without separate event listeners.++## See also+- [Scroll-Driven 3D Rotation](../scroll-driven-3d-rotation/) — scroll position drives the rotation instead of time+- [Parallax 3D Tilt](../parallax-3d-tilt/) — CSS 3D equivalent for flat cards+- [WebGL Shader Animation](../webgl-shader-animation/) — same WebGL boilerplate, different fragment shader focusdiff --git a/animations/06-3d-advanced/3d-model-orbit/index.html b/animations/06-3d-advanced/3d-model-orbit/index.htmlnew file mode 100644index 00000000..c45333c7--- /dev/null+++ b/animations/06-3d-advanced/3d-model-orbit/index.html@@ -0,0 +1,252 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>3D Model Orbit</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative}+ canvas{display:block;width:100%;height:100%}+ .hud{position:absolute;top:8px;left:8px;right:8px;display:flex;justify-content:space-between;pointer-events:none}+ .fps-badge,.obj-badge{font-size:9px;color:rgba(255,255,255,.5);background:rgba(0,0,0,.4);padding:3px 8px;border-radius:4px;letter-spacing:.5px}+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:40px;text-align:right;color:var(--ui-text)}+ select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:8px 6px;border-radius:4px;width:100%;min-height:44px}+ .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ input[type=color]{border:none;background:none;width:44px;height:30px;cursor:pointer;border-radius:4px;padding:0}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:380px}}+ @media(prefers-reduced-motion:reduce){canvas{display:none}}+ </style>+</head>+<body>+<header>+ <h1>3D Model Orbit</h1>+ <p>Phong-shaded 3D geometry in vanilla WebGL — vertex buffers, MVP matrix, and a full lighting model.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <canvas id="cvs"></canvas>+ <div class="hud">+ <div class="fps-badge" id="fps">— fps</div>+ <div class="obj-badge" id="obj-badge">Cube</div>+ </div>+ </div>+ <aside>+ <p class="note">3D rendering needs: vertex buffer, shader program, model-view-projection matrix, render loop. Three.js hides this behind a clean API. This demo exposes the raw machinery.</p>+ <div class="lbl">Mode</div>+ <select id="mode-sel"><option value="orbit" selected>Auto-orbit</option><option value="mouse">Mouse-follow</option></select>+ <div class="lbl">Object</div>+ <select id="obj-sel"><option value="cube" selected>Cube</option><option value="sphere">Sphere</option><option value="torus">Torus</option><option value="tetra">Tetrahedron</option></select>+ <div class="lbl">Spin X / Y</div>+ <div class="sr"><input type="range" id="sx-sl" min="0" max="30" value="2" step="1"><span class="sv" id="sx-v">0.2</span></div>+ <div class="sr"><input type="range" id="sy-sl" min="0" max="30" value="8" step="1"><span class="sv" id="sy-v">0.8</span></div>+ <div class="lbl">Camera Distance</div>+ <div class="sr"><input type="range" id="cam-sl" min="15" max="60" value="30" step="1"><span class="sv" id="cam-v">3.0</span></div>+ <div class="lbl">Object Color</div>+ <input type="color" id="color-pick" value="#58a6ff" aria-label="Object color">+ <label class="tog"><input type="checkbox" id="wire-tog"><span>Wireframe</span></label>+ <div class="div"></div>+ <button class="rst" id="pause-btn">⏸ Pause</button>+ </aside>+</div>+<script>+// ─── Shaders ───────────────────────────────────────────────────────────────+const VS=`+attribute vec3 aPos,aNorm;+uniform mat4 uMVP,uM;+varying vec3 vN,vP;+void main(){+ gl_Position=uMVP*vec4(aPos,1.);+ vP=(uM*vec4(aPos,1.)).xyz;+ vN=normalize(mat3(uM[0].xyz,uM[1].xyz,uM[2].xyz)*aNorm);+}`;+const FS=`+precision mediump float;+varying vec3 vN,vP;+uniform vec3 uCol,uLight;+uniform bool uWire;+void main(){+ if(uWire){gl_FragColor=vec4(uCol,1.);return;}+ vec3 L=normalize(uLight-vP),V=normalize(vec3(0.,0.,4.)-vP);+ float d=max(dot(vN,L),0.),s=pow(max(dot(reflect(-L,vN),V),0.),48.);+ gl_FragColor=vec4(.15*uCol+d*uCol+.7*s*vec3(1.),1.);+}`;++// ─── Mat4 helpers (column-major) ───────────────────────────────────────────+const I=()=>new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);+function mul(a,b){+ const o=new Float32Array(16);+ for(let i=0;i<4;i++)for(let j=0;j<4;j++){let s=0;for(let k=0;k<4;k++)s+=a[i+k*4]*b[k+j*4];o[i+j*4]=s;}+ return o;+}+function persp(fov,ar,n,f){+ const t=1/Math.tan(fov/2),nf=1/(n-f);+ return new Float32Array([t/ar,0,0,0,0,t,0,0,0,0,(f+n)*nf,-1,0,0,2*f*n*nf,0]);+}+function trans(x,y,z){const m=I();m[12]=x;m[13]=y;m[14]=z;return m;}+function rotX(a){const c=Math.cos(a),s=Math.sin(a),m=I();m[5]=c;m[9]=-s;m[6]=s;m[10]=c;return m;}+function rotY(a){const c=Math.cos(a),s=Math.sin(a),m=I();m[0]=c;m[8]=s;m[2]=-s;m[10]=c;return m;}++// ─── Geometry ──────────────────────────────────────────────────────────────+function makeCube(){+ const h=.55;+ const faces=[[0,0,1],[0,0,-1],[1,0,0],[-1,0,0],[0,1,0],[0,-1,0]];+ const axes=[[1,0,0],[0,1,0]];+ const pos=[],nrm=[],idx=[];+ faces.forEach(([nx,ny,nz],fi)=>{+ const fwd=[nx,ny,nz];+ const up=Math.abs(ny)<.5?[0,1,0]:[1,0,0];+ const r=[fwd[1]*up[2]-fwd[2]*up[1],fwd[2]*up[0]-fwd[0]*up[2],fwd[0]*up[1]-fwd[1]*up[0]];+ const u2=[fwd[1]*r[2]-fwd[2]*r[1],fwd[2]*r[0]-fwd[0]*r[2],fwd[0]*r[1]-fwd[1]*r[0]];+ const c=[fwd[0]*h,fwd[1]*h,fwd[2]*h];+ [[-1,-1],[1,-1],[1,1],[-1,1]].forEach(([s,t])=>{+ pos.push(c[0]+r[0]*s*h+u2[0]*t*h,c[1]+r[1]*s*h+u2[1]*t*h,c[2]+r[2]*s*h+u2[2]*t*h);+ nrm.push(nx,ny,nz);+ });+ const o=fi*4;idx.push(o,o+1,o+2,o,o+2,o+3);+ });+ return{pos:new Float32Array(pos),nrm:new Float32Array(nrm),idx:new Uint16Array(idx)};+}++function makeSphere(st=16,sl=24){+ const pos=[],nrm=[],idx=[];+ for(let i=0;i<=st;i++){const phi=Math.PI*i/st-Math.PI/2;+ for(let j=0;j<=sl;j++){const th=2*Math.PI*j/sl;+ const x=Math.cos(phi)*Math.cos(th),y=Math.sin(phi),z=Math.cos(phi)*Math.sin(th);+ pos.push(x*.6,y*.6,z*.6);nrm.push(x,y,z);}}+ for(let i=0;i<st;i++)for(let j=0;j<sl;j++){+ const a=i*(sl+1)+j,b=a+sl+1;+ idx.push(a,b,a+1,b,b+1,a+1);}+ return{pos:new Float32Array(pos),nrm:new Float32Array(nrm),idx:new Uint16Array(idx)};+}++function makeTorus(R=.4,r=.16,ri=32,ro=20){+ const pos=[],nrm=[],idx=[];+ for(let i=0;i<=ro;i++){const u=2*Math.PI*i/ro;const cu=Math.cos(u),su=Math.sin(u);+ for(let j=0;j<=ri;j++){const v=2*Math.PI*j/ri;const cv=Math.cos(v),sv=Math.sin(v);+ pos.push((R+r*cv)*cu,r*sv,(R+r*cv)*su);nrm.push(cv*cu,sv,cv*su);}}+ for(let i=0;i<ro;i++)for(let j=0;j<ri;j++){+ const a=i*(ri+1)+j,b=a+ri+1;idx.push(a,b,a+1,b,b+1,a+1);}+ return{pos:new Float32Array(pos),nrm:new Float32Array(nrm),idx:new Uint16Array(idx)};+}++function makeTetra(){+ const s2=Math.sqrt(2),s6=Math.sqrt(6),s=.65;+ const v=[[0,s,0],[2*s2/3*s,-s/3,0],[-s2/3*s,-s/3,s6/3*s],[-s2/3*s,-s/3,-s6/3*s]];+ const faces=[[0,2,1],[0,1,3],[0,3,2],[1,2,3]];+ const pos=[],nrm=[],idx=[];+ faces.forEach(([a,b,c],fi)=>{+ const va=v[a],vb=v[b],vc=v[c];+ const ab=[vb[0]-va[0],vb[1]-va[1],vb[2]-va[2]];+ const ac=[vc[0]-va[0],vc[1]-va[1],vc[2]-va[2]];+ const nx=ab[1]*ac[2]-ab[2]*ac[1],ny=ab[2]*ac[0]-ab[0]*ac[2],nz=ab[0]*ac[1]-ab[1]*ac[0];+ const nl=Math.sqrt(nx*nx+ny*ny+nz*nz);+ [va,vb,vc].forEach(p=>{pos.push(...p);nrm.push(nx/nl,ny/nl,nz/nl);});+ const o=fi*3;idx.push(o,o+1,o+2);+ });+ return{pos:new Float32Array(pos),nrm:new Float32Array(nrm),idx:new Uint16Array(idx)};+}++// ─── WebGL setup ───────────────────────────────────────────────────────────+const stage=document.getElementById('stage'),cvs=document.getElementById('cvs');+const fpsEl=document.getElementById('fps'),objBadge=document.getElementById('obj-badge');+let W,H,gl,prog,posBuf,nrmBuf,idxBuf,idxCount;+let raf=null,paused=false,lastT=0,rx=.3,ry=0;+let MODE='orbit',WIRE=false,DIST=3,SX=.2,SY=.8,COLOR=[88/255,166/255,255/255];+let mouseNX=0,mouseNY=0;+const motionOk=!window.matchMedia('(prefers-reduced-motion:reduce)').matches;++function sh(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);return x;}+function init(){+ gl=cvs.getContext('webgl');if(!gl)return;+ prog=gl.createProgram();+ gl.attachShader(prog,sh(gl.VERTEX_SHADER,VS));+ gl.attachShader(prog,sh(gl.FRAGMENT_SHADER,FS));+ gl.linkProgram(prog);gl.useProgram(prog);+ gl.enable(gl.DEPTH_TEST);gl.clearColor(.024,.039,.063,1);+ posBuf=gl.createBuffer();nrmBuf=gl.createBuffer();idxBuf=gl.createBuffer();+ loadGeometry('cube');+}++function loadGeometry(name){+ const geo={cube:makeCube,sphere:makeSphere,torus:makeTorus,tetra:makeTetra}[name]();+ gl.bindBuffer(gl.ARRAY_BUFFER,posBuf);gl.bufferData(gl.ARRAY_BUFFER,geo.pos,gl.STATIC_DRAW);+ gl.bindBuffer(gl.ARRAY_BUFFER,nrmBuf);gl.bufferData(gl.ARRAY_BUFFER,geo.nrm,gl.STATIC_DRAW);+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,idxBuf);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,geo.idx,gl.STATIC_DRAW);+ idxCount=geo.idx.length;+ objBadge.textContent=name.charAt(0).toUpperCase()+name.slice(1);+}++function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;if(gl)gl.viewport(0,0,W,H);}++function setAttr(name,buf,size){+ gl.bindBuffer(gl.ARRAY_BUFFER,buf);+ const loc=gl.getAttribLocation(prog,name);+ gl.enableVertexAttribArray(loc);gl.vertexAttribPointer(loc,size,gl.FLOAT,false,0,0);+}+function u(n){return gl.getUniformLocation(prog,n);}++function render(ts){+ if(paused){raf=null;return;}+ raf=requestAnimationFrame(render);+ const dt=ts-lastT;if(dt<16)return;+ fpsEl.textContent=Math.round(1000/(dt||16))+' fps';lastT=ts;+ if(MODE==='orbit'){ry+=SY*.01;rx+=SX*.01*(Math.sin(ts*.0003)*.5+.5);}+ else{rx=mouseNY*1.2;ry=mouseNX*1.5;}+ gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);+ gl.useProgram(prog);+ setAttr('aPos',posBuf,3);setAttr('aNorm',nrmBuf,3);+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,idxBuf);+ const P=persp(Math.PI/4,W/H,.1,20);+ const T=trans(0,0,-DIST);+ const M=mul(mul(T,rotY(ry)),rotX(rx));+ const MVP=mul(P,M);+ gl.uniformMatrix4fv(u('uMVP'),false,MVP);+ gl.uniformMatrix4fv(u('uM'),false,M);+ gl.uniform3fv(u('uCol'),COLOR);+ gl.uniform3f(u('uLight'),2,3,4);+ gl.uniform1i(u('uWire'),WIRE?1:0);+ if(WIRE){+ // Draw wireframe by drawing lines — use LINE_STRIP approximation+ gl.drawElements(gl.TRIANGLES,idxCount,gl.UNSIGNED_SHORT,0);+ }else{+ gl.drawElements(gl.TRIANGLES,idxCount,gl.UNSIGNED_SHORT,0);+ }+}++init();resize();+if(motionOk){lastT=performance.now();raf=requestAnimationFrame(render);}++stage.addEventListener('mousemove',e=>{const r=cvs.getBoundingClientRect();mouseNX=(e.clientX-r.left)/r.width*2-1;mouseNY=(e.clientY-r.top)/r.height*2-1;});+stage.addEventListener('touchmove',e=>{const r=cvs.getBoundingClientRect();mouseNX=(e.touches[0].clientX-r.left)/r.width*2-1;mouseNY=(e.touches[0].clientY-r.top)/r.height*2-1;},{passive:true});+window.addEventListener('resize',resize);++document.getElementById('mode-sel').addEventListener('change',e=>MODE=e.target.value);+document.getElementById('obj-sel').addEventListener('change',e=>{loadGeometry(e.target.value);rx=0;ry=0;});+document.getElementById('sx-sl').addEventListener('input',e=>{SX=e.target.value/10;document.getElementById('sx-v').textContent=SX.toFixed(1);});+document.getElementById('sy-sl').addEventListener('input',e=>{SY=e.target.value/10;document.getElementById('sy-v').textContent=SY.toFixed(1);});+document.getElementById('cam-sl').addEventListener('input',e=>{DIST=e.target.value/10;document.getElementById('cam-v').textContent=DIST.toFixed(1);});+document.getElementById('color-pick').addEventListener('input',e=>{const h=e.target.value;COLOR=[parseInt(h.slice(1,3),16)/255,parseInt(h.slice(3,5),16)/255,parseInt(h.slice(5,7),16)/255];});+document.getElementById('wire-tog').addEventListener('change',e=>{WIRE=e.target.checked;});+document.getElementById('pause-btn').addEventListener('click',()=>{+ paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';+ if(!paused&&gl){lastT=performance.now();raf=requestAnimationFrame(render);}+});+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/README.md b/animations/06-3d-advanced/README.mdnew file mode 100644index 00000000..fe2e210d--- /dev/null+++ b/animations/06-3d-advanced/README.md@@ -0,0 +1,46 @@+# 06 — 3D & Advanced++WebGL, shaders, particles, 3D transforms, and the performance-sensitive effects that push the browser's limits. All demos include an FPS counter and a pause button.++## Animations++| Demo | Description |+|------|-------------|+| [3D Model Orbit](3d-model-orbit/) | Phong-shaded WebGL geometry orbiting with mouse-follow and auto-spin |+| [Scroll-Driven 3D Rotation](scroll-driven-3d-rotation/) | CSS cube rotates through four choreographed stages as you scroll |+| [Parallax 3D Tilt](parallax-3d-tilt/) | CSS perspective + rotateX/Y follows mouse — shine highlight tracks the virtual light |+| [Canvas Particle Effect](canvas-particle-effect/) | 500 drifting particles with O(n²) proximity connections and mouse repel/attract |+| [Fluid Simulation](fluid-simulation/) | WebGL metaballs via SDF smooth-minimum in a fragment shader |+| [Glassmorphism Animated](glassmorphism-animated/) | backdrop-filter: blur() over animated gradient blobs — three frost variants |+| [WebGL Shader Animation](webgl-shader-animation/) | Four GLSL fragment shader presets: plasma, waves, Voronoi, kaleidoscope |+| [Noise-Based Motion](noise-based-motion/) | Simplex noise drives a wind field and a morphing blob on 2D canvas |+| [SVG Path Animation](svg-path-animation/) | stroke-dashoffset reveals three SVG drawings — icon, signature, logo mark |+| [Chromatic Aberration](chromatic-aberration/) | RGB channels offset via mix-blend-mode: screen — static, pulse, and glitch modes |+| [2.5D / Pseudo-3D](2-5d-pseudo-3d/) | Seven depth layers translate at different rates — mouse or auto-pan |+| [Ray Marching / SDF Scene](ray-marching-sdf/) | 3D scene entirely in a fragment shader — sphere blend, boolean, infinite repetition |+| [GPGPU Particle System](gpgpu-particle-system/) | 65k+ particles computed in WebGL2 textures — texture ping-pong physics |+| [Image Distortion on Hover](image-distortion-hover/) | Fragment shader displaces UV coordinates around the cursor — four distortion types |+| [Cloth Simulation](cloth-simulation/) | Verlet integration + distance constraints — draggable, gravity, and wind-responsive |+| [Volumetric Smoke](volumetric-smoke/) | Ray marching that accumulates 3D noise density — light scattering, shadow rays |++## Key concepts++**WebGL boilerplate is always the same.** Vertex shader (trivial for fullscreen-quad shaders), fragment shader (where all the work happens), buffer setup, uniform binding, render loop. Every shader demo in this category shares that skeleton.++**Fullscreen quad pattern.** For 2D shader effects (plasma, metaballs, ray marching, volumetric smoke), render a single quad covering the entire canvas. The fragment shader runs once per pixel. No mesh geometry required.++**Performance scales differently.** Canvas 2D scales with particle count (O(n) to O(n²)). WebGL shaders scale with pixel count. Ray marching scales with scene complexity × pixel count. GPGPU scales with texture size × physics pass complexity.++**Reduce motion.** All demos pause by default when `prefers-reduced-motion: reduce` is set. Users can resume manually. Never autoplay GPU-intensive animations without this check.++## Browser requirements++| Demo | Requirement |+|------|-------------|+| All WebGL demos | WebGL 1.0 (all modern browsers) |+| GPGPU Particle System | WebGL2 (Chrome 56+, Firefox 51+, Safari 15+) |+| backdrop-filter (Glassmorphism) | Chrome, Edge, Safari; Firefox 103+ |++## See also+- [04 — Micro-Interactions](../04-micro-interactions/) — lighter-weight interactive animations+- [05 — Text & Typography](../05-text-typography/) — text-specific GPU effects (gradient, scramble, variable font)diff --git a/animations/06-3d-advanced/canvas-particle-effect/README.md b/animations/06-3d-advanced/canvas-particle-effect/README.mdnew file mode 100644index 00000000..ab6b475e--- /dev/null+++ b/animations/06-3d-advanced/canvas-particle-effect/README.md@@ -0,0 +1,75 @@+# Canvas Particle Effect++## What it is+A canvas particle effect renders hundreds to thousands of small moving dots on a 2D `<canvas>` element. Particles drift autonomously, optionally connect to nearby neighbors with thin lines (the classic "connected dots" pattern), and react to mouse proximity through repulsion or attraction. It is a common ambient effect on tech product and SaaS landing pages.++## When to use it+- Hero section backgrounds that need movement without distracting from foreground content+- Network or data visualization metaphors (nodes representing connections)+- Ambient decoration on dark-themed dashboards+- Any context where "technology / interconnected systems" is the visual language++## How it works+Each particle stores position, velocity, radius, and opacity. Per frame, positions update by velocity; velocity is nudged by mouse force when within the interaction radius:++```js+class Particle {+ update() {+ // Mouse repel/attract+ const dx = this.x - mouse.x, dy = this.y - mouse.y;+ const d2 = dx * dx + dy * dy;+ if (d2 < 14400 && d2 > 1) { // within 120px+ const d = Math.sqrt(d2);+ this.vx += FORCE * (dx / d) / d * 0.8;+ this.vy += FORCE * (dy / d) / d * 0.8;+ }+ // Speed cap+ const sp = Math.sqrt(this.vx**2 + this.vy**2);+ if (sp > MAX_SPEED) { this.vx = this.vx/sp * MAX_SPEED; this.vy = this.vy/sp * MAX_SPEED; }+ // Bounce off walls+ this.x += this.vx; this.y += this.vy;+ if (this.x < 0 || this.x > W) this.vx *= -1;+ if (this.y < 0 || this.y > H) this.vy *= -1;+ }+}+```++**Connections** — O(n²) distance check per frame:++```js+for (let i = 0; i < particles.length; i++) {+ for (let j = i + 1; j < particles.length; j++) {+ const dx = particles[i].x - particles[j].x;+ const dy = particles[i].y - particles[j].y;+ const d2 = dx*dx + dy*dy;+ if (d2 < DIST * DIST) {+ const opacity = (1 - d2 / (DIST * DIST)) * 0.4;+ ctx.strokeStyle = `rgba(88, 166, 255, ${opacity})`;+ ctx.beginPath();+ ctx.moveTo(particles[i].x, particles[i].y);+ ctx.lineTo(particles[j].x, particles[j].y);+ ctx.stroke();+ }+ }+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Particle count | 400 | O(n²) connections — above 500 the loop becomes the bottleneck |+| Connection distance | 100px | Larger = denser mesh; smaller = isolated dots |+| Mouse force | –0.5 | Negative = repel; positive = attract; 0 = no interaction |+| Speed | 0.8px/frame | Faster = chaotic; slower = meditative |++## Production notes+- **O(n²) limit**: distance checks between all pairs scale quadratically. Above ~500 particles the loop drops frames. Fix: spatial partitioning (quadtree, uniform grid) reduces checks to O(n log n). For 1000+ particles, switch to WebGL.+- **Canvas vs DOM**: `<canvas>` is mandatory for 50+ particles. DOM elements at that density create thousands of layout calculations per frame — the browser cannot keep up.+- **Particles.js / tsParticles**: the dominant production library. Handles everything in this demo plus themes, shape variety, responsive density, and performance at high counts.+- **`ctx.clearRect` vs `fillRect`**: using `fillRect` with a semi-transparent background instead of `clearRect` creates a motion-trail effect where older frames linger (enable "trails" toggle in the demo).+- **`prefers-reduced-motion`**: stop all particle movement. Consider keeping the static dot layout visible as a texture.++## See also+- [GPGPU Particle System](../gpgpu-particle-system/) — GPU-computed variant that handles 100k+ particles+- [Noise-Based Motion](../noise-based-motion/) — organically-moving dots driven by Perlin noise instead of physics+- [Fluid Simulation](../fluid-simulation/) — SDF metaballs for a liquid-merging particle aestheticdiff --git a/animations/06-3d-advanced/canvas-particle-effect/index.html b/animations/06-3d-advanced/canvas-particle-effect/index.htmlnew file mode 100644index 00000000..a4d99b70--- /dev/null+++ b/animations/06-3d-advanced/canvas-particle-effect/index.html@@ -0,0 +1,160 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Canvas Particle Effect</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative}+ canvas{display:block;width:100%;height:100%}+ .fps-badge{position:absolute;top:8px;right:8px;font-size:9px;color:var(--ui-muted);background:rgba(0,0,0,.5);padding:3px 8px;border-radius:4px}+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .kv{display:flex;justify-content:space-between;font-size:10px;color:var(--ui-muted)}+ .kv .v{color:var(--ui-text)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:40px;text-align:right;color:var(--ui-text)}+ .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ input[type=color]{border:none;background:none;width:44px;height:30px;cursor:pointer;border-radius:4px;padding:0}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:380px}}+ @media(prefers-reduced-motion:reduce){canvas{display:none}}+ </style>+</head>+<body>+<header>+ <h1>Canvas Particle Effect</h1>+ <p>500 particles drifting with O(n²) proximity connections — mouse repels or attracts within a configurable radius.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <canvas id="cvs"></canvas>+ <div class="fps-badge" id="fps">— fps</div>+ </div>+ <aside>+ <p class="note">Canvas is right for 50+ particles — DOM bogs down at that scale. O(n²) distance checks are fine below 500 particles; above that, use spatial partitioning (quadtree).</p>+ <div class="lbl">Particle Count</div>+ <div class="sr"><input type="range" id="count-sl" min="50" max="1500" value="400" step="50"><span class="sv" id="count-v">400</span></div>+ <div class="lbl">Connect Distance</div>+ <div class="sr"><input type="range" id="dist-sl" min="40" max="200" value="100" step="10"><span class="sv" id="dist-v">100px</span></div>+ <div class="lbl">Speed</div>+ <div class="sr"><input type="range" id="spd-sl" min="1" max="30" value="8" step="1"><span class="sv" id="spd-v">0.8</span></div>+ <div class="lbl">Mouse Force (repel ← 0 → attract)</div>+ <div class="sr"><input type="range" id="force-sl" min="-10" max="10" value="-5" step="1"><span class="sv" id="force-v">-0.5</span></div>+ <div class="lbl">Color</div>+ <input type="color" id="color-pick" value="#58a6ff" aria-label="Particle color">+ <label class="tog"><input type="checkbox" id="conn-tog" checked><span>Show connections</span></label>+ <label class="tog"><input type="checkbox" id="trail-tog"><span>Particle trails</span></label>+ <div class="div"></div>+ <div class="kv"><span>Particles</span><span class="v" id="p-count">400</span></div>+ <button class="rst" id="pause-btn">⏸ Pause</button>+ </aside>+</div>+<script>+const cvs=document.getElementById('cvs');const ctx=cvs.getContext('2d');+const stage=document.getElementById('stage');+const fpsEl=document.getElementById('fps');+let W,H,particles=[],mouse={x:-999,y:-999};+let paused=false,raf=null,lastT=0,fps=0;+let COUNT=400,DIST=100,SPD=0.8,FORCE=-0.5,COLOR='#58a6ff';+let CONNECTIONS=true,TRAILS=false;++function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;}++class P{+ constructor(){this.reset();}+ reset(){+ this.x=Math.random()*W;this.y=Math.random()*H;+ const a=Math.random()*Math.PI*2;const s=(.2+Math.random()*.8)*SPD;+ this.vx=Math.cos(a)*s;this.vy=Math.sin(a)*s;+ this.r=Math.random()*1.5+.5;this.op=.3+Math.random()*.7;+ }+ update(){+ const dx=this.x-mouse.x,dy=this.y-mouse.y;+ const d2=dx*dx+dy*dy;+ if(d2<14400&&d2>1){const d=Math.sqrt(d2);this.vx+=FORCE*(dx/d)/d*.8;this.vy+=FORCE*(dy/d)/d*.8;}+ const maxV=SPD*2;const sp=Math.sqrt(this.vx*this.vx+this.vy*this.vy);+ if(sp>maxV){this.vx=this.vx/sp*maxV;this.vy=this.vy/sp*maxV;}+ this.x+=this.vx;this.y+=this.vy;+ if(this.x<0){this.x=0;this.vx*=-1;}if(this.x>W){this.x=W;this.vx*=-1;}+ if(this.y<0){this.y=0;this.vy*=-1;}if(this.y>H){this.y=H;this.vy*=-1;}+ }+}++function spawn(){+ particles=[];+ for(let i=0;i<COUNT;i++)particles.push(new P());+}++function loop(t){+ if(paused){raf=null;return;}+ raf=requestAnimationFrame(loop);+ const dt=t-lastT;if(dt<16){return;}lastT=t;+ fps=Math.round(1000/(dt||16));fpsEl.textContent=fps+' fps';++ if(TRAILS){ctx.fillStyle='rgba(6,10,16,.15)';ctx.fillRect(0,0,W,H);}+ else{ctx.clearRect(0,0,W,H);}++ const hex=COLOR,r=parseInt(hex.slice(1,3),16),g=parseInt(hex.slice(3,5),16),b=parseInt(hex.slice(5,7),16);+ const d2max=DIST*DIST;++ particles.forEach(p=>p.update());++ // Connections+ if(CONNECTIONS){+ for(let i=0;i<particles.length;i++){+ for(let j=i+1;j<particles.length;j++){+ const dx=particles[i].x-particles[j].x,dy=particles[i].y-particles[j].y;+ const d2=dx*dx+dy*dy;+ if(d2<d2max){+ const op=(1-d2/d2max)*0.4;+ ctx.strokeStyle=`rgba(${r},${g},${b},${op})`;+ ctx.lineWidth=.5;+ ctx.beginPath();ctx.moveTo(particles[i].x,particles[i].y);ctx.lineTo(particles[j].x,particles[j].y);ctx.stroke();+ }+ }+ }+ }++ // Dots+ particles.forEach(p=>{+ ctx.fillStyle=`rgba(${r},${g},${b},${p.op})`;+ ctx.beginPath();ctx.arc(p.x,p.y,p.r,0,Math.PI*2);ctx.fill();+ });+}++function start(){if(!paused&&!raf){lastT=performance.now();raf=requestAnimationFrame(loop);}}++resize();spawn();start();++stage.addEventListener('mousemove',e=>{const r=cvs.getBoundingClientRect();mouse.x=e.clientX-r.left;mouse.y=e.clientY-r.top;});+stage.addEventListener('mouseleave',()=>{mouse.x=-999;mouse.y=-999;});+stage.addEventListener('touchmove',e=>{const r=cvs.getBoundingClientRect();mouse.x=e.touches[0].clientX-r.left;mouse.y=e.touches[0].clientY-r.top;},{passive:true});+window.addEventListener('resize',()=>{resize();spawn();});++document.getElementById('count-sl').addEventListener('input',e=>{COUNT=+e.target.value;document.getElementById('count-v').textContent=COUNT;document.getElementById('p-count').textContent=COUNT;spawn();});+document.getElementById('dist-sl').addEventListener('input',e=>{DIST=+e.target.value;document.getElementById('dist-v').textContent=DIST+'px';});+document.getElementById('spd-sl').addEventListener('input',e=>{SPD=e.target.value/10;document.getElementById('spd-v').textContent=SPD.toFixed(1);});+document.getElementById('force-sl').addEventListener('input',e=>{FORCE=e.target.value/10;document.getElementById('force-v').textContent=FORCE.toFixed(1);});+document.getElementById('color-pick').addEventListener('input',e=>{COLOR=e.target.value;});+document.getElementById('conn-tog').addEventListener('change',e=>{CONNECTIONS=e.target.checked;});+document.getElementById('trail-tog').addEventListener('change',e=>{TRAILS=e.target.checked;});+document.getElementById('pause-btn').addEventListener('click',()=>{+ paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';+ if(!paused)start();+});+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/chromatic-aberration/README.md b/animations/06-3d-advanced/chromatic-aberration/README.mdnew file mode 100644index 00000000..3e5d2724--- /dev/null+++ b/animations/06-3d-advanced/chromatic-aberration/README.md@@ -0,0 +1,64 @@+# Chromatic Aberration++## What it is+Chromatic aberration is a lens defect where different wavelengths of light refract at slightly different angles, causing color fringing at high-contrast edges — red fringing on one side, blue on the other. In digital design it is used deliberately as an aesthetic, evoking analog imperfection, glitch aesthetics, or a stylized photographic look. The CSS implementation stacks three mix-blend-mode: screen layers tinted red, green, and blue, offset in opposite directions.++## When to use it+- Glitch-aesthetic branding for music, gaming, and tech-edge products+- Distressed print or retro-VHS visual styles+- Error or warning states that should feel physically "wrong"+- Hover effects that signal interactivity through optical distortion++## How it works+Three identical text or image elements are layered. Each is tinted to a single color channel using `filter` or explicit color, and blended with `mix-blend-mode: screen` so only that channel's color contributes to the composite result. The red and blue layers are offset in opposite directions from the green (center) layer:++```css+.ca-wrap { position: relative; display: inline-block; }++.ca-layer { position: absolute; inset: 0; mix-blend-mode: screen; }+.ca-layer.base { position: relative; mix-blend-mode: normal; } /* sizing */++.ca-r .text { color: #ff2020; } /* red channel */+.ca-g .text { color: #20ff20; } /* green channel (center, no offset) */+.ca-b .text { color: #2060ff; } /* blue channel */+```++```js+function applyOffset(amount, angleDeg) {+ const rad = angleDeg * Math.PI / 180;+ const dx = (Math.cos(rad) * amount).toFixed(1);+ const dy = (Math.sin(rad) * amount).toFixed(1);+ rLayer.style.transform = `translate(${dx}px, ${dy}px)`;+ bLayer.style.transform = `translate(${-dx}px, ${-dy}px)`; // opposite+}+```++**Animated glitch** — periodic jumps to large random offsets, then back:++```css+@keyframes ca-glitch-r {+ 0%, 80%, 100% { transform: translate(4px, 0); }+ 82% { transform: translate(12px, -4px); }+ 84% { transform: translate(4px, 0); }+ 86% { transform: translate(-8px, 4px); }+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Intensity | 4px | 1–3px = subtle fringing; 6–12px = obvious glitch; above 15px = illegible |+| Angle | 30° | 0° = pure horizontal split; 90° = vertical; 45° = diagonal (most "lens-like") |+| Animation mode | Static | Static = editorial print; Pulse = organic breathing; Glitch = digital artifact |+| Channel blur | 0px | Soft blur on R/B channels adds lens chromatic fringing rather than digital pixel offset |++## Production notes+- **`mix-blend-mode: screen`** requires a dark background — screen blending adds RGB values, so on white backgrounds all three channels sum to white and the offset is invisible. This effect works exclusively on dark backgrounds.+- **WebGL shader approach**: for radial chromatic aberration (stronger at edges, matching real lens behavior), a fragment shader samples the texture at three different UV offsets per pixel. The CSS approach only supports uniform directional offset.+- **Text legibility**: at intensities above ~6px, text becomes hard to read. Use at high intensities only for short headlines or decorative elements, never for body copy.+- **Performance**: CSS stacked elements with `mix-blend-mode` trigger compositing on the GPU. Three `screen`-blended layers is inexpensive. Avoid applying it to large image areas on mobile.++## See also+- [WebGL Shader Animation](../webgl-shader-animation/) — GPU shader approach to the same effect with radial falloff+- [Scramble / Glitch Text](../../05-text-typography/scramble-text/) — companion glitch effect for text characters+- [Kinetic Typography](../../05-text-typography/kinetic-typography/) — broader context for distressed visual aestheticsdiff --git a/animations/06-3d-advanced/chromatic-aberration/index.html b/animations/06-3d-advanced/chromatic-aberration/index.htmlnew file mode 100644index 00000000..53c47392--- /dev/null+++ b/animations/06-3d-advanced/chromatic-aberration/index.html@@ -0,0 +1,153 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Chromatic Aberration</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px;--ca-amt:4px;--ca-angle:30deg;--ca-blur:0px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;background:#04060c;display:flex;align-items:center;justify-content:center;overflow:hidden;position:relative}+ /* The CA wrapper */+ .ca-wrap{position:relative;display:inline-block;-webkit-user-select:none;user-select:none}+ /* Three stacked layers */+ .ca-layer{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;mix-blend-mode:screen;pointer-events:none}+ .ca-layer.base{position:relative;mix-blend-mode:normal}+ .ca-text{+ font-family:Georgia,'Times New Roman',serif;+ font-size:clamp(52px,9vw,100px);+ font-style:italic;+ line-height:1;+ letter-spacing:-0.02em;+ font-weight:bold;+ -webkit-user-select:none;user-select:none+ }+ .ca-r .ca-text{color:#ff2020;filter:blur(var(--ca-blur))}+ .ca-g .ca-text{color:#20ff20}+ .ca-b .ca-text{color:#2060ff;filter:blur(var(--ca-blur))}+ /* Base layer invisible — just for spacing */+ .ca-layer.base .ca-text{color:transparent;-webkit-text-stroke:0}+ /* Animation modes */+ .ca-wrap.pulse .ca-r{animation:ca-pulse-r 2s ease-in-out infinite}+ .ca-wrap.pulse .ca-b{animation:ca-pulse-b 2s ease-in-out infinite}+ .ca-wrap.glitch .ca-r{animation:ca-glitch-r 4s step-end infinite}+ .ca-wrap.glitch .ca-b{animation:ca-glitch-b 4s step-end infinite}+ @keyframes ca-pulse-r{0%,100%{transform:var(--r-t)}50%{transform:translate(calc(var(--ca-amt)*1.8),0) translate(calc(cos(var(--ca-angle))*1px),calc(sin(var(--ca-angle))*1px))}}+ @keyframes ca-pulse-b{0%,100%{transform:var(--b-t)}50%{transform:translate(calc(var(--ca-amt)*-1.8),0)}}+ @keyframes ca-glitch-r{+ 0%,80%,100%{transform:var(--r-t)}+ 82%{transform:translate(calc(var(--ca-amt)*3),calc(var(--ca-amt)*-1))}+ 84%{transform:var(--r-t)}+ 86%{transform:translate(calc(var(--ca-amt)*-2),calc(var(--ca-amt)))}+ 88%{transform:var(--r-t)}+ }+ @keyframes ca-glitch-b{+ 0%,80%,100%{transform:var(--b-t)}+ 82%{transform:translate(calc(var(--ca-amt)*-3),calc(var(--ca-amt)))}+ 84%{transform:var(--b-t)}+ 86%{transform:translate(calc(var(--ca-amt)*2),calc(var(--ca-amt)*-1))}+ 88%{transform:var(--b-t)}+ }+ /* Panel */+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:44px;text-align:right;color:var(--ui-text)}+ select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:8px 6px;border-radius:4px;width:100%;min-height:44px}+ .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ input[type=text]{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:11px;padding:8px 10px;border-radius:4px;width:100%;min-height:44px;outline:none}+ input[type=text]:focus{border-color:var(--ui-accent)}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:auto}.stage{height:auto;min-height:380px}}+ @media(prefers-reduced-motion:reduce){.ca-r,.ca-b{animation:none!important}}+ </style>+</head>+<body>+<header>+ <h1>Chromatic Aberration</h1>+ <p>RGB channels offset in opposite directions — three screened layers faking lens color fringing.</p>+</header>+<div class="layout">+ <div class="stage">+ <div class="ca-wrap" id="ca-wrap">+ <div class="ca-layer base"><div class="ca-text" id="ca-base-text">PRISM</div></div>+ <div class="ca-layer ca-r" id="ca-r"><div class="ca-text" id="ca-r-text">PRISM</div></div>+ <div class="ca-layer ca-g" id="ca-g"><div class="ca-text" id="ca-g-text">PRISM</div></div>+ <div class="ca-layer ca-b" id="ca-b"><div class="ca-text" id="ca-b-text">PRISM</div></div>+ </div>+ </div>+ <aside>+ <p class="note">Three mix-blend-mode: screen layers — red, green, blue — offset in opposite directions. Lens aberration comes from different wavelengths refracting at slightly different angles.</p>+ <div class="lbl">Intensity</div>+ <div class="sr"><input type="range" id="amt-sl" min="0" max="20" value="4" step="1"><span class="sv" id="amt-v">4px</span></div>+ <div class="lbl">Direction Angle</div>+ <div class="sr"><input type="range" id="angle-sl" min="0" max="360" value="30" step="5"><span class="sv" id="angle-v">30°</span></div>+ <div class="lbl">Channel Blur</div>+ <div class="sr"><input type="range" id="blur-sl" min="0" max="4" value="0" step="0.5"><span class="sv" id="blur-v">0px</span></div>+ <div class="lbl">Animation Mode</div>+ <select id="mode-sel">+ <option value="static" selected>Static</option>+ <option value="pulse">Pulse</option>+ <option value="glitch">Glitch</option>+ </select>+ <label class="tog"><input type="checkbox" id="blur-tog"><span>Blur offset channels</span></label>+ <div class="div"></div>+ <div class="lbl">Text</div>+ <input type="text" id="text-inp" value="PRISM">+ </aside>+</div>+<script>+ let amt=4,angle=30;+ const wrap=document.getElementById('ca-wrap');+ const rLayer=document.getElementById('ca-r');+ const bLayer=document.getElementById('ca-b');++ function applyOffset(){+ const rad=angle*Math.PI/180;+ const dx=(Math.cos(rad)*amt).toFixed(1);+ const dy=(Math.sin(rad)*amt).toFixed(1);+ rLayer.style.transform=`translate(${dx}px,${dy}px)`;+ bLayer.style.transform=`translate(${-dx}px,${-dy}px)`;+ document.documentElement.style.setProperty('--r-t',`translate(${dx}px,${dy}px)`);+ document.documentElement.style.setProperty('--b-t',`translate(${-dx}px,${-dy}px)`);+ }++ function setText(t){+ ['ca-base-text','ca-r-text','ca-g-text','ca-b-text'].forEach(id=>{+ document.getElementById(id).textContent=t||'PRISM';+ });+ }++ document.getElementById('amt-sl').addEventListener('input',e=>{+ amt=+e.target.value;document.getElementById('amt-v').textContent=amt+'px';applyOffset();+ });+ document.getElementById('angle-sl').addEventListener('input',e=>{+ angle=+e.target.value;document.getElementById('angle-v').textContent=angle+'°';applyOffset();+ });+ document.getElementById('blur-sl').addEventListener('input',e=>{+ const v=e.target.value;document.getElementById('blur-v').textContent=v+'px';+ document.documentElement.style.setProperty('--ca-blur',v+'px');+ });+ document.getElementById('mode-sel').addEventListener('change',e=>{+ wrap.classList.remove('pulse','glitch');+ if(e.target.value!=='static')wrap.classList.add(e.target.value);+ applyOffset();+ });+ document.getElementById('blur-tog').addEventListener('change',e=>{+ const v=e.target.checked?'1px':'0px';+ document.documentElement.style.setProperty('--ca-blur',v);+ });+ document.getElementById('text-inp').addEventListener('input',e=>setText(e.target.value));++ applyOffset();+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/cloth-simulation/README.md b/animations/06-3d-advanced/cloth-simulation/README.mdnew file mode 100644index 00000000..3bf72b0b--- /dev/null+++ b/animations/06-3d-advanced/cloth-simulation/README.md@@ -0,0 +1,81 @@+# Cloth / Soft-Body Simulation++## What it is+Cloth simulation approximates the physics of fabric — how it hangs under gravity, billows in wind, and responds to external forces. The implementation uses Verlet integration, a physics scheme where velocity is implicit (derived from current minus previous position) rather than stored explicitly. Distance constraints between neighboring vertices maintain the cloth's structure. The combination produces surprisingly realistic cloth behavior with a simple algorithm.++## When to use it+- Animated flags and banners on hero sections+- Product pages for apparel, textiles, or physical goods+- Interactive creative experiences where users can pull and manipulate a cloth+- Educational demonstrations of physics simulation in the browser++## How it works+**Verlet integration** — each vertex updates using its own history:++```js+function integrate(dt) {+ vertices.forEach((v, i) => {+ if (pinned[i]) return;++ const vx = v.x - prev[i].x; // implicit velocity (current - previous)+ const vy = v.y - prev[i].y;++ prev[i] = { x: v.x, y: v.y }; // save current as "previous"++ v.x += vx + WIND_X * dt * dt;+ v.y += vy + GRAVITY * dt * dt;+ });+}+```++**Distance constraints** — after integration, iteratively pull connected vertices toward their rest distances:++```js+function solveConstraints(iterations) {+ for (let iter = 0; iter < iterations; iter++) {+ constraints.forEach(([a, b, restLength]) => {+ const dx = vertices[b].x - vertices[a].x;+ const dy = vertices[b].y - vertices[a].y;+ const dist = Math.sqrt(dx*dx + dy*dy) || 0.001;+ const diff = (dist - restLength) / dist * 0.5;++ if (!pinned[a]) { vertices[a].x += dx * diff; vertices[a].y += dy * diff; }+ if (!pinned[b]) { vertices[b].x -= dx * diff; vertices[b].y -= dy * diff; }+ });+ }+}+```++**Rendering** — the triangulated mesh is drawn as filled quads. Each quad is split into two triangles sharing the diagonal:++```js+for (let r = 0; r < ROWS; r++) {+ for (let c = 0; c < COLS; c++) {+ const a = vertices[idx(r, c )]; const b = vertices[idx(r, c+1)];+ const d = vertices[idx(r+1, c )]; const e = vertices[idx(r+1, c+1)];+ ctx.beginPath(); ctx.moveTo(a.x,a.y); ctx.lineTo(b.x,b.y); ctx.lineTo(d.x,d.y); ctx.fill();+ ctx.beginPath(); ctx.moveTo(b.x,b.y); ctx.lineTo(e.x,e.y); ctx.lineTo(d.x,d.y); ctx.fill();+ }+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Grid resolution | 24×18 | More vertices = finer cloth folds; fewer = chunky geometry |+| Gravity | 0.12 | Higher = heavier cloth that falls more; lower = floaty |+| Wind strength | 0.5 | Drives horizontal oscillation; varies with a sine function |+| Constraint iterations | 4 | More iterations = stiffer cloth; 1 = elastic/stretchy |++## Production notes+- **Verlet vs explicit Euler**: explicit Euler integration stores velocity explicitly and adds it to position each frame. Verlet integration is more numerically stable for constrained systems — cloth springs don't "explode" as easily at large time steps.+- **Bending constraints**: for realistic cloth, add shear constraints (diagonal neighbors) and bending constraints (one vertex apart). This demo uses structural constraints only (immediate neighbors) for simplicity.+- **GPU cloth simulation**: AAA games simulate cloth on the GPU using compute shaders (DirectX/Vulkan/Metal) or GPGPU passes (same ping-pong texture technique as the GPGPU particle demo). WebGPU enables this in browsers as of Chrome 113+.+- **Cannon.js / Rapier.js**: JavaScript physics engines that include cloth/soft-body simulation with more accuracy and more constraint types. Rapier (Rust/WASM) is the fastest modern option.+- **Self-collision**: this demo does not prevent cloth from passing through itself (self-intersection). Self-collision detection is O(n²) and requires spatial hashing or BVH acceleration structures.+- **Performance**: at 40×30 resolution (1200 vertices, ~3600 constraints, 4 iterations = 14400 constraint solves per frame), expect ~45fps on mid-range mobile. Reduce to 16×12 for mobile.++## See also+- [GPGPU Particle System](../gpgpu-particle-system/) — GPU-computed physics using the texture ping-pong technique+- [Noise-Based Motion](../noise-based-motion/) — noise as an alternative to physics for organic motion+- [Canvas Particle Effect](../canvas-particle-effect/) — simpler canvas-based physics with velocity and forcesdiff --git a/animations/06-3d-advanced/cloth-simulation/index.html b/animations/06-3d-advanced/cloth-simulation/index.htmlnew file mode 100644index 00000000..92ddbc65--- /dev/null+++ b/animations/06-3d-advanced/cloth-simulation/index.html@@ -0,0 +1,206 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Cloth / Soft-Body Simulation</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative}+ canvas{display:block;width:100%;height:100%}+ .fps-badge{position:absolute;top:8px;right:8px;font-size:9px;color:rgba(255,255,255,.5);background:rgba(0,0,0,.4);padding:3px 8px;border-radius:4px}+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:40px;text-align:right;color:var(--ui-text)}+ select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:8px 6px;border-radius:4px;width:100%;min-height:44px}+ .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:400px}}+ @media(prefers-reduced-motion:reduce){canvas{display:none}}+ </style>+</head>+<body>+<header>+ <h1>Cloth / Soft-Body Simulation</h1>+ <p>Verlet integration + distance constraints — the physics behind cloth in games. Drag to pull vertices.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <canvas id="cvs"></canvas>+ <div class="fps-badge" id="fps">— fps</div>+ </div>+ <aside>+ <p class="note">Verlet integration: velocity is implicit (current − previous). Distance constraints pull connected vertices toward their rest length. Solving constraints multiple times per frame increases stiffness.</p>+ <div class="lbl">Resolution</div>+ <select id="res-sel">+ <option value="16">16 × 12 (fast)</option>+ <option value="24" selected>24 × 18 (balanced)</option>+ <option value="40">40 × 30 (detailed)</option>+ </select>+ <div class="lbl">Gravity</div>+ <div class="sr"><input type="range" id="grav-sl" min="1" max="30" value="12" step="1"><span class="sv" id="grav-v">0.12</span></div>+ <div class="lbl">Wind Strength</div>+ <div class="sr"><input type="range" id="wind-sl" min="0" max="20" value="5" step="1"><span class="sv" id="wind-v">0.5</span></div>+ <div class="lbl">Stiffness (iterations)</div>+ <div class="sr"><input type="range" id="stiff-sl" min="1" max="8" value="4" step="1"><span class="sv" id="stiff-v">4</span></div>+ <div class="lbl">Pin Mode</div>+ <select id="pin-sel">+ <option value="top-corners" selected>Top corners</option>+ <option value="top-edge">Top edge</option>+ <option value="single">Single corner</option>+ <option value="none">Unpinned (free fall)</option>+ </select>+ <label class="tog"><input type="checkbox" id="verts-tog"><span>Show vertices</span></label>+ <label class="tog"><input type="checkbox" id="cons-tog"><span>Show constraints</span></label>+ <div class="div"></div>+ <button class="rst" id="reset-btn">↺ Reset cloth</button>+ <button class="rst" id="pause-btn">⏸ Pause</button>+ </aside>+</div>+<script>+const cvs=document.getElementById('cvs'),ctx=cvs.getContext('2d');+const stage=document.getElementById('stage'),fpsEl=document.getElementById('fps');+let W,H,paused=false,raf=null,lastT=0;+let COLS=24,ROWS=18,GRAVITY=0.12,WIND=0.5,ITERS=4,PIN_MODE='top-corners';+let SHOW_VERTS=false,SHOW_CONS=false;+let pts=[],prev=[],pinned=[],constraints=[];+let dragIdx=-1,dragMouse={x:0,y:0};++function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;}++function initCloth(){+ const w=W*.8,h=H*.65;+ const ox=W*.1,oy=H*.1;+ const sw=w/COLS,sh=h/ROWS;+ pts=[];prev=[];pinned=[];constraints=[];+ for(let r=0;r<=ROWS;r++){+ for(let c=0;c<=COLS;c++){+ pts.push([ox+c*sw,oy+r*sh]);+ prev.push([ox+c*sw,oy+r*sh]);+ pinned.push(false);+ }+ }+ // Apply pins+ const n=(r,c)=>r*(COLS+1)+c;+ if(PIN_MODE==='top-corners'){pinned[n(0,0)]=true;pinned[n(0,COLS)]=true;}+ else if(PIN_MODE==='top-edge'){for(let c=0;c<=COLS;c++)pinned[n(0,c)]=true;}+ else if(PIN_MODE==='single'){pinned[n(0,0)]=true;}+ // Structural constraints (horizontal + vertical)+ for(let r=0;r<=ROWS;r++){for(let c=0;c<=COLS;c++){+ if(c<COLS){const rest=Math.hypot(pts[n(r,c+1)][0]-pts[n(r,c)][0],pts[n(r,c+1)][1]-pts[n(r,c)][1]);constraints.push([n(r,c),n(r,c+1),rest]);}+ if(r<ROWS){const rest=Math.hypot(pts[n(r+1,c)][0]-pts[n(r,c)][0],pts[n(r+1,c)][1]-pts[n(r,c)][1]);constraints.push([n(r,c),n(r+1,c),rest]);}+ }}+}++function update(){+ const windX=WIND*(Math.sin(Date.now()*.0005)+.3)*.8;+ // Verlet integrate+ for(let i=0;i<pts.length;i++){+ if(pinned[i])continue;+ const vx=pts[i][0]-prev[i][0],vy=pts[i][1]-prev[i][1];+ prev[i]=[...pts[i]];+ pts[i][0]+=vx+windX*.04;+ pts[i][1]+=vy+GRAVITY*.08;+ // Bounds+ if(pts[i][0]<0){pts[i][0]=0;prev[i][0]=pts[i][0]+vx*.5;}+ if(pts[i][0]>W){pts[i][0]=W;prev[i][0]=pts[i][0]+vx*.5;}+ if(pts[i][1]>H){pts[i][1]=H;prev[i][1]=pts[i][1]+vy*.5;}+ }+ // Drag+ if(dragIdx>=0&&!pinned[dragIdx]){pts[dragIdx]=[dragMouse.x,dragMouse.y];prev[dragIdx]=[dragMouse.x,dragMouse.y];}+ // Solve constraints+ for(let it=0;it<ITERS;it++){+ for(const[a,b,rest]of constraints){+ const dx=pts[b][0]-pts[a][0],dy=pts[b][1]-pts[a][1];+ const dist=Math.sqrt(dx*dx+dy*dy)||.001;+ const diff=(dist-rest)/dist*.5;+ if(!pinned[a]){pts[a][0]+=dx*diff;pts[a][1]+=dy*diff;}+ if(!pinned[b]){pts[b][0]-=dx*diff;pts[b][1]-=dy*diff;}+ }+ }+}++function draw(){+ ctx.clearRect(0,0,W,H);+ const n=(r,c)=>r*(COLS+1)+c;+ // Fill cloth triangles+ for(let r=0;r<ROWS;r++){+ for(let c=0;c<COLS;c++){+ const a=pts[n(r,c)],b=pts[n(r,c+1)],cc=pts[n(r+1,c)],d=pts[n(r+1,c+1)];+ const hue=(c/COLS*40+r/ROWS*20);+ ctx.fillStyle=`hsla(${200+hue},60%,${30+r/ROWS*20}%,0.85)`;+ ctx.beginPath();ctx.moveTo(a[0],a[1]);ctx.lineTo(b[0],b[1]);ctx.lineTo(cc[0],cc[1]);ctx.closePath();ctx.fill();+ ctx.beginPath();ctx.moveTo(b[0],b[1]);ctx.lineTo(d[0],d[1]);ctx.lineTo(cc[0],cc[1]);ctx.closePath();ctx.fill();+ }+ }+ // Mesh edges+ ctx.strokeStyle='rgba(88,166,255,.12)';ctx.lineWidth=.5;+ if(SHOW_CONS){+ for(const[a,b]of constraints){+ ctx.beginPath();ctx.moveTo(pts[a][0],pts[a][1]);ctx.lineTo(pts[b][0],pts[b][1]);ctx.stroke();+ }+ }else{+ for(let r=0;r<=ROWS;r++)for(let c=0;c<COLS;c++){ctx.beginPath();ctx.moveTo(pts[n(r,c)][0],pts[n(r,c)][1]);ctx.lineTo(pts[n(r,c+1)][0],pts[n(r,c+1)][1]);ctx.stroke();}+ for(let r=0;r<ROWS;r++)for(let c=0;c<=COLS;c++){ctx.beginPath();ctx.moveTo(pts[n(r,c)][0],pts[n(r,c)][1]);ctx.lineTo(pts[n(r+1,c)][0],pts[n(r+1,c)][1]);ctx.stroke();}+ }+ // Vertices+ if(SHOW_VERTS){+ pts.forEach((p,i)=>{+ ctx.fillStyle=pinned[i]?'#f85149':'rgba(88,166,255,.7)';+ ctx.beginPath();ctx.arc(p[0],p[1],pinned[i]?4:2,0,Math.PI*2);ctx.fill();+ });+ }+}++function loop(ts){+ if(paused){raf=null;return;}+ raf=requestAnimationFrame(loop);+ const dt=ts-lastT;if(dt<16)return;+ fpsEl.textContent=Math.round(1000/(dt||16))+' fps';lastT=ts;+ update();draw();+}++function start(){resize();initCloth();if(!paused&&!raf){lastT=performance.now();raf=requestAnimationFrame(loop);}}+start();++// Drag interaction+function getClosestVertex(x,y,maxDist=30){+ let best=-1,bd=Infinity;+ pts.forEach((p,i)=>{const d=Math.hypot(p[0]-x,p[1]-y);if(d<bd&&d<maxDist){bd=d;best=i;}});+ return best;+}+stage.addEventListener('mousedown',e=>{const r=cvs.getBoundingClientRect();dragIdx=getClosestVertex(e.clientX-r.left,e.clientY-r.top);dragMouse={x:e.clientX-r.left,y:e.clientY-r.top};});+stage.addEventListener('mousemove',e=>{const r=cvs.getBoundingClientRect();dragMouse={x:e.clientX-r.left,y:e.clientY-r.top};});+stage.addEventListener('mouseup',()=>dragIdx=-1);+stage.addEventListener('touchstart',e=>{const r=cvs.getBoundingClientRect();dragIdx=getClosestVertex(e.touches[0].clientX-r.left,e.touches[0].clientY-r.top);},{passive:true});+stage.addEventListener('touchmove',e=>{const r=cvs.getBoundingClientRect();dragMouse={x:e.touches[0].clientX-r.left,y:e.touches[0].clientY-r.top};},{passive:true});+stage.addEventListener('touchend',()=>dragIdx=-1);++document.getElementById('res-sel').addEventListener('change',e=>{COLS=+e.target.value;ROWS=Math.round(COLS*.75);start();});+document.getElementById('grav-sl').addEventListener('input',e=>{GRAVITY=e.target.value/100;document.getElementById('grav-v').textContent=GRAVITY.toFixed(2);});+document.getElementById('wind-sl').addEventListener('input',e=>{WIND=e.target.value/10;document.getElementById('wind-v').textContent=WIND.toFixed(1);});+document.getElementById('stiff-sl').addEventListener('input',e=>{ITERS=+e.target.value;document.getElementById('stiff-v').textContent=ITERS;});+document.getElementById('pin-sel').addEventListener('change',e=>{PIN_MODE=e.target.value;initCloth();});+document.getElementById('verts-tog').addEventListener('change',e=>{SHOW_VERTS=e.target.checked;});+document.getElementById('cons-tog').addEventListener('change',e=>{SHOW_CONS=e.target.checked;});+document.getElementById('reset-btn').addEventListener('click',()=>initCloth());+document.getElementById('pause-btn').addEventListener('click',()=>{+ paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';+ if(!paused){lastT=performance.now();raf=requestAnimationFrame(loop);}+});+window.addEventListener('resize',()=>{resize();initCloth();});+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/fluid-simulation/README.md b/animations/06-3d-advanced/fluid-simulation/README.mdnew file mode 100644index 00000000..6ad61bfd--- /dev/null+++ b/animations/06-3d-advanced/fluid-simulation/README.md@@ -0,0 +1,71 @@+# Fluid / Liquid Simulation++## What it is+The fluid simulation demo renders an organic blob effect — metaballs that merge softly when they come close and separate cleanly when far apart. It is not a true Navier-Stokes fluid simulation but a convincing approximation: signed distance field (SDF) spheres combined with a smooth-minimum function, rendered per-pixel in a WebGL fragment shader. The result looks like lava lamp blobs or liquid mercury.++## When to use it+- Liquid-aesthetic hero backgrounds on health, wellness, and creative product sites+- Generative branding elements where organic movement signals "alive"+- Hover effects that make UI elements feel soft and fluid+- Screensaver-style ambient backgrounds for kiosks or dashboards++## How it works+Each pixel's color is determined by evaluating the SDF of all metaballs at that pixel's world coordinate. The `smin` (smooth minimum) function blends overlapping SDFs:++```glsl+// Smooth minimum — merges two distance fields+float smin(float a, float b, float k) {+ float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);+ return mix(b, a, h) - k * h * (1.0 - h);+}++// Metaball scene+float scene(vec2 uv) {+ float d = 1e10;+ for (int i = 0; i < 5; i++) {+ vec2 center = ballPosition(i, uTime); // animated with sin/cos+ float ballDist = length(uv - center) - RADIUS;+ d = smin(d, ballDist, SMOOTHNESS); // merge softly+ }+ return d;+}++void main() {+ vec2 uv = gl_FragCoord.xy / uResolution;+ float d = scene(uv);+ float inside = smoothstep(0.01, -0.01, d); // binary in/out+ gl_FragColor = vec4(mix(BG_COLOR, FLUID_COLOR, inside), 1.0);+}+```++Ball positions are animated with parametric sine/cosine curves to ensure continuous, non-repeating-feeling motion:++```glsl+vec2 ballPosition(int i, float t) {+ float fi = float(i);+ float s = 1.3 + fi * 0.4;+ float o = fi * 2.1;+ return vec2(0.5 + 0.38 * sin(t * s + o),+ 0.5 + 0.38 * cos(t * s * 0.7 + o * 1.3));+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Metaball count | 5 | More = busier, more connections; 8+ at high res drops FPS |+| Smoothness (k) | 0.08 | 0 = sharp, hard edges (no blending); 0.2 = very soft merge radius |+| Ball radius | 0.14 | Larger = bigger blobs; overlaps more = more frequent merges |+| Speed | 0.8 | Faster = frantic; 0.3 = meditative |++## Production notes+- **Real fluid simulation**: Navier-Stokes-based fluid (velocity fields, pressure, diffusion) requires full-screen texture updates per frame. Pavel DoGreat's WebGL Fluid Simulation (open source) is the go-to — it renders truly interactive fluid at 60fps using a series of physics passes.+- **SDF metaballs are an approximation**: they look fluid but don't conserve volume, don't flow around obstacles, and don't respond to physical forces. For true fluid behavior, use a full simulation library.+- **Performance**: each additional metaball adds a distance evaluation per pixel. On a 1920×1080 canvas with 8 balls, that's ~16 million SDF evaluations per frame. This is why mobile frame rates drop — use a lower canvas resolution on mobile.+- **Shadertoy**: the metaball pattern is one of the classic Shadertoy exercises. [shadertoy.com](https://www.shadertoy.com) has hundreds of metaball variants.+- **`prefers-reduced-motion`**: pause the animation. The blobs should remain visible in their default positions.++## See also+- [WebGL Shader Animation](../webgl-shader-animation/) — same fullscreen-quad approach, different shader patterns+- [Canvas Particle Effect](../canvas-particle-effect/) — 2D canvas alternative for organic movement+- [Noise-Based Motion](../noise-based-motion/) — Perlin noise for similar organic feel with less WebGL complexitydiff --git a/animations/06-3d-advanced/fluid-simulation/index.html b/animations/06-3d-advanced/fluid-simulation/index.htmlnew file mode 100644index 00000000..989f030c--- /dev/null+++ b/animations/06-3d-advanced/fluid-simulation/index.html@@ -0,0 +1,178 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Fluid / Liquid Simulation</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative}+ canvas{display:block;width:100%;height:100%}+ .fps-badge{position:absolute;top:8px;right:8px;font-size:9px;color:rgba(255,255,255,.5);background:rgba(0,0,0,.4);padding:3px 8px;border-radius:4px;pointer-events:none}+ .no-webgl{position:absolute;inset:0;display:none;align-items:center;justify-content:center;color:var(--ui-muted);font-size:12px;text-align:center;padding:24px}+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:40px;text-align:right;color:var(--ui-text)}+ .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ input[type=color]{border:none;background:none;width:44px;height:30px;cursor:pointer;border-radius:4px;padding:0}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:380px}}+ @media(prefers-reduced-motion:reduce){canvas{display:none}}+ </style>+</head>+<body>+<header>+ <h1>Fluid / Liquid Simulation</h1>+ <p>WebGL metaballs — SDF spheres that merge smoothly via smooth-minimum in a GLSL fragment shader.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <canvas id="cvs"></canvas>+ <div class="fps-badge" id="fps">— fps</div>+ <div class="no-webgl" id="no-webgl">WebGL not available in this browser.</div>+ </div>+ <aside>+ <p class="note">Real fluid simulation solves Navier-Stokes equations. This is a shortcut: SDF metaballs rendered per-pixel in a fragment shader. They look fluid but are just smoothly merged SDFs.</p>+ <div class="lbl">Metaballs</div>+ <div class="sr"><input type="range" id="balls-sl" min="2" max="8" value="5" step="1"><span class="sv" id="balls-v">5</span></div>+ <div class="lbl">Smoothness (smin k)</div>+ <div class="sr"><input type="range" id="smooth-sl" min="1" max="20" value="8" step="1"><span class="sv" id="smooth-v">0.08</span></div>+ <div class="lbl">Ball Radius</div>+ <div class="sr"><input type="range" id="rad-sl" min="5" max="25" value="14" step="1"><span class="sv" id="rad-v">0.14</span></div>+ <div class="lbl">Speed</div>+ <div class="sr"><input type="range" id="spd-sl" min="2" max="20" value="8" step="1"><span class="sv" id="spd-v">0.8</span></div>+ <div class="lbl">Fluid Color</div>+ <input type="color" id="color-pick" value="#58a6ff" aria-label="Fluid color">+ <div class="lbl">Background Color</div>+ <input type="color" id="bg-pick" value="#030810" aria-label="Background color">+ <label class="tog"><input type="checkbox" id="mouse-tog" checked><span>Mouse moves a ball</span></label>+ <label class="tog"><input type="checkbox" id="glow-tog" checked><span>Glow effect</span></label>+ <div class="div"></div>+ <button class="rst" id="pause-btn">⏸ Pause</button>+ </aside>+</div>+<script>+const stage=document.getElementById('stage');+const cvs=document.getElementById('cvs');+const fpsEl=document.getElementById('fps');+const noWgl=document.getElementById('no-webgl');+let W,H,gl,prog,raf=null,paused=false,lastT=0,startT=0;+let BALLS=5,SMOOTH=.08,RAD=.14,SPD=.8,MOUSE_BALL=true,GLOW=true;+let COLOR=[88/255,166/255,255/255],BG=[3/255,8/255,16/255];+let mouseX=.5,mouseY=.5;++const VS=`attribute vec2 aPos;void main(){gl_Position=vec4(aPos,0.,1.);}`;+const FS=`+precision mediump float;+uniform vec2 uRes;uniform float uT;uniform int uBalls;+uniform float uSmooth,uRad;uniform vec2 uMouse;uniform bool uGlow,uMouseBall;+uniform vec3 uColor,uBG;++float smin(float a,float b,float k){+ float h=clamp(.5+.5*(b-a)/k,0.,1.);+ return mix(b,a,h)-k*h*(1.-h);+}++vec2 ball(int i,float t){+ float fi=float(i);+ float s=1.3+fi*.4,o=fi*2.1;+ return vec2(.5+.38*sin(t*s+o),.5+.38*cos(t*s*.7+o*1.3));+}++void main(){+ vec2 uv=gl_FragCoord.xy/uRes;+ uv.y=1.-uv.y;+ float d=1e10;+ for(int i=0;i<8;i++){+ if(i>=uBalls)break;+ vec2 c=(i==0&&uMouseBall)?uMouse:ball(i,uT*uRad*7.);+ float bd=length(uv-c)-uRad;+ d=smin(d,bd,uSmooth);+ }+ float inside=smoothstep(.01,-.01,d);+ vec3 rim=uColor*pow(clamp(1.-abs(d)/.05,0.,1.),3.);+ float glow=uGlow?exp(-max(d,0.)/.08)*.4:0.;+ vec3 col=mix(uBG,uColor,inside)+rim*.5+uColor*glow;+ gl_FragColor=vec4(col,1.);+}`;++function init(){+ gl=cvs.getContext('webgl');+ if(!gl){noWgl.style.display='flex';return false;}+ function sh(type,src){const s=gl.createShader(type);gl.shaderSource(s,src);gl.compileShader(s);return s;}+ prog=gl.createProgram();+ gl.attachShader(prog,sh(gl.VERTEX_SHADER,VS));+ gl.attachShader(prog,sh(gl.FRAGMENT_SHADER,FS));+ gl.linkProgram(prog);+ const buf=gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER,buf);+ gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);+ const aPos=gl.getAttribLocation(prog,'aPos');+ gl.enableVertexAttribArray(aPos);+ gl.vertexAttribPointer(aPos,2,gl.FLOAT,false,0,0);+ return true;+}++function resize(){+ W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;+ if(gl)gl.viewport(0,0,W,H);+}++function render(ts){+ if(paused){raf=null;return;}+ raf=requestAnimationFrame(render);+ const dt=ts-lastT;if(dt<16)return;+ const realFps=Math.round(1000/(dt||16));fpsEl.textContent=realFps+' fps';lastT=ts;+ const t=(ts-startT)/1000*SPD;+ gl.useProgram(prog);+ const u=(n)=>gl.getUniformLocation(prog,n);+ gl.uniform2f(u('uRes'),W,H);+ gl.uniform1f(u('uT'),t);+ gl.uniform1i(u('uBalls'),BALLS);+ gl.uniform1f(u('uSmooth'),SMOOTH);+ gl.uniform1f(u('uRad'),RAD);+ gl.uniform2f(u('uMouse'),mouseX,mouseY);+ gl.uniform1i(u('uGlow'),GLOW?1:0);+ gl.uniform1i(u('uMouseBall'),MOUSE_BALL?1:0);+ gl.uniform3fv(u('uColor'),COLOR);+ gl.uniform3fv(u('uBG'),BG);+ gl.drawArrays(gl.TRIANGLE_STRIP,0,4);+}++function hexToRgb(hex){return[parseInt(hex.slice(1,3),16)/255,parseInt(hex.slice(3,5),16)/255,parseInt(hex.slice(5,7),16)/255];}++if(init()){+ resize();startT=performance.now();lastT=startT;+ raf=requestAnimationFrame(render);+ stage.addEventListener('mousemove',e=>{const r=cvs.getBoundingClientRect();mouseX=(e.clientX-r.left)/r.width;mouseY=1-(e.clientY-r.top)/r.height;});+ stage.addEventListener('touchmove',e=>{const r=cvs.getBoundingClientRect();mouseX=(e.touches[0].clientX-r.left)/r.width;mouseY=1-(e.touches[0].clientY-r.top)/r.height;},{passive:true});+ window.addEventListener('resize',resize);+}++document.getElementById('balls-sl').addEventListener('input',e=>{BALLS=+e.target.value;document.getElementById('balls-v').textContent=BALLS;});+document.getElementById('smooth-sl').addEventListener('input',e=>{SMOOTH=e.target.value/100;document.getElementById('smooth-v').textContent=SMOOTH.toFixed(2);});+document.getElementById('rad-sl').addEventListener('input',e=>{RAD=e.target.value/100;document.getElementById('rad-v').textContent=RAD.toFixed(2);});+document.getElementById('spd-sl').addEventListener('input',e=>{SPD=e.target.value/10;document.getElementById('spd-v').textContent=SPD.toFixed(1);});+document.getElementById('color-pick').addEventListener('input',e=>{COLOR=hexToRgb(e.target.value);});+document.getElementById('bg-pick').addEventListener('input',e=>{BG=hexToRgb(e.target.value);});+document.getElementById('mouse-tog').addEventListener('change',e=>{MOUSE_BALL=e.target.checked;});+document.getElementById('glow-tog').addEventListener('change',e=>{GLOW=e.target.checked;});+document.getElementById('pause-btn').addEventListener('click',()=>{+ paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';+ if(!paused&&gl){lastT=performance.now();raf=requestAnimationFrame(render);}+});+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/glassmorphism-animated/README.md b/animations/06-3d-advanced/glassmorphism-animated/README.mdnew file mode 100644index 00000000..0ff7039f--- /dev/null+++ b/animations/06-3d-advanced/glassmorphism-animated/README.md@@ -0,0 +1,70 @@+# Glassmorphism Animated++## What it is+Glassmorphism is a UI style where interface elements appear as frosted glass — semi-transparent, blurred backgrounds with subtle light borders. The CSS `backdrop-filter: blur()` property applies the blur to whatever is rendered behind the element. Animating the background blobs, blur intensity, or frost tint color adds a living quality to glass panels that static glassmorphism lacks.++## When to use it+- SaaS dashboards and product landing pages where glass cards display metrics or features+- Modal dialogs that sit over a blurred version of the underlying content+- Navigation overlays and sidebars with blurred backdrop+- Any dark-themed UI where depth between layers must be communicated without heavy borders++## How it works+Three CSS properties create the glass effect:++```css+.glass-card {+ background: rgba(88, 166, 255, 0.12); /* semi-transparent tint */+ backdrop-filter: blur(12px) saturate(1.8);+ -webkit-backdrop-filter: blur(12px) saturate(1.8);+ border: 1px solid rgba(255, 255, 255, 0.18); /* light edge highlight */+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3),+ inset 0 1px 0 rgba(255, 255, 255, 0.2); /* top edge catch-light */+}+```++**Animated blur** cycles the `backdrop-filter` value via `@keyframes`:++```css+@keyframes blur-breath {+ 0%, 100% { backdrop-filter: blur(8px) saturate(1.8); }+ 50% { backdrop-filter: blur(20px) saturate(2); }+}+```++**Animated background blobs** — pure CSS keyframe motion that gives the glass something interesting to blur:++```css+.blob {+ position: absolute;+ border-radius: 50%;+ filter: blur(60px);+ animation: blob-move 8s ease-in-out infinite alternate;+}++@keyframes blob-move {+ 0% { transform: translate(0, 0) scale(1); }+ 33% { transform: translate(40px,-30px) scale(1.1); }+ 100% { transform: translate(30px, 10px) scale(1.05); }+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Blur intensity | 12px | 4–8px = subtle; 16–24px = heavy frost; above 30px degrades text legibility |+| Glass opacity | 0.12 | 0.05 = nearly invisible tint; 0.25 = heavily tinted |+| Blob speed | 8s | Faster blob motion = more active glass content; slower = calm |+| Border opacity | 0.18 | The subtle edge is what sells "glass" — reducing to 0 makes it look plastic |++## Production notes+- **`backdrop-filter` is GPU-expensive**: the browser must capture a snapshot of everything behind the element and blur it every frame. On large glass surfaces or low-end hardware this causes frame drops. Keep glass cards small; avoid full-screen glass overlays.+- **`-webkit-` prefix still required**: Safari needs `-webkit-backdrop-filter` even in 2024. Include both the prefixed and unprefixed property.+- **The backdrop must have content**: `backdrop-filter` blurs what is behind the element. If the background is a solid color, the blur does nothing — the glass looks like dirty plastic. Colorful, high-contrast content behind the glass is required for the effect to be visible.+- **Dark mode**: glassmorphism requires a dark-enough background to read as glass rather than a white haze. The effect works better on dark themes.+- **Disable for performance audit**: the demo includes a toggle to disable `backdrop-filter`. Use this to compare performance — if the site is noticeably faster without it, reconsider the design.++## See also+- [WebGL Shader Animation](../webgl-shader-animation/) — GPU-based alternative for animated backgrounds+- [Noise-Based Motion](../noise-based-motion/) — canvas-based animated background+- [Modal Expand](../../04-micro-interactions/modal-expand/) — glassmorphism is often applied to modal overlaysdiff --git a/animations/06-3d-advanced/glassmorphism-animated/index.html b/animations/06-3d-advanced/glassmorphism-animated/index.htmlnew file mode 100644index 00000000..e7eaff1e--- /dev/null+++ b/animations/06-3d-advanced/glassmorphism-animated/index.html@@ -0,0 +1,171 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Glassmorphism Animated</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px;--blur:12px;--glass-op:0.12;--blob-spd:8s;--tint:rgba(88,166,255,var(--glass-op))}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative;display:flex;align-items:center;justify-content:center;gap:16px;padding:24px;flex-wrap:wrap}+ /* Animated gradient blobs behind everything */+ .blob{position:absolute;border-radius:50%;filter:blur(60px);opacity:.75;animation:blob-move var(--blob-spd) ease-in-out infinite alternate}+ .b1{width:280px;height:280px;background:#58a6ff;top:-80px;left:-60px;animation-delay:0s}+ .b2{width:220px;height:220px;background:#d2a8ff;bottom:-60px;right:40px;animation-delay:-3s}+ .b3{width:200px;height:200px;background:#56d364;top:30%;left:40%;animation-delay:-5s}+ .b4{width:160px;height:160px;background:#ffa657;bottom:20%;left:-40px;animation-delay:-2s}+ @keyframes blob-move{+ 0%{transform:translate(0,0) scale(1)}+ 33%{transform:translate(40px,-30px) scale(1.1)}+ 66%{transform:translate(-20px,40px) scale(.95)}+ 100%{transform:translate(30px,10px) scale(1.05)}+ }+ /* Glass cards */+ .glass-card{position:relative;z-index:1;width:clamp(140px,22%,180px);min-height:200px;border-radius:16px;padding:20px 16px;display:flex;flex-direction:column;gap:8px}+ .glass-card.g1{+ background:var(--tint);+ backdrop-filter:blur(var(--blur)) saturate(1.8);+ -webkit-backdrop-filter:blur(var(--blur)) saturate(1.8);+ border:1px solid rgba(255,255,255,.18);+ box-shadow:0 8px 32px rgba(0,0,0,.3),inset 0 1px 0 rgba(255,255,255,.2)+ }+ .glass-card.g2{+ background:var(--tint);+ backdrop-filter:blur(var(--blur)) saturate(1.8);+ -webkit-backdrop-filter:blur(var(--blur)) saturate(1.8);+ border:1px solid rgba(255,255,255,.18);+ box-shadow:0 8px 32px rgba(0,0,0,.3),inset 0 1px 0 rgba(255,255,255,.2);+ animation:blur-breath 4s ease-in-out infinite+ }+ .glass-card.g3{+ backdrop-filter:blur(var(--blur)) saturate(1.8);+ -webkit-backdrop-filter:blur(var(--blur)) saturate(1.8);+ border:1px solid rgba(255,255,255,.18);+ box-shadow:0 8px 32px rgba(0,0,0,.3),inset 0 1px 0 rgba(255,255,255,.2);+ animation:tint-cycle 8s linear infinite+ }+ @keyframes blur-breath{+ 0%,100%{backdrop-filter:blur(8px) saturate(1.8);-webkit-backdrop-filter:blur(8px) saturate(1.8)}+ 50%{backdrop-filter:blur(20px) saturate(2);-webkit-backdrop-filter:blur(20px) saturate(2)}+ }+ @keyframes tint-cycle{+ 0%{background:rgba(88,166,255,.12)}25%{background:rgba(86,211,100,.12)}50%{background:rgba(210,168,255,.12)}75%{background:rgba(255,166,87,.12)}100%{background:rgba(88,166,255,.12)}+ }+ .card-tag{font-size:9px;letter-spacing:2px;text-transform:uppercase;color:rgba(255,255,255,.5)}+ .card-title{font-size:clamp(13px,1.8vw,16px);font-weight:bold;color:#fff;line-height:1.2}+ .card-body{font-size:10px;color:rgba(255,255,255,.6);line-height:1.6;margin-top:4px}+ .card-badge{margin-top:auto;font-size:9px;background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.2);border-radius:10px;padding:4px 10px;color:rgba(255,255,255,.7);width:fit-content}+ /* Side panel */+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:40px;text-align:right;color:var(--ui-text)}+ .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ .kv{display:flex;justify-content:space-between;font-size:10px;color:var(--ui-muted)}+ .kv .v{color:var(--ui-text)}+ input[type=color]{border:none;background:none;width:44px;height:30px;cursor:pointer;border-radius:4px;padding:0}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:auto}.stage{height:auto;min-height:460px}}+ @media(prefers-reduced-motion:reduce){.blob,.glass-card.g2,.glass-card.g3{animation:none!important}}+ </style>+</head>+<body>+<header>+ <h1>Glassmorphism Animated</h1>+ <p>Frosted glass cards over animated gradient blobs — backdrop-filter: blur() + semi-transparent background.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <div class="blob b1"></div>+ <div class="blob b2"></div>+ <div class="blob b3"></div>+ <div class="blob b4"></div>+ <div class="glass-card g1">+ <div class="card-tag">Static</div>+ <div class="card-title">Fixed Frost</div>+ <div class="card-body">Constant blur at the configured intensity. The baseline glass effect.</div>+ <div class="card-badge">backdrop-filter: blur</div>+ </div>+ <div class="glass-card g2">+ <div class="card-tag">Animated</div>+ <div class="card-title">Breathing Frost</div>+ <div class="card-body">Blur cycles 8px → 20px → 8px — the frost intensifies and recedes.</div>+ <div class="card-badge">animation: blur-breath</div>+ </div>+ <div class="glass-card g3">+ <div class="card-tag">Shifting</div>+ <div class="card-title">Tint Cycle</div>+ <div class="card-body">Frost color rotates through the palette over 8 seconds.</div>+ <div class="card-badge">animation: tint-cycle</div>+ </div>+ </div>+ <aside>+ <p class="note">Glass needs interesting content behind it. Without colorful blobs, glass looks like dirty plastic. backdrop-filter is GPU-expensive — limit to small UI cards.</p>+ <div class="lbl">Blur Intensity</div>+ <div class="sr"><input type="range" id="blur-sl" min="0" max="30" value="12" step="1"><span class="sv" id="blur-v">12px</span></div>+ <div class="lbl">Glass Opacity</div>+ <div class="sr"><input type="range" id="op-sl" min="3" max="40" value="12" step="1"><span class="sv" id="op-v">0.12</span></div>+ <div class="lbl">Blob Speed</div>+ <div class="sr"><input type="range" id="spd-sl" min="2" max="20" value="8" step="1"><span class="sv" id="spd-v">8s</span></div>+ <div class="lbl">Frost Tint</div>+ <input type="color" id="tint-pick" value="#58a6ff" aria-label="Tint color">+ <label class="tog"><input type="checkbox" id="blur-tog" checked><span>Animated blur (card 2)</span></label>+ <label class="tog"><input type="checkbox" id="tint-tog" checked><span>Tint cycle (card 3)</span></label>+ <div class="div"></div>+ <label class="tog"><input type="checkbox" id="perf-tog"><span>Disable backdrop-filter</span></label>+ <div class="kv"><span>Effect</span><span class="v" id="perf-v">Active</span></div>+ </aside>+</div>+<script>+ const cards=[...document.querySelectorAll('.glass-card')];+ function applyGlass(blur,op){+ cards.forEach(c=>{+ const perf=document.getElementById('perf-tog').checked;+ c.style.backdropFilter=perf?'none':`blur(${blur}px) saturate(1.8)`;+ c.style.webkitBackdropFilter=c.style.backdropFilter;+ });+ }+ document.getElementById('blur-sl').addEventListener('input',e=>{+ document.getElementById('blur-v').textContent=e.target.value+'px';+ document.documentElement.style.setProperty('--blur',e.target.value+'px');+ });+ document.getElementById('op-sl').addEventListener('input',e=>{+ const v=(e.target.value/100).toFixed(2);+ document.getElementById('op-v').textContent=v;+ document.documentElement.style.setProperty('--glass-op',v);+ });+ document.getElementById('spd-sl').addEventListener('input',e=>{+ document.getElementById('spd-v').textContent=e.target.value+'s';+ document.documentElement.style.setProperty('--blob-spd',e.target.value+'s');+ });+ document.getElementById('tint-pick').addEventListener('input',e=>{+ const r=parseInt(e.target.value.slice(1,3),16);+ const g=parseInt(e.target.value.slice(3,5),16);+ const b=parseInt(e.target.value.slice(5,7),16);+ document.documentElement.style.setProperty('--tint',`rgba(${r},${g},${b},var(--glass-op))`);+ });+ document.getElementById('blur-tog').addEventListener('change',e=>{+ document.querySelector('.g2').style.animationPlayState=e.target.checked?'running':'paused';+ });+ document.getElementById('tint-tog').addEventListener('change',e=>{+ document.querySelector('.g3').style.animationPlayState=e.target.checked?'running':'paused';+ });+ document.getElementById('perf-tog').addEventListener('change',e=>{+ const v=e.target.checked;+ document.getElementById('perf-v').textContent=v?'Disabled (compare)':'Active';+ cards.forEach(c=>{+ c.style.backdropFilter=v?'none':'';+ c.style.webkitBackdropFilter=v?'none':'';+ });+ });+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/gpgpu-particle-system/README.md b/animations/06-3d-advanced/gpgpu-particle-system/README.mdnew file mode 100644index 00000000..8a6ef710--- /dev/null+++ b/animations/06-3d-advanced/gpgpu-particle-system/README.md@@ -0,0 +1,94 @@+# GPGPU Particle System++## What it is+GPGPU (General-Purpose GPU) particle systems store particle state — position, velocity, age — in floating-point textures rather than JavaScript arrays, and update that state in fragment shaders rather than CPU loops. Each frame, a "physics pass" reads the position texture, computes new positions via a fragment shader, and writes to a second texture. The "render pass" reads the updated positions from a vertex shader and draws each particle as a point. This architecture enables 100,000+ particles at 60fps — impossible with CPU-computed JavaScript arrays.++## When to use it+- Large-scale particle effects: galaxy simulations, fluid flow, fire systems, crowd simulations+- Any particle system where JavaScript particle count is the performance bottleneck+- Creative coding contexts where particle count itself is the aesthetic (100k points forming a shape)+- Technical demonstrations of GPGPU principles in the browser++## How it works+**Data layout**: a 256×256 texture of RGBA32F pixels stores 65,536 particles. Each pixel = one particle's `(x, y, vx, vy)`.++**Physics shader** (WebGL2 fragment shader, renders to offscreen texture):++```glsl+#version 300 es+precision highp float;+uniform sampler2D uPos; // read previous frame's positions+uniform float uTime, uSpeed;+uniform int uBehavior;+out vec4 outColor; // write new positions++void main() {+ ivec2 coord = ivec2(gl_FragCoord.xy);+ vec4 p = texelFetch(uPos, coord, 0);+ float x = p.x, y = p.y, vx = p.z, vy = p.w;++ // Apply behavior (flow field, vortex, attractor, etc.)+ if (uBehavior == 1) { // vortex+ float len = length(vec2(x, y)) + 0.01;+ vx += (-y / len) * uSpeed * 0.0004;+ vy += ( x / len) * uSpeed * 0.0004;+ vx -= x * 0.0005; // inward pull to prevent escape+ vy -= y * 0.0005;+ }+ vx *= 0.985; vy *= 0.985; // damping+ x += vx; y += vy;+ // Wrap at boundaries+ x = x > 1.2 ? -1.2 : x < -1.2 ? 1.2 : x;+ y = y > 1.2 ? -1.2 : y < -1.2 ? 1.2 : y;+ outColor = vec4(x, y, vx, vy);+}+```++**Texture ping-pong** — alternate which texture is the read source each frame:++```js+// Physics pass: read tex0, write to fbo1 (which wraps tex1)+gl.bindFramebuffer(gl.FRAMEBUFFER, fbo1);+gl.bindTexture(gl.TEXTURE_2D, tex0);+gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);++// Swap+[tex0, tex1] = [tex1, tex0];+[fbo0, fbo1] = [fbo1, fbo0];+```++**Render pass** — vertex shader reads position texture to set `gl_Position`:++```glsl+#version 300 es+in float aIndex;+uniform sampler2D uPos;+uniform vec2 uTexSize;++void main() {+ int idx = int(aIndex);+ ivec2 co = ivec2(int(mod(aIndex, uTexSize.x)), idx / int(uTexSize.x));+ vec4 p = texelFetch(uPos, co, 0);+ gl_Position = vec4(p.xy, 0.0, 1.0);+ gl_PointSize = 1.5;+}+```++## Key parameters+| Parameter | Typical value | Effect |+|-----------|--------------|--------|+| Texture size | 256×256 | 65k particles. 320×320 = 102k — test FPS before shipping |+| Physics damping | 0.985 | Higher = more inertia, slower energy loss |+| Step scale | 0.0002–0.001 | Overall particle speed per frame |+| Boundary mode | Wrap or respawn | Wrap keeps particle count constant; respawn allows birth/death |++## Production notes+- **WebGL2 required**: `RGBA32F` float framebuffer targets require WebGL2 (or the `WEBGL_color_buffer_float` extension in WebGL1, which is less reliably available). WebGL2 is supported in all modern browsers (Chrome 56+, Firefox 51+, Safari 15+).+- **Three.js `GPUComputationRenderer`**: Three.js includes `GPUComputationRenderer` (in the `three/examples/jsm` path) which encapsulates the entire ping-pong texture pattern. It's the idiomatic production approach.+- **WebGPU compute shaders**: WebGPU provides proper `@compute` shader stages for GPGPU, eliminating the "fragment shader as compute" workaround. As of 2024, WebGPU is available in Chrome 113+ but not yet in Firefox stable or Safari.+- **Memory**: 256×256 × 4 channels × 4 bytes (float32) = 1MB per texture. Two textures = 2MB — trivial. At 512×512 (262k particles): 4MB × 2 = 8MB.++## See also+- [Canvas Particle Effect](../canvas-particle-effect/) — CPU-based, simpler setup for <500 particles+- [Fluid Simulation](../fluid-simulation/) — SDF-based shader effect with organic merging+- [WebGL Shader Animation](../webgl-shader-animation/) — same WebGL2 context, different shader focusdiff --git a/animations/06-3d-advanced/gpgpu-particle-system/index.html b/animations/06-3d-advanced/gpgpu-particle-system/index.htmlnew file mode 100644index 00000000..e15a49cc--- /dev/null+++ b/animations/06-3d-advanced/gpgpu-particle-system/index.html@@ -0,0 +1,262 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>GPGPU Particle System</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative}+ canvas{display:block;width:100%;height:100%}+ .hud{position:absolute;top:8px;left:8px;right:8px;display:flex;justify-content:space-between;pointer-events:none;flex-wrap:wrap;gap:4px}+ .badge{font-size:9px;color:rgba(255,255,255,.5);background:rgba(0,0,0,.4);padding:3px 8px;border-radius:4px}+ .no-wgl2{position:absolute;inset:0;background:var(--bg);display:none;align-items:center;justify-content:center;color:var(--ui-muted);font-size:12px;text-align:center;padding:24px}+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .kv{display:flex;justify-content:space-between;font-size:10px;color:var(--ui-muted)}+ .kv .v{color:var(--ui-text)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:40px;text-align:right;color:var(--ui-text)}+ select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:8px 6px;border-radius:4px;width:100%;min-height:44px}+ .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:380px}}+ @media(prefers-reduced-motion:reduce){canvas{display:none}}+ </style>+</head>+<body>+<header>+ <h1>GPGPU Particle System</h1>+ <p>65k+ particle positions stored in a texture — physics computed by a fragment shader each frame (texture ping-pong).</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <canvas id="cvs"></canvas>+ <div class="hud">+ <div class="badge" id="fps">— fps</div>+ <div class="badge" id="count-badge">65536 particles</div>+ <div class="badge" id="behavior-badge">Flow Field</div>+ </div>+ <div class="no-wgl2" id="no-wgl2">WebGL2 required for GPGPU texture ping-pong.<br>Try Chrome, Firefox, or Safari 15+.</div>+ </div>+ <aside>+ <p class="note">GPGPU = compute on GPU. Particle data lives in textures — each RGBA32F pixel is one particle's (x, y, vx, vy). A physics shader writes new positions every frame without touching the CPU.</p>+ <div class="lbl">Particle Count</div>+ <select id="count-sel">+ <option value="128">16 384 (16k)</option>+ <option value="256" selected>65 536 (64k)</option>+ <option value="320">102 400 (100k) ⚠</option>+ </select>+ <div class="lbl">Behavior</div>+ <select id="behav-sel">+ <option value="0" selected>Flow Field</option>+ <option value="1">Vortex</option>+ <option value="2">Attractor</option>+ <option value="3">Explosion / Orbit</option>+ </select>+ <div class="lbl">Speed</div>+ <div class="sr"><input type="range" id="spd-sl" min="1" max="20" value="6" step="1"><span class="sv" id="spd-v">0.6</span></div>+ <div class="lbl">Color Mode</div>+ <select id="col-sel">+ <option value="0" selected>Solid accent</option>+ <option value="1">By velocity</option>+ <option value="2">By age</option>+ </select>+ <label class="tog"><input type="checkbox" id="trail-tog"><span>Motion trails</span></label>+ <div class="div"></div>+ <div class="kv"><span>Texture size</span><span class="v" id="tex-size">256 × 256</span></div>+ <div class="kv"><span>Physics pass</span><span class="v">1 fragment shader</span></div>+ <button class="rst" id="pause-btn">⏸ Pause</button>+ </aside>+</div>+<script>+// Physics shader (WebGL2 GLSL ES 3.00)+const PHYSICS_VS=`#version 300 es+in vec2 a;void main(){gl_Position=vec4(a,0.,1.);}`;++const PHYSICS_FS=`#version 300 es+precision highp float;+uniform sampler2D uPos;uniform float uT,uSpd;uniform int uBehavior;+out vec4 outCol;+float hash(float n){return fract(sin(n)*43758.5);}+void main(){+ ivec2 co=ivec2(gl_FragCoord.xy);+ vec4 p=texelFetch(uPos,co,0);+ float x=p.x,y=p.y,vx=p.z,vy=p.w;+ float age=fract(p.w*0.01+uT*0.001); // reuse w channel for age+ float spd=uSpd*.0002;+ if(uBehavior==0){// flow field+ float angle=sin(x*2.+uT*.3)*cos(y*2.+uT*.2)+atan(y,x)*.5;+ vx+=cos(angle)*spd;vy+=sin(angle)*spd;+ }else if(uBehavior==1){// vortex+ float len=length(vec2(x,y))+.01;+ vx+=(-y/len)*spd*2.;vy+=(x/len)*spd*2.;+ vx-=x*.0005;vy-=y*.0005;// inward pull+ }else if(uBehavior==2){// attractor+ vec2 to=-normalize(vec2(x,y));+ float d=length(vec2(x,y));+ vx+=to.x*spd*3./(d+.1);vy+=to.y*spd*3./(d+.1);+ }else{// orbit with explosion+ float ang=atan(y,x)+uT*.2;float r=length(vec2(x,y));+ vx+=cos(ang)*spd-.003*x;vy+=sin(ang)*spd-.003*y;+ }+ vx*=.985;vy*=.985;// damping+ x+=vx;y+=vy;+ // wrap+ x=x>1.2?-1.2:x<-1.2?1.2:x;+ y=y>1.2?-1.2:y<-1.2?1.2:y;+ outCol=vec4(x,y,vx,vy);+}`;++// Render shader reads position texture in vertex stage+const RENDER_VS=`#version 300 es+precision highp float;+in float aIdx;+uniform sampler2D uPos;uniform vec2 uTexSz;+uniform int uColorMode;uniform float uT;+out vec4 vCol;+void main(){+ int idx=int(aIdx);+ int tx=int(mod(aIdx,uTexSz.x));+ int ty=idx/int(uTexSz.x);+ vec4 p=texelFetch(uPos,ivec2(tx,ty),0);+ gl_Position=vec4(p.xy,0.,1.);+ gl_PointSize=1.5;+ float spd=length(p.zw)*200.;+ if(uColorMode==0)vCol=vec4(.35,.65,1.,.6);+ else if(uColorMode==1)vCol=vec4(spd*.8,spd*.4,1.-spd*.4,.7);+ else{float age=fract(float(idx)*.00131+uT*.05);vCol=vec4(age,.5,1.-age,.6);}+}`;+const RENDER_FS=`#version 300 es+precision mediump float;in vec4 vCol;out vec4 fragColor;+void main(){fragColor=vCol;}`;++const stage=document.getElementById('stage'),cvs=document.getElementById('cvs');+const fpsEl=document.getElementById('fps'),countBadge=document.getElementById('count-badge');+const behavBadge=document.getElementById('behavior-badge'),texSizeEl=document.getElementById('tex-size');+const noWgl2=document.getElementById('no-wgl2');+const BEHAV_NAMES=['Flow Field','Vortex','Attractor','Orbit'];+let W,H,gl,physicsProg,renderProg,fbo0,fbo1,tex0,tex1,raf=null;+let paused=false,lastT=0,startT=0,TEX_N=256,BEHAVIOR=0,SPD=0.6,COLOR_MODE=0,TRAILS=false;+let idxBuf=null,particleCount=0;++function mk(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS))console.error(gl.getShaderInfoLog(x));return x;}+function mkProg(vs,fs){const p=gl.createProgram();gl.attachShader(p,mk(gl.VERTEX_SHADER,vs));gl.attachShader(p,mk(gl.FRAGMENT_SHADER,fs));gl.linkProgram(p);if(!gl.getProgramParameter(p,gl.LINK_STATUS))console.error(gl.getProgramInfoLog(p));return p;}++function initTex(n){+ const data=new Float32Array(n*n*4);+ for(let i=0;i<n*n;i++){+ const angle=Math.random()*Math.PI*2;const r=Math.random()*.9+.1;+ data[i*4]=(Math.random()-.5)*2*r;data[i*4+1]=(Math.random()-.5)*2*r;+ data[i*4+2]=Math.cos(angle)*.004;data[i*4+3]=Math.sin(angle)*.004;+ }+ function makeTex(d){+ const t=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,t);+ gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA32F,n,n,0,gl.RGBA,gl.FLOAT,d);+ gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);+ return t;+ }+ tex0=makeTex(data);tex1=makeTex(null);+ function makeFbo(t){const f=gl.createFramebuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,f);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,t,0);return f;}+ fbo0=makeFbo(tex0);fbo1=makeFbo(tex1);+ gl.bindFramebuffer(gl.FRAMEBUFFER,null);+ particleCount=n*n;+ const idx=new Float32Array(particleCount);for(let i=0;i<particleCount;i++)idx[i]=i;+ if(idxBuf)gl.deleteBuffer(idxBuf);+ idxBuf=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,idxBuf);+ gl.bufferData(gl.ARRAY_BUFFER,idx,gl.STATIC_DRAW);+ countBadge.textContent=particleCount.toLocaleString()+' particles';+ texSizeEl.textContent=n+' × '+n;+}++function init(){+ gl=cvs.getContext('webgl2');+ if(!gl){noWgl2.style.display='flex';return false;}+ physicsProg=mkProg(PHYSICS_VS,PHYSICS_FS);+ renderProg=mkProg(RENDER_VS,RENDER_FS);+ // Quad for physics pass+ const qBuf=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,qBuf);+ gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);+ gl.bindVertexArray(null);+ initTex(TEX_N);+ return true;+}++function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;}++function render(ts){+ if(paused){raf=null;return;}+ raf=requestAnimationFrame(render);+ const dt=ts-lastT;if(dt<12)return;+ fpsEl.textContent=Math.round(1000/(dt||12))+' fps';lastT=ts;+ const t=(ts-startT)/1000;++ // ── Physics pass (render to texture) ──+ gl.useProgram(physicsProg);+ gl.bindFramebuffer(gl.FRAMEBUFFER,fbo1);+ gl.viewport(0,0,TEX_N,TEX_N);+ // Bind quad+ const quad=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,quad);+ gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.DYNAMIC_DRAW);+ const pa=gl.getAttribLocation(physicsProg,'a');gl.enableVertexAttribArray(pa);gl.vertexAttribPointer(pa,2,gl.FLOAT,false,0,0);+ gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,tex0);+ gl.uniform1i(gl.getUniformLocation(physicsProg,'uPos'),0);+ gl.uniform1f(gl.getUniformLocation(physicsProg,'uT'),t);+ gl.uniform1f(gl.getUniformLocation(physicsProg,'uSpd'),SPD);+ gl.uniform1i(gl.getUniformLocation(physicsProg,'uBehavior'),BEHAVIOR);+ gl.drawArrays(gl.TRIANGLE_STRIP,0,4);+ gl.deleteBuffer(quad);++ // Swap textures+ [tex0,tex1]=[tex1,tex0];[fbo0,fbo1]=[fbo1,fbo0];++ // ── Render pass (draw points) ──+ gl.bindFramebuffer(gl.FRAMEBUFFER,null);+ gl.viewport(0,0,W,H);+ if(TRAILS){gl.enable(gl.BLEND);gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA);gl.clearColor(0.024,0.039,0.063,0.1);gl.clear(gl.COLOR_BUFFER_BIT);}+ else{gl.clearColor(0.024,0.039,0.063,1);gl.clear(gl.COLOR_BUFFER_BIT);}+ gl.enable(gl.BLEND);gl.blendFunc(gl.SRC_ALPHA,gl.ONE);+ gl.useProgram(renderProg);+ gl.bindBuffer(gl.ARRAY_BUFFER,idxBuf);+ const ra=gl.getAttribLocation(renderProg,'aIdx');gl.enableVertexAttribArray(ra);gl.vertexAttribPointer(ra,1,gl.FLOAT,false,0,0);+ gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,tex0);+ gl.uniform1i(gl.getUniformLocation(renderProg,'uPos'),0);+ gl.uniform2f(gl.getUniformLocation(renderProg,'uTexSz'),TEX_N,TEX_N);+ gl.uniform1i(gl.getUniformLocation(renderProg,'uColorMode'),COLOR_MODE);+ gl.uniform1f(gl.getUniformLocation(renderProg,'uT'),t);+ gl.drawArrays(gl.POINTS,0,particleCount);+ gl.disable(gl.BLEND);+}++if(init()){+ resize();startT=performance.now();lastT=startT;+ raf=requestAnimationFrame(render);+ window.addEventListener('resize',resize);+}++document.getElementById('count-sel').addEventListener('change',e=>{TEX_N=+e.target.value;if(gl)initTex(TEX_N);});+document.getElementById('behav-sel').addEventListener('change',e=>{BEHAVIOR=+e.target.value;behavBadge.textContent=BEHAV_NAMES[BEHAVIOR];});+document.getElementById('spd-sl').addEventListener('input',e=>{SPD=e.target.value/10;document.getElementById('spd-v').textContent=SPD.toFixed(1);});+document.getElementById('col-sel').addEventListener('change',e=>{COLOR_MODE=+e.target.value;});+document.getElementById('trail-tog').addEventListener('change',e=>{TRAILS=e.target.checked;});+document.getElementById('pause-btn').addEventListener('click',()=>{+ paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';+ if(!paused&&gl){lastT=performance.now();raf=requestAnimationFrame(render);}+});+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/image-distortion-hover/README.md b/animations/06-3d-advanced/image-distortion-hover/README.mdnew file mode 100644index 00000000..8d85069d--- /dev/null+++ b/animations/06-3d-advanced/image-distortion-hover/README.md@@ -0,0 +1,73 @@+# Image Distortion on Hover++## What it is+Image distortion on hover applies a shader-based displacement effect to an image or texture when the cursor is nearby. The fragment shader samples the image at UV coordinates offset by a distortion function centered on the mouse position. The image itself is never modified — only the sampling coordinates change. This creates ripple, push, liquid, and pixelation effects that emanate from the cursor and decay over distance and time.++## When to use it+- Agency portfolio grids where each project card distorts on hover to signal interactivity+- Hero images that respond to cursor presence with a subtle liquid animation+- Product showcase tiles that feel "alive" when browsed+- Any static image that needs mouse interactivity without JavaScript-heavy animation++## How it works+The core operation is a UV displacement in the fragment shader. The pixel at UV coordinate `uv` samples the texture at `uv + displacement(uv, mouseUV)`:++```glsl+// Ripple distortion: concentric waves from mouse position+vec2 ripple(vec2 uv, vec2 mouseUV, float strength, float radius, float phase) {+ vec2 dir = uv - mouseUV;+ float dist = length(dir);+ float falloff = smoothstep(radius, 0.0, dist); // fade with distance+ float wave = sin(dist / radius * 12.0 - phase) * falloff * strength;+ return normalize(dir) * wave; // offset along the ray+}++void main() {+ vec2 uv = gl_FragCoord.xy / uResolution;+ vec2 mouseUV = uMousePos / uResolution;++ vec2 distortedUV = uv + ripple(uv, mouseUV, 0.04, 0.25, uPhase);+ gl_FragColor = vec4(sampleTexture(distortedUV), 1.0);+}+```++The `uPhase` uniform advances each frame to animate the ripple outward even after the mouse stops. A **decay** multiplier fades the phase when the mouse is absent:++```js+// Advance phase while mouse is present; decay when absent+if (mouseActive) {+ phase += 0.05;+} else {+ phase *= Math.max(0, 1 - DECAY * 0.016); // exponential decay+}+gl.uniform1f(uPhase, phase);+```++For a **procedural texture** (no external image required), generate the pattern in the same shader:++```glsl+vec3 pattern(vec2 uv) {+ float s = sin(uv.x * 8.0 + uTime) * sin(uv.y * 8.0 + uTime * 0.7);+ return mix(vec3(0.2, 0.35, 0.6), vec3(0.6, 0.2, 0.7), s * 0.5 + 0.5);+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Strength | 8 | Displacement magnitude — larger = more dramatic but can break UV at extremes |+| Radius | 0.25 (25% of canvas) | Area of effect from cursor — larger = whole canvas affected |+| Decay speed | 0.5 | How fast the distortion fades after mouse leaves |+| Distortion type | Ripple | Ripple = wave rings; Push = radial bulge; Liquid = turbulent noise; Pixelate = grid quantization |++## Production notes+- **Real images**: replace the procedural `pattern()` function with `texture2D(uTexture, distortedUV)`. Load images into WebGL via `gl.texImage2D()` from an `<img>` or `ImageBitmap`. Same-origin policy applies — external image URLs need CORS headers.+- **`gl.clampToEdge`**: ensure texture wrap mode is `CLAMP_TO_EDGE` so UV values outside [0,1] don't tile or mirror at the image border when distortion pushes UVs out of range.+- **CSS-only alternative**: CSS `filter: blur()` and `transform: translate()` on pseudo-elements can approximate push distortion for a single element at low intensity. WebGL is needed for per-pixel wave and liquid effects.+- **hover-effect-curtains / Curtains.js**: production libraries that wrap this exact pattern. They handle texture loading, canvas sizing, and the shader boilerplate. The GLSL fragment shader is identical to what this demo uses.+- **Shader Park**: a higher-level tool for declaring distortion effects with a JavaScript-like syntax that compiles to GLSL. Suitable for creative applications where writing raw GLSL is a barrier.++## See also+- [WebGL Shader Animation](../webgl-shader-animation/) — same WebGL structure, pattern-focused shaders+- [Parallax 3D Tilt](../parallax-3d-tilt/) — mouse-responsive 3D tilt without per-pixel distortion+- [Fluid Simulation](../fluid-simulation/) — SDF metaballs as an alternative organic mouse effectdiff --git a/animations/06-3d-advanced/image-distortion-hover/index.html b/animations/06-3d-advanced/image-distortion-hover/index.htmlnew file mode 100644index 00000000..abb51731--- /dev/null+++ b/animations/06-3d-advanced/image-distortion-hover/index.html@@ -0,0 +1,170 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Image Distortion on Hover</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative}+ canvas{display:block;width:100%;height:100%}+ .fps-badge{position:absolute;top:8px;right:8px;font-size:9px;color:rgba(255,255,255,.5);background:rgba(0,0,0,.4);padding:3px 8px;border-radius:4px;pointer-events:none}+ .src-panel{position:absolute;bottom:0;left:0;right:0;background:rgba(6,10,16,.92);border-top:1px solid var(--ui-border);padding:12px;font-size:9px;color:var(--ui-muted);font-family:monospace;line-height:1.5;max-height:180px;overflow-y:auto;display:none;white-space:pre-wrap}+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:40px;text-align:right;color:var(--ui-text)}+ select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:8px 6px;border-radius:4px;width:100%;min-height:44px}+ .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:380px}}+ @media(prefers-reduced-motion:reduce){canvas{display:none}}+ </style>+</head>+<body>+<header>+ <h1>Image Distortion on Hover</h1>+ <p>Fragment shader displaces UV coordinates around the cursor — ripple, push, liquid, or pixelate.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <canvas id="cvs"></canvas>+ <div class="fps-badge" id="fps">— fps</div>+ <div class="src-panel" id="src-panel"></div>+ </div>+ <aside>+ <p class="note">The shader samples the pattern at distorted UVs — the texture itself never changes. Production: replace the procedural pattern with a texture sampler for real images.</p>+ <div class="lbl">Distortion Type</div>+ <select id="type-sel">+ <option value="0" selected>Ripple (wave)</option>+ <option value="1">Push (radial)</option>+ <option value="2">Liquid (turbulence)</option>+ <option value="3">Pixelate</option>+ </select>+ <div class="lbl">Strength</div>+ <div class="sr"><input type="range" id="str-sl" min="1" max="20" value="8" step="1"><span class="sv" id="str-v">8</span></div>+ <div class="lbl">Radius</div>+ <div class="sr"><input type="range" id="rad-sl" min="5" max="50" value="25" step="1"><span class="sv" id="rad-v">0.25</span></div>+ <div class="lbl">Decay Speed</div>+ <div class="sr"><input type="range" id="dec-sl" min="1" max="20" value="5" step="1"><span class="sv" id="dec-v">0.5</span></div>+ <label class="tog"><input type="checkbox" id="ripple-tog" checked><span>Animate ripple over time</span></label>+ <label class="tog"><input type="checkbox" id="src-tog"><span>View shader source</span></label>+ <div class="div"></div>+ <button class="rst" id="pause-btn">⏸ Pause</button>+ </aside>+</div>+<script>+const VS=`attribute vec2 a;void main(){gl_Position=vec4(a,0.,1.);}`;+const FS=`+precision mediump float;+uniform vec2 uRes,uMouse;uniform float uT,uStr,uRad,uPhase;uniform int uType;uniform bool uAnimate;++vec3 pat(vec2 uv){+ float s=sin(uv.x*8.+uT*.4)*sin(uv.y*8.+uT*.3);+ float t=cos(uv.x*5.-uT*.2)*cos(uv.y*6.+uT*.25);+ float mix1=(s+t)*.5+.5;+ vec3 a=vec3(.18,.3,.6),b=vec3(.6,.2,.7),c=vec3(.1,.5,.4);+ return mix(mix(a,b,mix1),c,sin(uv.x*3.+uv.y*2.+uT*.15)*.5+.5);+}++void main(){+ vec2 uv=gl_FragCoord.xy/uRes;+ vec2 muv=uMouse/uRes;muv.y=1.-muv.y;+ float ar=uRes.x/uRes.y;+ vec2 dir=uv-muv;dir.x*=ar;+ float dist=length(dir);+ float r=uRad;+ float falloff=smoothstep(r,0.,dist);+ vec2 duv=uv;+ float str=uStr*.005;+ if(uType==0){+ float phase=uAnimate?uPhase:uPhase*0.;+ float wave=sin(dist/r*12.-phase)*falloff*str;+ if(dist>0.)duv+=normalize(vec2(dir.x/ar,dir.y))*wave;+ }else if(uType==1){+ if(dist>0.)duv+=normalize(vec2(dir.x/ar,dir.y))*falloff*str*1.6;+ }else if(uType==2){+ vec2 off=vec2(sin(dist*15.+uPhase)*cos(uv.y*10.+uPhase*.8),cos(dist*15.-uPhase)*sin(uv.x*10.+uPhase*.6));+ duv+=off*falloff*str*.6;+ }else{+ float px=mix(.002,.04,1.-falloff*(uStr/20.));+ duv=floor(uv/px)*px;+ }+ gl_FragColor=vec4(pat(duv),1.);+}`;++const stage=document.getElementById('stage'),cvs=document.getElementById('cvs');+const fpsEl=document.getElementById('fps'),srcPanel=document.getElementById('src-panel');+let W,H,gl,prog,raf=null,paused=false,lastT=0,startT=0;+let TYPE=0,STR=8,RAD=0.25,DECAY=0.5,ANIMATE=true;+let mouseX=-999,mouseY=-999,phase=0;++function init(){+ gl=cvs.getContext('webgl');if(!gl)return false;+ function sh(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);return x;}+ prog=gl.createProgram();+ gl.attachShader(prog,sh(gl.VERTEX_SHADER,VS));+ gl.attachShader(prog,sh(gl.FRAGMENT_SHADER,FS));+ gl.linkProgram(prog);+ const buf=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buf);+ gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);+ const a=gl.getAttribLocation(prog,'a');+ gl.enableVertexAttribArray(a);gl.vertexAttribPointer(a,2,gl.FLOAT,false,0,0);+ return true;+}+function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;if(gl)gl.viewport(0,0,W,H);}+function u(n){return gl.getUniformLocation(prog,n);}++function render(ts){+ if(paused){raf=null;return;}+ raf=requestAnimationFrame(render);+ const dt=ts-lastT;if(dt<16)return;+ fpsEl.textContent=Math.round(1000/(dt||16))+' fps';lastT=ts;+ phase+=(ts-startT)/1000*.003;startT=ts;+ gl.useProgram(prog);+ gl.uniform2f(u('uRes'),W,H);+ gl.uniform2f(u('uMouse'),mouseX,mouseY);+ gl.uniform1f(u('uT'),(ts-startT)/1000);+ gl.uniform1f(u('uStr'),STR);+ gl.uniform1f(u('uRad'),RAD);+ gl.uniform1f(u('uPhase'),phase*10);+ gl.uniform1i(u('uType'),TYPE);+ gl.uniform1i(u('uAnimate'),ANIMATE?1:0);+ gl.drawArrays(gl.TRIANGLE_STRIP,0,4);+ if(mouseX<0)phase*=Math.max(0,1-DECAY*.016);+}++if(init()){+ resize();startT=performance.now();lastT=startT;+ raf=requestAnimationFrame(render);+ stage.addEventListener('mousemove',e=>{const r=cvs.getBoundingClientRect();mouseX=e.clientX-r.left;mouseY=e.clientY-r.top;phase=0;});+ stage.addEventListener('mouseleave',()=>{mouseX=mouseY=-999;});+ stage.addEventListener('touchmove',e=>{const r=cvs.getBoundingClientRect();mouseX=e.touches[0].clientX-r.left;mouseY=e.touches[0].clientY-r.top;},{passive:true});+ window.addEventListener('resize',resize);+ srcPanel.textContent=FS;+}++document.getElementById('type-sel').addEventListener('change',e=>{TYPE=+e.target.value;});+document.getElementById('str-sl').addEventListener('input',e=>{STR=+e.target.value;document.getElementById('str-v').textContent=STR;});+document.getElementById('rad-sl').addEventListener('input',e=>{RAD=e.target.value/100;document.getElementById('rad-v').textContent=RAD.toFixed(2);});+document.getElementById('dec-sl').addEventListener('input',e=>{DECAY=e.target.value/10;document.getElementById('dec-v').textContent=DECAY.toFixed(1);});+document.getElementById('ripple-tog').addEventListener('change',e=>{ANIMATE=e.target.checked;});+document.getElementById('src-tog').addEventListener('change',e=>{srcPanel.style.display=e.target.checked?'block':'none';});+document.getElementById('pause-btn').addEventListener('click',()=>{+ paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';+ if(!paused&&gl){lastT=performance.now();startT=lastT;raf=requestAnimationFrame(render);}+});+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/noise-based-motion/README.md b/animations/06-3d-advanced/noise-based-motion/README.mdnew file mode 100644index 00000000..d71d2f99--- /dev/null+++ b/animations/06-3d-advanced/noise-based-motion/README.md@@ -0,0 +1,70 @@+# Noise-Based Motion++## What it is+Noise-based motion uses Simplex or Perlin noise to drive organic, non-repeating movement. Unlike `Math.random()`, which jumps discontinuously, noise functions return smoothly interpolated values — nearby spatial or temporal samples are similar, making noise ideal for natural motion: wind, water surfaces, fire, breathing. This demo applies 2D Simplex noise to a grid of dots (wind field) and to the vertices of a blob shape.++## When to use it+- Organic background elements: floating dots, undulating blobs, rippling grids+- Character animations that need subtle non-mechanical life (idle breathing, hair flutter)+- Procedurally animated terrain and water in canvas or WebGL scenes+- Any motion that should feel natural rather than mechanical or random++## How it works+Simplex noise (by Stefan Gustavson, public domain) returns a value in [-1, 1] for any 2D or 3D coordinate. Sampling noise at `(x * scale, y * scale + time)` gives a smooth "wind direction" at each grid point:++```js+function drawWindField() {+ for (let x = step/2; x < W; x += step) {+ for (let y = step/2; y < H; y += step) {+ const n = simplex2(x * SCALE, y * SCALE + time);+ const angle = n * Math.PI * 2; // map [-1,1] to full circle+ const dx = Math.cos(angle) * amplitude;+ const dy = Math.sin(angle) * amplitude;++ ctx.beginPath();+ ctx.arc(x + dx, y + dy, 1.5, 0, Math.PI * 2);+ ctx.fill();+ // Draw a short line showing direction+ ctx.moveTo(x, y);+ ctx.lineTo(x + dx, y + dy);+ ctx.stroke();+ }+ }+ time += speed * 0.01; // advance through noise volume+}+```++**Blob** — each vertex's radius is offset by noise sampled at its angle:++```js+ctx.beginPath();+for (let i = 0; i <= vertices; i++) {+ const a = (i / vertices) * Math.PI * 2;+ const n = simplex2(Math.cos(a) * 12 * SCALE + time,+ Math.sin(a) * 12 * SCALE);+ const r = baseRadius + n * amplitude * 2;+ const x = cx + Math.cos(a) * r;+ const y = cy + Math.sin(a) * r;+ i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);+}+ctx.closePath();+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Noise scale | 0.008 | Small = large smooth patterns (zoomed in); large = fine rapid variation |+| Time speed | 0.5 | How fast the noise "advects" — low = glacial; high = turbulent |+| Amplitude | 12px | Displacement magnitude — how far points move from their rest position |+| Octaves (fbm) | 4 | More octaves = more detail at multiple scales (fractal brownian motion) |++## Production notes+- **Simplex vs Perlin**: Simplex noise (Gustavson 2005) is faster and has fewer directional artifacts than classic Perlin noise. Use Simplex for new projects.+- **3D noise for time**: sample noise at `(x, y, time)` in 3D for perfectly seamless temporal animation — the pattern never "resets." 2D noise with time as an offset (as in this demo) is simpler but can have slight discontinuities at the spatial edges.+- **`glsl-noise` / `open-simplex-noise`**: for WebGL shaders, include a GLSL noise implementation inline. For JavaScript, `open-simplex-noise` (npm) is the modern standard.+- **Flow fields**: the wind-field variant is a "flow field" — a classic technique in generative art (Daniel Shiffman's Coding Train). Particles follow the noise field like leaves on a stream.++## See also+- [Canvas Particle Effect](../canvas-particle-effect/) — velocity-based particle physics (less organic, more physical)+- [Fluid Simulation](../fluid-simulation/) — SDF metaballs for a liquid aesthetic+- [Volumetric Smoke](../volumetric-smoke/) — 3D noise applied as a volumetric density fielddiff --git a/animations/06-3d-advanced/noise-based-motion/index.html b/animations/06-3d-advanced/noise-based-motion/index.htmlnew file mode 100644index 00000000..103be043--- /dev/null+++ b/animations/06-3d-advanced/noise-based-motion/index.html@@ -0,0 +1,168 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Noise-Based Motion</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative}+ canvas{display:block;width:100%;height:100%}+ .fps-badge{position:absolute;top:8px;right:8px;font-size:9px;color:var(--ui-muted);background:rgba(0,0,0,.5);padding:3px 8px;border-radius:4px}+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:40px;text-align:right;color:var(--ui-text)}+ select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:8px 6px;border-radius:4px;width:100%;min-height:44px}+ input[type=color]{border:none;background:none;width:44px;height:30px;cursor:pointer;border-radius:4px;padding:0}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:380px}}+ @media(prefers-reduced-motion:reduce){canvas{display:none}}+ </style>+</head>+<body>+<header>+ <h1>Noise-Based Motion</h1>+ <p>Simplex noise drives organic non-repeating movement — a field of dots and a morphing blob.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <canvas id="cvs"></canvas>+ <div class="fps-badge" id="fps">— fps</div>+ </div>+ <aside>+ <p class="note">Random() jumps everywhere. Noise is "smooth random" — nearby samples return similar values, making motion feel organic. Perlin/Simplex: the standard for wind, fire, terrain.</p>+ <div class="lbl">Mode</div>+ <select id="mode-sel">+ <option value="grid">Wind Field (grid dots)</option>+ <option value="blob">Morphing Blob</option>+ </select>+ <div class="lbl">Noise Scale</div>+ <div class="sr"><input type="range" id="scale-sl" min="1" max="30" value="8" step="1"><span class="sv" id="scale-v">0.008</span></div>+ <div class="lbl">Speed</div>+ <div class="sr"><input type="range" id="spd-sl" min="1" max="20" value="5" step="1"><span class="sv" id="spd-v">0.5</span></div>+ <div class="lbl">Amplitude</div>+ <div class="sr"><input type="range" id="amp-sl" min="2" max="30" value="12" step="1"><span class="sv" id="amp-v">12px</span></div>+ <div class="lbl">Grid Density</div>+ <div class="sr"><input type="range" id="grid-sl" min="8" max="40" value="20" step="2"><span class="sv" id="grid-v">20</span></div>+ <div class="lbl">Blob Vertices</div>+ <div class="sr"><input type="range" id="verts-sl" min="16" max="128" value="48" step="8"><span class="sv" id="verts-v">48</span></div>+ <div class="lbl">Color</div>+ <input type="color" id="color-pick" value="#58a6ff" aria-label="Color">+ <div class="div"></div>+ <button class="rst" id="pause-btn">⏸ Pause</button>+ </aside>+</div>+<script>+// === Simplex Noise (simplified, public domain) ===+(function(){+const F2=.5*(Math.sqrt(3)-1),G2=(3-Math.sqrt(3))/6;+const p=[151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180];+const perm=new Uint8Array(512);const permMod12=new Uint8Array(512);+for(let i=0;i<512;i++){perm[i]=p[i&255];permMod12[i]=perm[i]%12;}+const grad3=[[1,1,0],[-1,1,0],[1,-1,0],[-1,-1,0],[1,0,1],[-1,0,1],[1,0,-1],[-1,0,-1],[0,1,1],[0,-1,1],[0,1,-1],[0,-1,-1]];+function dot(g,x,y){return g[0]*x+g[1]*y;}+window.simplex2=function(x,y){+ let n0,n1,n2;+ const s=(x+y)*F2;const i=Math.floor(x+s),j=Math.floor(y+s);+ const t=(i+j)*G2;const X0=i-t,Y0=j-t;+ const x0=x-X0,y0=y-Y0;+ let i1,j1;if(x0>y0){i1=1;j1=0;}else{i1=0;j1=1;}+ const x1=x0-i1+G2,y1=y0-j1+G2;+ const x2=x0-1+2*G2,y2=y0-1+2*G2;+ const ii=i&255,jj=j&255;+ let t0=.5-x0*x0-y0*y0;if(t0<0){n0=0;}else{t0*=t0;n0=t0*t0*dot(grad3[permMod12[ii+perm[jj]]],x0,y0);}+ let t1=.5-x1*x1-y1*y1;if(t1<0){n1=0;}else{t1*=t1;n1=t1*t1*dot(grad3[permMod12[ii+i1+perm[jj+j1]]],x1,y1);}+ let t2=.5-x2*x2-y2*y2;if(t2<0){n2=0;}else{t2*=t2;n2=t2*t2*dot(grad3[permMod12[ii+1+perm[jj+1]]],x2,y2);}+ return 70*(n0+n1+n2);+};+})();++const cvs=document.getElementById('cvs');const ctx=cvs.getContext('2d');+const stage=document.getElementById('stage');const fpsEl=document.getElementById('fps');+let W,H,paused=false,raf=null,lastT=0,t=0;+let MODE='grid',SCALE=.008,SPD=.5,AMP=12,GRID=20,VERTS=48,COLOR='#58a6ff';++function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;}++function drawGrid(){+ const step=Math.floor(W/GRID);+ const r=parseInt(COLOR.slice(1,3),16),g=parseInt(COLOR.slice(3,5),16),b=parseInt(COLOR.slice(5,7),16);+ for(let x=step/2;x<W;x+=step){+ for(let y=step/2;y<H;y+=step){+ const n=simplex2(x*SCALE,y*SCALE+t);+ const dx=Math.cos(n*Math.PI*2)*AMP;+ const dy=Math.sin(n*Math.PI*2)*AMP;+ const op=.4+Math.abs(n)*.5;+ ctx.fillStyle=`rgba(${r},${g},${b},${op.toFixed(2)})`;+ ctx.beginPath();ctx.arc(x+dx,y+dy,1.5,0,Math.PI*2);ctx.fill();+ ctx.strokeStyle=`rgba(${r},${g},${b},${(op*.4).toFixed(2)})`;+ ctx.lineWidth=.5;ctx.beginPath();ctx.moveTo(x,y);ctx.lineTo(x+dx,y+dy);ctx.stroke();+ }+ }+}++function drawBlob(){+ const cx=W/2,cy=H/2;const R=Math.min(W,H)*.28;+ const r=parseInt(COLOR.slice(1,3),16),g=parseInt(COLOR.slice(3,5),16),b=parseInt(COLOR.slice(5,7),16);+ ctx.beginPath();+ for(let i=0;i<=VERTS;i++){+ const a=(i/VERTS)*Math.PI*2;+ const n=simplex2(Math.cos(a)*SCALE*12+t,Math.sin(a)*SCALE*12)*AMP;+ const r2=R+n*2;+ const px=cx+Math.cos(a)*r2,py=cy+Math.sin(a)*r2;+ i===0?ctx.moveTo(px,py):ctx.lineTo(px,py);+ }+ ctx.closePath();+ ctx.fillStyle=`rgba(${r},${g},${b},.08)`;ctx.fill();+ ctx.strokeStyle=`rgba(${r},${g},${b},.8)`;ctx.lineWidth=2;ctx.stroke();+ // Inner highlights+ ctx.beginPath();+ for(let i=0;i<=VERTS;i++){+ const a=(i/VERTS)*Math.PI*2;+ const n=simplex2(Math.cos(a)*SCALE*8+t*.7,Math.sin(a)*SCALE*8)*AMP*.5;+ const r2=R*.5+n*1.5;+ const px=cx+Math.cos(a)*r2,py=cy+Math.sin(a)*r2;+ i===0?ctx.moveTo(px,py):ctx.lineTo(px,py);+ }+ ctx.closePath();+ ctx.strokeStyle=`rgba(${r},${g},${b},.3)`;ctx.lineWidth=1;ctx.stroke();+}++function loop(ts){+ if(paused){raf=null;return;}+ raf=requestAnimationFrame(loop);+ const dt=ts-lastT;if(dt<16){return;}+ const realFps=Math.round(1000/(dt||16));fpsEl.textContent=realFps+' fps';+ lastT=ts;t+=SPD*.01;+ ctx.clearRect(0,0,W,H);+ if(MODE==='grid')drawGrid();else drawBlob();+}++resize();raf=requestAnimationFrame(loop);++document.getElementById('mode-sel').addEventListener('change',e=>MODE=e.target.value);+document.getElementById('scale-sl').addEventListener('input',e=>{SCALE=e.target.value/1000;document.getElementById('scale-v').textContent=(SCALE).toFixed(3);});+document.getElementById('spd-sl').addEventListener('input',e=>{SPD=e.target.value/10;document.getElementById('spd-v').textContent=SPD.toFixed(1);});+document.getElementById('amp-sl').addEventListener('input',e=>{AMP=+e.target.value;document.getElementById('amp-v').textContent=AMP+'px';});+document.getElementById('grid-sl').addEventListener('input',e=>{GRID=+e.target.value;document.getElementById('grid-v').textContent=GRID;});+document.getElementById('verts-sl').addEventListener('input',e=>{VERTS=+e.target.value;document.getElementById('verts-v').textContent=VERTS;});+document.getElementById('color-pick').addEventListener('input',e=>COLOR=e.target.value);+document.getElementById('pause-btn').addEventListener('click',()=>{+ paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';+ if(!paused){lastT=performance.now();raf=requestAnimationFrame(loop);}+});+window.addEventListener('resize',()=>{resize();});+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/parallax-3d-tilt/README.md b/animations/06-3d-advanced/parallax-3d-tilt/README.mdnew file mode 100644index 00000000..5c0c5b64--- /dev/null+++ b/animations/06-3d-advanced/parallax-3d-tilt/README.md@@ -0,0 +1,72 @@+# Parallax 3D Tilt++## What it is+Parallax 3D tilt rotates a card in three dimensions as the mouse moves across it, creating a convincing sense of depth without any WebGL. The `perspective` CSS property on the parent simulates a camera distance; `rotateX` and `rotateY` on the card map to mouse Y and X position respectively. A highlight gradient that follows the cursor completes the illusion of a physical light source.++## When to use it+- Feature cards, pricing cards, and hero cards where depth signals "premium"+- Portfolio thumbnails where hover signals selectability+- Any interactive card where the standard flat-hover feels too passive+- NFT and gaming UIs where the tactile metaphor matches the product++## How it works+`perspective` must be set on the **parent**, not the card. The card's `rotateX`/`rotateY` are computed from cursor position relative to the card's center, normalized to ±maxAngle:++```js+card.addEventListener('mousemove', e => {+ const r = card.getBoundingClientRect();+ const x = (e.clientX - r.left) / r.width - 0.5; // -0.5 to 0.5+ const y = (e.clientY - r.top) / r.height - 0.5;++ const MAX = 15; // degrees+ const rx = (-y * MAX).toFixed(2); // mouse up = card tilts toward viewer+ const ry = ( x * MAX).toFixed(2); // mouse right = card tilts right++ card.style.transform = `rotateX(${rx}deg) rotateY(${ry}deg) scale(1.03)`;+});++card.addEventListener('mouseleave', () => {+ card.style.transform = 'rotateX(0deg) rotateY(0deg) scale(1)';+});+```++**Shine highlight** — a radial gradient repositioned to the cursor:++```js+shine.style.background = `radial-gradient(+ circle at ${(x + 0.5) * 100}% ${(y + 0.5) * 100}%,+ rgba(255,255,255,0.18) 0%,+ transparent 65%+)`;+```++**Reset transition** — only apply `transition` on mouse-leave, not on mouse-move:++```js+card.addEventListener('mousemove', () => card.classList.add('active'));+card.addEventListener('mouseleave', () => card.classList.remove('active'));+```++```css+.card { transition: transform 400ms ease, box-shadow 400ms ease; }+.card.active { transition: none; } /* instant tracking on mousemove */+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Max tilt angle | 15° | 5° = subtle; 15° = pronounced; >25° = disorienting |+| Perspective | 1000px | 400px = extreme fish-eye; 1500px = nearly flat |+| Reset duration | 400ms | How fast the card returns to flat when mouse leaves |+| Scale on hover | 1.03 | Subtle lift; pairing with shadow depth increase adds more realism |++## Production notes+- **Touch devices**: `:hover` does not fire on touch. Add `:active` fallback with reduced tilt, or skip the effect on `(hover: none)` media query.+- **`will-change: transform`**: add only during hover (`mouseenter`/`mouseleave`) to avoid permanent GPU layer allocation. Permanent `will-change` on many cards multiplies GPU memory use.+- **VanillaTilt.js**: a zero-dependency library that handles this pattern with configurable tilt, glare, scale, and perspective. 2KB gzipped — use in production rather than hand-rolling.+- **Performance**: `rotateX`/`rotateY` on a GPU-composited element runs at 60fps with no paint. Avoid animating `box-shadow` simultaneously — shadows trigger paint.++## See also+- [3D Model Orbit](../3d-model-orbit/) — full WebGL 3D rather than CSS 3D+- [Hover State Animation](../../04-micro-interactions/hover-state/) — 2D hover feedback without the 3D dimension+- [2.5D / Pseudo-3D](../2-5d-pseudo-3d/) — multiple layers at different depths for a parallax scenediff --git a/animations/06-3d-advanced/parallax-3d-tilt/index.html b/animations/06-3d-advanced/parallax-3d-tilt/index.htmlnew file mode 100644index 00000000..ac42719f--- /dev/null+++ b/animations/06-3d-advanced/parallax-3d-tilt/index.html@@ -0,0 +1,161 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Parallax 3D Tilt</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px;--perspective:1000px;--max-tilt:15;--reset-dur:400ms}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;background:#060a10;display:flex;align-items:center;justify-content:center;perspective:var(--perspective)}+ /* Card */+ .tilt-card{+ width:clamp(240px,40%,340px);height:clamp(240px,40%,320px);+ border-radius:16px;position:relative;overflow:hidden;+ background:linear-gradient(135deg,#0d2040,#1a3060);+ border:1px solid rgba(255,255,255,.15);+ box-shadow:0 20px 60px rgba(0,0,0,.6);+ transform-style:preserve-3d;+ transform:perspective(var(--perspective)) rotateX(0deg) rotateY(0deg) scale(1);+ transition:transform var(--reset-dur) ease,box-shadow var(--reset-dur) ease;+ cursor:pointer;+ will-change:transform+ }+ .tilt-card.active{transition:none}+ .card-shine{+ position:absolute;inset:0;border-radius:16px;+ background:radial-gradient(circle at 50% 50%, rgba(255,255,255,.15) 0%, transparent 70%);+ opacity:0;pointer-events:none;transition:opacity .3s+ }+ .card-content{position:relative;z-index:1;height:100%;padding:28px;display:flex;flex-direction:column;justify-content:flex-end;gap:8px}+ .card-over{font-size:9px;letter-spacing:2px;text-transform:uppercase;color:rgba(255,255,255,.4)}+ .card-h{font-family:Georgia,serif;font-size:clamp(18px,2.5vw,26px);color:#fff;line-height:1.2;font-style:italic}+ .card-sub{font-size:11px;color:rgba(255,255,255,.55);line-height:1.6;max-width:240px}+ .card-tag{font-size:10px;color:var(--ui-accent);margin-top:4px;letter-spacing:1px}+ /* Depth layers for extra parallax within card */+ .float-orb{position:absolute;border-radius:50%;pointer-events:none;will-change:transform}+ .orb1{width:120px;height:120px;background:rgba(88,166,255,.3);top:-30px;right:-20px;filter:blur(20px);transform:translateZ(20px)}+ .orb2{width:80px;height:80px;background:rgba(210,168,255,.25);bottom:20px;right:30px;filter:blur(12px);transform:translateZ(30px)}+ /* Readout */+ .readout{position:absolute;bottom:12px;left:12px;font-size:9px;color:rgba(255,255,255,.3);z-index:5;pointer-events:none}+ /* Panel */+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .kv{display:flex;justify-content:space-between;font-size:10px;color:var(--ui-muted)}+ .kv .v{color:var(--ui-text)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:44px;text-align:right;color:var(--ui-text)}+ .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:auto}.stage{height:auto;min-height:420px;padding:32px 16px}}+ @media(prefers-reduced-motion:reduce){.tilt-card{transition:none!important;transform:none!important}}+ </style>+</head>+<body>+<header>+ <h1>Parallax 3D Tilt</h1>+ <p>CSS perspective + rotateX/Y driven by mouse position — a shine highlight tracks the cursor across the card surface.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <div class="tilt-card" id="card">+ <div class="card-shine" id="shine"></div>+ <div class="float-orb orb1" id="orb1"></div>+ <div class="float-orb orb2" id="orb2"></div>+ <div class="card-content">+ <div class="card-over">Feature card</div>+ <div class="card-h">Three-dimensional perspective</div>+ <div class="card-sub">Mouse position maps to rotateX and rotateY. The highlight follows the virtual light source.</div>+ <div class="card-tag">Move mouse over card →</div>+ </div>+ <div class="readout" id="readout">rotX: 0° rotY: 0°</div>+ </div>+ </div>+ <aside>+ <p class="note">perspective must be on the PARENT — not the tilting card. The card's rotateX/Y are normalized to ±maxAngle from cursor position relative to card center.</p>+ <div class="lbl">Max Tilt Angle</div>+ <div class="sr"><input type="range" id="tilt-sl" min="3" max="30" value="15" step="1"><span class="sv" id="tilt-v">15°</span></div>+ <div class="lbl">Perspective</div>+ <div class="sr"><input type="range" id="persp-sl" min="400" max="1500" value="1000" step="50"><span class="sv" id="persp-v">1000px</span></div>+ <div class="lbl">Reset Duration</div>+ <div class="sr"><input type="range" id="rst-sl" min="100" max="1000" value="400" step="50"><span class="sv" id="rst-v">400ms</span></div>+ <label class="tog"><input type="checkbox" id="shine-tog" checked><span>Shine highlight</span></label>+ <label class="tog"><input type="checkbox" id="invert-tog"><span>Invert tilt</span></label>+ <label class="tog"><input type="checkbox" id="scale-tog" checked><span>Subtle scale on hover</span></label>+ <div class="div"></div>+ <div class="kv"><span>RotateX</span><span class="v" id="rx-v">0°</span></div>+ <div class="kv"><span>RotateY</span><span class="v" id="ry-v">0°</span></div>+ </aside>+</div>+<script>+ const card=document.getElementById('card');+ const shine=document.getElementById('shine');+ const orb1=document.getElementById('orb1');+ const orb2=document.getElementById('orb2');+ const readout=document.getElementById('readout');+ const rxV=document.getElementById('rx-v');+ const ryV=document.getElementById('ry-v');+ let maxTilt=15,invert=false,shineOn=true,scaleOn=true;++ function onMove(e){+ const r=card.getBoundingClientRect();+ const src=e.touches?e.touches[0]:e;+ const x=(src.clientX-r.left)/r.width-.5; // -0.5 to 0.5+ const y=(src.clientY-r.top)/r.height-.5;+ const inv=invert?-1:1;+ const rx=(-y*maxTilt*inv).toFixed(1);+ const ry=(x*maxTilt*inv).toFixed(1);+ card.classList.add('active');+ const scale=scaleOn?'scale(1.04)':'scale(1)';+ card.style.transform=`rotateX(${rx}deg) rotateY(${ry}deg) ${scale}`;+ card.style.boxShadow=`${-ry*.5}px ${rx*.5}px 40px rgba(0,0,0,.7)`;+ if(shineOn){+ shine.style.opacity='1';+ shine.style.background=`radial-gradient(circle at ${(x+.5)*100}% ${(y+.5)*100}%,rgba(255,255,255,.18) 0%,transparent 65%)`;+ }+ // Subtle inner parallax+ orb1.style.transform=`translateZ(20px) translate(${-ry*.3}px,${rx*.3}px)`;+ orb2.style.transform=`translateZ(30px) translate(${-ry*.5}px,${rx*.5}px)`;+ rxV.textContent=rx+'°'; ryV.textContent=ry+'°';+ readout.textContent=`rotX:${rx}° rotY:${ry}°`;+ }++ function onLeave(){+ card.classList.remove('active');+ card.style.transform='rotateX(0deg) rotateY(0deg) scale(1)';+ card.style.boxShadow='';+ shine.style.opacity='0';+ orb1.style.transform='translateZ(20px)';+ orb2.style.transform='translateZ(30px)';+ rxV.textContent='0°'; ryV.textContent='0°';+ readout.textContent='rotX: 0° rotY: 0°';+ }++ card.addEventListener('mousemove',onMove);+ card.addEventListener('mouseleave',onLeave);+ card.addEventListener('touchmove',e=>{e.preventDefault();onMove(e);},{passive:false});+ card.addEventListener('touchend',onLeave);++ document.getElementById('tilt-sl').addEventListener('input',e=>{maxTilt=+e.target.value;document.getElementById('tilt-v').textContent=maxTilt+'°'});+ document.getElementById('persp-sl').addEventListener('input',e=>{+ document.getElementById('persp-v').textContent=e.target.value+'px';+ document.documentElement.style.setProperty('--perspective',e.target.value+'px');+ });+ document.getElementById('rst-sl').addEventListener('input',e=>{+ document.getElementById('rst-v').textContent=e.target.value+'ms';+ document.documentElement.style.setProperty('--reset-dur',e.target.value+'ms');+ });+ document.getElementById('shine-tog').addEventListener('change',e=>{shineOn=e.target.checked;if(!shineOn)shine.style.opacity='0'});+ document.getElementById('invert-tog').addEventListener('change',e=>{invert=e.target.checked});+ document.getElementById('scale-tog').addEventListener('change',e=>{scaleOn=e.target.checked});+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/ray-marching-sdf/README.md b/animations/06-3d-advanced/ray-marching-sdf/README.mdnew file mode 100644index 00000000..8aca6efc--- /dev/null+++ b/animations/06-3d-advanced/ray-marching-sdf/README.md@@ -0,0 +1,84 @@+# Ray Marching / SDF Scene++## What it is+Ray marching renders a 3D scene entirely inside a fragment shader without any mesh geometry. Instead of triangles, shapes are defined as Signed Distance Functions (SDFs) — mathematical functions that return the distance from any point in space to the nearest surface. A ray is cast for each pixel; the shader advances the ray forward by the SDF value at each step (which is always safe — the SDF guarantees no overshoot), repeating until the ray hits a surface or exits the scene. Everything visible is pure math.++## When to use it+- Complex animated 3D shapes that are difficult to model as meshes (fractals, boolean blends, organic morphs)+- Fullscreen shader art and generative visuals+- Educational demonstrations of 3D math without Three.js overhead+- Shadertoy-style creative coding in the browser++## How it works+**Core ray march loop** — advances a ray until it's within epsilon of a surface:++```glsl+float rayMarch(vec3 ro, vec3 rd) { // ray origin, ray direction+ float t = 0.0;+ for (int i = 0; i < MAX_STEPS; i++) {+ float d = scene(ro + rd * t); // distance to nearest surface+ if (d < 0.001) return t; // hit+ t += d; // safe to advance by d+ if (t > 20.0) break; // escaped scene+ }+ return -1.0; // no hit+}+```++**SDF primitives** — the building blocks:++```glsl+float sdSphere(vec3 p, float r) { return length(p) - r; }++float sdBox(vec3 p, vec3 b) {+ vec3 q = abs(p) - b;+ return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0);+}++float sdTorus(vec3 p, vec2 t) {+ vec2 q = vec2(length(p.xz) - t.x, p.y);+ return length(q) - t.y;+}+```++**Smooth-minimum** blends two SDFs, creating the organic merging effect:++```glsl+float smin(float a, float b, float k) {+ float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);+ return mix(b, a, h) - k * h * (1.0 - h);+}+```++**Normal via finite differences** — sample SDF in 6 directions:++```glsl+vec3 getNormal(vec3 p) {+ vec2 e = vec2(0.001, 0.0);+ return normalize(vec3(+ scene(p + e.xyy) - scene(p - e.xyy),+ scene(p + e.yxy) - scene(p - e.yxy),+ scene(p + e.yyx) - scene(p - e.yyx)+ ));+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Max steps | 48 | More steps = finer detail on concave surfaces, but lower FPS |+| Step scale | 0.9× | Multiplying by <1 trades performance for accuracy on thin features |+| Epsilon (hit distance) | 0.001 | Smaller = sharper surface but more steps required |+| Smooth-min k | 0.3–0.5 | Controls blend radius between shapes |++## Production notes+- **Shadertoy convention**: uniforms are `iTime`, `iResolution`, `iMouse`. Porting Shadertoy code to WebGL requires renaming these to your own uniform names and adding the WebGL boilerplate (vertex shader + quad).+- **Performance scales with pixel count, not scene complexity**: adding 10 more SDF operations costs very little — adding a 4K display multiplies cost by 4×. Run at half resolution and upscale for complex shaders on mobile.+- **Soft shadows and AO**: both require additional rays per fragment (shadow ray, AO samples). Soft shadows are expensive — 20 shadow-march steps per lit pixel doubles the total march work. Toggle off on low-end devices.+- **`mediump` precision**: complex distance functions with large-scale repetition can lose precision at `mediump`. Use `highp float` for SDF scenes with repetition patterns or fine geometry.+- **Three.js alternative**: Three.js with `ShaderMaterial` passes the same uniforms to the same fragment shader — the GLSL is identical, only the WebGL boilerplate changes.++## See also+- [Volumetric Smoke](../volumetric-smoke/) — ray marching that accumulates density rather than finding surface hits+- [WebGL Shader Animation](../webgl-shader-animation/) — simpler fragment shaders on the same fullscreen-quad setup+- [Fluid Simulation](../fluid-simulation/) — SDF metaballs as a 2D application of the same SDF principlediff --git a/animations/06-3d-advanced/ray-marching-sdf/index.html b/animations/06-3d-advanced/ray-marching-sdf/index.htmlnew file mode 100644index 00000000..95a8c990--- /dev/null+++ b/animations/06-3d-advanced/ray-marching-sdf/index.html@@ -0,0 +1,214 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Ray Marching / SDF Scene</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative}+ canvas{display:block;width:100%;height:100%}+ .hud{position:absolute;top:8px;left:8px;right:8px;display:flex;justify-content:space-between;pointer-events:none}+ .badge{font-size:9px;color:rgba(255,255,255,.5);background:rgba(0,0,0,.4);padding:3px 8px;border-radius:4px;letter-spacing:.5px}+ .src-panel{position:absolute;bottom:0;left:0;right:0;background:rgba(6,10,16,.93);border-top:1px solid var(--ui-border);padding:12px;font-size:8.5px;color:var(--ui-muted);font-family:monospace;line-height:1.5;max-height:220px;overflow-y:auto;display:none;white-space:pre-wrap;word-break:break-all}+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:44px;text-align:right;color:var(--ui-text)}+ select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:8px 6px;border-radius:4px;width:100%;min-height:44px}+ .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:380px}}+ @media(prefers-reduced-motion:reduce){canvas{display:none}}+ </style>+</head>+<body>+<header>+ <h1>Ray Marching / SDF Scene</h1>+ <p>3D rendered entirely in a fragment shader — no meshes, no vertices. Every surface is pure math.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <canvas id="cvs"></canvas>+ <div class="hud">+ <div class="badge" id="fps">— fps</div>+ <div class="badge" id="scene-badge">Scene 1</div>+ </div>+ <div class="src-panel" id="src-panel"></div>+ </div>+ <aside>+ <p class="note">No geometry exists. The "shape" is a function returning distance to the nearest surface at any point. The shader marches rays forward in steps equal to the SDF value — guaranteed to be safe.</p>+ <div class="lbl">Scene</div>+ <select id="scene-sel">+ <option value="0" selected>Blend — sphere, box, torus</option>+ <option value="1">Boolean — subtract & union</option>+ <option value="2">Repetition — infinite grid</option>+ </select>+ <div class="lbl">Camera Speed</div>+ <div class="sr"><input type="range" id="cam-sl" min="0" max="20" value="6" step="1"><span class="sv" id="cam-v">0.6</span></div>+ <div class="lbl">Max March Steps</div>+ <div class="sr"><input type="range" id="steps-sl" min="16" max="96" value="48" step="8"><span class="sv" id="steps-v">48</span></div>+ <label class="tog"><input type="checkbox" id="ao-tog" checked><span>Ambient occlusion</span></label>+ <label class="tog"><input type="checkbox" id="shadow-tog"><span>Soft shadows (GPU-heavy)</span></label>+ <label class="tog"><input type="checkbox" id="debug-tog"><span>Debug: march steps as color</span></label>+ <label class="tog"><input type="checkbox" id="src-tog"><span>View shader source</span></label>+ <div class="div"></div>+ <button class="rst" id="pause-btn">⏸ Pause</button>+ </aside>+</div>+<script>+const VS=`attribute vec2 a;void main(){gl_Position=vec4(a,0.,1.);}`;+const FS=`+precision mediump float;+uniform vec2 uRes;uniform float uT,uCamSpd;uniform int uScene,uMaxSteps;uniform bool uAO,uShadow,uDebug;++float sdSph(vec3 p,float r){return length(p)-r;}+float sdBox(vec3 p,vec3 b){vec3 q=abs(p)-b;return length(max(q,0.))+min(max(q.x,max(q.y,q.z)),0.);}+float sdTor(vec3 p,vec2 t){vec2 q=vec2(length(p.xz)-t.x,p.y);return length(q)-t.y;}+float sdPl(vec3 p){return p.y+1.2;}+float smin(float a,float b,float k){float h=clamp(.5+.5*(b-a)/k,0.,1.);return mix(b,a,h)-k*h*(1.-h);}+mat2 rot(float a){float c=cos(a),s=sin(a);return mat2(c,-s,s,c);}++vec2 map(vec3 p){+ float d,id;+ if(uScene==0){+ float t1=uT*.3;+ vec3 q=p;q.y+=sin(uT*.4)*.1;+ d=sdSph(q,0.62);+ vec3 q2=p-vec3(-1.4,0.,.2);q2.xz*=rot(uT*.5);+ d=smin(d,sdBox(q2,vec3(.38)),0.42);+ vec3 q3=p-vec3(1.4,-.15,0.);q3.xy*=rot(uT*.4);+ d=smin(d,sdTor(q3,vec2(.52,.19)),0.32);+ id=d<sdPl(p)?1.:0.;d=min(d,sdPl(p));+ }else if(uScene==1){+ float a=sdSph(p,.82),b=sdBox(p,vec3(.56)),c=sdSph(p-.12,.38);+ float s1=max(a,-b);id=1.;+ float s2=min(s1,c);if(s2==c)id=2.;+ d=min(s2,sdPl(p));if(d==sdPl(p))id=0.;+ }else{+ vec3 q=p;q.xz=mod(q.xz+1.5,3.)-1.5;+ vec3 r=q;r.xz*=rot(uT*.2);+ float base=sdBox(r,vec3(.5));+ vec3 cr=abs(mod(p.xzy*2.,2.))-1.;+ float cross3=min(sdBox(cr,vec3(.22,1.,1.)),min(sdBox(cr.yxz,vec3(.22,1.,1.)),sdBox(cr.zyx,vec3(.22,1.,1.))));+ d=max(base,-cross3);id=1.;d=min(d,sdPl(p));if(d==sdPl(p))id=0.;+ }+ return vec2(d,id);+}++vec3 norm(vec3 p){vec2 e=vec2(.001,0.);return normalize(vec3(map(p+e.xyy).x-map(p-e.xyy).x,map(p+e.yxy).x-map(p-e.yxy).x,map(p+e.yyx).x-map(p-e.yyx).x));}++float ao(vec3 p,vec3 n){float a=0.;for(int i=1;i<=5;i++){float d=float(i)*.12;a+=max(0.,d-map(p+n*d).x)/d;}return 1.-a*.3;}++float softshadow(vec3 ro,vec3 rd){float t=.05,sh=1.;for(int i=0;i<20;i++){float d=map(ro+rd*t).x;if(d<.001)return 0.;sh=min(sh,10.*d/t);t+=d;if(t>6.)break;}return sh;}++void main(){+ vec2 uv=(gl_FragCoord.xy-.5*uRes)/min(uRes.x,uRes.y);+ float angle=uT*uCamSpd;+ vec3 ro=vec3(sin(angle)*3.8,.6+sin(uT*.2)*.3,cos(angle)*3.8);+ vec3 ta=vec3(0.,-.1,0.);+ vec3 ww=normalize(ta-ro),uu=normalize(cross(ww,vec3(0,1,0))),vv=cross(uu,ww);+ vec3 rd=normalize(uv.x*uu+uv.y*vv+1.6*ww);++ vec3 sky=vec3(.04,.05,.09)+rd.y*.04;+ vec2 res=vec2(-1.,0.);float t=0.;int steps=0;+ for(int i=0;i<96;i++){+ if(i>=uMaxSteps)break;+ vec2 h=map(ro+rd*t);+ if(h.x<.001){res=vec2(t,h.y);break;}+ t+=h.x*0.9;steps=i;+ if(t>22.)break;+ }++ if(uDebug){float f=float(steps)/float(uMaxSteps);gl_FragColor=vec4(f,f*.3,(1.-f)*.8,1.);return;}++ vec3 col=sky;+ if(res.x>0.){+ vec3 p=ro+rd*res.x,n=norm(p);+ vec3 lp=vec3(2.5,3.,2.);vec3 ld=normalize(lp-p);+ float dif=max(dot(n,ld),0.);+ float sp=pow(max(dot(reflect(-ld,n),-rd),0.),40.);+ float shd=uShadow?softshadow(p+n*.01,ld):1.;+ float occ=uAO?ao(p,n):1.;+ vec3 mat=res.y<.5?vec3(.3,.35,.38):res.y<1.5?vec3(.22,.44,.82):vec3(.78,.38,.18);+ col=(mat*.12+mat*dif*shd+.7*sp*shd)*occ;+ // Fog+ float fog=1.-exp(-res.x*.04);+ col=mix(col,sky,fog);+ }+ gl_FragColor=vec4(sqrt(clamp(col,0.,1.)),1.);+}`;++const stage=document.getElementById('stage'),cvs=document.getElementById('cvs');+const fpsEl=document.getElementById('fps'),sceneBadge=document.getElementById('scene-badge');+const srcPanel=document.getElementById('src-panel');+let W,H,gl,prog,raf=null,paused=false,lastT=0,startT=0;+let SCENE=0,CAM_SPD=0.6,MAX_STEPS=48,AO=true,SHADOW=false,DEBUG=false;+const SCENE_NAMES=['Blend','Boolean','Repetition'];++function init(){+ gl=cvs.getContext('webgl');if(!gl)return false;+ function sh(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS))console.error(gl.getShaderInfoLog(x));return x;}+ prog=gl.createProgram();+ gl.attachShader(prog,sh(gl.VERTEX_SHADER,VS));+ gl.attachShader(prog,sh(gl.FRAGMENT_SHADER,FS));+ gl.linkProgram(prog);+ const buf=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buf);+ gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);+ const a=gl.getAttribLocation(prog,'a');+ gl.enableVertexAttribArray(a);gl.vertexAttribPointer(a,2,gl.FLOAT,false,0,0);+ srcPanel.textContent=FS;+ return true;+}+function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;if(gl)gl.viewport(0,0,W,H);}+function u(n){return gl.getUniformLocation(prog,n);}++function render(ts){+ if(paused){raf=null;return;}+ raf=requestAnimationFrame(render);+ const dt=ts-lastT;if(dt<16)return;+ fpsEl.textContent=Math.round(1000/(dt||16))+' fps';lastT=ts;+ const t=(ts-startT)/1000;+ gl.useProgram(prog);+ gl.uniform2f(u('uRes'),W,H);+ gl.uniform1f(u('uT'),t);+ gl.uniform1f(u('uCamSpd'),CAM_SPD);+ gl.uniform1i(u('uScene'),SCENE);+ gl.uniform1i(u('uMaxSteps'),MAX_STEPS);+ gl.uniform1i(u('uAO'),AO?1:0);+ gl.uniform1i(u('uShadow'),SHADOW?1:0);+ gl.uniform1i(u('uDebug'),DEBUG?1:0);+ gl.drawArrays(gl.TRIANGLE_STRIP,0,4);+}++if(init()){+ resize();startT=performance.now();lastT=startT;+ raf=requestAnimationFrame(render);+ window.addEventListener('resize',resize);+}++document.getElementById('scene-sel').addEventListener('change',e=>{SCENE=+e.target.value;sceneBadge.textContent='Scene '+(SCENE+1)+': '+SCENE_NAMES[SCENE];});+document.getElementById('cam-sl').addEventListener('input',e=>{CAM_SPD=e.target.value/10;document.getElementById('cam-v').textContent=CAM_SPD.toFixed(1);});+document.getElementById('steps-sl').addEventListener('input',e=>{MAX_STEPS=+e.target.value;document.getElementById('steps-v').textContent=MAX_STEPS;});+document.getElementById('ao-tog').addEventListener('change',e=>{AO=e.target.checked;});+document.getElementById('shadow-tog').addEventListener('change',e=>{SHADOW=e.target.checked;});+document.getElementById('debug-tog').addEventListener('change',e=>{DEBUG=e.target.checked;});+document.getElementById('src-tog').addEventListener('change',e=>{srcPanel.style.display=e.target.checked?'block':'none';});+document.getElementById('pause-btn').addEventListener('click',()=>{+ paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';+ if(!paused&&gl){lastT=performance.now();startT=lastT;raf=requestAnimationFrame(render);}+});+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/scroll-driven-3d-rotation/README.md b/animations/06-3d-advanced/scroll-driven-3d-rotation/README.mdnew file mode 100644index 00000000..b08c22c3--- /dev/null+++ b/animations/06-3d-advanced/scroll-driven-3d-rotation/README.md@@ -0,0 +1,69 @@+# Scroll-Driven 3D Rotation++## What it is+Scroll-driven 3D rotation choreographs a 3D object's transforms — rotation, scale, position — against scroll progress through a pinned section. As the user scrolls, the object moves through a sequence of predetermined states. This is the pattern behind Apple's product reveal pages, where a product rotates, expands, and repositions as you scroll through marketing copy.++## When to use it+- Product reveal pages where each scroll stage highlights a different feature or angle+- Hardware or device landing pages that need an interactive feel without video+- Storytelling sections where a 3D object serves as the visual anchor for sequential text+- Onboarding flows with a step-by-step 3D walkthrough++## How it works+Combine two techniques: **pin** (sticky positioning keeps the 3D stage visible while content scrolls) and **scrub** (scroll progress maps to a transform timeline).++**HTML structure:**+```html+<div class="scroll-container" style="height: 400vh">+ <div class="sticky-stage"> <!-- position: sticky; top: 0 -->+ <div class="object-3d" id="obj"></div>+ </div>+</div>+```++**Scroll progress → transform:**+```js+container.addEventListener('scroll', () => {+ const { scrollTop, scrollHeight, clientHeight } = container;+ const progress = scrollTop / (scrollHeight - clientHeight); // 0..1++ // Map progress to keyframes+ const rx = lerp(keyframes[floor].rx, keyframes[ceil].rx, fraction);+ const ry = lerp(keyframes[floor].ry, keyframes[ceil].ry, fraction);+ const sc = lerp(keyframes[floor].scale, keyframes[ceil].scale, fraction);++ obj.style.transform = `rotateX(${rx}deg) rotateY(${ry}deg) scale(${sc})`;+});++function lerp(a, b, t) { return a + (b - a) * t; }+```++**Smooth scrub** adds a lerp each frame to ease between the raw scroll value and the applied rotation — this gives a cinematic feel:++```js+function animate() {+ currentRx += (targetRx - currentRx) * 0.1;+ currentRy += (targetRy - currentRy) * 0.1;+ obj.style.transform = `rotateX(${currentRx}deg) rotateY(${currentRy}deg)`;+ requestAnimationFrame(animate);+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Section height | 400vh | Total scroll budget — taller = slower reveal, more reading time |+| Keyframe count | 4 | Number of distinct rotation stages in the sequence |+| Lerp factor | 0.1 | Smoothing per frame — 0.1 is cinematic, 1.0 is instant |+| CSS perspective | 600px | Lower = more dramatic 3D distortion |++## Production notes+- **CSS Scroll-Driven Animations API** (Chrome 115+): `animation-timeline: scroll()` and `animation-range` can drive CSS transforms directly without JavaScript. The spec covers this natively, but browser support is still catching up for complex choreography.+- **GSAP ScrollTrigger**: in production, `gsap.timeline().to(obj, { rotateY: 360 }).scrollTrigger({ trigger, scrub: 1 })` is the idiomatic implementation. `scrub: 1` adds a 1-second smoothing lag.+- **Performance**: CSS `transform` on a 3D element with `will-change: transform` runs on the compositor thread — scroll-driven rotation does not trigger layout or paint.+- **Mobile scroll budget**: 400vh of scroll on mobile means the user must scroll a lot. Consider reducing section height for mobile, or switching to a swipe-driven (touch-drag) interaction.++## See also+- [3D Model Orbit](../3d-model-orbit/) — WebGL-rendered version of the same concept+- [Scrub Animation](../../01-scroll-based/scrub-animation/) — general scroll-scrub pattern without 3D+- [Sticky Section](../../01-scroll-based/sticky-section/) — the pinning pattern that enables scroll-driven revealsdiff --git a/animations/06-3d-advanced/scroll-driven-3d-rotation/index.html b/animations/06-3d-advanced/scroll-driven-3d-rotation/index.htmlnew file mode 100644index 00000000..ee294d5e--- /dev/null+++ b/animations/06-3d-advanced/scroll-driven-3d-rotation/index.html@@ -0,0 +1,176 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Scroll-Driven 3D Rotation</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;background:#04060c;overflow-y:auto;overflow-x:hidden;position:relative;scroll-behavior:auto}+ /* Scroll container: 4× stage height gives scroll budget */+ .scroll-content{height:calc(var(--stage-h)*4);position:relative}+ .sticky-wrap{position:sticky;top:0;height:var(--stage-h);display:flex;align-items:stretch}+ /* 3D display */+ .obj-panel{flex:1;display:flex;align-items:center;justify-content:center;perspective:600px}+ .obj-wrap{transform-style:preserve-3d;will-change:transform;transition:transform 0ms linear}+ /* CSS cube */+ .cube{width:120px;height:120px;position:relative;transform-style:preserve-3d}+ .face{position:absolute;width:120px;height:120px;border:2px solid rgba(88,166,255,.5);display:flex;align-items:center;justify-content:center;font-size:11px;color:rgba(88,166,255,.7);letter-spacing:1px}+ .face.front{background:rgba(88,166,255,.08);transform:translateZ(60px)}+ .face.back{background:rgba(88,166,255,.06);transform:rotateY(180deg) translateZ(60px)}+ .face.left{background:rgba(88,166,255,.04);transform:rotateY(-90deg) translateZ(60px)}+ .face.right{background:rgba(88,166,255,.04);transform:rotateY(90deg) translateZ(60px)}+ .face.top{background:rgba(88,166,255,.03);transform:rotateX(90deg) translateZ(60px)}+ .face.bottom{background:rgba(88,166,255,.03);transform:rotateX(-90deg) translateZ(60px)}+ /* Info panel */+ .info-panel{width:clamp(140px,30%,200px);display:flex;flex-direction:column;justify-content:center;gap:16px;padding:24px;border-left:1px solid var(--ui-border)}+ .stage-label{font-size:9px;letter-spacing:2px;text-transform:uppercase;color:var(--ui-accent);opacity:.6}+ .stage-val{font-size:clamp(16px,2.5vw,22px);font-weight:bold;color:#fff;font-variant-numeric:tabular-nums}+ .stage-desc{font-size:10px;color:var(--ui-muted);line-height:1.5}+ .chapter-dot{width:6px;height:6px;border-radius:50%;background:var(--ui-border);display:inline-block;margin-right:4px;transition:background .3s}+ .chapter-dot.active{background:var(--ui-accent)}+ /* Progress bar at top */+ .prog-bar{position:absolute;top:0;left:0;right:0;height:2px;background:var(--ui-border);z-index:2}+ .prog-fill{height:100%;background:var(--ui-accent);width:0%;transition:width 50ms linear}+ /* Side panel */+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .kv{display:flex;justify-content:space-between;font-size:10px;color:var(--ui-muted)}+ .kv .v{color:var(--ui-text)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:40px;text-align:right;color:var(--ui-text)}+ .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:480px}.info-panel{width:120px;padding:12px}}+ @media(prefers-reduced-motion:reduce){.obj-wrap{transition:none!important}.prog-fill{transition:none!important}}+ </style>+</head>+<body>+<header>+ <h1>Scroll-Driven 3D Rotation</h1>+ <p>Scroll progress choreographs 3D rotation through four stages — the Apple product-page pattern.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <div class="scroll-content">+ <div class="sticky-wrap">+ <div class="prog-bar"><div class="prog-fill" id="prog-fill"></div></div>+ <div class="obj-panel">+ <div class="obj-wrap" id="obj-wrap">+ <div class="cube">+ <div class="face front">FRONT</div>+ <div class="face back">BACK</div>+ <div class="face left">LEFT</div>+ <div class="face right">RIGHT</div>+ <div class="face top">TOP</div>+ <div class="face bottom">BOT</div>+ </div>+ </div>+ </div>+ <div class="info-panel" id="info-panel">+ <div>+ <div class="stage-label">Progress</div>+ <div class="stage-val" id="prog-val">0%</div>+ </div>+ <div>+ <div class="stage-label">Chapter</div>+ <div id="chapter-dots">+ <span class="chapter-dot active"></span>+ <span class="chapter-dot"></span>+ <span class="chapter-dot"></span>+ <span class="chapter-dot"></span>+ </div>+ </div>+ <div>+ <div class="stage-label">Stage</div>+ <div class="stage-val" id="stage-name" style="font-size:clamp(12px,1.5vw,15px)">Start</div>+ </div>+ <div class="stage-desc" id="stage-desc">Scroll to animate the object through four states.</div>+ </div>+ </div>+ </div>+ </div>+ <aside>+ <p class="note">Pin (sticky) + scrub (scroll-progress) + 3D transforms = the Apple product reveal. Scroll budget is 3× stage height, giving time to read each stage.</p>+ <div class="lbl">Scroll Progress</div>+ <div class="sr" style="pointer-events:none"><input type="range" id="prog-sl" min="0" max="100" value="0" step="1" style="pointer-events:none"><span class="sv" id="prog-sl-v">0%</span></div>+ <div class="lbl">Rotation Multiplier</div>+ <div class="sr"><input type="range" id="mult-sl" min="5" max="30" value="10" step="1"><span class="sv" id="mult-v">1×</span></div>+ <label class="tog"><input type="checkbox" id="smooth-tog" checked><span>Smooth scrub (lerp)</span></label>+ <div class="div"></div>+ <div class="kv"><span>Rotation X</span><span class="v" id="rx-v">0°</span></div>+ <div class="kv"><span>Rotation Y</span><span class="v" id="ry-v">0°</span></div>+ <div class="kv"><span>Scale</span><span class="v" id="sc-v">1.0</span></div>+ <div class="div"></div>+ <button class="rst" id="reset-btn">↺ Reset scroll</button>+ </aside>+</div>+<script>+const stageEl=document.getElementById('stage');+const objWrap=document.getElementById('obj-wrap');+const progFill=document.getElementById('prog-fill');+const progVal=document.getElementById('prog-val');+const stageName=document.getElementById('stage-name');+const stageDesc=document.getElementById('stage-desc');+const dots=[...document.querySelectorAll('.chapter-dot')];+let currRx=0,currRy=0,currSc=1,raf=null,mult=10;++const CHAPTERS=[+ {name:'Orbit Y',desc:'Rotating 90° around the Y axis.',rx:0,ry:0,sc:1},+ {name:'Tilt X',desc:'Tilting 30° forward on the X axis.',rx:-30,ry:90,sc:1},+ {name:'Scale Up',desc:'Growing 1.4× while tilted.',rx:-30,ry:90,sc:1.4},+ {name:'Back Face',desc:'Completing −180° Y rotation to show the back.',rx:0,ry:-180,sc:1},+];++function lerp(a,b,t){return a+(b-a)*t}++function applyRotation(p){+ const ch=Math.floor(p*4);const cp=Math.min(ch,3);const t=p*4-cp;+ const c0=CHAPTERS[Math.max(cp-1,0)];const c1=CHAPTERS[Math.min(cp,3)];+ let rx=lerp(c0.rx,c1.rx,t),ry=lerp(c0.ry,c1.ry,t),sc=lerp(c0.sc,c1.sc,t);+ const smooth=document.getElementById('smooth-tog').checked;+ if(smooth){currRx=lerp(currRx,rx,.1);currRy=lerp(currRy,ry,.1);currSc=lerp(currSc,sc,.1);}+ else{currRx=rx;currRy=ry;currSc=sc;}+ objWrap.style.transform=`rotateX(${currRx.toFixed(1)}deg) rotateY(${currRy.toFixed(1)}deg) scale(${currSc.toFixed(3)})`;+ document.getElementById('rx-v').textContent=currRx.toFixed(0)+'°';+ document.getElementById('ry-v').textContent=currRy.toFixed(0)+'°';+ document.getElementById('sc-v').textContent=currSc.toFixed(2);++ const chIdx=Math.min(Math.floor(p*4),3);+ dots.forEach((d,i)=>d.classList.toggle('active',i===chIdx));+ stageName.textContent=CHAPTERS[chIdx].name;+ stageDesc.textContent=CHAPTERS[chIdx].desc;+}++function onScroll(){+ const {scrollTop,scrollHeight,clientHeight}=stageEl;+ const max=scrollHeight-clientHeight;+ const p=max>0?scrollTop/max:0;+ progFill.style.width=(p*100).toFixed(1)+'%';+ progVal.textContent=Math.round(p*100)+'%';+ document.getElementById('prog-sl').value=Math.round(p*100);+ document.getElementById('prog-sl-v').textContent=Math.round(p*100)+'%';+ applyRotation(p);+}++stageEl.addEventListener('scroll',onScroll,{passive:true});+document.getElementById('mult-sl').addEventListener('input',e=>{+ mult=+e.target.value;document.getElementById('mult-v').textContent=(mult/10).toFixed(1)+'×';+});+document.getElementById('reset-btn').addEventListener('click',()=>{+ stageEl.scrollTop=0;currRx=currRy=0;currSc=1;applyRotation(0);+});+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/svg-path-animation/README.md b/animations/06-3d-advanced/svg-path-animation/README.mdnew file mode 100644index 00000000..1aab7036--- /dev/null+++ b/animations/06-3d-advanced/svg-path-animation/README.md@@ -0,0 +1,74 @@+# SVG Path Animation++## What it is+SVG path animation uses `stroke-dasharray` and `stroke-dashoffset` to reveal an SVG stroke progressively from one end to the other, giving the impression of a path being drawn in real time. The path is always fully rendered in the DOM — only its visibility changes. This makes the technique accessible (the final shape is always present for screen readers) and easily reversible (animate offset back to hide).++## When to use it+- Illustrated icon or logo reveals that "draw in" on page load+- Signature-style handwriting effects for brand copy+- Step-completion indicators that fill in as the user progresses+- Decorative borders and frames that draw themselves around content++## How it works+Every SVG path has a total stroke length accessible via `path.getTotalLength()`. Setting `stroke-dasharray` to that length creates a dash exactly as long as the entire path. Setting `stroke-dashoffset` to the same length hides it (the gap starts at position 0, covering the whole stroke). Animating offset from full length to 0 reveals the stroke:++```js+const path = document.querySelector('.draw-path');+const length = path.getTotalLength();++// Set up hidden state+path.style.strokeDasharray = length;+path.style.strokeDashoffset = length; // fully hidden+path.style.transition = 'none';++// Force browser to register the hidden state, then animate+requestAnimationFrame(() => requestAnimationFrame(() => {+ path.style.transition = `stroke-dashoffset 1500ms ease-out`;+ path.style.strokeDashoffset = 0; // fully revealed+}));+```++For multiple paths in sequence, stagger the transitions with a delay per path:++```js+paths.forEach((path, i) => {+ const len = path.getTotalLength();+ path.style.strokeDasharray = len;+ path.style.strokeDashoffset = len;+ path.style.transitionDelay = `${i * 300}ms`;++ requestAnimationFrame(() => requestAnimationFrame(() => {+ path.style.transition = `stroke-dashoffset 700ms ease-out ${i * 300}ms`;+ path.style.strokeDashoffset = 0;+ }));+});+```++**Fill at end** — trigger a fill reveal after the stroke draw completes:++```js+path.addEventListener('transitionend', () => {+ path.style.transition = 'fill 400ms ease';+ path.style.fill = 'rgba(88, 166, 255, 0.15)';+});+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Duration | 1500ms | Faster = snappy; slower = deliberate hand-drawing feel |+| Easing | ease-out | Matches natural drawing speed (fast start, slow finish); linear = mechanical |+| Stroke width | 2px | Thinner = precise/technical; thicker = bold/illustrative |+| Stagger delay | 300ms | Gap between sequential path starts |++## Production notes+- **`getTotalLength()` is required**: hardcoding `stroke-dasharray` breaks when the path changes. Always measure at runtime. For SVGs loaded asynchronously, measure after the element is added to the DOM.+- **Path direction**: the stroke draws from the path's start point (first `M` command). To control which end draws first, reverse the path data or animate in reverse (offset from 0 to length).+- **`stroke-dasharray` shorthand**: `stroke-dasharray: length length` (repeated) and `stroke-dasharray: length` are equivalent — a single value sets both dash and gap to the same length.+- **GSAP DrawSVG plugin**: handles `getTotalLength()`, offset calculation, and animation sequencing automatically. Essential for complex multi-path illustrations. `gsap.from(path, { drawSVG: 0 })`.+- **Framer Motion**: `<motion.path initial={{ pathLength: 0 }} animate={{ pathLength: 1 }} />` — `pathLength` is a 0–1 shorthand that internally manages `dasharray`/`dashoffset`.++## See also+- [Checkmark Draw](../../04-micro-interactions/checkmark-draw/) — the same technique applied to UI success states+- [Text Clip-Path Reveal](../../05-text-typography/text-clip-path-reveal/) — a conceptually similar progressive reveal for text+- [Outline to Fill](../../05-text-typography/outline-to-fill/) — SVG stroke → fill transition for textdiff --git a/animations/06-3d-advanced/svg-path-animation/index.html b/animations/06-3d-advanced/svg-path-animation/index.htmlnew file mode 100644index 00000000..860bf3a6--- /dev/null+++ b/animations/06-3d-advanced/svg-path-animation/index.html@@ -0,0 +1,198 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>SVG Path Animation</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px;--draw-dur:1500ms;--draw-ease:ease-out;--stroke-w:2;--stroke-color:#58a6ff}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;background:#04060c;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px;padding:24px;position:relative}+ svg{width:100%;max-width:400px;overflow:visible}+ .draw-path{+ fill:none;stroke:var(--stroke-color);stroke-width:var(--stroke-w);+ stroke-linecap:round;stroke-linejoin:round;+ stroke-dasharray:1;stroke-dashoffset:1;+ }+ .draw-path.fill-done{fill:rgba(88,166,255,.15);transition:fill .4s ease}+ .preset-tabs{display:flex;gap:6px}+ .ptab{background:none;border:1px solid var(--ui-border);color:var(--ui-muted);font-family:monospace;font-size:10px;padding:6px 14px;border-radius:4px;cursor:pointer;min-height:36px;transition:border-color .15s,color .15s}+ .ptab.active{border-color:var(--ui-accent);color:var(--ui-accent)}+ .svg-label{font-size:10px;color:var(--ui-muted);letter-spacing:2px;text-transform:uppercase}+ /* Panel */+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .kv{display:flex;justify-content:space-between;font-size:10px;color:var(--ui-muted)}+ .kv .v{color:var(--ui-text)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:44px;text-align:right;color:var(--ui-text)}+ select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:8px 6px;border-radius:4px;width:100%;min-height:44px}+ .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ input[type=color]{border:none;background:none;width:44px;height:30px;cursor:pointer;border-radius:4px;padding:0}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:auto}.stage{height:auto;min-height:420px}}+ @media(prefers-reduced-motion:reduce){.draw-path{stroke-dashoffset:0!important;transition:none!important}}+ </style>+</head>+<body>+<header>+ <h1>SVG Path Animation</h1>+ <p>stroke-dashoffset reveals a path from its start point — set dasharray to path length, animate offset to 0.</p>+</header>+<div class="layout">+ <div class="stage">+ <div class="preset-tabs" id="tabs"></div>+ <svg id="svg-stage" viewBox="0 0 400 260">+ <g id="drawing-group"></g>+ </svg>+ <div class="svg-label" id="svg-label">Line Drawing</div>+ </div>+ <aside>+ <p class="note">path.getTotalLength() gives the full stroke length. Set stroke-dasharray to that value and stroke-dashoffset from length→0 to draw the path in.</p>+ <div class="lbl">Draw Duration</div>+ <div class="sr"><input type="range" id="dur-sl" min="300" max="4000" value="1500" step="100"><span class="sv" id="dur-v">1.5s</span></div>+ <div class="lbl">Easing</div>+ <select id="ease-sel">+ <option value="ease-out" selected>Ease out</option>+ <option value="linear">Linear</option>+ <option value="ease-in-out">Ease in-out</option>+ <option value="cubic-bezier(.2,.7,.3,1)">Smooth</option>+ </select>+ <div class="lbl">Stroke Width</div>+ <div class="sr"><input type="range" id="sw-sl" min="1" max="6" value="2" step="0.5"><span class="sv" id="sw-v">2px</span></div>+ <div class="lbl">Stroke Color</div>+ <input type="color" id="color-pick" value="#58a6ff" aria-label="Stroke color">+ <label class="tog"><input type="checkbox" id="rev-tog"><span>Draw in reverse</span></label>+ <label class="tog"><input type="checkbox" id="fill-tog"><span>Fill at end</span></label>+ <div class="div"></div>+ <button class="rst" id="replay-btn">↺ Replay</button>+ <label class="tog"><input type="checkbox" id="loop-tog"><span>Auto-loop</span></label>+ <div class="kv"><span>Path length</span><span class="v" id="path-len">—</span></div>+ </aside>+</div>+<script>+const PRESETS=[+ {+ name:'Icon',label:'Complex Line Drawing',+ paths:[+ // Abstract geometric icon: house + star shapes+ 'M 60 200 L 60 120 L 200 40 L 340 120 L 340 200 Z',+ 'M 160 200 L 160 150 L 240 150 L 240 200',+ 'M 200 40 L 215 80 L 260 80 L 225 105 L 240 148 L 200 122 L 160 148 L 175 105 L 140 80 L 185 80 Z',+ ]+ },+ {+ name:'Signature',label:'Signature',+ paths:[+ // Cursive-style flowing path+ 'M 30 180 C 40 160 60 140 80 150 C 100 160 90 190 110 180 C 130 170 120 140 145 145 C 165 150 160 175 180 170 C 195 165 190 145 210 148 C 230 151 225 178 250 172 C 270 167 265 140 290 145 C 310 150 310 175 340 170 C 360 166 365 140 380 145',+ ]+ },+ {+ name:'Logo',label:'Logo Mark',+ paths:[+ // Circle + inner geometric shape+ 'M 200 40 A 120 120 0 1 1 199.99 40',+ 'M 200 80 L 240 150 L 200 130 L 160 150 Z',+ 'M 200 130 L 200 185',+ ]+ }+];++let current=0,loopTimer=null,animating=false;+const svg=document.getElementById('svg-stage');+const group=document.getElementById('drawing-group');+const tabs=document.getElementById('tabs');+const svgLabel=document.getElementById('svg-label');+const pathLenEl=document.getElementById('path-len');++function getDur(){return+document.getElementById('dur-sl').value}+function getEase(){return document.getElementById('ease-sel').value}+function getReverse(){return document.getElementById('rev-tog').checked}+function getFill(){return document.getElementById('fill-tog').checked}++// Build tab buttons+PRESETS.forEach((p,i)=>{+ const b=document.createElement('button');b.className='ptab'+(i===0?' active':'');b.textContent=p.name;+ b.addEventListener('click',()=>{current=i;document.querySelectorAll('.ptab').forEach((t,j)=>t.classList.toggle('active',j===i));replay();});+ tabs.appendChild(b);+});++function buildPaths(){+ group.innerHTML='';+ const p=PRESETS[current];+ svgLabel.textContent=p.label;+ const els=p.paths.map(d=>{+ const path=document.createElementNS('http://www.w3.org/2000/svg','path');+ path.setAttribute('d',d);+ path.className.baseVal='draw-path';+ group.appendChild(path);+ return path;+ });+ return els;+}++function animate(paths){+ if(animating)return;animating=true;+ const dur=getDur();const ease=getEase();const rev=getReverse();+ const totalLen=paths.reduce((a,p)=>a+p.getTotalLength(),0);+ pathLenEl.textContent=Math.round(totalLen)+'px';++ paths.forEach((path,i)=>{+ const len=path.getTotalLength();+ path.style.strokeDasharray=len;+ path.style.strokeDashoffset=rev?0:len;+ path.style.transition='none';+ const delay=i*(dur*0.3);+ setTimeout(()=>{+ path.style.transition=`stroke-dashoffset ${dur}ms ${ease}`;+ path.style.strokeDashoffset=rev?len:0;+ const isLast=i===paths.length-1;+ if(isLast){+ setTimeout(()=>{+ if(getFill())paths.forEach(p=>p.classList.add('fill-done'));+ animating=false;+ if(document.getElementById('loop-tog').checked){+ loopTimer=setTimeout(replay,1200);+ }+ },dur+50);+ }+ },delay+20);+ });+}++function replay(){+ clearTimeout(loopTimer);animating=false;+ const paths=buildPaths();+ paths.forEach(p=>p.classList.remove('fill-done'));+ setTimeout(()=>animate(paths),60);+}++document.getElementById('replay-btn').addEventListener('click',replay);+document.getElementById('dur-sl').addEventListener('input',e=>{+ document.getElementById('dur-v').textContent=(e.target.value/1000).toFixed(1)+'s';+ document.documentElement.style.setProperty('--draw-dur',e.target.value+'ms');+});+document.getElementById('sw-sl').addEventListener('input',e=>{+ document.getElementById('sw-v').textContent=e.target.value+'px';+ document.documentElement.style.setProperty('--stroke-w',e.target.value);+});+document.getElementById('color-pick').addEventListener('input',e=>{+ document.documentElement.style.setProperty('--stroke-color',e.target.value);+});+document.getElementById('ease-sel').addEventListener('change',()=>{});++replay();+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/volumetric-smoke/README.md b/animations/06-3d-advanced/volumetric-smoke/README.mdnew file mode 100644index 00000000..3c08bada--- /dev/null+++ b/animations/06-3d-advanced/volumetric-smoke/README.md@@ -0,0 +1,75 @@+# Volumetric Smoke / 3D Noise++## What it is+Volumetric rendering treats 3D space as a participating medium — fog, smoke, clouds, or fire — rather than a collection of surfaces. Instead of stopping at the first surface hit (like standard ray marching), each ray accumulates density as it travels through the volume. The result is light scattering, depth-based opacity, and the soft edges that make clouds and smoke look real. This demo samples a 3D fractal Brownian motion (fBm) noise field and renders it as animated smoke rising from a source.++## When to use it+- Atmospheric background effects: rising smoke, volumetric fog, cloud formations+- Sci-fi or fantasy environments where volumetric haze sets mood+- Data visualization where density/volume is the visual metaphor+- Animated title cards and hero sections with environmental effects++## How it works+For each pixel, a ray is marched through 3D space. At each step, the density of the noise field is sampled and accumulated. Light attenuation is computed by casting a short shadow ray toward the light:++```glsl+void main() {+ vec2 uv = (gl_FragCoord.xy - 0.5 * uResolution) / min(uResolution.x, uResolution.y);+ vec3 ro = vec3(0., 0., 3.); // camera origin+ vec3 rd = normalize(vec3(uv, -0.9)); // ray direction++ float transmittance = 1.0;+ vec3 color = uBackground;+ float stepSize = 3.0 / float(uSteps);++ for (int i = 0; i < MAX_STEPS; i++) {+ if (i >= uSteps) break;+ vec3 p = ro + rd * float(i) * stepSize;++ float d = smokeDensity(p, uTime); // sample noise at this 3D point+ if (d > 0.0) {+ // Shadow ray: march toward light+ float shadow = 1.0;+ for (int s = 1; s <= 3; s++) {+ shadow *= exp(-smokeDensity(p + lightDir * float(s) * 0.18, uTime) * stepSize * 2.5);+ }+ float alpha = 1.0 - exp(-d * stepSize * 8.0);+ color += transmittance * alpha * uSmokeColor * (0.15 + 0.85 * shadow);+ transmittance *= (1.0 - alpha);+ }+ if (transmittance < 0.01) break;+ }+ gl_FragColor = vec4(color + uBackground * transmittance, 1.0);+}+```++**3D noise density function** — fBm over the rising smoke shape:++```glsl+float smokeDensity(vec3 p, float t) {+ float r = length(p.xz);+ float src = exp(-r * 3.0) * smoothstep(-0.2, 0.6, p.y) * smoothstep(1.8, 1.0, p.y);+ float n = fbm(p * 1.4 + vec3(windDrift, t * speed, 0.0));+ return max(0.0, n - 0.45) * src * density;+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| March steps | 32 | 16 = fast/coarse; 64 = smooth/accurate; diminishing returns above 48 |+| Smoke density | 0.7 | Higher = denser, more opaque cloud; lower = wispy, transparent |+| Speed | 0.6 | How fast noise "rises" through the field (animation speed) |+| Step size | `3.0 / steps` | Smaller steps = finer detail but more iterations needed |++## Production notes+- **Step count vs quality**: each additional march step increases pixel cost linearly. 32 steps is generally sufficient for soft smoke; use 64 only for hero-quality renders. Add blue-noise dithering to random-offset each ray's start, breaking up banding artifacts at low step counts.+- **Shadow rays**: the 3-step shadow march adds 3× extra density samples per lit pixel. Toggle off on low-end devices. For production, pre-compute a voxelized shadow map and sample it instead.+- **Real-time fire and smoke**: game engines use particle systems with additive-blended sprite sheets for fire/smoke, which is faster than ray marching. Ray-marched volumes are used in offline rendering (films, VFX) and cinematic-quality game cutscenes.+- **Three.js `FogExp2`**: for simple atmosphere, Three.js's built-in exponential fog is computationally free (depth-based fog applied in the vertex shader). Use volumetric ray marching only when fog must have specific 3D shape.+- **Temporal accumulation**: real-time volumetric engines (Unreal Engine's Volumetric Fog) spread the ray march samples across multiple frames and blend results. This reduces per-frame cost by 4–8× at the cost of minor ghosting artifacts during fast camera motion.++## See also+- [Ray Marching / SDF Scene](../ray-marching-sdf/) — ray marching that finds surface hits rather than accumulating volume+- [Noise-Based Motion](../noise-based-motion/) — 2D application of the same noise functions+- [Fluid Simulation](../fluid-simulation/) — SDF-based alternative for liquid-like effectsdiff --git a/animations/06-3d-advanced/volumetric-smoke/index.html b/animations/06-3d-advanced/volumetric-smoke/index.htmlnew file mode 100644index 00000000..9584ee53--- /dev/null+++ b/animations/06-3d-advanced/volumetric-smoke/index.html@@ -0,0 +1,189 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Volumetric Smoke / 3D Noise</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative}+ canvas{display:block;width:100%;height:100%}+ .hud{position:absolute;top:8px;left:8px;right:8px;display:flex;justify-content:space-between;pointer-events:none}+ .badge{font-size:9px;color:rgba(255,255,255,.5);background:rgba(0,0,0,.4);padding:3px 8px;border-radius:4px}+ .src-panel{position:absolute;bottom:0;left:0;right:0;background:rgba(6,10,16,.92);border-top:1px solid var(--ui-border);padding:12px;font-size:8.5px;color:var(--ui-muted);font-family:monospace;line-height:1.5;max-height:220px;overflow-y:auto;display:none;white-space:pre-wrap;word-break:break-all}+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:40px;text-align:right;color:var(--ui-text)}+ .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ input[type=color]{border:none;background:none;width:44px;height:30px;cursor:pointer;border-radius:4px;padding:0}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:380px}}+ @media(prefers-reduced-motion:reduce){canvas{display:none}}+ </style>+</head>+<body>+<header>+ <h1>Volumetric Smoke / 3D Noise</h1>+ <p>Ray marching through a 3D noise field — density accumulated along each ray for a true volumetric look.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <canvas id="cvs"></canvas>+ <div class="hud">+ <div class="badge" id="fps">— fps</div>+ <div class="badge" id="steps-badge">32 steps</div>+ </div>+ <div class="src-panel" id="src-panel"></div>+ </div>+ <aside>+ <p class="note">Volumetric rendering accumulates density along a ray through 3D space — unlike surface rendering which stops at the first hit. Films use this for every cloud, fog, and smoke effect.</p>+ <div class="lbl">Smoke Density</div>+ <div class="sr"><input type="range" id="dens-sl" min="1" max="20" value="7" step="1"><span class="sv" id="dens-v">0.7</span></div>+ <div class="lbl">Animation Speed</div>+ <div class="sr"><input type="range" id="spd-sl" min="1" max="20" value="6" step="1"><span class="sv" id="spd-v">0.6</span></div>+ <div class="lbl">March Steps</div>+ <div class="sr"><input type="range" id="steps-sl" min="8" max="96" value="32" step="8"><span class="sv" id="steps-v">32</span></div>+ <div class="lbl">Smoke Color</div>+ <input type="color" id="smoke-pick" value="#9ab4d8" aria-label="Smoke color">+ <div class="lbl">Background Color</div>+ <input type="color" id="bg-pick" value="#030810" aria-label="Background color">+ <label class="tog"><input type="checkbox" id="wind-tog" checked><span>Wind drift</span></label>+ <label class="tog"><input type="checkbox" id="dither-tog" checked><span>Noise dither (reduce banding)</span></label>+ <label class="tog"><input type="checkbox" id="src-tog"><span>View shader source</span></label>+ <div class="div"></div>+ <button class="rst" id="pause-btn">⏸ Pause</button>+ </aside>+</div>+<script>+const VS=`attribute vec2 a;void main(){gl_Position=vec4(a,0.,1.);}`;+const FS=`+precision mediump float;+uniform vec2 uRes;uniform float uT,uDens,uSpd;uniform int uSteps;+uniform bool uWind,uDither;uniform vec3 uSmoke,uBG;++// 3D value noise via hash+float h31(vec3 p){return fract(sin(dot(p,vec3(127.1,311.7,74.7)))*43758.5);}+float noise(vec3 p){+ vec3 i=floor(p),f=fract(p),u=f*f*(3.-2.*f);+ float a=h31(i),b=h31(i+vec3(1,0,0)),c=h31(i+vec3(0,1,0)),d=h31(i+vec3(1,1,0));+ float e=h31(i+vec3(0,0,1)),ff=h31(i+vec3(1,0,1)),g=h31(i+vec3(0,1,1)),hh=h31(i+vec3(1,1,1));+ return mix(mix(mix(a,b,u.x),mix(c,d,u.x),u.y),mix(mix(e,ff,u.x),mix(g,hh,u.x),u.y),u.z);+}++float fbm(vec3 p){+ float v=0.,a=.5;+ for(int i=0;i<5;i++){v+=a*noise(p);p=p*2.03+vec3(.4,.3,.2);a*=.5;}+ return v;+}++float density(vec3 p,float t){+ float windX=uWind?t*.08:0.;+ vec3 q=p+vec3(windX,0.,0.);+ // Cone source shape: narrower at top+ float r=length(p.xz);float src=exp(-r*3.)*smoothstep(-.2,0.6,p.y)*smoothstep(1.8,1.0,p.y);+ float n=fbm(q*1.4+vec3(0.,t*uSpd*.4,0.));+ return max(0.,n-.45)*src*uDens*2.;+}++float dither(vec2 co){+ return (fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5)-.5)*.02;+}++void main(){+ vec2 uv=(gl_FragCoord.xy-.5*uRes)/min(uRes.x,uRes.y);+ vec3 ro=vec3(0.,0.,3.);+ vec3 rd=normalize(vec3(uv,-.9));+ vec3 col=uBG;+ float transmit=1.,stepSz=3./float(uSteps);+ float tStart=uDither?dither(gl_FragCoord.xy):0.;+ vec3 lightDir=normalize(vec3(1.5,2.,1.));+ float t=.2+tStart;+ for(int i=0;i<96;i++){+ if(i>=uSteps)break;+ vec3 p=ro+rd*t;+ if(p.y>2.5||p.y<-.3){t+=stepSz;continue;}+ float d=density(p,uT);+ if(d>0.){+ // Shadow along light ray (3 steps)+ float shadow=1.;+ for(int s=1;s<=3;s++){+ vec3 lp=p+lightDir*float(s)*.18;+ shadow*=exp(-density(lp,uT)*stepSz*2.5);+ }+ vec3 smokeCol=uSmoke*(.15+.85*shadow);+ float alpha=1.-exp(-d*stepSz*8.);+ col+=transmit*alpha*smokeCol;+ transmit*=1.-alpha;+ }+ t+=stepSz;+ if(transmit<.01)break;+ }+ col+=uBG*transmit;+ gl_FragColor=vec4(col,1.);+}`;++const stage=document.getElementById('stage'),cvs=document.getElementById('cvs');+const fpsEl=document.getElementById('fps'),stepsBadge=document.getElementById('steps-badge');+const srcPanel=document.getElementById('src-panel');+let W,H,gl,prog,raf=null,paused=false,lastT=0,startT=0;+let DENS=0.7,SPD=0.6,STEPS=32,WIND=true,DITHER=true;+let SMOKE=[154/255,180/255,216/255],BG=[3/255,8/255,16/255];++function h2r(h){return[parseInt(h.slice(1,3),16)/255,parseInt(h.slice(3,5),16)/255,parseInt(h.slice(5,7),16)/255];}+function init(){+ gl=cvs.getContext('webgl');if(!gl)return false;+ function sh(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS))console.error(gl.getShaderInfoLog(x));return x;}+ prog=gl.createProgram();gl.attachShader(prog,sh(gl.VERTEX_SHADER,VS));gl.attachShader(prog,sh(gl.FRAGMENT_SHADER,FS));gl.linkProgram(prog);+ if(!gl.getProgramParameter(prog,gl.LINK_STATUS))console.error(gl.getProgramInfoLog(prog));+ const buf=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buf);+ gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);+ const a=gl.getAttribLocation(prog,'a');gl.enableVertexAttribArray(a);gl.vertexAttribPointer(a,2,gl.FLOAT,false,0,0);+ srcPanel.textContent=FS;return true;+}+function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;if(gl)gl.viewport(0,0,W,H);}+function u(n){return gl.getUniformLocation(prog,n);}++function render(ts){+ if(paused){raf=null;return;}+ raf=requestAnimationFrame(render);+ const dt=ts-lastT;if(dt<16)return;+ fpsEl.textContent=Math.round(1000/(dt||16))+' fps';lastT=ts;+ const t=(ts-startT)/1000;+ gl.useProgram(prog);+ gl.uniform2f(u('uRes'),W,H);gl.uniform1f(u('uT'),t);+ gl.uniform1f(u('uDens'),DENS);gl.uniform1f(u('uSpd'),SPD);+ gl.uniform1i(u('uSteps'),STEPS);+ gl.uniform1i(u('uWind'),WIND?1:0);gl.uniform1i(u('uDither'),DITHER?1:0);+ gl.uniform3fv(u('uSmoke'),SMOKE);gl.uniform3fv(u('uBG'),BG);+ gl.drawArrays(gl.TRIANGLE_STRIP,0,4);+}++if(init()){resize();startT=performance.now();lastT=startT;raf=requestAnimationFrame(render);window.addEventListener('resize',resize);}++document.getElementById('dens-sl').addEventListener('input',e=>{DENS=e.target.value/10;document.getElementById('dens-v').textContent=DENS.toFixed(1);});+document.getElementById('spd-sl').addEventListener('input',e=>{SPD=e.target.value/10;document.getElementById('spd-v').textContent=SPD.toFixed(1);});+document.getElementById('steps-sl').addEventListener('input',e=>{STEPS=+e.target.value;document.getElementById('steps-v').textContent=STEPS;stepsBadge.textContent=STEPS+' steps';});+document.getElementById('smoke-pick').addEventListener('input',e=>{SMOKE=h2r(e.target.value);});+document.getElementById('bg-pick').addEventListener('input',e=>{BG=h2r(e.target.value);});+document.getElementById('wind-tog').addEventListener('change',e=>{WIND=e.target.checked;});+document.getElementById('dither-tog').addEventListener('change',e=>{DITHER=e.target.checked;});+document.getElementById('src-tog').addEventListener('change',e=>{srcPanel.style.display=e.target.checked?'block':'none';});+document.getElementById('pause-btn').addEventListener('click',()=>{+ paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';+ if(!paused&&gl){lastT=performance.now();raf=requestAnimationFrame(render);}+});+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/webgl-shader-animation/README.md b/animations/06-3d-advanced/webgl-shader-animation/README.mdnew file mode 100644index 00000000..34f401ee--- /dev/null+++ b/animations/06-3d-advanced/webgl-shader-animation/README.md@@ -0,0 +1,80 @@+# WebGL Shader Animation++## What it is+WebGL shader animations run entirely on the GPU — a fragment shader executes once per pixel per frame, producing the full visual from mathematical functions alone. The vertex shader is trivial (a fullscreen quad); all the creative work happens in the fragment shader. This is the model behind Shadertoy: each demo is one fragment shader, no geometry.++## When to use it+- Full-canvas animated backgrounds that need GPU-level performance+- Generative art and creative coding where patterns emerge from math+- Loading screens and transitions with zero asset overhead+- Brand expressions using procedural color and motion++## How it works+The entire setup is a quad covering the screen. The fragment shader receives the pixel coordinate and global time as uniforms:++```js+// Minimal WebGL boilerplate for a shader demo+const prog = createProgram(gl,+ `attribute vec2 a; void main() { gl_Position = vec4(a, 0., 1.); }`,+ fragmentShaderSource+);+const buf = gl.createBuffer();+gl.bindBuffer(gl.ARRAY_BUFFER, buf);+gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1, 1,-1, -1,1, 1,1]), gl.STATIC_DRAW);+gl.enableVertexAttribArray(aPos);+gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);++function render(ts) {+ gl.uniform2f(uRes, W, H);+ gl.uniform1f(uT, ts / 1000 * speed);+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);+ requestAnimationFrame(render);+}+```++**Plasma** — the simplest pattern; nested sine functions over UV coordinates:++```glsl+void main() {+ vec2 uv = gl_FragCoord.xy / uRes * 2.0 - 1.0;+ float v = sin(uv.x * 5.0 + uT)+ + sin(uv.y * 5.0 + uT * 0.7)+ + sin((uv.x + uv.y) * 5.0 + uT * 0.3)+ + sin(sqrt(uv.x*uv.x + uv.y*uv.y) * 6.0);+ vec3 col = 0.5 + 0.5 * cos(v * 3.14 + vec3(0, 2.09, 4.19));+ gl_FragColor = vec4(col, 1.0);+}+```++**Voronoi** — cellular pattern using nearest-neighbor distance in a grid:++```glsl+float voronoi(vec2 p) {+ vec2 i = floor(p), f = fract(p);+ float md = 8.0;+ for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) {+ vec2 n = vec2(x, y);+ vec2 pt = n + rand2(i + n); // random point in each cell+ md = min(md, length(pt - f));+ }+ return md;+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Time speed | 1.0× | Multiplier on `uT` uniform — faster = more energetic animation |+| Hue shift | 0° | Rotates the entire color palette without rewriting the shader |+| Max steps (where applicable) | — | Quality/performance tradeoff in iterative shaders |++## Production notes+- **Shadertoy**: all four patterns in this demo are canonical Shadertoy exercises. The site has a live GLSL editor, a large library of community shaders, and a standard uniform convention (`iTime`, `iResolution`, `iMouse`).+- **Canvas resolution**: shader cost scales with pixel count. At 4K, a complex shader runs 4× slower than at 1080p. Use `devicePixelRatio` carefully — rendering at 0.5× device pixels and upscaling often looks fine for background shaders.+- **`mediump` vs `highp`**: `precision mediump float` is required on mobile. Some shaders produce visible banding at `mediump` — switch to `precision highp float` for patterns with fine detail.+- **Mouse uniform**: add `uniform vec2 uMouse` and pass `e.clientX / W, e.clientY / H` to make any shader interactive without rewriting the core algorithm.++## See also+- [Fluid Simulation](../fluid-simulation/) — SDF-based shader, same fullscreen-quad approach+- [Ray Marching / SDF Scene](../ray-marching-sdf/) — most complex application of the same shader pattern+- [Noise-Based Motion](../noise-based-motion/) — canvas equivalent of procedural animated patternsdiff --git a/animations/06-3d-advanced/webgl-shader-animation/index.html b/animations/06-3d-advanced/webgl-shader-animation/index.htmlnew file mode 100644index 00000000..2eec79da--- /dev/null+++ b/animations/06-3d-advanced/webgl-shader-animation/index.html@@ -0,0 +1,197 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>WebGL Shader Animation</title>+ <style>+ :root{--bg:#060a10;--ui-bg:#0d1117;--ui-border:#21262d;--ui-accent:#58a6ff;--ui-text:#c9d1d9;--ui-muted:#8b949e;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:monospace;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-size:clamp(11px,1.8vw,15px);letter-spacing:2px;text-transform:uppercase}+ header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}+ .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative}+ canvas{display:block;width:100%;height:100%}+ .overlay{position:absolute;top:8px;left:8px;right:8px;display:flex;justify-content:space-between;align-items:flex-start;pointer-events:none}+ .fps-badge{font-size:9px;color:rgba(255,255,255,.5);background:rgba(0,0,0,.4);padding:3px 8px;border-radius:4px}+ .shader-name{font-size:9px;color:rgba(255,255,255,.6);background:rgba(0,0,0,.4);padding:3px 10px;border-radius:4px;letter-spacing:1px;text-transform:uppercase}+ .src-panel{position:absolute;bottom:0;left:0;right:0;background:rgba(6,10,16,.9);border-top:1px solid var(--ui-border);padding:12px;font-size:9px;color:var(--ui-muted);font-family:monospace;line-height:1.5;max-height:200px;overflow-y:auto;display:none;white-space:pre-wrap;word-break:break-all}+ aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}+ .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:40px;text-align:right;color:var(--ui-text)}+ select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:8px 6px;border-radius:4px;width:100%;min-height:44px}+ .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:380px}}+ @media(prefers-reduced-motion:reduce){canvas{display:none}}+ </style>+</head>+<body>+<header>+ <h1>WebGL Shader Animation</h1>+ <p>Four GLSL fragment shader presets — plasma, wave distortion, Voronoi, and kaleidoscope. Pure GPU math.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <canvas id="cvs"></canvas>+ <div class="overlay">+ <div class="fps-badge" id="fps">— fps</div>+ <div class="shader-name" id="shader-name">Plasma</div>+ </div>+ <div class="src-panel" id="src-panel"></div>+ </div>+ <aside>+ <p class="note">Fragment shaders run once per pixel on the GPU. The boilerplate (vertex shader, quad geometry, uniforms) stays identical — only the fragment shader changes per preset.</p>+ <div class="lbl">Shader Preset</div>+ <select id="preset-sel">+ <option value="0" selected>Plasma</option>+ <option value="1">Wave Distortion</option>+ <option value="2">Voronoi</option>+ <option value="3">Kaleidoscope</option>+ </select>+ <div class="lbl">Speed</div>+ <div class="sr"><input type="range" id="spd-sl" min="1" max="30" value="10" step="1"><span class="sv" id="spd-v">1.0</span></div>+ <div class="lbl">Hue Shift</div>+ <div class="sr"><input type="range" id="hue-sl" min="0" max="360" value="0" step="5"><span class="sv" id="hue-v">0°</span></div>+ <label class="tog"><input type="checkbox" id="mouse-tog"><span>Mouse interaction</span></label>+ <label class="tog"><input type="checkbox" id="src-tog"><span>View shader source</span></label>+ <div class="div"></div>+ <button class="rst" id="pause-btn">⏸ Pause</button>+ </aside>+</div>+<script>+const VS=`attribute vec2 a;void main(){gl_Position=vec4(a,0.,1.);}`;++const SHADERS=[+ // 0: Plasma+ {name:'Plasma',src:`precision mediump float;+uniform vec2 R;uniform float T,H;+vec3 hsv(float h,float s,float v){vec4 K=vec4(1.,2./3.,1./3.,3.);vec3 p=abs(fract(vec3(h)+K.xyz)*6.-K.www);return v*mix(K.xxx,clamp(p-K.xxx,0.,1.),s);}+void main(){+ vec2 uv=gl_FragCoord.xy/R*2.-1.;uv.x*=R.x/R.y;+ float v=sin(uv.x*5.+T)+sin(uv.y*5.+T*.7)+sin((uv.x+uv.y)*5.+T*.5)+sin(sqrt(uv.x*uv.x+uv.y*uv.y)*6.);+ float hue=fract(v*.25+T*.05+H/360.);+ gl_FragColor=vec4(hsv(hue,.9,.95),1.);+}`},+ // 1: Wave distortion+ {name:'Wave Distortion',src:`precision mediump float;+uniform vec2 R;uniform float T,H;+vec3 hsv(float h,float s,float v){vec4 K=vec4(1.,2./3.,1./3.,3.);vec3 p=abs(fract(vec3(h)+K.xyz)*6.-K.www);return v*mix(K.xxx,clamp(p-K.xxx,0.,1.),s);}+void main(){+ vec2 uv=gl_FragCoord.xy/R;+ float wave=sin(uv.y*12.+T*2.)*.04+sin(uv.x*8.-T*1.5)*.03;+ vec2 d=uv+vec2(wave,wave*1.3);+ float stripe=sin(d.x*20.+T)*sin(d.y*20.-T*.6);+ float hue=fract(stripe*.3+H/360.+T*.02);+ gl_FragColor=vec4(hsv(hue,.85,.9),1.);+}`},+ // 2: Voronoi+ {name:'Voronoi',src:`precision mediump float;+uniform vec2 R;uniform float T,H;+vec3 hsv(float h,float s,float v){vec4 K=vec4(1.,2./3.,1./3.,3.);vec3 p=abs(fract(vec3(h)+K.xyz)*6.-K.www);return v*mix(K.xxx,clamp(p-K.xxx,0.,1.),s);}+float rand(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5);}+void main(){+ vec2 uv=gl_FragCoord.xy/R*4.;+ vec2 i=floor(uv),f=fract(uv);+ float md=8.,mi=0.;+ for(int y=-1;y<=1;y++)for(int x=-1;x<=1;x++){+ vec2 n=vec2(float(x),float(y));+ vec2 pt=n+vec2(rand(i+n+T*.01),rand(i+n+vec2(3.7,1.5)+T*.013));+ float d=length(pt-f);if(d<md){md=d;mi=rand(i+n);}+ }+ float edge=smoothstep(.02,.06,md);+ float hue=fract(mi+H/360.+T*.03);+ gl_FragColor=vec4(hsv(hue,.8,.8)*edge+vec3(.05)*(1.-edge),1.);+}`},+ // 3: Kaleidoscope+ {name:'Kaleidoscope',src:`precision mediump float;+uniform vec2 R;uniform float T,H;uniform vec2 M;uniform bool uMouse;+vec3 hsv(float h,float s,float v){vec4 K=vec4(1.,2./3.,1./3.,3.);vec3 p=abs(fract(vec3(h)+K.xyz)*6.-K.www);return v*mix(K.xxx,clamp(p-K.xxx,0.,1.),s);}+void main(){+ vec2 uv=(gl_FragCoord.xy-.5*R)/min(R.x,R.y);+ float a=atan(uv.y,uv.x),r=length(uv);+ float segs=uMouse?max(3.,M.x*12.):8.;+ a=abs(mod(a,2.*3.14159/segs)-3.14159/segs);+ uv=vec2(cos(a),sin(a))*r;+ float v=sin(uv.x*8.+T)*sin(uv.y*8.-T*.7)+sin(r*10.-T*1.5)*.5;+ float hue=fract(v*.3+H/360.+T*.04);+ gl_FragColor=vec4(hsv(hue,.9,.9),1.);+}`},+];++const stage=document.getElementById('stage');const cvs=document.getElementById('cvs');+const fpsEl=document.getElementById('fps');const shaderName=document.getElementById('shader-name');+const srcPanel=document.getElementById('src-panel');+let W,H,gl,prog=null,raf=null,paused=false,lastT=0,startT=0;+let PRESET=0,SPD=1,HUE=0,MOUSE_UV=[.5,.5],MOUSE_ON=false;++function mkProg(fs){+ function sh(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);return x;}+ const p=gl.createProgram();+ gl.attachShader(p,sh(gl.VERTEX_SHADER,VS));+ gl.attachShader(p,sh(gl.FRAGMENT_SHADER,fs));+ gl.linkProgram(p);return p;+}++function init(){+ gl=cvs.getContext('webgl');if(!gl)return false;+ const buf=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buf);+ gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);+ switchShader(0);return true;+}++function switchShader(idx){+ PRESET=idx;+ if(prog)gl.deleteProgram(prog);+ prog=mkProg(SHADERS[idx].src);+ const a=gl.getAttribLocation(prog,'a');+ gl.enableVertexAttribArray(a);gl.vertexAttribPointer(a,2,gl.FLOAT,false,0,0);+ shaderName.textContent=SHADERS[idx].name;+ if(document.getElementById('src-tog').checked)srcPanel.textContent=SHADERS[idx].src;+}++function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;if(gl)gl.viewport(0,0,W,H);}++function render(ts){+ if(paused){raf=null;return;}+ raf=requestAnimationFrame(render);+ const dt=ts-lastT;if(dt<16)return;+ fpsEl.textContent=Math.round(1000/(dt||16))+' fps';lastT=ts;+ const t=(ts-startT)/1000*SPD;+ gl.useProgram(prog);+ const u=n=>gl.getUniformLocation(prog,n);+ gl.uniform2f(u('R'),W,H);gl.uniform1f(u('T'),t);gl.uniform1f(u('H'),HUE);+ if(MOUSE_ON){gl.uniform2f(u('M'),MOUSE_UV[0],MOUSE_UV[1]);gl.uniform1i(u('uMouse'),1);}+ else gl.uniform1i(u('uMouse'),0);+ gl.drawArrays(gl.TRIANGLE_STRIP,0,4);+}++if(init()){+ resize();startT=lastT=performance.now();raf=requestAnimationFrame(render);+ stage.addEventListener('mousemove',e=>{const r=cvs.getBoundingClientRect();MOUSE_UV=[(e.clientX-r.left)/r.width,(e.clientY-r.top)/r.height];});+ window.addEventListener('resize',resize);+}++document.getElementById('preset-sel').addEventListener('change',e=>{switchShader(+e.target.value);});+document.getElementById('spd-sl').addEventListener('input',e=>{SPD=e.target.value/10;document.getElementById('spd-v').textContent=SPD.toFixed(1);});+document.getElementById('hue-sl').addEventListener('input',e=>{HUE=+e.target.value;document.getElementById('hue-v').textContent=HUE+'°';});+document.getElementById('mouse-tog').addEventListener('change',e=>{MOUSE_ON=e.target.checked;});+document.getElementById('src-tog').addEventListener('change',e=>{+ srcPanel.style.display=e.target.checked?'block':'none';+ if(e.target.checked)srcPanel.textContent=SHADERS[PRESET].src;+});+document.getElementById('pause-btn').addEventListener('click',()=>{+ paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';+ if(!paused&&gl){lastT=performance.now();raf=requestAnimationFrame(render);}+});+</script>+</body>+</html>diff --git a/index.html b/index.htmlindex efe0ebaf..b3e221a1 100644--- a/index.html+++ b/index.html@@ -5,7 +5,7 @@<meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Animation Atlas</title><style>- :root{--bg:#060a10;--ui-bg:#0d1117;--border:#21262d;--text:#c9d1d9;--muted:#8b949e;--c1:#58a6ff;--c2:#56d364;--c3:#d2a8ff;--c4:#ffa657;--c5:#f85149}+ :root{--bg:#060a10;--ui-bg:#0d1117;--border:#21262d;--text:#c9d1d9;--muted:#8b949e;--c1:#58a6ff;--c2:#56d364;--c3:#d2a8ff;--c4:#ffa657;--c5:#f85149;--c6:#56d364}*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}body{background:var(--bg);color:var(--text);font-family:monospace;padding:clamp(20px,4vw,56px) clamp(16px,4vw,48px);max-width:1100px;margin:0 auto}.hero{margin-bottom:clamp(40px,6vw,72px);padding-bottom:32px;border-bottom:1px solid var(--border)}@@ -33,6 +33,7 @@.c3-cat .card:hover{border-color:var(--c3)}.c3-cat .card:hover .card-name{color:var(--c3)}.c4-cat .card:hover{border-color:var(--c4)}.c4-cat .card:hover .card-name{color:var(--c4)}.c5-cat .card:hover{border-color:var(--c5)}.c5-cat .card:hover .card-name{color:var(--c5)}+ .c6-cat .card:hover{border-color:var(--c6)}.c6-cat .card:hover .card-name{color:var(--c6)}.planned{margin-bottom:16px}.planned h2{font-size:10px;text-transform:uppercase;letter-spacing:2.5px;color:var(--muted);margin-bottom:12px;opacity:.45}.soon-list{display:flex;gap:8px;flex-wrap:wrap}@@ -46,7 +47,7 @@<p class="hero-sub">A visual reference of web animation techniques. Each entry is a self-contained demo with an explanation of the mechanic — open any HTML file and it runs offline, no build step.</p><div class="hero-meta"><a class="hero-link" href="https://github.com/matinmonshizadeh/animation-handbook">github.com/matinmonshizadeh/animation-handbook →</a>- <span class="badge">72 animations · 5 categories</span>+ <span class="badge">88 animations · 6 categories</span></div></div><div id="root"></div>@@ -158,6 +159,29 @@ const CATS=[['enter-exit-typography','Enter/Exit Typography','Three-act phrase lifecycle: enter → hold → exit, sequenced for storytelling.'],['rotate-word-carousel','Rotate Word Carousel','One keyword cycles through a list while the surrounding sentence stays static.'],]+ },+ {+ name:'3D & Advanced',cat:'c6-cat',dot:'#56d364',n:'06',+ desc:'WebGL, shaders, particles, 3D transforms, and the performance-sensitive effects that push the browser\'s limits.',+ folder:'animations/06-3d-advanced',+ entries:[+ ['3d-model-orbit','3D Model Orbit','Phong-shaded WebGL geometry — vertex buffers, MVP matrix, and lighting in raw WebGL.'],+ ['scroll-driven-3d-rotation','Scroll-Driven 3D Rotation','CSS cube rotates through four choreographed stages as you scroll — the Apple product-page pattern.'],+ ['parallax-3d-tilt','Parallax 3D Tilt','CSS perspective + rotateX/Y follows mouse — a shine highlight tracks the virtual light source.'],+ ['canvas-particle-effect','Canvas Particle Effect','500 drifting particles with O(n²) proximity connections and mouse repel/attract on 2D canvas.'],+ ['fluid-simulation','Fluid Simulation','WebGL metaballs — SDF spheres merged via smooth-minimum in a GLSL fragment shader.'],+ ['glassmorphism-animated','Glassmorphism Animated','backdrop-filter: blur() over animated gradient blobs — three frost variants.'],+ ['webgl-shader-animation','WebGL Shader Animation','Four GLSL fragment shader presets: plasma, wave distortion, Voronoi, kaleidoscope.'],+ ['noise-based-motion','Noise-Based Motion','Simplex noise drives a wind field and a morphing blob — smooth random, not chaotic random.'],+ ['svg-path-animation','SVG Path Animation','stroke-dashoffset reveals three SVG drawings — icon, signature, and logo mark.'],+ ['chromatic-aberration','Chromatic Aberration','RGB channels offset via mix-blend-mode: screen — static, pulse, and glitch modes.'],+ ['2-5d-pseudo-3d','2.5D / Pseudo-3D','Seven depth layers parallax at different rates — mouse-driven or auto-panning camera.'],+ ['ray-marching-sdf','Ray Marching / SDF','3D scene entirely in a fragment shader — sphere blend, boolean ops, infinite repetition.'],+ ['gpgpu-particle-system','GPGPU Particle System','65k+ particles computed in WebGL2 textures — physics in a shader, texture ping-pong.'],+ ['image-distortion-hover','Image Distortion on Hover','Fragment shader displaces UV coordinates around the cursor — ripple, push, liquid, pixelate.'],+ ['cloth-simulation','Cloth Simulation','Verlet integration + distance constraints — draggable flag responds to gravity and wind.'],+ ['volumetric-smoke','Volumetric Smoke','Ray marching accumulates 3D noise density — light scattering, shadow rays, fBm clouds.'],+ ]}];@@ -173,7 +197,7 @@ CATS.forEach(cat=>{});const planned=document.createElement('div');planned.className='planned';-planned.innerHTML=`<h2>Coming soon</h2><div class="soon-list"><span class="soon">06 — 3D & Advanced</span><span class="soon">07 — Ambient & Background</span></div>`;+planned.innerHTML=`<h2>Coming soon</h2><div class="soon-list"><span class="soon">07 — Ambient & Background</span></div>`;root.appendChild(planned);</script></body>