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.

34.8 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>3D Model Orbit — Animation Handbook</title>
  <meta name="description" content="A lit 3D shape spins, or turns to face your pointer. Best for product views.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/3d-model-orbit/">
  <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="3D Model Orbit — Animation Handbook">
  <meta property="og:description" content="A lit 3D shape spins, or turns to face your pointer. Best for product views.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/3d-model-orbit/">
  <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="3D Model Orbit — Animation Handbook">
  <meta name="twitter:description" content="A lit 3D shape spins, or turns to face your pointer. Best for product views.">
  <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": "3D Model Orbit", "name": "3D Model Orbit", "description": "A lit 3D shape spins, or turns to face your pointer. Best for product views.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/3d-model-orbit/", "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, 3D Model Orbit"}</script>
  <style>
    :root{--ui-accent:#3fd6c4;--sun:#ffd35c;--pill:rgba(6,10,16,.92);--ink:#f4f4f2}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{position:relative;background:#060a10;touch-action:pan-y}
    canvas{display:block;width:100%;height:100%}
    .msg{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;text-align:center;padding:24px;font-size:13px;line-height:1.7;color:rgba(255,255,255,.72)}
    /* See inside and Compare: plain words and marks over the picture (the picture itself is drawn on the canvas) */
    .cap,.sunlay{display:none;position:absolute}
    .cap{padding:3px 8px;border-radius:5px;background:var(--pill);color:var(--ink);font:600 13px/1.2 var(--hb-font);white-space:nowrap}
    .sunlay{inset:0;width:100%;height:100%;pointer-events:none}
    .sunlay *{stroke:var(--sun);stroke-width:2;stroke-linecap:round;fill:none}
    .sunlay circle{fill:var(--sun)}
    .sunlay .sline{stroke-width:1.5;stroke-dasharray:3 6}
    .cap.half{top:6px}
    .cap.first{left:10px}
    .cap.second{left:calc(50% + 10px)}
    .stage[data-hb-mode="inside"] .cap.in,.stage[data-hb-mode="inside"] .sunlay{display:block}
    .stage[data-hb-mode="inside"].wired .sunlay,.stage[data-hb-mode="inside"].wired .cap.lit{display:none}
    .stage[data-hb-mode="compare"] .cap.half{display:block}
    .stage[data-hb-mode="compare"].stack .cap.second{left:10px;top:calc(50% + 6px)}
    .stage.no-gl .cap,.stage.no-gl .sunlay{display:none!important}
  </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="../scroll-driven-3d-rotation/" rel="next" aria-label="Next: Scroll-Driven 3D Rotation"><span><span class="hb-dir">Next: </span>Scroll-Driven 3D Rotation</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.01 · 3D &amp; Advanced</p>
    <h1>3D Model Orbit</h1>
    <p class="hb-lede">A lit 3D shape spins, or turns to face your pointer. Best for product views.</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="A lit 3D shape turning on a dark background"></canvas>
      <svg class="sunlay" aria-hidden="true"><line class="sline"/><g class="sung"><circle r="6"/><path d="M0-9v-5M0 9v5M-9 0h-5M9 0h5M-6.4-6.4l-3.5-3.5M6.4 6.4l3.5 3.5M-6.4 6.4l-3.5 3.5M6.4-6.4l3.5-3.5"/></g></svg>
      <span class="cap in lit sunl" aria-hidden="true" data-hb-caption>Light shines from here</span>
      <span class="cap in keya" aria-hidden="true" data-hb-caption>White lines: its flat triangles</span>
      <span class="cap in lit keyb" aria-hidden="true" data-hb-caption>Sides facing the light are brightest</span>
      <span class="cap half first" aria-hidden="true" data-hb-caption>Flat color</span>
      <span class="cap half second" aria-hidden="true" data-hb-caption>Lit</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>Inside, the white lines are the flat triangles the shape is built from. The light shines from the sun mark, so the sides facing it are brightest.</p>
      <p data-hb-for="compare" hidden>Flat color paints every triangle the same, so the shape looks like a flat cutout. Lit shades each side by how it faces the light, so it reads as solid.</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="shape-lbl">Shape</p>
        <div class="seg" id="shape-seg" role="group" aria-labelledby="shape-lbl">
          <button type="button" data-shape="cube" class="on" aria-pressed="true">Cube</button>
          <button type="button" data-shape="sphere" aria-pressed="false">Sphere</button>
          <button type="button" data-shape="torus" aria-pressed="false">Ring</button>
          <button type="button" data-shape="tetra" aria-pressed="false">Pyramid</button>
        </div>
        <p class="hb-hint">The object that is drawn and lit.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="move-lbl">Movement</p>
        <div class="seg" id="move-seg" role="group" aria-labelledby="move-lbl">
          <button type="button" data-mode="orbit" class="on" aria-pressed="true">Spins</button>
          <button type="button" data-mode="mouse" aria-pressed="false">Follows the pointer</button>
        </div>
        <p class="hb-hint">Or it turns to face your pointer or finger.</p>
      </div>
      <div class="hb-setting" id="speed-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-sy="0.5" data-sx="0.12" aria-pressed="false">Slow</button>
          <button type="button" data-sy="0.8" data-sx="0.2" class="on" aria-pressed="true">Normal</button>
          <button type="button" data-sy="1.3" data-sx="0.32" aria-pressed="false">Fast</button>
        </div>
        <p class="hb-hint">How fast it spins.</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" id="tumble-setting">
          <label class="hb-switch-row"><span>Tumbles as it spins</span><input class="hb-switch" type="checkbox" role="switch" id="tumble-tog" checked autocomplete="off"></label>
          <p class="hb-hint">Also rolls it forward, so the top and bottom show.</p>
        </div>
        <div class="hb-setting">
          <p class="hb-setting-name" id="dist-lbl">Distance</p>
          <div class="seg" id="dist-seg" role="group" aria-labelledby="dist-lbl">
            <button type="button" data-dist="2.6" aria-pressed="false">Close</button>
            <button type="button" data-dist="3" class="on" aria-pressed="true">Medium</button>
            <button type="button" data-dist="4.2" aria-pressed="false">Far</button>
          </div>
          <p class="hb-hint">How close the camera is; closer looks bigger.</p>
        </div>
        <div class="hb-setting">
          <p class="hb-setting-name" id="color-lbl">Color</p>
          <div class="swatches" id="color-sw" role="group" aria-labelledby="color-lbl">
            <button type="button" aria-pressed="false" aria-label="Pink" data-color="#ff6f8b" style="background:#ff6f8b"></button>
            <button type="button" aria-pressed="false" aria-label="White" data-color="#f4f4f2" style="background:#f4f4f2"></button>
            <button type="button" class="on" aria-pressed="true" aria-label="Blue" data-color="#58a6ff" style="background:#58a6ff"></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="Green" data-color="#56d364" style="background:#56d364"></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 object.</p>
        </div>
        <div class="hb-setting">
          <label class="hb-switch-row"><span>Edges only</span><input class="hb-switch" type="checkbox" role="switch" id="wire-tog" autocomplete="off"></label>
          <p class="hb-hint">Draws the triangles' edges instead of a lit surface.</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 a spinning 3D object to [the product or shape you want to show]. Draw it with WebGL: store the shape as triangles and light every point with a soft base light, a direct light and a shiny highlight, so it reads as solid. Turn it around its own axis so every side comes into view, or let it turn to face the pointer, which a tap or a sideways drag should also do on touch screens. Change its size by moving the camera closer or further, not by changing the lens. If the visitor has reduced motion turned on, show the object 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>Product showcases</li><li>Hero sections</li><li>Logos</li><li>3D previews</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Long reading pages</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>
// ─── 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 float uDim; // 1 as the page draws it; See inside dims the solid
uniform bool uWire;
void main(){
  if(uWire){gl_FragColor=vec4(uCol,1.);return;}
  vec3 L=normalize(uLight-vP),V=normalize(-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.))*uDim,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 slowTog=document.getElementById('slow-tog');
let W,H,gl,prog,posBuf,nrmBuf,idxBuf,lineBuf,idxCount,lineCount;
const TILT=.3; // the forward tilt it starts with, and returns to when the shape changes: at 0 a ring is seen edge-on
let raf=null,paused=false,last=null,clock=0,rx=TILT,ry=0;
let MODE='orbit',SHAPE='cube',WIRE=false,DIST=3,SX=.2,SY=.8,COLOR=[88/255,166/255,255/255];
let rollSpeed=.2,tumbles=true;
let mouseNX=0,mouseNY=0;
// See inside and Compare: what the box shows, the angles it draws, and where the pointer is
const FOV=Math.PI/4,LIGHT=[2,3,4],CLEAR=[.024,.039,.063,1];
const POSE_SPIN=[.5,.6],PARK=[.5,-.7]; // the angles the views rest at until the loop or the pointer takes over
let VIEW='normal',ax=TILT,ay=0,cRx=TILT,cRy=0,spun=0,driven=false,ptrSeen=false,ptrX=0,ptrY=0,BOUND=1;

// A failed shader is otherwise a silent black canvas — say so instead.
function fail(msg){gl=null;if(raf){cancelAnimationFrame(raf);raf=null;}
  cvs.style.display='none';stage.classList.add('no-gl');
  const d=document.createElement('div');d.className='msg';d.textContent=msg;stage.appendChild(d);}
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 null;}
  return x;
}
function init(){
  gl=cvs.getContext('webgl');
  if(!gl){fail('WebGL is unavailable in this browser, so there is nothing to render.');return;}
  const vs=sh(gl.VERTEX_SHADER,VS),fs=sh(gl.FRAGMENT_SHADER,FS);
  if(!vs||!fs){fail('Shader compilation failed — the log is in the browser console.');return;}
  prog=gl.createProgram();
  gl.attachShader(prog,vs);gl.attachShader(prog,fs);
  gl.linkProgram(prog);
  if(!gl.getProgramParameter(prog,gl.LINK_STATUS)){console.error(gl.getProgramInfoLog(prog));fail('Shader program failed to link — the log is in the browser console.');return;}
  gl.useProgram(prog);
  gl.enable(gl.DEPTH_TEST);gl.clearColor(...CLEAR);
  posBuf=gl.createBuffer();nrmBuf=gl.createBuffer();idxBuf=gl.createBuffer();lineBuf=gl.createBuffer();
  loadGeometry('cube');
}

