Skip to content

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.

31.6 KB
Raw Blame
<!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 — Animation Handbook</title>
  <meta name="description" content="Soft smoke curls upward, drawn as a real 3D cloud. Best for moody backgrounds.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/volumetric-smoke/">
  <link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png">
  <link rel="icon" type="image/svg+xml" href="../../../favicon.svg">
  <link rel="apple-touch-icon" href="../../../apple-touch-icon.png">
  <meta property="og:type" content="article">
  <meta property="og:site_name" content="Animation Handbook">
  <meta property="og:title" content="Volumetric Smoke / 3D Noise — Animation Handbook">
  <meta property="og:description" content="Soft smoke curls upward, drawn as a real 3D cloud. Best for moody backgrounds.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/volumetric-smoke/">
  <meta property="og:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:title" content="Volumetric Smoke / 3D Noise — Animation Handbook">
  <meta name="twitter:description" content="Soft smoke curls upward, drawn as a real 3D cloud. Best for moody backgrounds.">
  <meta name="twitter:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
  <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Volumetric Smoke / 3D Noise", "name": "Volumetric Smoke / 3D Noise", "description": "Soft smoke curls upward, drawn as a real 3D cloud. Best for moody backgrounds.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/volumetric-smoke/", "inLanguage": "en", "articleSection": "3D & Advanced", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, 3D & Advanced, Volumetric Smoke / 3D Noise"}</script>
  <style>
    :root{--ui-accent:#3fd6c4;--gold:#ffbf3c}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{position:relative;background:#030810}
    canvas{display:block;width:100%;height:100%}
    .msg{position:absolute;inset:0;display:none;align-items:center;justify-content:center;text-align:center;padding:clamp(16px,4vw,32px);font-size:13px;line-height:1.7;color:rgba(255,255,255,.72);white-space:pre-wrap;overflow-y:auto}
    .msg.on{display:flex}
    /* See inside and Compare: lines and plain words over the picture (the picture itself is drawn by the shader) */
    .ov,.cap{display:none;position:absolute;pointer-events:none}
    .ov{inset:0;width:100%;height:100%}
    .cap{padding:3px 8px;border-radius:5px;background:rgba(3,8,16,.9);color:#f4f4f2;font:600 13px/1.2 var(--hb-font);white-space:nowrap}
    .cap.gold{color:var(--gold)}
    .stage[data-hb-mode="inside"] .ov,.stage[data-hb-mode="compare"] .ov,.stage[data-hb-mode="inside"] .c-in,.stage[data-hb-mode="compare"] .c-cmp{display:block}
    .stage .cap[hidden],.stage.no-gl .ov,.stage.no-gl .cap{display:none!important}
    .ov *{fill:none;stroke-linecap:round;stroke-width:2}
    .ov .div{stroke:#2b2b33}
    .ov .ray{stroke:rgba(244,244,242,.3);stroke-width:1}
    .ov .dots{stroke:rgba(244,244,242,.8);stroke-width:var(--dot)}
    .ov .arrow{stroke:#f4f4f2}
    .ov .eye{fill:#f4f4f2}
    .ov .gold{stroke:var(--gold)}
    .ov .ray.gold{stroke-width:1.5}
  </style>
  <link rel="stylesheet" href="../../../assets/css/demo-page.css?v=11">
  <script src="../../../assets/js/demo-page.js?v=11" defer></script>
</head>
<body class="hb" data-hb-kind="loop">
<nav class="hb-bar" aria-label="Animation Handbook">
  <a class="hb-home" href="../../../"><svg class="hb-mark" viewBox="0 0 32 32" aria-hidden="true"><g class="g"><circle cx="11.16" cy="20.84" r="6.1"/><circle cx="15.12" cy="16.88" r="6.1"/><circle cx="18.51" cy="13.49" r="6.1"/></g><circle class="b" cx="21.2" cy="10.8" r="6.6"/></svg><span>Animation Handbook</span></a>
  <span class="hb-pager"><a href="../cloth-simulation/" rel="prev" aria-label="Previous: Cloth / Soft-Body Simulation"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg><span><span class="hb-dir">Previous: </span>Cloth / Soft-Body Simulation</span></a><a href="../morphing-blob/" rel="next" aria-label="Next: Morphing Blob"><span><span class="hb-dir">Next: </span>Morphing Blob</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg></a></span>
  <a class="hb-star" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener" aria-label="Star on GitHub"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg><span>Star on GitHub</span></a>
</nav>
<main class="hb-page">
  <header class="hb-head">
    <p class="hb-cat">06.16 · 3D &amp; Advanced</p>
    <h1>Volumetric Smoke / 3D Noise</h1>
    <p class="hb-lede">Soft smoke curls upward, drawn as a real 3D cloud. Best for moody backgrounds.</p>
  </header>

  <section class="hb-step hb-watch" aria-labelledby="hb-watch-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">1</span>
      <div><h2 id="hb-watch-title">Watch it</h2><p>It moves by itself. Pause it to look closely, or turn on slow motion to see each part of the movement.</p></div>
    </div>
    <div class="seg hb-modes" role="group" aria-label="What the box shows" data-hb-modes>
      <button type="button" data-hb-mode="normal" class="on" aria-pressed="true">Normal</button>
      <button type="button" data-hb-mode="inside" aria-pressed="false">See inside</button>
      <button type="button" data-hb-mode="compare" aria-pressed="false">Compare</button>
    </div>
    <div class="stage" id="stage">
      <canvas id="cvs" role="img" aria-label="Soft smoke rising and curling against a dark background"></canvas>
      <div class="msg" id="msg" role="status"></div>
      <svg class="ov" id="ov" aria-hidden="true"></svg>
      <span class="cap c-in" data-cap="front" data-hb-caption aria-hidden="true">What you see</span>
      <span class="cap c-in gold" data-cap="pixel" data-hb-caption aria-hidden="true">This pixel</span>
      <span class="cap c-in" data-cap="side" data-hb-caption aria-hidden="true">From the side</span>
      <span class="cap c-in" data-cap="eye" data-hb-caption aria-hidden="true">Your eye</span>
      <span class="cap c-in gold" data-cap="line" data-hb-caption aria-hidden="true">Its line of sight: a dot at each step</span>
      <span class="cap c-in" data-cap="light" data-hb-caption aria-hidden="true">Light</span>
      <span class="cap c-cmp" data-cap="flat" data-hb-caption aria-hidden="true">Flat picture</span>
      <span class="cap c-cmp" data-cap="cloud" data-hb-caption aria-hidden="true">3D cloud</span>
    </div>
    <div class="hb-player">
      <button class="hb-play" type="button" id="btn-pause" data-hb-pause data-state="playing"><svg class="hb-ic hb-i-pause" viewBox="0 0 24 24" aria-hidden="true"><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></svg><svg class="hb-ic hb-i-play" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 3l14 9-14 9z"/></svg><span class="hb-pause-label">Pause</span></button>
      <label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="slow-tog" data-hb-slowmo autocomplete="off"><span>Slow motion</span></label>
    </div>
    <div class="hb-mode-notes" aria-live="polite">
      <p data-hb-for="inside" hidden>From the side, each pixel's line of sight takes steps through the cloud (the dots), adding up the smoke it meets. Fine grain staggers the steps, so no stripes form.</p>
      <p data-hb-for="compare" hidden>Flat picture is the same smoke pattern at one depth, flat and unlit; 3D cloud adds up smoke along each line of sight and shades it from the light, so it looks soft and deep.</p>
    </div>
  </section>

  <section class="hb-step hb-try" aria-labelledby="hb-try-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">2</span>
      <div><h2 id="hb-try-title">Try it</h2><p>Change a setting and see the difference as it moves.</p></div>
    </div>
    <div class="hb-settings">
      <div class="hb-setting">
        <p class="hb-setting-name" id="dens-lbl">Thickness</p>
        <div class="seg" id="dens-seg" role="group" aria-labelledby="dens-lbl">
          <button type="button" data-dens="0.4" aria-pressed="false">Thin</button>
          <button type="button" data-dens="0.7" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-dens="1.2" aria-pressed="false">Thick</button>
        </div>
        <p class="hb-hint">Thin smoke is wispy; thick smoke hides what is behind.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="speed-lbl">Speed</p>
        <div class="seg" id="speed-seg" role="group" aria-labelledby="speed-lbl">
          <button type="button" data-spd="0.35" aria-pressed="false">Slow</button>
          <button type="button" data-spd="0.6" class="on" aria-pressed="true">Normal</button>
          <button type="button" data-spd="1" aria-pressed="false">Fast</button>
        </div>
        <p class="hb-hint">How fast the smoke rises.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="steps-lbl">Detail</p>
        <div class="seg" id="steps-seg" role="group" aria-labelledby="steps-lbl">
          <button type="button" data-steps="16" aria-pressed="false">Low</button>
          <button type="button" data-steps="32" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-steps="64" aria-pressed="false">High</button>
        </div>
        <p class="hb-hint">More steps look smoother but cost more.</p>
      </div>
    </div>
    <details class="hb-options">
      <summary><span class="hb-more-label">More options</span><span class="hb-less">Fewer options</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></summary>
      <div class="hb-settings">
        <div class="hb-setting">
          <p class="hb-setting-name" id="smoke-lbl">Smoke color</p>
          <div class="swatches" id="smoke-sw" role="group" aria-labelledby="smoke-lbl">
            <button type="button" class="on" aria-pressed="true" aria-label="Gray blue" data-color="#9ab4d8" style="background:#9ab4d8"></button>
            <button type="button" aria-pressed="false" aria-label="White" data-color="#f4f4f2" style="background:#f4f4f2"></button>
            <button type="button" aria-pressed="false" aria-label="Purple" data-color="#d2a8ff" style="background:#d2a8ff"></button>
            <button type="button" aria-pressed="false" aria-label="Orange" data-color="#ffa657" style="background:#ffa657"></button>
          </div>
          <p class="hb-hint">The color of the lit smoke.</p>
        </div>
        <div class="hb-setting">
          <label class="hb-switch-row"><span>Wind</span><input class="hb-switch" type="checkbox" role="switch" id="wind-tog" checked autocomplete="off"></label>
          <p class="hb-hint">The smoke drifts slowly to one side.</p>
        </div>
        <div class="hb-setting">
          <label class="hb-switch-row"><span>Fine grain</span><input class="hb-switch" type="checkbox" role="switch" id="dither-tog" checked autocomplete="off"></label>
          <p class="hb-hint">Grain hides the stripes that few steps leave.</p>
        </div>
      </div>
    </details>
  </section>

  <section class="hb-step hb-prompt-step" aria-labelledby="hb-prompt-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">3</span>
      <div><h2 id="hb-prompt-title">Copy the prompt</h2><p>Paste it into an AI assistant such as ChatGPT, Claude or Cursor to build this in your own project.</p></div>
    </div>
    <div class="hb-card">
      <p class="hb-prompt">Add volumetric smoke to [the section you want it in]. In a fragment shader, send a ray through a 3D cloud of smooth noise for every pixel and add up how much smoke it passes through, shading each step by how much smoke lies between it and the light, so the plume looks soft, deep and lit from one side. Move the noise upward over time so the smoke rises and curls, and let it drift sideways when the settings include wind. It is costly, so draw fewer pixels and take fewer steps on phones. If the visitor has reduced motion turned on, show the smoke still. Match the settings listed below.</p>
      <div class="hb-chips-box" hidden>
        <p class="hb-chips-title">Your settings</p>
        <ul class="hb-chips"></ul>
      </div>
      <div class="hb-copy-row">
        <button class="hb-copy" type="button"><svg class="hb-ic hb-i-copy" viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg><svg class="hb-ic hb-i-done" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg><span class="hb-copy-label" aria-live="polite">Copy prompt</span></button>
        <p class="hb-hint">Replace the words in brackets with your own element. Your settings are added at the end.</p>
      </div>
    </div>
    <div class="hb-star-row"><p>Free and open source. If this helped, a star on GitHub helps other people find it.</p><a class="hb-star-btn" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg>Star on GitHub</a></div>
  </section>

  <section class="hb-about" aria-labelledby="hb-what-title">
    <div class="hb-what">
      <h2 id="hb-what-title">What it is</h2>
      <div class="hb-what-text"><p>The full explanation is in <a href="README.md">README.md</a>.</p></div>
    </div>
    <div class="hb-fit">
      <h2>Good for</h2>
      <ul class="hb-tags hb-good"><li>Moody backgrounds</li><li>Title cards</li><li>Games</li><li>Sci-fi themes</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Behind text</li><li>Low-power devices</li></ul>
    </div>
  </section>

  <section class="hb-related" aria-labelledby="hb-related-title" hidden>
    <h2 id="hb-related-title">Similar animations</h2>
    <div class="hb-rel-list"></div>
  </section>
</main>
<footer class="hb-foot"><span>Animation Handbook</span><a href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener">Source on GitHub</a><a href="#top">Back to top ↑</a></footer>
<script>
const VS=`attribute vec2 a;void main(){gl_Position=vec4(a,0.,1.);}`;
const FS=`
#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp float;
#else
precision mediump float;
#endif
uniform vec2 uRes,uOrigin,uSc;uniform float uT,uDens,uRise;uniform int uSteps,uView;
uniform bool uWind,uDither;uniform vec3 uSmoke,uBG;uniform vec4 uSl;

// 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)*(1.-smoothstep(1.0,1.8,p.y));
  // Nothing to add where the plume has faded out, so the five noise samples are only taken where there can be smoke
  if(src<1e-3)return 0.;
  float n=fbm(q*1.4+vec3(0.,uRise*.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;
}

// The three short taps toward the light: 1 in full light, .15 in full shade
float lit(vec3 p,float stepSz){
  vec3 lightDir=normalize(vec3(1.5,2.,1.));
  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);
  }
  return .15+.85*shadow;
}

// See inside, from the side: the cloud's middle slice (x = 0), each spot colored by the same density() and light as the smoke
vec3 slice(){
  vec2 f=(gl_FragCoord.xy-uOrigin)/uRes;
  vec3 p=vec3(0.,uSl.y+f.y*uSl.w,uSl.x-f.x*uSl.z);
  vec3 bg=uBG*2.2;
  float d=density(p,uT);
  if(d<=0.)return bg;
  return mix(bg,uSmoke*lit(p,3./float(uSteps)),1.-exp(-d*9.));
}

// Compare, the flat picture: density() read once where each pixel's line of sight meets the column's middle plane (z = 0), no steps, no light
vec3 flatPic(vec2 uv){
  float d=density(vec3(uv*(3./.9),0.),uT);
  return mix(uBG,uSmoke*.85,smoothstep(0.,.008,d)*.19);
}

void main(){
  vec2 uv=(gl_FragCoord.xy-uOrigin-.5*uRes)/min(uRes.x,uRes.y);
  uv=uv*uSc.x+vec2(0.,uSc.y);
  if(uView==1){gl_FragColor=vec4(slice(),1.);return;}
  if(uView==2){gl_FragColor=vec4(flatPic(uv),1.);return;}
  vec3 ro=vec3(0.,0.,3.);
  vec3 rd=normalize(vec3(uv,-.9));
  vec3 col=vec3(0.);
  float transmit=1.,stepSz=3./float(uSteps);
  float tStart=uDither?dither(gl_FragCoord.xy)*stepSz:0.;
  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.){
      vec3 smokeCol=uSmoke*lit(p,stepSz);
      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 msgEl=document.getElementById('msg'),slowTog=document.getElementById('slow-tog');
const UNIFORMS=['uRes','uOrigin','uSc','uSl','uView','uT','uDens','uRise','uSteps','uWind','uDither','uSmoke','uBG'];
// The clock and the rise start where the old still frame was (2 seconds in, at the default speed), so the first picture is that frame
let W=0,H=0,gl=null,prog=null,U=null,raf=null,paused=false,last=null,curT=2,rise=1.2,wasPhone=false,lost=false;
let DENS=0.7,SPD=0.6,STEPS=32,WIND=true,DITHER=true;
let SMOKE=[154/255,180/255,216/255];
const BG=[3/255,8/255,16/255];
// Phones are screens up to 600px wide, or up to 500px tall when held sideways
const PHONE=matchMedia('(max-width:600px),(max-height:500px)');

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];}
// A canvas that can never draw is also taken out of the page for screen readers (hide); a lost context leaves it under the message.
function fail(msg,hide){msgEl.textContent=msg;msgEl.classList.add('on');stage.classList.add('no-gl');if(hide)cvs.hidden=true;}
function init(){
  gl=cvs.getContext('webgl');
  if(!gl){fail('WebGL is unavailable in this browser, so the volume cannot be ray marched.',true);return false;}
  let glErr='';
  function sh(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS)){glErr=(gl.getShaderInfoLog(x)||'shader compile failed').replace(/\0/g,'').trim();console.error(glErr);}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)){const e=(gl.getProgramInfoLog(prog)||'program link failed').replace(/\0/g,'').trim();console.error(e);if(!glErr)glErr=e;}
  // A failed compile otherwise draws nothing at all, with no visible symptom.
  if(glErr){fail('Shader failed to build: '+glErr,true);gl=null;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);
  const a=gl.getAttribLocation(prog,'a');gl.enableVertexAttribArray(a);gl.vertexAttribPointer(a,2,gl.FLOAT,false,0,0);
  U={};UNIFORMS.forEach(n=>{U[n]=gl.getUniformLocation(prog,n);});
  return true;
}
// After a lost context nothing draws again until the page is reloaded (as the message says), even if the browser restores the context
const live=()=>!!gl&&!lost&&!gl.isContextLost();

// Ray marching is fill-rate bound, so the backing store never exceeds one CSS pixel per fragment, and holds about 65,000 pixels
// at most: the browser scales the canvas up to the stage, which suits smoke this soft. Phones render at most 0.75 of the stage
// and take at most 48 steps, so High is 48 there: that is the reduced-quality path this effect needs on mobile.
// The visitor's Detail stays as chosen; the limit is applied when drawing, so it follows the screen both ways.
function steps(){return Math.min(STEPS,PHONE.matches?48:64);}
function layout(force){
  const phone=PHONE.matches,s=Math.min(window.devicePixelRatio||1,phone?.75:1,Math.sqrt(65000/Math.max(1,stage.clientWidth*stage.clientHeight)));
  const w=Math.max(1,Math.round(stage.clientWidth*s)),h=Math.max(1,Math.round(stage.clientHeight*s));
  // Setting the size clears the canvas, so nothing is touched when the canvas would come out the same size and the phone limits are the same
  // (a phone's address bar showing or hiding also fires resize).
  if(!force&&w===W&&h===H&&phone===wasPhone)return false;
  W=cvs.width=w;H=cvs.height=h;wasPhone=phone;
  if(gl)gl.viewport(0,0,W,H);
  return true;
}
// While paused a setting still draws the picture again, so its effect shows without anything moving.
function refresh(){if(paused&&live())draw(curT);}

// The loop keeps exactly one pending frame in raf. The clock and the rise add up the time of each drawn frame (at most 50 ms,
// and a third of it while Slow motion is on); the rise adds the speed as well, so a pause or a new speed never makes the smoke jump.
function render(ts){
  raf=requestAnimationFrame(render);
  if(last===null){last=ts;return;} // the first frame after a start only takes the time
  const dt=ts-last;if(dt<16)return;
  last=ts;
  const step=Math.min(dt,50)/1000/(slowTog.checked?3:1);
  curT+=step;rise+=step*SPD;
  draw(curT);
}
function draw(t){
  gl.useProgram(prog);
  gl.uniform1f(U.uT,t);
  gl.uniform1f(U.uDens,DENS);gl.uniform1f(U.uRise,rise);
  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);
  if(!views){paint(0,0,W,H,0,1,0);return;}
  // One context, a viewport for each picture (given in stage pixels)
  gl.viewport(0,0,W,H);gl.clearColor(BG[0],BG[1],BG[2],1);gl.clear(gl.COLOR_BUFFER_BIT);
  const kx=W/stage.clientWidth,ky=H/stage.clientHeight;
  for(let i=0;i<views.length;i++){
    const v=views[i],h=Math.round(v.h*ky);
    paint(Math.round(v.x*kx),H-Math.round(v.y*ky)-h,Math.round(v.w*kx),h,v.kind,v.sc,v.cy,v.sl);
  }
}
// One picture in a part of the canvas: kind 0 the smoke, 1 the side slice, 2 the flat picture
function paint(x,y,w,h,kind,sc,cy,sl){
  gl.viewport(x,y,w,h);
  gl.uniform2f(U.uOrigin,x,y);gl.uniform2f(U.uRes,w,h);gl.uniform2f(U.uSc,sc,cy);
  gl.uniform1i(U.uView,kind);if(sl)gl.uniform4fv(U.uSl,sl);
  gl.drawArrays(gl.TRIANGLE_STRIP,0,4);
}

// See inside and Compare: the mode on show, the pictures it draws (null in Normal) and what the canvas says it shows
const ov=document.getElementById('ov'),caps={};
document.querySelectorAll('[data-cap]').forEach(c=>{caps[c.dataset.cap]=c;});
const LABELS={normal:cvs.getAttribute('aria-label'),
  inside:'The smoke beside a side view of the cloud, with lines of sight from the eye taking steps through it and an arrow where the light comes from',
  compare:'Two pictures of the smoke side by side: a flat, unlit noise pattern on the left and the soft 3D cloud on the right'};
let mode='normal',views=null;
// The seven lines of sight leave rows of the front view (a share of its height above the middle); the fifth is the gold one.
// Fine grain starts each line's steps a fixed part of a step further in; with it off every line steps alike.
const ROWS=[-.25,-.125,0,.125,.25,.375,.5],GOLD=4,OFFS=[.35,-.3,.1,-.45,.4,-.15,.25];
const LINE_FULL='Its line of sight: a dot at each step',LINE_SHORT='A dot at each step';
let taken=[],marks=[];
// A caption goes at the first spot (a function of its size) that stays inside the stage and clear of the marks and other captions
function put(el,spots){
  el.hidden=false;
  const w=el.offsetWidth,h=el.offsetHeight,cw=stage.clientWidth,ch=stage.clientHeight;
  for(const [x,y] of spots(w,h)){
    if(x<2||y<2||x+w>cw-2||y+h>ch-2)continue;
    if(marks.some(m=>m[0]>x-6&&m[0]<x+w+6&&m[1]>y-6&&m[1]<y+h+6))continue;
    if(taken.some(b=>x<b[2]+4&&x+w>b[0]-4&&y<b[3]+4&&y+h>b[1]-4))continue;
    el.style.left=x+'px';el.style.top=y+'px';taken.push([x,y,x+w,y+h]);return true;
  }
  el.hidden=true;return false;
}
function rebuild(){
  views=null;ov.innerHTML='';taken=[];marks=[];
  for(const k in caps)caps[k].hidden=true;
  if(mode==='normal'||!live())return;
  const cw=stage.clientWidth,ch=stage.clientHeight,g=2,phone=PHONE.matches,svg=[];
  ov.setAttribute('viewBox',`0 0 ${cw} ${ch}`);
  if(mode==='compare'){
    // Each half's name has a band of its own, and its picture starts under it
    const half=Math.floor((cw-g)/2),band=32;
    views=[{x:0,y:band,w:half,h:ch-band,kind:2,sc:1,cy:0},{x:half+g,y:band,w:cw-half-g,h:ch-band,kind:0,sc:1,cy:0}];
    ov.innerHTML=`<path class="div" d="M${half+1} 0V${ch}M0 ${band-1}H${cw}"/>`;
    put(caps.flat,()=>[[8,5]]);put(caps.cloud,()=>[[half+g+8,5]]);
    return;
  }
  // The real smoke at the left (a strip across the top when the box is narrow), the side view beside (under) it
  const stack=cw<480,fw=stack?cw:Math.round(cw*.38),fh=stack?Math.round(ch*.34):ch,m=Math.min(fw,fh);
  const front={x:0,y:0,w:fw,h:fh,kind:0,sc:stack?.7:1,cy:stack?.15:0};
  const side={x:stack?0:fw+g,y:stack?fh+g:0,w:stack?cw:cw-fw-g,h:stack?ch-fh-g:ch,kind:1};
  // The side view keeps both directions in proportion: s pixels to a unit, the eye at z 3 and the column's middle at z 0.
  // It frames the column (y from -.8 to 2.7) and also the far ends of the lowest and highest lines of sight, with room for their last dots.
  const uys=ROWS.map(r=>front.cy+front.sc*r*fh/m),endY=u=>u*3.2/Math.hypot(u,.9);
  const yB=Math.min(-.8,endY(Math.min(...uys))-.18),yTop=Math.max(2.7,endY(Math.max(...uys))+.18),sh=yTop-yB;
  const s=Math.min(side.w/4.05,side.h/sh),zL=3.4+(side.w/s-4.05)/2,yT=yTop+(side.h/s-sh)/2;
  side.sl=[zL,yT-side.h/s,side.w/s,side.h/s];
  views=[front,side];
  svg.push(`<path class="div" d="${stack?`M0 ${fh+1}H${cw}`:`M${fw+1} 0V${ch}`}"/>`);
  const X=z=>side.x+(zL-z)*s,Y=y=>side.y+(yT-y)*s,n=steps(),eye=[X(3),Y(0)];
  ROWS.forEach((r,i)=>{
    const uy=uys[i],len=Math.hypot(uy,.9),at=t=>[X(3-.9*t/len),Y(uy*t/len)],c=i===GOLD?' gold':'';
    svg.push(`<path class="ray${c}" d="M${at(0)}L${at(3.2)}"/>`);
    let d='';
    for(let j=0;j<n;j++){const p=at(.2+(j+(DITHER?OFFS[i]:0))*3/n);d+=`M${p[0].toFixed(1)} ${p[1].toFixed(1)}h0`;}
    svg.push(`<path class="dots${c}" d="${d}"/>`);
    for(let k=0;k<=30;k++)marks.push(at(3.2*k/30));
  });
  ov.style.setProperty('--dot',Math.max(3,Math.min(4,s/28)));
  svg.push(`<circle class="eye" cx="${eye[0]}" cy="${eye[1]}" r="5"/>`);marks.push(eye);
  // The light comes from above, on the eye's side: the arrow points the way it travels
  const A=[X(.3),Y(2.5)],B=[X(-.06),Y(1.78)],L=Math.hypot(B[0]-A[0],B[1]-A[1]),ux=(B[0]-A[0])/L,uy=(B[1]-A[1])/L;
  svg.push(`<path class="arrow" d="M${A}L${B}M${B[0]-ux*9-uy*5},${B[1]-uy*9+ux*5}L${B}L${B[0]-ux*9+uy*5},${B[1]-uy*9-ux*5}"/>`);
  for(let k=0;k<=8;k++)marks.push([A[0]+(B[0]-A[0])*k/8,A[1]+(B[1]-A[1])*k/8]);
  const px=fw/2,py=fh*.25;
  svg.push(`<g class="cross gold"><circle cx="${px}" cy="${py}" r="9"/><path d="M${px-15} ${py}h8M${px+7} ${py}h8M${px} ${py-15}v8M${px} ${py+7}v8"/></g>`);
  marks.push([px,py],[px-15,py],[px+15,py],[px,py-15],[px,py+15]);
  ov.innerHTML=svg.join('');
  put(caps.side,()=>[[side.x+8,side.y+8]]);
  put(caps.eye,w=>[12,18,24,30].map(dy=>[Math.max(6,eye[0]-w/2),eye[1]+dy]));
  put(caps.light,(w,h)=>[[A[0]+12,A[1]-h/2],[A[0]-w-12,A[1]-h/2]]);
  const under=(w,h)=>[[side.x+8,side.y+16+caps.side.offsetHeight],[side.x+side.w-w-8,side.y+8]];
  caps.line.textContent=phone?LINE_SHORT:LINE_FULL;
  if(!put(caps.line,under)&&!phone){caps.line.textContent=LINE_SHORT;put(caps.line,under);}
  if(!phone){
    put(caps.front,()=>[[8,8]]);
    if(put(caps.pixel,(w,h)=>[[fw-w-8,py-h/2]])){
      const x2=parseFloat(caps.pixel.style.left)-2;
      ov.insertAdjacentHTML('beforeend',`<path class="cross gold" d="M${px+11} ${py}H${x2}"/>`);
    }
  }
}

// Play carries on from the clock and the rise where they stopped; it never stacks a second loop.
function start(){if(raf!==null||!live())return;last=null;raf=requestAnimationFrame(render);}
function stop(){if(raf!==null)cancelAnimationFrame(raf);raf=null;}

// Registered at the top level, before the shared script (deferred) can run: under reduced motion it pauses the
// loop on arrival, which this listener must catch. Pause cancels the pending frame and the picture stays.
document.addEventListener('hb:pause',e=>{
  paused=e.detail.paused;
  if(paused)stop();else start();
  words();
});
// Under reduced motion the notes say "Shown still" while the smoke is paused and the markup's own words while it plays
const noteEl={inside:document.querySelector('[data-hb-for="inside"]'),compare:document.querySelector('[data-hb-for="compare"]')};
const NOTE_MOVING={inside:noteEl.inside.textContent,compare:noteEl.compare.textContent};
const NOTE_STILL={inside:"Shown still from the side: each pixel's line of sight takes steps through the cloud (the dots), adding up the smoke it meets. Fine grain staggers the steps, so no stripes form.",
  compare:'Shown still: Flat picture is the same smoke pattern at one depth, flat and unlit; 3D cloud adds up smoke along each line of sight and shades it from the light.'};
function words(){
  const still=matchMedia('(prefers-reduced-motion: reduce)').matches&&paused;
  for(const k in noteEl){const w=(still?NOTE_STILL:NOTE_MOVING)[k];if(noteEl[k].textContent!==w)noteEl[k].textContent=w;}
}

// The mode switch: the pictures it draws are made and drawn at once, also while paused. The canvas's name says what it shows.
document.addEventListener('hb:mode',e=>{
  mode=e.detail.mode;
  cvs.setAttribute('aria-label',LABELS[mode]);
  rebuild();
  if(live())draw(curT);
});

if(init()){
  layout(true);
  draw(curT); // the first picture, so a loop that is paused on arrival never shows an empty stage
  start();
  window.addEventListener('resize',()=>{const c=layout();rebuild();if((c||views)&&live())draw(curT);});
  document.fonts.ready.then(rebuild);
  cvs.addEventListener('webglcontextlost',e=>{e.preventDefault();lost=true;stop();fail('WebGL context lost — reload the page to restart the render.');});
}

function choices(id,pick){
  const buttons=document.querySelectorAll('#'+id+' button');
  buttons.forEach(b=>b.addEventListener('click',()=>{
    buttons.forEach(x=>{x.classList.toggle('on',x===b);x.setAttribute('aria-pressed',String(x===b))});
    pick(b.dataset);
  }));
}
choices('dens-seg',d=>{DENS=+d.dens;refresh();});
choices('speed-seg',d=>{SPD=+d.spd;});
choices('steps-seg',d=>{STEPS=+d.steps;rebuild();refresh();});
choices('smoke-sw',d=>{SMOKE=h2r(d.color);refresh();});
document.getElementById('wind-tog').addEventListener('change',e=>{WIND=e.target.checked;refresh();});
document.getElementById('dither-tog').addEventListener('change',e=>{DITHER=e.target.checked;rebuild();refresh();});
</script>
</body>
</html>