GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / kuiper-belt / learn-the-kuiper/202610050609

Play and 2 more files (part 3)

A JavaScript module in the learn the kuiper folder of Kuiper Belt that adds rat (`addRat`), steps dec (`stepDec`), snaps to (`snapTo`) and calculates planar distances and angles (units: kV).

683 lines of JavaScript and HTML from kuiper-belt, in 3 files. Topic: Kuiper, cosmos and drawing engines. Section 1539 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Play render · kuiper-belt / learn-the-kuiper/202610050609/play.js lines 1315–1722
  2. Solid render · kuiper-belt / learn-the-kuiper/202610050609/solid.html lines 1–27
  3. Solid render · kuiper-belt / learn-the-kuiper/202610050609/solid.js lines 1–248

Play

A JavaScript module in the learn the kuiper folder of Kuiper Belt that adds rat (`addRat`), steps dec (`stepDec`), snaps to (`snapTo`) and calculates planar distances and angles (units: kV).

renderkuiper-belt / learn-the-kuiper/202610050609/play.js · lines 1315–1722 of 1722 · version 2026-10-05 06:09 (continued from section 1537) · Entry point · pattern exportState (shared by 2 files)

What it does
It draws wind. Defines 156 functions or classes, including divmod, ratio, addRat, mulRat, ratText. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: wind.
Inputs & outputs
Out: canvas drawing; SVG drawing.
Downstream impact
Used directly by 1 file: Play (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/play.html). Reached from 3 other entry points, including Lesson (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/lesson.html); Menu (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050354/menu.html); Solid (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/solid.html).
What it achieves
It adds rat (`addRat`), parses one (`parseOne`) and opens editor (`openEditor`). `play.js` LEARN THE KUIPER: place a dot with numbers. It responds to click, pointerdown and pointerup events.
Why it matters
Loaded by the page of the same name at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/play.html.
Application
kuiper-belt · learn-the-kuiper/202610050609 · JavaScript module
Uses
none found
Used by
loaded by Play (script src)
Produces
divmod, ratio, addRat, mulRat, ratText, exact, mod, circles, clean, r9, parseOne, parse
Defines here
queueRoll, findTick, facts, closedRing, tick, positions, lab, text, arcPoly, rimSteps, draw, drawGrid, tgPath, drawTarget, drawBuild, drawDots, drawProbe, drawNova, drawHud, scaleMark, starShape, stars
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 learn-the-kuiper/202610050609/play.js:1315-1722 · blob e238ce0b975aa329e9d9faa4a5413541775d5a8d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
    if (!nv.gentle) { f.lastFlash = now; f.flashTimes.push(now); if (f.flashTimes.length > 12) f.flashTimes.shift(); }
    for (i = 0; i < 96; i++) { var a = s.rand() * TAU, v = (0.35 + s.rand() * 0.9) * nv.scale; P[4 * i] = Math.cos(a) * v; P[4 * i + 1] = Math.sin(a) * v; P[4 * i + 2] = 0.5 + s.rand() * 0.5; P[4 * i + 3] = s.rand(); }
    var b = nv.scale > 1.4 ? 5 : nv.scale > 1.1 ? 4 : 3; for (i = 0; i < b; i++) tone(262 * Math.pow(2, [0, 4, 7, 12, 16][i] / 12), 0.1, 0.9, i * 0.1);
    f.nextAt = now + 1700; f.evalAt = 0;
    need();
  }
  function queueRoll() { if(S) { S.find.quietAt=nowMs()+220; need(); } }
  function findTick(now) {
    var s = S, f = s.find, tg = f.target; if (!f.on) return false;
    if (f.nova.on && now - f.nova.t0 > 1700) { f.nova.on = false; newTarget(true); refresh(); return true; }
    if (!tg) return false;
    if(f.quietAt && now>=f.quietAt && !busy()) { f.quietAt=0; if(!tg.found && inCell(false)>=0 && f.lastHow==='explore') { tg.found=true; s.p.score+=1; s.p.found.push(PT.x,PT.y); if(s.p.found.length>160)s.p.found.splice(0,2); newTarget(true); refresh(); return true; } }
    var i, n = s.nDraw, xy = s.xy, best = -1, bw = -1, w;
    for (i = 0; i < n; i++) { w = warm(s.T, tg, xy[2 * i], xy[2 * i + 1]); if (w > bw) { bw = w; best = i; } }
    f.heat = bw < 0 ? 0 : bw; f.hot = best; f.inside = best >= 0 && M.insideAt(tg, xy[2 * best], xy[2 * best + 1]);
    if (f.evalAt && now >= f.evalAt && !busy() && !f.nova.on) { f.evalAt = 0; judge(now); }
    return true;
  }
  // small things to come across, each one a fact of the rule: typed values earn them
  function facts() {
    var s = S, p = s.p, k = p.facts, r = p.rung, got = '';
    if (!s.factsDue || busy()) return; s.factsDue = false;
    if (s.find.lastHow !== 'type') return;
    if (!k.wind && Math.abs(circles(p.start, p.mod)) >= 1) got = 'wind';
    if (r >= 3) {
      var n = M.count(p);
      if (!k.spokes && closedRing(p)) got = 'spokes';
      else if (!k.real && n >= 30 && p.turn === 2654435769 && p.mod === 4294967296) got = 'real';   // the exact whole-number rule, never a rounded turn
    }
    if (!got) return;
    k[got] = 1; s.cele.t0 = nowMs(); s.cele.kind = got; phrase(4, 392, 0.09); need();
  }
  // a ring closes when STEP is 0 and HOW MANY x TURN is a whole number of circles
  function closedRing(a) { var n = M.count(a); return a.rung >= 3 && n >= 2 && a.step === 0 && mod(a.turn, a.mod) !== 0 && exact({rung:2,start:0,turn:a.turn,mod:a.mod},n).m === '0'; }

  // ------------------------------------------------------------------ one frame
  function tick(now) {
    var s = S; if (!s) return; s.raf = 0;
    var dt = Math.min(0.1, Math.max(0, (now - s.last) / 1000)), p = s.p, a = s.a, anim = false, landed = false, i, id, w, k;
    s.last = now;
    if (s.needLayout && !s.drag) { s.needLayout = false; layout(); }
    if (s.pips && (now - (s.kChk || 0) > 800)) { s.kChk = now; s.pips.kuiper(!!(root.KGLesson && typeof root.KGLesson.open === 'function')); }
    for (i = 0; i < IDS.length; i++) {
      id = IDS[i]; w = s.tw[id]; if (!w.on) continue;
      k = (now - w.t0) / w.dur;
      if (k >= 1) { a[id] = w.to; w.on = false; landed = true; } else { k = 1 - Math.pow(1 - k, 3); a[id] = w.from + (w.to - w.from) * k; }
      anim = true;
    }
    if (s.ptw.on) { k = (now - s.ptw.t0) / s.ptw.dur; if (k >= 1) { s.ptw.on = false; landed = true; } anim = true; }
    if (landed && !busy()) landNote();
    if (s.factsDue) facts();
    if (s.playing) {
      p.t += dt; if (p.t > LIMIT) { p.t = LIMIT; setPlaying(false); s.F.limit(); }
      a.t = p.t; s.F.setValue('t', p.t); var ex=exact(p,selN()); s.F.setText('ang',ex.m); s.F.workingEl.textContent=ex.raw+' = '+ex.q+' × '+p.mod+' + '+ex.m; s.F.setText('dis', fmt(M.dist(p, selN()), 4));
      drawTape(); fit(false); camTarget(); anim = true;
    }
    k = 1 - Math.exp(-dt / 0.09);
    if (Math.abs(s.cxT - s.cx) + Math.abs(s.cyT - s.cy) + Math.abs(s.RT - s.R) > 0.3) { s.cx += (s.cxT - s.cx) * k; s.cy += (s.cyT - s.cy) * k; s.R += (s.RT - s.R) * k; camTarget(); anim = true; }
    else if (s.cx !== s.cxT || s.cy !== s.cyT || s.R !== s.RT) { s.cx = s.cxT; s.cy = s.cyT; s.R = s.RT; camTarget(); anim = true; }
    var c = s.cam, ct = s.camT, lz = Math.log(c.z), lt = Math.log(ct.z), kc = 1 - Math.exp(-dt / 0.12);
    if (Math.abs(lt - lz) > 0.002 || (Math.abs(ct.x - c.x) + Math.abs(ct.y - c.y)) * c.z > 0.3) { c.z = Math.exp(lz + (lt - lz) * kc); c.x += (ct.x - c.x) * kc; c.y += (ct.y - c.y) * kc; anim = true; }
    else if (c.z !== ct.z || c.x !== ct.x || c.y !== ct.y) { c.z = ct.z; c.x = ct.x; c.y = ct.y; anim = true; }
    var j = s.joy, pr = s.probe;
    if (j.on) {
      var kj = 1 - Math.exp(-dt * 8); pr.vx += (j.x * 300 - pr.vx) * kj; pr.vy += (j.y * 300 - pr.vy) * kj;
      if (Math.abs(pr.vx) + Math.abs(pr.vy) > 0.5) {
        var sx = Math.min(s.box.r - 6, Math.max(s.box.l + 6, X(pr.x) + pr.vx * dt)), sy = Math.min(s.box.b - 6, Math.max(s.box.t + 6, Y(pr.y) + pr.vy * dt));
        pr.x = WX(sx); pr.y = WY(sy); pr.on = true; emitProbe(); anim = true;
      }
    }
    positions();
    if (findTick(now)) anim = true;
    if (now - s.cele.t0 < 1400 || now - s.stackPulse < 500) anim = true;
    if (s.dirty || anim) { s.dirty = false; draw(now); }
    if (anim || s.dirty) need();
  }
  function positions() {
    var s = S, a = s.a, r = a.rung, n = M.count(a), nd = n > CAP ? CAP : n, xy = s.xy, i, N, w = s.ptw;
    for (i = 0; i < nd; i++) { N = n > CAP ? Math.floor(i * n / CAP) : i; M.place(a, N, PT); xy[2 * i] = PT.x; xy[2 * i + 1] = PT.y; }
    if (r === 1 && w.on) { var k = (nowMs() - w.t0) / w.dur; k = k >= 1 ? 1 : 1 - Math.pow(1 - k, 3); xy[0] = w.x0 + (w.x1 - w.x0) * k; xy[1] = w.y0 + (w.y1 - w.y0) * k; }
    s.nAnim = n; s.nDraw = nd; s.ghost = r >= 3 && n <= CAP;
    if (s.ghost) { M.place(a, n, PT); xy[2 * nd] = PT.x; xy[2 * nd + 1] = PT.y; }
  }

  // ------------------------------------------------------------------ drawing
  function lab(v, dec) {
    var s = S, m = s.labels[dec] || (s.labels[dec] = new Map()), t = m.get(v);
    if (t === undefined) { if (m.size > 400) m.clear(); t = fmt(v, dec); m.set(v, t); }
    return t;
  }
  function text(ctx, t, x, y, color, align) { ctx.textAlign = align || 'center'; ctx.lineWidth = 5; ctx.strokeStyle = 'rgba(0,0,0,.9)'; ctx.strokeText(t, x, y); ctx.fillStyle = 'rgba(255,255,255,.8)'; ctx.fillText(t, x, y); }
  function arcPoly(ctx, ox, oy, rp, t0, t1, cont) {
    var i, n = 28, t;
    for (i = 0; i <= n; i++) { t = t0 + (t1 - t0) * i / n; if (i === 0 && !cont) ctx.moveTo(ox + rp * Math.cos(t), oy - rp * Math.sin(t)); else ctx.lineTo(ox + rp * Math.cos(t), oy - rp * Math.sin(t)); }
  }
  function rimSteps() {
    var s = S, C = s.p.mod, key = C + ':' + Math.round(s.R); if (key === s.rimKey) return;
    s.rimKey = key;
    var st = C / 12; if (Math.abs(st - Math.round(st)) > 1e-9) st = niceUp(C / 12);
    var wmax = 14.5 * fmt(C, 4).length + 12, g = 0;
    while (TAU * (s.R - 26) * st / C < wmax && g++ < 8) st *= 2;
    var mn = 0; if (Math.abs(st - Math.round(st)) < 1e-9) { var q = Math.round(st); mn = q % 3 === 0 ? q / 3 : q % 5 === 0 ? q / 5 : q % 2 === 0 ? q / 2 : 0; }
    if (mn && (C / mn > 150 || TAU * s.R * mn / C < 7)) mn = 0;
    s.rimStep = st; s.rimMinor = mn; s.rimDec = stepDec(st);
  }
  function draw(now) {
    var s = S, ctx = s.ctx, dpr = s.dpr, b = s.box;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, s.W, s.H);
    ctx.save(); ctx.beginPath(); ctx.rect(b.l, b.t, b.r - b.l, b.b - b.t); ctx.clip();
    ctx.font = '400 24px ' + FONT; ctx.textBaseline = 'middle'; ctx.lineJoin = 'round'; ctx.lineCap = 'round';
    drawGrid(ctx);
    if(s.ringFlash && now-s.ringFlash.t<800) { ctx.strokeStyle='rgba(0,255,255,'+(1-(now-s.ringFlash.t)/800)+')'; ctx.lineWidth=3; ctx.beginPath(); ctx.arc(X(0),Y(0),s.ringFlash.d*s.cam.z,0,TAU); ctx.stroke(); }
    drawTarget(ctx, now);
    drawBuild(ctx, now);
    drawDots(ctx, now);
    drawProbe(ctx);
    drawNova(ctx, now);
    drawHud(ctx, now);
    ctx.restore();
  }
  function drawGrid(ctx) {
    var s = S, b = s.box, z = s.cam.z, p = s.p, C = p.mod, ox = X(0), oy = Y(0), xyMode = p.rung === 1 && p.xy, i, k, t;
    var centred = Math.abs(s.cam.x) * z < 0.75 && Math.abs(s.cam.y) * z < 0.75;
    var bx = (b.l + b.r) / 2, by = (b.t + b.b) / 2, hw = (b.r - b.l) / 2, hh = (b.b - b.t) / 2, hm = Math.min(hw, hh);
    var fx = Math.max(Math.abs(ox - b.l), Math.abs(ox - b.r)), fy = Math.max(Math.abs(oy - b.t), Math.abs(oy - b.b)), rmax = Math.sqrt(fx * fx + fy * fy);
    var nx = ox < b.l ? b.l - ox : ox > b.r ? ox - b.r : 0, ny = oy < b.t ? b.t - oy : oy > b.b ? oy - b.b : 0, rmin = Math.sqrt(nx * nx + ny * ny), inside = rmin === 0;
    var dr = niceUp(58 / z), drp = dr * z, dec = stepDec(dr), i0 = Math.max(1, Math.ceil(rmin / drp - 1e-9)), i1 = Math.floor(rmax / drp + 1e-9);
    if (i1 - i0 > 70) i1 = i0 + 70;
    s.dr = dr; s.drp = drp; s.centred = centred;
    var thc = 0, th0 = 0, th1 = TAU;
    if (!inside) {
      thc = Math.atan2(oy - by, bx - ox); var lo = 0, hi = 0, cxs = [b.l, b.r, b.r, b.l], cys = [b.t, b.t, b.b, b.b];
      for (i = 0; i < 4; i++) { t = Math.atan2(oy - cys[i], cxs[i] - ox) - thc; if (t > Math.PI) t -= TAU; else if (t < -Math.PI) t += TAU; if (t < lo) lo = t; if (t > hi) hi = t; }
      th0 = thc + lo; th1 = thc + hi;
    }
    // distance rings at round numbers
    ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(102,204,255,' + (xyMode ? '.1' : '.2') + ')';
    for (i = i0; i <= i1; i++) { ctx.beginPath(); if (inside) ctx.arc(ox, oy, i * drp, 0, TAU); else arcPoly(ctx, ox, oy, i * drp, th0, th1); ctx.globalAlpha = centred && i * drp > s.R + 2 ? 0.45 : 1; ctx.stroke(); }
    ctx.globalAlpha = 1;
    var every = Math.max(1, Math.ceil((14.5 * lab(i1 * dr, dec).length + 14) / drp));
    if (xyMode) {
      // the X, Y grid: lines at the same round numbers, numbered along the two axes
      var kx0 = Math.ceil((b.l - ox) / drp), kx1 = Math.floor((b.r - ox) / drp), ky0 = Math.ceil((oy - b.b) / drp), ky1 = Math.floor((oy - b.t) / drp);
      if (kx1 - kx0 > 80) kx1 = kx0 + 80; if (ky1 - ky0 > 80) ky1 = ky0 + 80;
      ctx.strokeStyle = 'rgba(102,204,255,.2)'; ctx.beginPath();
      for (k = kx0; k <= kx1; k++) { ctx.moveTo(ox + k * drp, b.t); ctx.lineTo(ox + k * drp, b.b); }
      for (k = ky0; k <= ky1; k++) { ctx.moveTo(b.l, oy - k * drp); ctx.lineTo(b.r, oy - k * drp); }
      ctx.stroke();
      ctx.strokeStyle = 'rgba(0,255,255,.45)'; ctx.beginPath(); ctx.moveTo(b.l, oy); ctx.lineTo(b.r, oy); ctx.moveTo(ox, b.t); ctx.lineTo(ox, b.b); ctx.stroke();
      var ly = Math.min(b.b - 16, Math.max(b.t + 16, oy + 18)), lx = Math.min(b.r - 8, Math.max(b.l + 46, ox - 10));
      for (k = kx0; k <= kx1; k++) if (k !== 0 && k % every === 0) text(ctx, lab(k * dr, dec), ox + k * drp, ly, 'rgba(255,255,255,.55)');
      for (k = ky0; k <= ky1; k++) if (k !== 0 && k % every === 0) text(ctx, lab(k * dr, dec), lx, oy - k * drp, 'rgba(255,255,255,.55)', 'right');
      if (centred) { ctx.strokeStyle = 'rgba(0,255,255,.3)'; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.arc(ox, oy, s.R, 0, TAU); ctx.stroke(); }
      return;
    }
    // the zero line at 3 o'clock
    if (oy > b.t && oy < b.b) { ctx.strokeStyle = 'rgba(0,255,255,.38)'; ctx.beginPath(); ctx.moveTo(Math.max(ox, b.l), oy); ctx.lineTo(centred ? ox + s.R : b.r, oy); ctx.stroke(); }
    if (inside) {
      rimSteps();
      var st = s.rimStep, mn = s.rimMinor, rr = centred ? s.R : Math.min(0.8 * hm, Math.max(60, rmax * 0.5)), a, ca, sa;
      if (centred) { ctx.strokeStyle = 'rgba(0,255,255,.5)'; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.arc(ox, oy, s.R, 0, TAU); ctx.stroke(); }
      ctx.strokeStyle = 'rgba(0,255,255,.5)'; ctx.lineWidth = 1.5; ctx.beginPath();
      if (mn && centred) for (k = 0; k * mn < C - 1e-9 && k < 400; k++) { a = k * mn / C * TAU; ca = Math.cos(a); sa = Math.sin(a); ctx.moveTo(ox + (s.R - 5) * ca, oy - (s.R - 5) * sa); ctx.lineTo(ox + s.R * ca, oy - s.R * sa); }
      for (k = 0; k * st < C - 1e-9 && k < 400; k++) {
        a = k * st / C * TAU; ca = Math.cos(a); sa = Math.sin(a);
        if (centred) { ctx.moveTo(ox + (s.R - 11) * ca, oy - (s.R - 11) * sa); ctx.lineTo(ox + s.R * ca, oy - s.R * sa); }
        else { ctx.moveTo(ox, oy); ctx.lineTo(ox + rmax * ca, oy - rmax * sa); }
      }
      ctx.stroke();
      for (k = 0; k * st < C - 1e-9 && k < 400; k++) { a = k * st / C * TAU; text(ctx, lab(k * st, s.rimDec), ox + (rr - 27) * Math.cos(a), oy - (rr - 27) * Math.sin(a), 'rgba(0,255,255,.62)'); }
      // ring numbers along the zero line
      for (i = i0; i <= i1; i++) { var rp = i * drp; if (i % every !== 0 || (centred && rp > s.R - 58) || !inBox(ox + rp, oy + 17, 10)) continue; text(ctx, lab(i * dr, dec), ox + rp, oy + 17, 'rgba(159,220,255,.6)'); }
    } else {
      // far from the centre: the piece of the circle in view, lines of equal angle and arcs of equal distance, numbered
      var rc = Math.sqrt((bx - ox) * (bx - ox) + (by - oy) * (by - oy)), need = 110 / rc * (C / TAU), da = niceUp(need), u12 = C / 360;
      if (Math.abs(C / 12 - Math.round(C / 12)) < 1e-9 && need > 2 * u12) da = (need <= 5 * u12 ? 5 : need <= 10 * u12 ? 10 : need <= 30 * u12 ? 30 : 90) * u12;
      var adec = stepDec(da);
      var k0 = Math.ceil(th0 * C / TAU / da), k1 = Math.floor(th1 * C / TAU / da); if (k1 - k0 > 60) k1 = k0 + 60;
      ctx.strokeStyle = 'rgba(0,255,255,.26)'; ctx.lineWidth = 1; ctx.beginPath();
      for (k = k0; k <= k1; k++) { t = k * da * TAU / C; ctx.moveTo(ox + rmin * Math.cos(t), oy - rmin * Math.sin(t)); ctx.lineTo(ox + rmax * Math.cos(t), oy - rmax * Math.sin(t)); }
      ctx.stroke();
      var rl = rc - 0.4 * hm, tl = thc - 0.4 * hm / rc, xx, yy;
      for (k = k0; k <= k1; k++) { t = k * da * TAU / C; xx = ox + rl * Math.cos(t); yy = oy - rl * Math.sin(t); if (inBox(xx, yy, 26)) text(ctx, lab(mod(k * da, C), adec), xx, yy, 'rgba(0,255,255,.8)'); }
      for (i = i0; i <= i1; i++) { xx = ox + i * drp * Math.cos(tl); yy = oy - i * drp * Math.sin(tl); if (inBox(xx, yy, 26)) text(ctx, lab(i * dr, dec), xx, yy, 'rgba(159,220,255,.8)'); }
    }
  }
  function tgPath(ctx, tg, grow) {
    var g = grow || 0;
    if (tg.kind === 'xy') { var h = tg.s / 2; ctx.rect(X(tg.x - h) - g, Y(tg.y + h) - g, tg.s * S.cam.z + 2 * g, tg.s * S.cam.z + 2 * g); return; }
    var ox = X(0), oy = Y(0), z = S.cam.z, a0 = (tg.deg - tg.wdeg / 2) * RAD, a1 = (tg.deg + tg.wdeg / 2) * RAD, r0 = Math.max(0, tg.d - tg.wd / 2) * z, r1 = (tg.d + tg.wd / 2) * z;
    arcPoly(ctx, ox, oy, r1 + g, a0, a1, false); arcPoly(ctx, ox, oy, Math.max(0, r0 - g), a1, a0, true); ctx.closePath();
  }
  function drawTarget(ctx, now) {
    var s = S, f = s.find, tg = f.target, i, fd = s.p.found;
    if (s.p.rung === 1) for (i = 0; i < fd.length; i += 2) { starShape(ctx, X(fd[i]), Y(fd[i + 1]), 9); ctx.fillStyle = 'rgba(255,176,0,.9)'; ctx.fill(); }
    if (!f.on || !tg) return;
    var z = s.cam.z, tx = tg.kind === 'xy' ? tg.x : tg.d * Math.cos(tg.deg * RAD), ty = tg.kind === 'xy' ? tg.y : tg.d * Math.sin(tg.deg * RAD), sx = X(tx), sy = Y(ty);
    var size = (tg.kind === 'xy' ? tg.s : Math.min(tg.wd, tg.wdeg * RAD * tg.d)) * z;
    var heat = s.T.lights === 2 ? f.heat : 0, hz = 0.45 + 1.1 * heat, pulse = s.reduced ? 0.5 : 0.5 + 0.5 * Math.sin((now - f.born) / 1000 * TAU * hz);
    var softK = Math.max(0, 1 - (now - f.softAt) / 900), inK = f.inside ? 1 : 0, born = Math.min(1, (now - f.born) / 500);
    var al = (0.16 + 0.16 * pulse * (0.4 + 0.6 * heat) + 0.2 * inK + 0.25 * softK) * born;
    // the faint dots of earlier tries
    ctx.lineWidth = 1.5; ctx.strokeStyle = 'rgba(0,255,255,.4)';
    ctx.lineWidth = 1.5; ctx.strokeStyle = 'rgba(0,255,255,.55)'; ctx.fillStyle = 'rgba(0,255,255,.55)';
    for (i = 0; i < f.gN; i++) { var gx = X(f.ghosts[2 * i]), gy = Y(f.ghosts[2 * i + 1]); ctx.beginPath(); ctx.arc(gx, gy, 7, 0, TAU); ctx.stroke(); ctx.beginPath(); ctx.arc(gx, gy, 2, 0, TAU); ctx.fill(); }
    if (tg.found) return;
    if (size < 20) { var gr = 16 + 5 * pulse + 6 * inK; ctx.globalAlpha = Math.min(1, 0.55 + 0.3 * pulse) * born; ctx.drawImage(s.glowG, sx - gr, sy - gr, 2 * gr, 2 * gr); ctx.globalAlpha = 1; }
    ctx.beginPath(); tgPath(ctx, tg, 0); ctx.fillStyle = 'rgba(0,255,255,' + al.toFixed(3) + ')'; ctx.fill();
    ctx.lineWidth = 2; ctx.strokeStyle = 'rgba(0,255,255,' + Math.min(1, 0.55 + 0.25 * pulse + 0.2 * inK).toFixed(3) + ')'; ctx.stroke();
    // empty rings beside the target: this one wants a number that goes round that many whole circles
    if (tg.turns > 0) {
      var have = Math.abs(circles(M.raw(s.a, 0), s.a.mod)), ex = sx + Math.max(size / 2, 12) + 22, ey = sy;
      for (i = 0; i < tg.turns; i++) { ctx.beginPath(); ctx.ellipse(ex, ey - i * 8 + (tg.turns - 1) * 4, 14, 5, 0, 0, TAU); ctx.strokeStyle = i < have ? 'rgba(0,255,255,.95)' : 'rgba(0,255,255,' + (0.4 + 0.4 * pulse).toFixed(2) + ')'; ctx.lineWidth = i < have ? 3 : 1.5; ctx.stroke(); }
    }
  }
  // what the formula builds: the arc from 3 o'clock, the distance line, the equal wedges, the triangle
  function drawBuild(ctx, now) {
    var s = S, p = s.p, a = s.a, r = p.rung, z = s.cam.z, ox = X(0), oy = Y(0), xy = s.xy, n = s.nDraw, C = a.mod, sel = selN(), i;
    if (!n) return;
    var x0 = xy[0], y0 = xy[1], sx0 = X(x0), sy0 = Y(y0), d0 = Math.sqrt(x0 * x0 + y0 * y0), dpx = d0 * z, deg0 = Math.atan2(y0, x0) / RAD; if (deg0 < 0) deg0 += 360;
    var cA = 'rgba(0,255,255,.95)', cD = 'rgba(102,204,255,.95)', cT = 'rgba(0,255,255,.95)';
    if (r === 1 && p.xy) {
      // the triangle under the dot: across is X, up is Y
      var fx = X(x0), fy = oy;
      ctx.lineWidth = 3; ctx.strokeStyle = 'rgba(255,255,255,.9)'; ctx.beginPath(); ctx.moveTo(ox, oy); ctx.lineTo(fx, fy); ctx.lineTo(sx0, sy0); ctx.stroke();
      ctx.lineWidth = 2; ctx.strokeStyle = cD; ctx.beginPath(); ctx.moveTo(ox, oy); ctx.lineTo(sx0, sy0); ctx.stroke();
      var q = Math.min(12, Math.abs(fx - ox) / 2, Math.abs(sy0 - fy) / 2), sgx = x0 >= 0 ? -1 : 1, sgy = y0 >= 0 ? -1 : 1;
      ctx.lineWidth = 1.5; ctx.strokeStyle = 'rgba(255,255,255,.6)'; ctx.beginPath(); ctx.moveTo(fx + sgx * q, fy); ctx.lineTo(fx + sgx * q, fy + sgy * q); ctx.lineTo(fx, fy + sgy * q); ctx.stroke();
      if (Math.abs(fx - ox) > 44) text(ctx, lab(Number(x0.toFixed(2)), 2), (ox + fx) / 2, fy + (y0 >= 0 ? 17 : -17), '#fff');
      if (Math.abs(sy0 - fy) > 30) text(ctx, lab(Number(y0.toFixed(2)), 2), fx + (x0 >= 0 ? 10 : -10), (fy + sy0) / 2, '#fff', x0 >= 0 ? 'left' : 'right');
      return;
    }
    // the distance line to dot 0, with its number
    ctx.lineWidth = 2; ctx.strokeStyle = cD; ctx.beginPath(); ctx.moveTo(ox, oy); ctx.lineTo(sx0, sy0); ctx.stroke();
    var ra = Math.max(24, Math.min(0.5 * dpx, 0.3 * s.R)), am = deg0 * RAD;
    if (dpx > 50 && inBox(ox + (sx0 - ox) * 0.68, oy + (sy0 - oy) * 0.68, 10)) { var pa = am + Math.PI / 2; text(ctx, lab(Number(d0.toFixed(4)), 4), ox + (sx0 - ox) * 0.68 + 17 * Math.cos(pa), oy + (sy0 - oy) * 0.68 - 17 * Math.sin(pa), cD); }
    // the arc from 3 o'clock to dot 0, with the remainder on it
    if (deg0 > 0.05 && dpx > 6) {
      ctx.lineWidth = 3; ctx.strokeStyle = cA; ctx.beginPath(); ctx.arc(ox, oy, ra, 0, -am, true); ctx.stroke();
      if (deg0 > 12 && r === 1) text(ctx, s.tw.start.on ? lab(Math.floor(mod(a.start, C)), 0) : lab(Number(mod(a.start, C).toFixed(4)), 4), ox + (ra + 22) * Math.cos(am / 2), oy - (ra + 22) * Math.sin(am / 2), cA);
    }
    // winding: a tail behind the dot while the number runs round
    if (s.tw.start.on && dpx > 10) {
      var dirn = s.tw.start.to > s.tw.start.from ? 1 : -1, tail = Math.min(1.4, Math.abs(s.tw.start.to - a.start) / C * TAU + 0.25);
      ctx.lineWidth = 5; ctx.strokeStyle = 'rgba(0,255,255,.35)'; ctx.beginPath(); ctx.arc(ox, oy, dpx, -am, -(am - dirn * tail), dirn > 0); ctx.stroke();
    }
    if (r < 2 || n < 2) return;
    // one equal wedge for every step of N, up to the chosen dot
    var tu = a.turn, sweep = (tu >= 0 ? 1 : -1) * mod(Math.abs(tu), C) / C * TAU, st0 = mod(M.raw(a, 0), C) / C * TAU, rw = Math.max(34, Math.min(0.62 * dpx, 0.5 * s.R)), m = Math.min(sel, 72), closed = closedRing(a);
    if (sweep !== 0 && dpx > 20) {
      for (i = 0; i < m; i++) {
        var w0 = st0 + i * sweep, w1 = w0 + sweep;
        ctx.beginPath(); ctx.moveTo(ox, oy); ctx.arc(ox, oy, rw, -w0, -w1, sweep > 0); ctx.closePath();
        ctx.fillStyle = 'rgba(0,255,255,' + (i % 2 ? '.1' : '.17') + ')'; ctx.fill(); ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(0,255,255,.55)'; ctx.stroke();
      }
      if (m >= 1 && Math.abs(sweep) > 0.2) { var wm = st0 + sweep / 2; text(ctx, lab(Number(mod(Math.abs(tu), C).toFixed(4)) * (tu < 0 ? -1 : 1), 4), ox + (rw + 20) * Math.cos(wm), oy - (rw + 20) * Math.sin(wm), cT); }
    }
    // the path from dot to dot, and on to where the next dot would land
    if (r >= 3 && n <= 600) {
      ctx.lineWidth = closed ? 2 : 1; ctx.strokeStyle = closed ? 'rgba(0,255,255,.75)' : 'rgba(102,204,255,.3)'; ctx.beginPath(); ctx.moveTo(sx0, sy0);
      for (i = 1; i < n; i++) ctx.lineTo(X(xy[2 * i]), Y(xy[2 * i + 1]));
      if (s.ghost) ctx.lineTo(X(xy[2 * n]), Y(xy[2 * n + 1]));
      ctx.stroke();
    }
    // the distance line to the chosen dot
    if (sel >= 1 && sel <= n && (sel < n || s.ghost) && s.nAnim <= CAP) { ctx.lineWidth = 2; ctx.strokeStyle = 'rgba(255,176,0,.8)'; ctx.beginPath(); ctx.moveTo(ox, oy); ctx.lineTo(X(xy[2 * sel]), Y(xy[2 * sel + 1])); ctx.stroke(); }
    // a closed ring says how many places its dots stand on
    if (closed && inBox(ox, oy - 26, 8)) text(ctx, lab(M.places(M.count(a), a.turn, C), 0), ox, oy - 26, cT);
  }
  function drawDots(ctx, now) {
    var s = S, p = s.p, r = p.rung, xy = s.xy, n = s.nDraw, b = s.box, f = s.find, sel = selN(), i, sx, sy;
    var hs = n <= 2 ? 20 : Math.max(5, Math.min(20, 27 - 3.1 * Math.log(n) / Math.LN2)), cele = Math.max(0, 1 - (now - s.cele.t0) / 1300), big = hs * (1 + 0.6 * cele);
    var few = r >= 2 && s.nAnim <= 24, ox = X(0), oy = Y(0);
    for (i = 0; i < n; i++) {
      sx = X(xy[2 * i]); sy = Y(xy[2 * i + 1]);
      if (sx < b.l - 24 || sx > b.r + 24 || sy < b.t - 24 || sy > b.b + 24) continue;
      ctx.drawImage(s.sprC, sx - big, sy - big, 2 * big, 2 * big);
    }
    // the chosen dot is amber; on rung 1 the dot is amber while it is held
    var am = r >= 2 ? (sel < n && s.nAnim <= CAP ? sel : -1) : (s.drag ? 0 : -1);
    if (am >= 0) { sx = X(xy[2 * am]); sy = Y(xy[2 * am + 1]); ctx.drawImage(s.sprA, sx - big * 1.25, sy - big * 1.25, big * 2.5, big * 2.5); }
    // the dot nearest the target burns warmer and brighter the closer it is
    if (f.on && f.target && f.hot >= 0 && f.hot < n) {
      var h = f.heat, k = Math.pow(Math.max(0, (h - 0.22) / 0.78), 1.6), g = hs * (1.1 + 1.5 * k);
      sx = X(xy[2 * f.hot]); sy = Y(xy[2 * f.hot + 1]);
      ctx.globalAlpha = Math.min(1, 0.15 + 0.85 * k); ctx.drawImage(s.sprH, sx - g, sy - g, 2 * g, 2 * g); ctx.globalAlpha = 1;
    }
    if (s.ghost) {
      sx = X(xy[2 * n]); sy = Y(xy[2 * n + 1]);
      ctx.lineWidth = 2; ctx.strokeStyle = sel === n ? '#ffb000' : 'rgba(255,255,255,.55)'; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.arc(sx, sy, Math.max(7, hs * 0.55), 0, TAU); ctx.stroke(); ctx.setLineDash([]);
    }
    if (few) {
      var m = n + (s.ghost ? 1 : 0), dx, dy, l;
      for (i = 0; i < m; i++) {
        sx = X(xy[2 * i]); sy = Y(xy[2 * i + 1]); dx = sx - ox; dy = sy - oy; l = Math.sqrt(dx * dx + dy * dy);
        if (l < 1) { dx = 0; dy = -1; l = 1; }
        sx += dx / l * (hs * 0.5 + 17); sy += dy / l * (hs * 0.5 + 17);
        if (inBox(sx, sy, 8)) text(ctx, lab(i, 0), sx, sy, i === sel ? '#ffb000' : i === n ? 'rgba(255,255,255,.5)' : 'rgba(255,255,255,.85)');
      }
    }
  }
  function drawProbe(ctx) {
    var s = S, pr = s.probe; if (!pr.on) return;
    var ox = X(0), oy = Y(0), sx = X(pr.x), sy = Y(pr.y), d = Math.sqrt(pr.x * pr.x + pr.y * pr.y), dp = d * s.cam.z, a = Math.atan2(pr.y, pr.x); if (a < 0) a += TAU;
    var ra = Math.max(18, Math.min(dp * 0.42, 0.24 * s.R)), C = s.p.mod, dec = Math.min(4, stepDec(niceDown(3 / Math.max(20, dp) / RAD * (C / 360)))), ddec = Math.min(4, stepDec(niceDown(3 / s.cam.z)));
    ctx.lineWidth = 1.5; ctx.strokeStyle = 'rgba(255,255,255,.7)';
    ctx.beginPath(); ctx.moveTo(ox, oy); ctx.lineTo(sx, sy); ctx.stroke();
    if (dp > 6) { ctx.beginPath(); ctx.arc(ox, oy, ra, 0, -a, true); ctx.stroke(); }
    ctx.beginPath(); ctx.arc(sx, sy, 9, 0, TAU); ctx.moveTo(sx - 14, sy); ctx.lineTo(sx + 14, sy); ctx.moveTo(sx, sy - 14); ctx.lineTo(sx, sy + 14); ctx.stroke();
    var right = sx < s.box.r - 150, up = sy > s.box.t + 70;
    text(ctx, lab(Number((a / TAU * C).toFixed(dec)), dec), sx + (right ? 18 : -18), sy + (up ? -40 : 24), 'rgba(0,255,255,.95)', right ? 'left' : 'right');
    text(ctx, lab(Number(d.toFixed(ddec)), ddec), sx + (right ? 18 : -18), sy + (up ? -16 : 48), 'rgba(102,204,255,.95)', right ? 'left' : 'right');
  }
  function drawNova(ctx, now) {
    var s = S, nv = s.find.nova; if (!nv.on) return;
    var t = (now - nv.t0) / 1000, sx = X(nv.x), sy = Y(nv.y), i, P = s.part, R = Math.max(s.box.r - s.box.l, s.box.b - s.box.t);
    ctx.save(); ctx.globalCompositeOperation = 'lighter';
    if (nv.gentle) { var g = Math.sin(Math.min(1, t / 1.6) * Math.PI), gr = 70 * nv.scale; ctx.globalAlpha = 0.55 * g; ctx.drawImage(s.glowW, sx - gr, sy - gr, 2 * gr, 2 * gr); ctx.restore(); return; }
    var k = Math.min(1, t / 0.9), e = 1 - Math.pow(1 - k, 3), fr = (30 + R * 0.75 * e) * nv.scale;
    ctx.globalAlpha = Math.max(0, 0.8 * (1 - k)); ctx.drawImage(s.glowW, sx - fr, sy - fr, 2 * fr, 2 * fr);
    ctx.globalAlpha = Math.max(0, 1 - k); ctx.lineWidth = 4; ctx.strokeStyle = '#fff3c4'; ctx.beginPath(); ctx.arc(sx, sy, 10 + R * 0.5 * e * nv.scale, 0, TAU); ctx.stroke();
    var n = Math.min(96, Math.round(56 * nv.scale)), tp = Math.min(1, t / 1.5), ep = 1 - Math.pow(1 - tp, 2);
    for (i = 0; i < n; i++) {
      var px = sx + P[4 * i] * R * 0.42 * ep, py = sy + P[4 * i + 1] * R * 0.42 * ep, z = 5 + 9 * P[4 * i + 2] * (1 - tp);
      ctx.globalAlpha = Math.max(0, (1 - tp) * (0.5 + 0.5 * P[4 * i + 3])); ctx.drawImage(i % 3 ? s.sprH : s.sprC, px - z, py - z, 2 * z, 2 * z);
    }
    ctx.restore();
  }
  // the figures that go with the drawing: the stack of whole circles and what it adds back to, the running product,
  // one ring's worth, the row of lit stars
  function drawHud(ctx, now) {
    var s = S, p = s.p, a = s.a, b = s.box, r = p.rung, C = a.mod, sel = selN(), x = b.l + 14, y = b.t + 20, i, t;
    s.hudR = 0;
    if (r === 1 && p.xy) { scaleMark(ctx); stars(ctx); return; }
    var raw = M.raw(a, r === 1 ? 0 : sel), dm = divmod(raw, C), q = dm.q, m = dm.m;
    if (q !== s.lastCirc) { s.lastCirc = q; s.stackPulse = now; }
    if (q !== 0) {
      var k = Math.max(0, 1 - (now - s.stackPulse) / 450), nn = Math.min(Math.abs(q), 5), w = 15 + 4 * k;
      ctx.lineWidth = 2 + 2 * k; ctx.strokeStyle = q < 0 ? '#ffb000' : '#00ffff';
      if (q < 0) ctx.setLineDash([4, 3]);
      for (i = 0; i < nn; i++) { ctx.beginPath(); ctx.ellipse(x + 17, y + 6 - i * 5 + (nn - 1) * 2, w, 5 + k, 0, 0, TAU); ctx.stroke(); }
      ctx.setLineDash([]);
      var busyW = s.tw.start.on, dec = busyW ? 0 : 4;
      t = lab(q,0); if(ctx.measureText(t).width < b.r-x-70) text(ctx,t,x+42,y,'#fff','left');
    }
    scaleMark(ctx); stars(ctx);
  }
  function scaleMark(ctx) {
    var s = S, b = s.box, w = s.drp, x1 = b.r - 12, x0 = x1 - w, y = b.t + 26; if (!(w > 0) || w > (b.r - b.l) * 0.5 || s.hudR > x0 - 60) return;
    ctx.lineWidth = 2; ctx.strokeStyle = 'rgba(159,220,255,.75)'; ctx.beginPath(); ctx.moveTo(x0, y - 7); ctx.lineTo(x0, y); ctx.lineTo(x1, y); ctx.lineTo(x1, y - 7); ctx.stroke();
    text(ctx, lab(s.dr, stepDec(s.dr)), x0 - 8, y - 8, 'rgba(159,220,255,.8)', 'right');
  }
  function starShape(ctx, x, y, R) { var i, a; ctx.beginPath(); for (i = 0; i < 10; i++) { a = -Math.PI / 2 + i * Math.PI / 5; var rr = i % 2 ? R * 0.45 : R; if (i) ctx.lineTo(x + rr * Math.cos(a), y + rr * Math.sin(a)); else ctx.moveTo(x + rr * Math.cos(a), y + rr * Math.sin(a)); } ctx.closePath(); }
  function stars(ctx) {
    var s = S, p = s.p, b = s.box, x = b.l + 18, y = b.b - 18, i, k, fresh = s.find.nova.on;
    if (p.score > 0) { starShape(ctx, x, y, 10); ctx.fillStyle = fresh ? '#fff3c4' : '#ffb000'; ctx.fill(); var st = lab(p.score, 0); text(ctx, st, x + 16, y + 1, fresh ? '#fff3c4' : '#ffb000', 'left'); x += 30 + ctx.measureText(st).width + 14; }
    // the facts come across so far: a wound circle, a closed ring, the whole-number rule
    for (k in p.facts) {
      ctx.lineWidth = 2; ctx.strokeStyle = '#00ffff'; ctx.beginPath();
      if (k === 'wind') ctx.arc(x, y, 7, 0, TAU);
      else if (k === 'spokes') { for (i = 0; i < 3; i++) { var an = i * Math.PI / 3; ctx.moveTo(x - 8 * Math.cos(an), y - 8 * Math.sin(an)); ctx.lineTo(x + 8 * Math.cos(an), y + 8 * Math.sin(an)); } }
      else { for (i = 0; i < 8; i++) { var g = i * 2.39996, rr = 2.6 * Math.sqrt(i + 0.5); ctx.moveTo(x + rr * Math.cos(g) + 1.4, y - rr * Math.sin(g)); ctx.arc(x + rr * Math.cos(g), y - rr * Math.sin(g), 1.4, 0, TAU); } }
      ctx.stroke(); x += 24;
    }
  }

  // ------------------------------------------------------------------ the doors
  var api = {
    open: open, close: close, math: M, tuning: TUNING,
    rung: function (r) { if (S && r >= 1 && r <= 4) setRung(r | 0); },
    find: function (on) { if (S) setFind(on); },
    exportState: function () { return S ? exportState() : null; },
    // a plain copy of what is on screen, for looking at from outside
    state: function () {
      if (!S) return null;
      var s = S, p = s.p, f = s.find, tg = f.target, o = {
        rung: p.rung, start: p.start, mod: p.mod, dist: p.dist, square: p.square == null ? p.dist * p.dist : p.square, turn: p.turn, step: p.step, count: p.count, speed: p.speed, grow: p.grow, newDots: p.newDots, t: p.t, xy: p.xy, sel: selN(),
        dots: M.count(p), drawn: s.nDraw, viewR: s.viewR, cam: { x: s.cam.x, y: s.cam.y, z: s.cam.z }, box: { l: s.box.l, t: s.box.t, r: s.box.r, b: s.box.b }, cx: s.cx, cy: s.cy, R: s.R, W: s.W, H: s.H, wide: s.wide,
        editing: s.F.editing(), buffer: s.F.buffer(), more: s.F.moreOpen(), busy: busy(), playing: s.playing, reduced: s.reduced, audio: s.ac ? s.ac.state : 'none', muted: !!muted(),
        probe: { on: s.probe.on, x: s.probe.x, y: s.probe.y }, joy: s.joy.on, facts: Object.keys(p.facts), stars: p.stars, score: p.score, found: p.found.length / 2, circles: Number(exact(p,selN()).q), remainder: Number(exact(p,selN()).m), exact: exact(p,selN()),
        closed: closedRing(p), places: closedRing(p) ? M.places(M.count(p), p.turn, p.mod) : null,
        find: { on: f.on, seq: f.seq, tries: f.tries, novas: f.novas, softs: f.softs, heat: f.heat, inside: f.inside, ghosts: f.gN, novaOn: f.nova.on, gentle: f.nova.gentle, scale: f.nova.scale, flashTimes: f.flashTimes.slice(), pending: !!f.pending,
          target: tg ? { kind: tg.kind, deg: tg.deg, u: tg.u, d: tg.d, wdeg: tg.wdeg, wd: tg.wd, x: tg.x, y: tg.y, s: tg.s, turns: tg.turns, lv: tg.lv, found: tg.found } : null }
      };
      return o;
    },
    // where dot n really is: the formula's point and its place on the screen
    dot: function (n) { if (!S) return null; var o = M.place(S.p, n || 0, { x: 0, y: 0, d: 0, deg: 0 }); o.sx = X(o.x); o.sy = Y(o.y); return o; },
    toScreen: function (x, y) { return S ? { x: X(x), y: Y(y) } : null; },
    toWorld: function (sx, sy) { return S ? { x: WX(sx), y: WY(sy) } : null; },
    formula: function () { return S ? S.F : null; },
    reset: function () { var h = S ? S.host : null, o = S ? S.opts : null; if (S) close(true); KEEP = null; if (h) open(h, o); }
  };
  var KGFormula = {
    create: create, pips: pips, css: css, parse: parse, fmt: fmt, plain: plain, check: check, mod: mod, circles: circles, divmod: divmod,
    LIMIT: LIMIT, LIMIT_TEXT: LIMIT_TEXT, PIPS: PIPS, math: M,
    // fn(angleDeg, distance) is called as the probe moves (mouse over the circle, or the joystick)
    onProbe: function (fn) { if (typeof fn === 'function' && probeFns.indexOf(fn) < 0) probeFns.push(fn); return function () { var i = probeFns.indexOf(fn); if (i >= 0) probeFns.splice(i, 1); }; },
    // the row of number chips of the open play screen (null when it is not open)
    chips: function () { return S ? S.F : null; }
  };
  root.KGFormula = KGFormula;
  root.KGPlay = api;
  if (typeof document !== 'undefined') {
    (root.KGModules = root.KGModules || []).push({ id: 'play', label: 'PLAY', sentence: 'Place a dot with numbers', open: function (host) { return open(host, {}); }, close: function () { close(); } });
  }
  if (typeof module !== 'undefined' && module.exports) module.exports = { KGPlay: api, KGFormula: KGFormula, math: M, mod: mod, circles: circles, divmod: divmod, parse: parse, fmt: fmt, plain: plain, check: check, snapTo: snapTo, niceDown: niceDown, niceUp: niceUp, tuning: TUNING, LIMIT: LIMIT };
})(typeof window !== 'undefined' ? window : globalThis);