function loadGeometry(name){
  const geo={cube:makeCube,sphere:makeSphere,torus:makeTorus,tetra:makeTetra}[name]();
  // Wireframe edges: each triangle (a,b,c) becomes three line segments
  const lines=[];
  for(let i=0;i<geo.idx.length;i+=3){const a=geo.idx[i],b=geo.idx[i+1],c=geo.idx[i+2];lines.push(a,b,b,c,c,a);}
  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);
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,lineBuf);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,new Uint16Array(lines),gl.STATIC_DRAW);
  idxCount=geo.idx.length;lineCount=lines.length;
  BOUND=0;for(let i=0;i<geo.pos.length;i+=3)BOUND=Math.max(BOUND,Math.hypot(geo.pos[i],geo.pos[i+1],geo.pos[i+2]));
}

// Backing store in device pixels (capped at 2x) so the render is not upscaled on retina.
function resize(){
  const d=Math.min(window.devicePixelRatio||1,2);
  W=cvs.width=Math.round(stage.clientWidth*d);H=cvs.height=Math.round(stage.clientHeight*d);
  if(gl)gl.viewport(0,0,W,H);
  if(VIEW!=='normal')refreshViews();
}

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);
}
const ul={};
function u(n){return ul[n]||(ul[n]=gl.getUniformLocation(prog,n));}

function edges(){gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,lineBuf);gl.drawElements(gl.LINES,lineCount,gl.UNSIGNED_SHORT,0);}
// One shape in a part of the canvas (x, y, w, h in canvas pixels, y from the bottom), turned by a and b. Kind 'lit' is the page as it
// is; 'flat' paints every triangle one color; 'inside' dims the lit solid and draws the triangles' edges in white over it.
function shape(x,y,w,h,a,b,kind){
  gl.viewport(x,y,w,h);
  const M=mul(mul(trans(0,0,-DIST),rotY(b)),rotX(a));
  gl.uniformMatrix4fv(u('uMVP'),false,mul(persp(FOV,w/h,.1,20),M));
  gl.uniformMatrix4fv(u('uM'),false,M);
  gl.uniform3fv(u('uCol'),COLOR);
  gl.uniform3fv(u('uLight'),LIGHT);
  gl.uniform1f(u('uDim'),kind==='inside'&&!WIRE?.66:1);
  gl.uniform1i(u('uWire'),WIRE||kind==='flat'?1:0);
  if(WIRE){edges();return;}
  // the solid is pushed back a little in See inside, so only the edges in front of it show
  if(kind==='inside'){gl.enable(gl.POLYGON_OFFSET_FILL);gl.polygonOffset(1,1);}
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,idxBuf);gl.drawElements(gl.TRIANGLES,idxCount,gl.UNSIGNED_SHORT,0);
  if(kind!=='inside')return;
  gl.disable(gl.POLYGON_OFFSET_FILL);
  gl.uniform1i(u('uWire'),1);gl.uniform3f(u('uCol'),1,1,1);
  // a line is one canvas pixel wide: on a sharp screen (two pixels to a CSS pixel) it is drawn again one pixel over, so it stays a CSS pixel wide
  const n=W/stage.clientWidth>=1.5?1:0;
  for(let i=0;i<=n;i++)for(let j=0;j<=n;j++){gl.viewport(x+i,y+j,w,h);edges();}
}
// The angles the views draw: the page's own while the loop runs or after it has turned for a while (spun counts the page's own time
// it has turned, so a frame or two before a pause on arrival still counts as not yet turned), or once the pointer has moved the
// shape; before that a posed angle, so three sides show
function pickAngles(){
  if(VIEW==='compare'&&MODE==='mouse'&&driven){ax=cRx;ay=cRy;}
  else if(MODE==='orbit'?!paused||spun>400:driven){ax=rx;ay=ry;}
  else{const p=MODE==='orbit'?POSE_SPIN:PARK;ax=p[0];ay=p[1];}
}