Solid

A web page in the learn the kuiper folder of Kuiper Belt. Published at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/solid.html.

renderkuiper-belt / learn-the-kuiper/202610050609/solid.html · lines 1–27 of 27 · version 2026-10-05 06:09 · Entry point

What it does
It draws its content. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
Out: web page.
Downstream impact
Used directly by 1 file: Menu (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050354/menu.html). Reached from 2 other entry points, including Lesson (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/lesson.html); Play (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/play.html). It is itself an entry point, published at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/solid.html.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Loaded by the Menu page at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050354/menu.html.
Application
kuiper-belt · learn-the-kuiper/202610050609 · page
Uses
Audio Unlock (script src), Solid (script src), Menu (link)
Used by
linked from Menu (link)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 learn-the-kuiper/202610050609/solid.html:1-27 · blob 16cd419b1e27d9732d33a67fa4190134838c04b1 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover,user-scalable=no">
<title>Learn the Kuiper</title>
<style>html,body{margin:0;height:100%;background:#000;overflow:hidden}#host{position:fixed;inset:0}</style>
</head>
<body>
<div id="host"></div>
<script src="audio-unlock.js"></script><script src="solid.js"></script>
<script>
(function () {
  var q = new URLSearchParams(location.search), o = {};
  if (q.get('canvas') === '1') o.forceCanvas = true;
  var api = window.KGSolid.open(document.getElementById('host'), o);
  window.solidApi = api;
  var set = {};
  ['N', 'key', 'G1', 'G2', 'G0'].forEach(function (k) { if (q.get(k)) set[k] = Number(q.get(k)); });
  if (q.get('shape')) api.setShape(q.get('shape'));
  if (Object.keys(set).length) api.set(set);
})();
</script>
<style>#host{top:40px!important}.kgm{position:fixed;left:0;top:0;height:40px;display:flex;align-items:center;padding:0 12px;z-index:60;font:400 24px/1 "Segoe UI",system-ui,-apple-system,Arial,sans-serif;color:rgba(255,255,255,.75);text-decoration:none;letter-spacing:.04em}</style>
<a class="kgm" href="menu.html">MENU</a>
</body>
</html>

Solid

A JavaScript module in the learn the kuiper folder of Kuiper Belt that groups digits (`groupDigits`), parses typed (`parseTyped`) and draws on a canvas.

renderkuiper-belt / learn-the-kuiper/202610050609/solid.js · lines 1–248 of 248 · version 2026-10-05 06:09 · Entry point · pattern parseTyped (shared by 2 files)

What it does
It draws its content. Defines 52 functions or classes, including mod32, mulmod32, rootFn, invRoot, wholeRoot. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
Out: canvas drawing.
Downstream impact
Used directly by 1 file: Solid (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/solid.html). Reached from 3 other entry points, including Lesson (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/lesson.html); Menu (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050354/menu.html); Play (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/play.html).
What it achieves
It groups digits (`groupDigits`) and parses typed (`parseTyped`). `solid.js` Learn the Kuiper: the same rule one dimension up (SPHERE, CUBE, and the flat CIRCLE and SQUARE).
Why it matters
Loaded by the page of the same name at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/solid.html.
Application
kuiper-belt · learn-the-kuiper/202610050609 · JavaScript module
Uses
none found
Used by
loaded by Solid (script src)
Produces
mod32, mulmod32, rootFn, invRoot, wholeRoot, pw, shellOf, place, measure, keyFromMeasure, outerRadius, groupDigits
Defines here
mod32, mulmod32, rootFn, invRoot, wholeRoot, pw, shellOf, place, measure, keyFromMeasure, outerRadius, groupDigits, fmtWhole, fmtReal, parseTyped, hash01, h32, icbrt, decimal, integer, format, rootLabel, divmod, point, pos, cell, lights, create, targetFor, next
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 learn-the-kuiper/202610050609/solid.js:1-248 · blob 25f424d516ba984f7133eff40624ac424c0b0370 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
/* solid.js  Learn the Kuiper: the same rule one dimension up (SPHERE, CUBE, and the flat CIRCLE and SQUARE).
   Plain classic script, no build step, no network, works from file://. Own WebGL point renderer, Canvas 2D fallback.
   Registers as a module: window.KGModules.push({id:'solid', ...}). Exposes window.KGSolid (maths + test hooks).

   The rules (every key k is a whole number; MOD is exact in whole numbers for every k up to 2^53):
     SPHERE  r = CBRT(k)           u = MOD(k x G1, 2^32) / 2^32   v = MOD(k x G2, 2^32) / 2^32
             angle = 2 PI u,  h = 1 - 2 v,  X = r SQRT(1 - h h) COS(angle),  Y = r SQRT(1 - h h) SIN(angle),  Z = r h
     CUBE    s = CBRT(k), the surface of the centred cube of side s, unfolded as a 3 x 2 net of six equal faces:
             col = FLOOR(3u), row = FLOOR(2v), a = 3u - col, b = 2v - row, face = 3 row + col
     CIRCLE  r = SQRT(k), angle = 2 PI MOD(k x G0, 2^32) / 2^32   (the 2D Kuiper rule, G0 = 2654435769)
     SQUARE  s = SQRT(k), the perimeter of the centred square of side s: t = 4 u0, edge = FLOOR(t), a = t - edge
   Defaults G1 = 2447445413 (turn), G2 = 3242174889 (height): the plastic-number pair, chosen by the GPU run
   (solid\out\even.json): round-odd(0.5698402909980532 x 2^32) and round-odd(0.7548776662466927 x 2^32). */
(function () {
  'use strict';
  var T32 = 4294967296, T16 = 65536, LIMIT = 9007199254740992;
  var LIMIT_LINE = 'THAT NUMBER IS TOO LARGE FOR THIS COMPUTER TO SHOW. THE REAL LIMIT HERE IS 9,007,199,254,740,992.';
  var DEF = { G0: 2654435769, G1: 2447445413, G2: 3242174889 };

  /* ---------- exact maths ---------- */
  function mod32(x) { return x - Math.floor(x / T32) * T32; }          // exact for whole x <= 2^53 (power-of-two divide)
  function mulmod32(k, G) {                                              // MOD(k x G, 2^32), exact for whole k, G <= 2^53
    var kl = mod32(k), g = mod32(G), gh = Math.floor(g / T16), gl = g - gh * T16;
    var hi = (kl * gh) % T16;                                            // kl*gh < 2^48: exact
    return (hi * T16 + kl * gl) % T32;                                   // < 2^32 + 2^48: exact
  }
  function rootFn(name) { return name === 'CBRT' ? Math.cbrt : name === 'SQRT' ? Math.sqrt : function (k) { return k; }; }
  function invRoot(name, d) { return name === 'CBRT' ? d * d * d : name === 'SQRT' ? d * d : d; }
  function wholeRoot(k, p) {                                             // FLOOR(k^(1/p)) exactly, k whole <= 2^53
    var n = Math.floor(p === 3 ? Math.cbrt(k) : Math.sqrt(k));
    if (k < 9e15) {                                                      // fast exact path: every power below 2^53 is exact
      var m = Math.floor(p === 3 ? Math.cbrt(k) : Math.sqrt(k)), pm = function (x) { return p === 3 ? x * x * x : x * x; };
      while (m > 0 && pm(m) > k) m--; while (pm(m + 1) <= k) m++; if (pm(m + 1) < 9007199254740992) return m;
    }
    function pw(x) { return p === 3 ? BigInt(x) * BigInt(x) * BigInt(x) : BigInt(x) * BigInt(x); }
    var K = BigInt(k);
    while (n > 0 && pw(n) > K) n--;
    while (pw(n + 1) <= K) n++;
    return n;
  }
  function shellOf(k, root) {                                            // which shell (ring) key k starts in
    if (root === 'CBRT') return wholeRoot(k, 3);
    if (root === 'SQRT') return wholeRoot(k, 2);
    return k;
  }
  function place(shape, k, P, out) {                                     // P: {G0,G1,G2,root}; out: [x,y,z]
    out = out || [0, 0, 0];
    var rr = rootFn(P.root)(k), u, v, h, s, a, b, col, row, f, H, A, B, t, e;
    if (shape === 'sphere') {
      u = mulmod32(k, P.G1) / T32; v = mulmod32(k, P.G2) / T32; h = 1 - 2 * v; s = Math.sqrt(Math.max(0, 1 - h * h));
      a = 2 * Math.PI * u; out[0] = rr * s * Math.cos(a); out[1] = rr * s * Math.sin(a); out[2] = rr * h;
    } else if (shape === 'cube') {
      u = mulmod32(k, P.G1) / T32; v = mulmod32(k, P.G2) / T32;
      col = Math.floor(3 * u); row = Math.floor(2 * v); a = 3 * u - col; b = 2 * v - row; f = row * 3 + col;
      A = rr * (a - 0.5); B = rr * (b - 0.5); H = rr / 2;
      if (f === 0) { out[0] = H; out[1] = A; out[2] = B; } else if (f === 1) { out[0] = -H; out[1] = A; out[2] = B; }
      else if (f === 2) { out[0] = A; out[1] = H; out[2] = B; } else if (f === 3) { out[0] = A; out[1] = -H; out[2] = B; }
      else if (f === 4) { out[0] = A; out[1] = B; out[2] = H; } else { out[0] = A; out[1] = B; out[2] = -H; }
    } else if (shape === 'circle') {
      a = 2 * Math.PI * mulmod32(k, P.G0) / T32; out[0] = rr * Math.cos(a); out[1] = rr * Math.sin(a); out[2] = 0;
    } else {                                                             // square
      t = 4 * mulmod32(k, P.G0) / T32; e = Math.floor(t); a = t - e; H = rr / 2; A = rr * (a - 0.5);
      if (e === 0) { out[0] = A; out[1] = -H; } else if (e === 1) { out[0] = H; out[1] = A; }
      else if (e === 2) { out[0] = -A; out[1] = H; } else { out[0] = -H; out[1] = -A; }
      out[2] = 0;
    }
    return out;
  }
  function measure(shape, k) {                                           // VOLUME or AREA held by the first k keys
    if (shape === 'sphere') return 4 / 3 * Math.PI * k;
    if (shape === 'circle') return Math.PI * k;
    return k;                                                            // cube VOLUME = k, square AREA = k
  }
  function keyFromMeasure(shape, m) {
    if (shape === 'sphere') return Math.round(m * 3 / (4 * Math.PI));
    if (shape === 'circle') return Math.round(m / Math.PI);
    return Math.round(m);
  }
  function outerRadius(shape, root, k) {                                 // farthest a key-k point can be from the centre
    var r = rootFn(root)(k);
    return shape === 'cube' ? r * Math.sqrt(3) / 2 : shape === 'square' ? r * Math.SQRT2 / 2 : r;
  }
  function groupDigits(s) { var neg = s[0] === '-'; if (neg) s = s.slice(1); var p = s.split('.'), i = p[0], o = '';
    while (i.length > 3) { o = ',' + i.slice(-3) + o; i = i.slice(0, -3); } return (neg ? '-' : '') + i + o + (p.length > 1 ? '.' + p[1] : ''); }
  function fmtWhole(n) { return groupDigits(String(Math.round(n))); }
  function fmtReal(x, dp) {
    if (!isFinite(x)) return '0';
    if (Math.abs(x) >= 1e15) { var m = x.toPrecision(15).split('e+'), dg = m[0].replace('.', ''), ex = +m[1]; while (dg.length < ex + 1) dg += '0'; return '≈ ' + groupDigits(dg); }   // 15 significant digits, marked as near
    if (dp === undefined) dp = Math.abs(x) >= 1e6 ? 0 : Math.abs(x) >= 1000 ? 1 : 2;
    return groupDigits(x.toFixed(dp));
  }
  /* parse a typed number. whole: digits only. Returns {ok, v} or {over:true} or {bad:true} */
  function parseTyped(str, whole) {
    str = String(str).replace(/,/g, '').trim();
    if (!str || str === '.' || str === '-') return { bad: true };
    if (whole) {
      if (!/^\d+$/.test(str)) return { bad: true };
      if (BigInt(str) > BigInt(LIMIT)) return { over: true };
      var v = Number(str); return v < 1 ? { bad: true } : { ok: true, v: v };
    }
    if (!/^\d*\.?\d*$/.test(str)) return { bad: true };
    var ip = str.split('.')[0] || '0';
    if (BigInt(ip) > BigInt(LIMIT)) return { over: true };
    var x = Number(str); return isFinite(x) ? { ok: true, v: x } : { bad: true };
  }
  function hash01(i, seed) {                                             // 53-bit fair uniform in [0,1)
    function h32(x) { x = Math.imul(x ^ (x >>> 16), 0x7feb352d); x = Math.imul(x ^ (x >>> 15), 0x846ca68b); return (x ^ (x >>> 16)) >>> 0; }
    var a = h32(i * 2 + 1 + seed), b = h32(i * 2 + 2 + seed * 7919);
    return (a * 2097152 + (b >>> 11)) / 9007199254740992;
  }

  var KGSolid = {mulmod32,mod32,place,shellOf,wholeRoot,measure,keyFromMeasure,outerRadius,parseTyped,fmtWhole,fmtReal,DEF,LIMIT,LIMIT_LINE};
  if(typeof module!=='undefined'&&module.exports)module.exports=KGSolid;
  if(typeof window!=='undefined')window.KGSolid=KGSolid;
})();
/* FIX-solid: three-control teaching shell. Exact domain/membership; approximate XYZ.
 * Legacy pure maths above is preserved from Claude; S1 comparisons pin multiplier order explicitly.
 * This 3D experiment is not the canonical 2D Kuiper law. */
(function(root){'use strict';
const K=typeof module==='object'&&module.exports?module.exports:root.KGSolid;
const MAX=9007199254740991n,TAU=2*Math.PI,F=['a','b','d'];
function icbrt(n){let lo=0n,hi=1n;while(hi**3n<=n)hi*=2n;while(hi-lo>1n){const m=(lo+hi)/2n;if(m**3n<=n)lo=m;else hi=m;}return lo;}
function decimal(t){if(typeof t!=='string'||t.length>128||!/^\d+(?:\.\d*)?$/.test(t))return null;const [a,b='']=t.split('.'),den=10n**BigInt(b.length),num=BigInt(a+b);return num<=MAX*den?{num,den,text:t}:null;}
function integer(t){if(typeof t!=='string'||t.length>128||! /^-?\d+$/.test(t))return null;const n=BigInt(t);return n>=-MAX&&n<=MAX?n:null;}
function format(n,d){let s=n<0n?'-':'';if(n<0n)n=-n;s+=n/d;let r=n%d;if(r)s+='.';while(r){r*=10n;s+=r/d;r%=d;}return s;}
function rootLabel(a){let x=a.num,y=a.den;while(y){const t=x%y;x=y;y=t;}const n=a.num/x,d=a.den/x,u=icbrt(n),v=icbrt(d);if(u**3n===n&&v**3n===d)return '= '+format(u,v);return '≈ '+Math.cbrt(Number(a.num)/Number(a.den)).toPrecision(7).replace(/(\.\d*?[1-9])0+(?=e|$)|\.0+(?=e|$)/g,'$1');}
function divmod(n,c){const r=(n%c+c)%c;return {product:n,q:(n-r)/c,r};}
function point(a,b,d,g1,c,g2,shape='sphere'){
 const turn=divmod(b*g1,c),up=divmod(d*g2,c),shell=icbrt(a.num/a.den),radius=Math.cbrt(Number(a.num)/Number(a.den)),u=Number(turn.r)/Number(c),v=Number(up.r)/Number(c),h=1-2*v,t=TAU*u;
 let x,y,z;
 if(shape==='cube'){const col=Math.floor(3*u),row=Math.floor(2*v),A=radius*(3*u-col-.5),B=radius*(2*v-row-.5),H=radius/2;[x,y,z]=[[H,A,B],[-H,A,B],[A,H,B],[A,-H,B],[A,B,H],[A,B,-H]][row*3+col];}
 else {const rho=radius*Math.sqrt(Math.max(0,1-h*h));x=rho*Math.cos(t);y=rho*Math.sin(t);z=radius*h;}
 return {turn,up,shell,radius,u,v,h,x,y,z,a};
}
function pos(s){return point(s.a,s.b,s.d,s.g1,s.c,s.g2,s.shape);}
function cell(p,c){const bins=c<12n?c:12n;return {shell:p.shell,turn:p.turn.r*bins/c,up:p.up.r*bins/c,bins};}
function lights(t,p,c){const v=cell(p,c);const a=decimal(t.a);return [a.num*p.a.den===p.a.num*a.den,t.turn===v.turn,t.up===v.up];}
function create(){const s={a:decimal('8'),b:0n,d:2n,g1:1n,g2:1n,c:4n,shape:'sphere',linked:false,score:0,hits:0,target:null};next(s);return s;}
function targetFor(s,a,b,d){const p=point(a,b,d,s.g1,s.c,s.g2,s.shape);return {...cell(p,s.c),a:a.text,b:String(b),d:String(d)};}
function next(s){
 const current=cell(pos(s),s.c);let t;
 for(let j=1;j<200;j++){
  const key=BigInt(2+(s.hits*3+j)%12)**3n,stage=s.hits%9;
  let a=s.a,b=s.b,d=s.d;
  if(s.linked){a=decimal(String(key));b=key;d=key;}
  else if(stage<3)a=decimal(String(((current.shell+BigInt(j)-1n)%icbrt(MAX)+1n)**3n));
  else if(stage<6)b=s.b+BigInt(j);
  else d=s.d+BigInt(j);
  // At the domain edge wrap target witnesses into the supported input domain.
  if(b>MAX)b%=MAX;if(d>MAX)d%=MAX;
  if(!a)continue;t=targetFor(s,a,b,d);
  if(!lights(t,pos(s),s.c).every(Boolean)){s.target=t;return t;}
 }
 throw Error('No reachable distinct target');
}
function apply(s,field,text){const v=field==='a'?decimal(text):integer(text);if(v===null)return false;
 if(s.linked){const n=integer(text);if(n===null||n<0n)return false;s.a=decimal(String(n));s.b=n;s.d=n;}
 else s[field]=v;return true;}
function link(s){const was=s.linked;if(!was){const n=s.a.num/s.a.den;s.a=decimal(String(n));s.b=n;s.d=n;}s.linked=!was;next(s);}
function award(s,kind){if(!['typed','roll'].includes(kind)||!lights(s.target,pos(s),s.c).every(Boolean))return 0;const points=kind==='typed'?30:1;s.score+=points;s.hits++;next(s);return points;}
const CSS=`.fs{position:absolute;inset:0;background:#000;color:#fff;font:400 24px/1.15 system-ui,sans-serif;font-variant-numeric:tabular-nums;display:grid;grid-template-rows:32px minmax(0,1fr) 182px 60px;gap:6px;overflow:hidden;user-select:none;-webkit-user-select:none;touch-action:none;padding:0 8px max(8px,env(safe-area-inset-bottom));box-sizing:border-box}
.fs *{box-sizing:border-box;touch-action:none;min-width:0}.fs button{color:#fff;background:#000;border:1px solid #fff;border-radius:0;font:inherit;cursor:pointer}.fs-head{display:flex;justify-content:space-between;align-items:center}.fs-head button{border:0}.fs-view{position:relative;min-height:0}.fs canvas{position:absolute;width:100%;height:100%}.fs-target{display:none}.fs-rolls{display:grid;gri  … [line shortened here: 2,096 characters; full line on GitHub]
@media(min-aspect-ratio:1/1){.fs{grid-template-columns:minmax(250px,1fr) 300px;grid-template-rows:32px minmax(0,1fr);gap:6px}.fs-head{grid-column:1/-1}.fs-view{grid-column:1;grid-row:2}.fs-rolls{grid-column:2;grid-row:2;grid-template-columns:1fr;grid-template-rows:repeat(3,minmax(min-content,1fr));gap:4px;overflow:auto}.fs-roll{grid-template-columns:minmax(0,1fr) minmax(0,1fr);grid-template-rows:m  … [line shortened here: 980 characters; full line on GitHub]
`;
let active=null;
function open(host,opts={}){
 if(active)active.close();const s=create(),listeners=[],rollers={},motions=new Map();let selected='a',draft=null,dirty=false,dead=false,raf=0,settle=0,pendingRoll=false,burst=0,viewScale=4,audio=null,muted=false,yaw=.45,pitch=.25,drag=null,lastFrame=0;
 function el(tag,cls,text,parent){const e=document.createElement(tag);e.className=cls||'';if(text!==undefined)e.textContent=text;if(parent)parent.appendChild(e);return e;}
 const style=el('style','',CSS,host),box=el('div','fs',undefined,host),head=el('div','fs-head',undefined,box),score=el('span','','0',head),menu=el('button','','…',head),view=el('div','fs-view',undefined,box),canvas=el('canvas','',undefined,view),ctx=canvas.getContext('2d'),target=el('div','fs-target','',view),row=el('div','fs-rolls',undefined,box),panel=el('div','fs-panel',undefined,box),tools=el(  … [line shortened here: 543 characters; full line on GitHub]
 menu.setAttribute('aria-label','Tools');
 box.appendChild(panel);
 function on(e,t,fn,opt){e.addEventListener(t,fn,opt);listeners.push([e,t,fn,opt]);}
 function button(t,fn){const b=el('button','',t,tools);on(b,'click',fn);return b;}
 const linked=button('LINK',()=>{stop();link(s);draft=null;dirty=false;render();});
 button('4',()=>preset(1n,1n,4n));button('12',()=>preset(1n,1n,12n));button('2³²',()=>preset(2447445413n,3242174889n,4294967296n));
 const shape=button('CUBE',()=>{stop();s.shape=s.shape==='sphere'?'cube':'sphere';shape.textContent=s.shape==='sphere'?'CUBE':'SPHERE';draft=null;dirty=false;next(s);render();});
 const mute=button('♪',()=>{muted=!muted;mute.textContent=muted?'×♪':'♪';});button('×',()=>{box.classList.remove('open');box.classList.remove('menu-open');draft=null;dirty=false;render();});
 function unlock(){try{const A=root.AudioContext||root.webkitAudioContext;if(!A)return;if(!audio)audio=new A();if(audio.state==='suspended')audio.resume();}catch(_){}}
 function sound(hit){if(muted)return;try{unlock();if(!audio)return;[0,...(hit?[4,7]:[])].forEach((n,i)=>{const o=audio.createOscillator(),g=audio.createGain(),t=audio.currentTime+i*.08;o.frequency.value=220*Math.pow(2,n/12);g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(.025,t+.02);g.gain.exponentialRampToValueAtTime(.0001,t+.3);o.connect(g);g.connect(audio.destination);o.start(t);o.sto  … [line shortened here: 424 characters; full line on GitHub]
 function stop(){motions.clear();clearTimeout(settle);settle=0;pendingRoll=false;}
 function preset(g1,g2,c){stop();s.g1=g1;s.g2=g2;s.c=c;s.hits=0;draft=null;dirty=false;next(s);render();}
 function textValue(f){return f==='a'?s.a.text:String(s[f]);}
 function preview(){if(draft===null)return s;const t={...s};return apply(t,selected,draft)?t:null;}
 function render(){const shown=preview(),p=shown?pos(shown):null;F.forEach((f,i)=>{const r=rollers[f];if(!r)return;r.box.classList.toggle('selected',selected===f);r.value.textContent=draft!==null&&selected===f?draft||'·':textValue(f);r.label.textContent=f==='a'?'CBRT':f==='b'?'MOD ↺':'MOD ↕';r.result.textContent=p?(f==='a'?rootLabel(shown.a):'→ '+(f==='b'?p.turn.r:p.up.r)):'·';r.light.classList.to  … [line shortened here: 576 characters; full line on GitHub]
 const t=s.target;function goalPart(n){const lo=(n*s.c+t.bins-1n)/t.bins,hi=((n+1n)*s.c+t.bins-1n)/t.bins;return hi-lo===1n?String(lo):lo+'…'+(hi-1n);}rollers.a.goal.textContent=rootLabel(decimal(t.a)).replace(/^= /,'');rollers.b.goal.textContent=goalPart(t.turn);rollers.d.goal.textContent=goalPart(t.up);target.textContent='';

 working.textContent=p?p.turn.product+' = '+p.turn.q+' × '+s.c+' + '+p.turn.r+'\n'+p.up.product+' = '+p.up.q+' × '+s.c+' + '+p.up.r:'';working.title=p?'MOD('+shown.b+' × '+s.g1+', '+s.c+') = '+p.turn.r+'; MOD('+shown.d+' × '+s.g2+', '+s.c+') = '+p.up.r:'';

 }
 function edit(f){stop();selected=f;draft=null;dirty=false;box.classList.add('open');error.textContent='';render();}
 function reward(kind){const n=award(s,kind);if(n){burst=kind==='typed'?1:0;sound(kind==='typed');}render();return n;}
 function key(k){unlock();stop();if(k==='Enter'||k==='OK'){if(dirty&&draft!==null){const before=selected==='a'?s.a:s[selected];if(apply(s,selected,draft)){const changed=selected==='a'?before.num*s.a.den!==s.a.num*before.den:before!==s[selected];draft=null;dirty=false;error.textContent='';if(changed)reward('typed');sound(false);}}render();return;}
 if(k==='Escape'){draft=null;dirty=false;error.textContent='';render();return;}
 if(k==='ArrowUp'||k==='ArrowDown'){if(roll(selected,k==='ArrowUp'?1:-1))schedule();return;}
 if(k.length!==1&&!['Backspace','C'].includes(k))return;
 box.classList.add('open');if(draft===null)draft='';dirty=true;
 if(k==='C')draft='';else if(k==='Backspace')draft=draft.slice(0,-1);else if(k==='-')draft=draft.startsWith('-')?draft.slice(1):'-'+draft;else if(draft.length<129)draft+=k;
 let over=false;if(/^-?\d+(?:\.\d*)?$/.test(draft)){const [a,b='']=draft.replace('-','').split('.');over=BigInt(a+b)>MAX*10n**BigInt(b.length);}
 error.textContent=over?'THAT NUMBER IS TOO LARGE FOR THIS COMPUTER TO SHOW. THE REAL LIMIT HERE IS 9,007,199,254,740,991.':'';render();}
 function roll(f,steps,fine=false){draft=null;dirty=false;error.textContent='';selected=f;let value;const before=textValue(f);
 if(f==='a'&&!s.linked){const scale=fine?10n:1n,den=s.a.den*scale;let n=s.a.num*scale+BigInt(steps)*s.a.den;if(n<0n)n=0n;if(n>MAX*den)n=MAX*den;value=format(n,den);}
 else {let n=(s.linked?BigInt(s.a.text):s[f])+BigInt(steps);if(n>MAX)n=MAX;if(n<(s.linked?0n:-MAX))n=s.linked?0n:-MAX;value=String(n);}
 apply(s,f,value);render();const changed=before!==textValue(f);pendingRoll=pendingRoll||changed;return changed;}
 function schedule(){clearTimeout(settle);settle=setTimeout(()=>{settle=0;if(!motions.size&&pendingRoll){pendingRoll=false;reward('roll');}},180);}
 F.forEach(f=>{const b=el('button','fs-roll',undefined,row),label=el('span','fs-label','',b),value=el('span','fs-value','',b),result=el('span','fs-result','',b),goalBox=el('span','fs-goal','',b),light=el('span','fs-light','',goalBox),goal=el('span','','',goalBox);b.setAttribute('aria-label',f==='a'?'Distance cube-root input':f==='b'?'Turn MOD input':'Height MOD input');rollers[f]={box:b,label,valu  … [line shortened here: 421 characters; full line on GitHub]
 on(b,'focus',()=>{if(selected!==f){draft=null;dirty=false;}selected=f;render();});on(b,'wheel',e=>{e.preventDefault();if(!e.deltaY)return;stop();if(roll(f,e.deltaY<0?1:-1))schedule();},{passive:false});
 on(b,'pointerdown',e=>{unlock();e.preventDefault();clearTimeout(settle);selected=f;draft=null;dirty=false;b.setPointerCapture(e.pointerId);motions.set(e.pointerId,{f,y:e.clientY,start:e.clientY,t:performance.now(),last:performance.now(),v:0,carry:0,moved:false,held:false});render();});
 on(b,'pointermove',e=>{const m=motions.get(e.pointerId);if(!m)return;const now=performance.now(),dy=m.y-e.clientY,dt=Math.max(1,now-m.last);m.v=dy/dt;m.carry+=dy;m.moved=m.moved||Math.abs(e.clientY-m.start)>5;m.held=m.held||now-m.last>=2000;const n=Math.trunc(m.carry/14);if(n){m.changed=roll(f,n,m.held)||m.changed;m.carry-=n*14;}m.last=now;m.y=e.clientY;});
 on(b,'pointerup',e=>{const m=motions.get(e.pointerId);if(!m)return;motions.delete(e.pointerId);const age=performance.now()-m.last;if(!m.moved&&performance.now()-m.t<450&&!pendingRoll){edit(f);return;}if(age<120&&Math.abs(m.v)>.45){m.inertia=true;m.v*=18;m.last=performance.now();motions.set(e.pointerId,m);}else if(pendingRoll&&!motions.size)schedule();});
 on(b,'pointercancel',e=>{motions.delete(e.pointerId);clearTimeout(settle);pendingRoll=false;});
 on(b,'lostpointercapture',e=>{const m=motions.get(e.pointerId);if(m&&!m.inertia){motions.delete(e.pointerId);clearTimeout(settle);pendingRoll=false;}});
 on(b,'click',e=>{if(e.detail===0)edit(f);});
 });
 ['7','8','9','Backspace','4','5','6','C','1','2','3','-','0','.','OK'].forEach(k=>{const b=el('button','',k==='Backspace'?'⌫':k,pad);if(k==='OK')b.style.gridColumn='span 2';on(b,'click',()=>key(k));});
 on(menu,'click',()=>{stop();box.classList.toggle('menu-open');render();});
 on(root,'keydown',e=>{if(e.ctrlKey||e.metaKey||e.altKey)return;if(e.key.length===1||['Enter','Escape','ArrowUp','ArrowDown','Backspace'].includes(e.key)){e.preventDefault();key(e.key);}});
 on(box,'touchmove',e=>e.preventDefault(),{passive:false});
 on(root,'blur',()=>{stop();draft=null;dirty=false;render();});
 on(canvas,'pointerdown',e=>{canvas.setPointerCapture(e.pointerId);drag={id:e.pointerId,x:e.clientX,y:e.clientY};});
 on(canvas,'pointermove',e=>{if(!drag||drag.id!==e.pointerId)return;yaw+=(e.clientX-drag.x)*.01;pitch=Math.max(-1.4,Math.min(1.4,pitch+(e.clientY-drag.y)*.01));drag.x=e.clientX;drag.y=e.clientY;});
 on(canvas,'pointerup',()=>{drag=null;});on(canvas,'pointercancel',()=>{drag=null;});
 function draw(time){if(dead)return;const dt=Math.min(40,Math.max(0,time-lastFrame));lastFrame=time;
 motions.forEach((m,id)=>{if(!m.inertia)return;m.carry+=m.v*dt/16;m.v*=Math.exp(-dt/140);const n=Math.trunc(m.carry/14);if(n){roll(m.f,n);m.carry-=n*14;}if(Math.abs(m.v)<.15){motions.delete(id);if(!motions.size)schedule();}});
 const rect=view.getBoundingClientRect(),w=Math.max(1,rect.width),h=Math.max(1,rect.height),dpr=Math.min(2,root.devicePixelRatio||1);if(canvas.width!==Math.round(w*dpr)||canvas.height!==Math.round(h*dpr)){canvas.width=Math.round(w*dpr);canvas.height=Math.round(h*dpr);}ctx.setTransform(dpr,0,0,dpr,0,0);ctx.clearRect(0,0,w,h);
 const show=preview()||s,p=pos(show),t=s.target,need=Math.max(p.radius,Math.cbrt(Number(decimal(t.a).num)/Number(decimal(t.a).den)),1)*1.06;viewScale=need>viewScale?need:viewScale+(need-viewScale)*Math.min(1,dt/100);const reserve=0,R=Math.max(10,Math.min(w-16,h-16)/2),cx=w/2,cy=reserve+(h-reserve)/2,sc=R/viewScale;
 function project(x,y,z){const X=x*Math.cos(yaw)-y*Math.sin(yaw),Y=x*Math.sin(yaw)+y*Math.cos(yaw);return [cx+X*sc,cy-(z*Math.cos(pitch)-Y*Math.sin(pitch))*sc];}
 function path(points,col,width=1,fill=false){ctx.beginPath();points.forEach((p,i)=>{const q=project(...p);if(i)ctx.lineTo(...q);else ctx.moveTo(...q);});ctx.strokeStyle=col;ctx.lineWidth=width;if(fill){ctx.closePath();ctx.fillStyle=fill;ctx.fill();}ctx.stroke();}
 function spherePoint(r,u,v){const z=1-2*v,q=Math.sqrt(Math.max(0,1-z*z));return [r*q*Math.cos(TAU*u),r*q*Math.sin(TAU*u),r*z];}
 function wire(r,col){if(s.shape==='cube'){const v=[];for(let i=0;i<8;i++)v.push([i&1?r/2:-r/2,i&2?r/2:-r/2,i&4?r/2:-r/2]);[[0,1],[1,3],[3,2],[2,0],[4,5],[5,7],[7,6],[6,4],[0,4],[1,5],[2,6],[3,7]].forEach(e=>path([v[e[0]],v[e[1]]],col));}else{for(let plane=0;plane<3;plane++){const pts=[];for(let i=0;i<=80;i++){const a=TAU*i/80,c=r*Math.cos(a),d=r*Math.sin(a);pts.push(plane===0?[c,d,0]:plane===1?[c  … [line shortened here: 433 characters; full line on GitHub]
 const lit=lights(t,p,s.c);wire(p.radius,'rgba(255,255,255,.22)');wire(Math.cbrt(Number(decimal(t.a).num)/Number(decimal(t.a).den)),lit[0]?'#8ce6ff':'rgba(255,209,154,.65)');
 if(s.shape==='sphere'){
 const pts=[],bins=Number(t.bins),u=Number(t.turn)/bins,v=Number(t.up)/bins,r=Math.cbrt(Number(decimal(t.a).num)/Number(decimal(t.a).den));
 for(let i=0;i<=12;i++)pts.push(spherePoint(r,u+i/12/bins,v));for(let i=0;i<=12;i++)pts.push(spherePoint(r,u+1/bins,v+i/12/bins));for(let i=12;i>=0;i--)pts.push(spherePoint(r,u+i/12/bins,v+1/bins));for(let i=12;i>=0;i--)pts.push(spherePoint(r,u,v+i/12/bins));path(pts,'#ffd19a',2,'rgba(255,209,154,.32)');
 const lat=[],lon=[];for(let i=0;i<=80;i++){lat.push(spherePoint(p.radius,i/80,p.v));lon.push(spherePoint(p.radius,p.u,i/80));}path(lat,lit[2]?'#8ce6ff':'rgba(255,255,255,.16)');path(lon,lit[1]?'#8ce6ff':'rgba(255,255,255,.16)');
 }else {const bins=Number(t.bins),u0=Number(t.turn)/bins,u1=(Number(t.turn)+1)/bins,v0=Number(t.up)/bins,v1=(Number(t.up)+1)/bins,r=Math.cbrt(Number(decimal(t.a).num)/Number(decimal(t.a).den));
 for(let face=0;face<6;face++){const col=face%3,row=Math.floor(face/3),lo=Math.max(u0,col/3),hi=Math.min(u1,(col+1)/3),bot=Math.max(v0,row/2),top=Math.min(v1,(row+1)/2);if(lo>=hi||bot>=top)continue;
 const pts=[[lo,bot],[hi,bot],[hi,top],[lo,top]].map(([u,v])=>{const A=r*(3*u-col-.5),B=r*(2*v-row-.5),H=r/2;return [[H,A,B],[-H,A,B],[A,H,B],[A,-H,B],[A,B,H],[A,B,-H]][face];});path(pts,'#ffd19a',2,'rgba(255,209,154,.32)');}}
 const xy=project(p.x,p.y,p.z);path([[0,0,0],[p.x,p.y,p.z]],'rgba(255,255,255,.35)');ctx.globalAlpha=draft===null?1:.55;const glow=ctx.createRadialGradient(...xy,1,...xy,18);glow.addColorStop(0,'#fff');glow.addColorStop(.2,'#8ce6ff');glow.addColorStop(1,'rgba(140,230,255,0)');ctx.fillStyle=glow;ctx.beginPath();ctx.arc(...xy,18,0,TAU);ctx.fill();ctx.globalAlpha=1;
 if(burst>0){ctx.strokeStyle='rgba(255,209,154,'+burst+')';ctx.lineWidth=2;for(let i=0;i<28;i++){const a=TAU*i/28,l=(1-burst)*R;ctx.beginPath();ctx.moveTo(xy[0]+Math.cos(a)*l,xy[1]+Math.sin(a)*l);ctx.lineTo(xy[0]+Math.cos(a)*(l+25),xy[1]+Math.sin(a)*(l+25));ctx.stroke();}burst=Math.max(0,burst-dt/900);}
 raf=requestAnimationFrame(draw);
 }
 function close(){if(dead)return;dead=true;stop();cancelAnimationFrame(raf);listeners.forEach(([e,t,fn,opt])=>e.removeEventListener(t,fn,opt));if(audio)audio.close();box.remove();style.remove();if(active===api)active=null;}
 const api={state:s,close,set:o=>{if(o.key!==undefined)api.setKey(o.key);if(o.G1!==undefined)s.g1=BigInt(o.G1);if(o.G2!==undefined)s.g2=BigInt(o.G2);next(s);render();},controls:{rollers,menu,pad,linked,shape,working,error,canvas,box,view},render,info:()=>({renderer:'canvas2d',drawn:1,scale:viewScale}),setKey:k=>{stop();const a=decimal(String(k)),n=integer(String(k));if(!a||n===null||n<0n)return fa  … [line shortened here: 573 characters; full line on GitHub]
 active=api;render();raf=requestAnimationFrame(draw);return api;
}
K.steering={MAX,icbrt,decimal,integer,rootLabel,divmod,point,pos,cell,lights,create,next,targetFor,apply,link,award};K.open=open;K.close=()=>active&&active.close();K.instance=()=>active;
if(typeof window==='object')(window.KGModules=window.KGModules||[]).push({id:'solid',label:'SPHERE',open,close:K.close});
})(typeof window==='object'?window:globalThis);