function draw(){
  gl.disable(gl.SCISSOR_TEST);
  if(VIEW==='compare'){
    gl.viewport(0,0,W,H);gl.clearColor(.2,.25,.32,1);gl.clear(gl.COLOR_BUFFER_BIT); // the thin divider between the halves
    gl.clearColor(...CLEAR);
  }else{gl.viewport(0,0,W,H);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);}
  gl.useProgram(prog);
  setAttr('aPos',posBuf,3);setAttr('aNorm',nrmBuf,3);
  if(VIEW==='normal'){shape(0,0,W,H,rx,ry,'lit');return;}
  pickAngles();
  if(VIEW==='inside'){shape(0,0,W,H,ax,ay,'inside');return;}
  gl.enable(gl.SCISSOR_TEST);
  for(let k=0;k<2;k++){
    const h=DEVH[k],c=DEVS[k];
    gl.scissor(h[0],h[1],h[2],h[3]);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);
    shape(c[0],c[1],c[2],c[3],ax,ay,k?'lit':'flat');
  }
  gl.disable(gl.SCISSOR_TEST);
}

// One step is 1/60 s: the shape turns SY x 0.01 radians in that time, whatever the screen's refresh rate.
const FRAME=1000/60;
// The loop keeps exactly one pending frame in raf. Each drawn frame turns the shape by the time since the last drawn one
// (a gap counts for at most 50 ms), counted in steps of 1/60 s, and by a third of that while Slow motion is on. The page's own
// clock adds up the same time, so the roll's speed wave slows down with the spin and the forward roll carries on smoothly
// after a pause instead of jumping. At most one picture is drawn per 16 ms. A tab that comes back to the front starts again
// from its next frame, so the time away adds no step.
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;
  const s=Math.min(dt,50)/FRAME*(slowTog.checked?1/3:1);
  last=ts;clock+=s*FRAME;
  if(MODE==='orbit'){
    ry+=SY*.01*s;rx+=SX*.01*s*(Math.sin(clock*.0003)*.5+.5);spun+=s*FRAME;
  }else{rx=mouseNY*1.2;ry=mouseNX*1.5;driven=ptrSeen;if(VIEW==='compare'&&ptrSeen)cmpAim();}
  draw();
}
function start(){if(raf||!gl)return;last=null;raf=requestAnimationFrame(render);}
document.addEventListener('visibilitychange',()=>{last=null;});
// While paused a setting or a resize draws the picture again, so the change shows without anything moving.
function redraw(){if(gl&&paused)draw();}

// 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;
// Play calls start(), which carries on from the current angles.
document.addEventListener('hb:pause',e=>{
  paused=e.detail.paused;
  if(paused){cancelAnimationFrame(raf);raf=null;}
  else start();
});

// ─── See inside and Compare ────────────────────────────────────────────────
const NAME_H=34,SUN_Y=20,SUN_R=14; // the strip that holds a Compare half's name; the sun mark's height and size
const q=sel=>stage.querySelector(sel),noteEl={},NOTE0={};
const sunG=q('.sung'),sunLine=q('.sline'),sunLbl=q('.sunl'),keyA=q('.keya'),keyB=q('.keyb');
document.querySelectorAll('[data-hb-for]').forEach(p=>{noteEl[p.dataset.hbFor]=p;NOTE0[p.dataset.hbFor]=p.textContent;});
const EDGE_NOTE={inside:'Inside, the lines are the flat triangles the shape is built from. Edges only is on, so you see all of them, front and back, with no light.',
  compare:'Edges only is on, so Flat color and Lit both draw bare edges with no light. Turn it off in Try it to see them differ.'};
const NAMES={normal:cvs.getAttribute('aria-label'),
  inside:'The shape dimmed, with white lines along the flat triangles it is built from and a sun mark where the light comes from',
  compare:'The same shape twice: painted one flat color, and lit so each side has its own shade',
  insideEdges:"The shape's edges only: every flat triangle it is built from, front and back",
  compareEdges:"The same shape's edges twice; with Edges only on, both look alike"};
let side=true,CX=0,CY=0,KEEP=0,KEEPY=1e9;
const SCENE=[[0,0,0,0],[0,0,0,0]],DEVH=[[0,0,0,0],[0,0,0,0]],DEVS=[[0,0,0,0],[0,0,0,0]];

// Compare: side by side while each half is about as wide as the box is tall, else one above the other. Each half keeps its name in a
// strip at the top and the shape below it. SCENE holds the shapes' rects in CSS pixels; DEVH and DEVS the halves' and shapes' rects
// in canvas pixels from the bottom left.
function dev(x,y,w,h){const fx=W/stage.clientWidth,fy=H/stage.clientHeight;return[Math.round(x*fx),Math.round(H-(y+h)*fy),Math.round(w*fx),Math.round(h*fy)];}
function layoutViews(){
  const cw=stage.clientWidth,ch=stage.clientHeight;
  side=cw/2>=.9*ch;stage.classList.toggle('stack',!side);
  for(let k=0;k<2;k++){
    const x=side?k*(cw/2+1):0,y=side?0:k*(ch/2+1),w=side?cw/2-1:cw,h=side?ch:ch/2-1;
    SCENE[k]=[x,y+NAME_H,w,h-NAME_H];DEVH[k]=dev(x,y,w,h);DEVS[k]=dev(x,y+NAME_H,w,h-NAME_H);
  }
}
// The pointer is read inside the half it is over, so pointing at either shape turns both alike
function cmpAim(){
  const k=(side?ptrX>=SCENE[1][0]:ptrY>=SCENE[1][1]-NAME_H)?1:0,c=SCENE[k];
  cRy=Math.max(-1,Math.min(1,(ptrX-c[0])/c[2]*2-1))*1.5;cRx=Math.max(-1,Math.min(1,(ptrY-c[1])/c[3]*2-1))*1.2;
}
// A caption goes at the first of its places where the shape never passes under it: outside the circle the shape turns inside, or,
// for the cube (whose corners never rise or sink as far as that circle), far enough above or below the middle. With none free it is left out.
function place(el,spots){
  el.style.display='';
  const w=el.offsetWidth,h=el.offsetHeight;
  for(const f of spots){
    const [x,y]=f(w,h),nx=Math.max(x,Math.min(CX,x+w)),ny=Math.max(y,Math.min(CY,y+h));
    if(x<8||x+w>2*CX-8||Math.hypot(nx-CX,ny-CY)<KEEP&&Math.max(y-CY,CY-y-h)<KEEPY)continue;
    el.style.left=x+'px';el.style.top=y+'px';return;
  }
  el.style.display='none';
}
// See inside: the sun mark sits where the light really comes from (its slant on the screen: up and to the right), near the top edge,
// and the dashed line runs from it to the shape's outer reach, which grows and shrinks with Distance and the shape.
function layoutInside(){
  const cw=stage.clientWidth,ch=stage.clientHeight,L=Math.hypot(LIGHT[0],LIGHT[1]),c=LIGHT[0]/L,sn=LIGHT[1]/L;
  CX=cw/2;CY=ch/2;
  const f=CY/Math.tan(FOV/2),R=f*BOUND/Math.sqrt(DIST*DIST-BOUND*BOUND),t=(CY-SUN_Y)/sn,sx=CX+t*c,g=SUN_R+4,e=BOUND/Math.sqrt(3);
  KEEP=R+2; // captions keep out of the circle the shape turns inside
  KEEPY=SHAPE==='cube'?f*e*Math.SQRT2/(DIST-e)+2:1e9; // a cube corner rises highest when two of its sides lean 45 degrees
  sunG.setAttribute('transform','translate('+sx+' '+SUN_Y+')');
  sunLine.setAttribute('x1',sx-g*c);sunLine.setAttribute('y1',SUN_Y+g*sn);
  sunLine.setAttribute('x2',CX+R*c);sunLine.setAttribute('y2',CY-R*sn);
  sunLine.style.display=t-R-g>10?'':'none';
  place(sunLbl,[(w,h)=>[sx-SUN_R-6-w,SUN_Y-h/2],(w,h)=>[sx+SUN_R+6,SUN_Y-h/2],(w,h)=>[cw-10-w,SUN_Y+SUN_R+6]]);
  place(keyA,[(w,h)=>[10,ch-10-h]]);
  place(keyB,[(w,h)=>[10,ch-16-h-keyA.offsetHeight]]);
}
// Runs in a mode, and on a resize or a setting while one shows: the canvas's name, the notes' words, the places of the marks
function refreshViews(){
  cvs.setAttribute('aria-label',NAMES[VIEW==='normal'?'normal':VIEW+(WIRE?'Edges':'')]);
  if(VIEW==='normal')return;
  stage.classList.toggle('wired',WIRE);
  for(const k in noteEl){const t=WIRE?EDGE_NOTE[k]:NOTE0[k];if(noteEl[k].textContent!==t)noteEl[k].textContent=t;}
  const a=WIRE?'Lines: its flat triangles':'White lines: its flat triangles';
  if(keyA.textContent!==a)keyA.textContent=a;
  layoutViews();
  if(VIEW==='compare'&&MODE==='mouse'&&driven)cmpAim();
  if(VIEW==='inside')layoutInside();
}
// Registered at the top level, like the pause listener: the view is drawn at once, and the loop carries on as it was
document.addEventListener('hb:mode',e=>{VIEW=e.detail.mode;refreshViews();if(gl)draw();});
document.fonts.ready.then(()=>{if(VIEW==='inside')layoutInside();});

init();resize();
if(gl){draw();start();}

// The pointer is recorded even while paused; it turns the shape only when a frame is drawn.
function aim(e){
  const r=cvs.getBoundingClientRect();mouseNX=(e.clientX-r.left)/r.width*2-1;mouseNY=(e.clientY-r.top)/r.height*2-1;
  ptrX=e.clientX-r.left;ptrY=e.clientY-r.top;ptrSeen=true;
}
stage.addEventListener('pointermove',aim);
stage.addEventListener('pointerdown',aim);
window.addEventListener('resize',()=>{resize();redraw();});

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);
  }));
}
const speedSetting=document.getElementById('speed-setting'),tumbleSetting=document.getElementById('tumble-setting');
function setRoll(){SX=tumbles?rollSpeed:0;}
choices('shape-seg',d=>{if(!gl||d.shape===SHAPE)return;SHAPE=d.shape;loadGeometry(SHAPE);rx=TILT;ry=0;if(paused){spun=0;driven=false;}refreshViews();redraw();});
// Speed and Tumbles only matter while it spins
choices('move-seg',d=>{MODE=d.mode;speedSetting.hidden=tumbleSetting.hidden=MODE!=='orbit';if(VIEW!=='normal'){refreshViews();redraw();}});
choices('speed-seg',d=>{SY=+d.sy;rollSpeed=+d.sx;setRoll();});
document.getElementById('tumble-tog').addEventListener('change',e=>{tumbles=e.target.checked;setRoll();});
choices('dist-seg',d=>{DIST=+d.dist;refreshViews();redraw();});
choices('color-sw',d=>{
  const h=d.color;
  COLOR=[parseInt(h.slice(1,3),16)/255,parseInt(h.slice(3,5),16)/255,parseInt(h.slice(5,7),16)/255];
  redraw();
});
document.getElementById('wire-tog').addEventListener('change',e=>{WIRE=e.target.checked;refreshViews();redraw();});
</script>
</body>
</html>