Ver Fonte

feat: 升级9维视线估计模型,新增EAR眨眼过滤和头部姿态估计

基于文献研究结论进行改造升级:
- 新增 EAR (Eye Aspect Ratio) 眨眼检测,阈值0.22,眨眼时orb保持位置不跳
- 新增几何头部姿态估计 (pitch/yaw),用鼻尖相对眼角/前额/下巴偏移计算
- 回归模型从6维 [1,rX,rY,rX²,rY²,rXrY] 扩展为9维 [1,rX,rY,ear,pitch,yaw,rX²,rY²,rXrY]
- OLS求解器从Cramer法则升级为高斯消元法(solveNxN),支持任意维度
- RANSAC异常检测新增EAR过滤,防止眨眼样本污染回归
- CAL_VERSION升级到4,旧6维系数自动失效
- 调试面板新增EAR/blink/pitch/yaw实时显示
- 眨眼时orb视觉变暗+暖色调反馈
- 新增研究文档 docs/research-eye-features-and-gaze.md

涉及文件:config.js gaze.js math.js calibration.js renderer.js index.html
root há 5 meses atrás
pai
commit
e1c9c57b67
11 ficheiros alterados com 2796 adições e 1944 exclusões
  1. 498 0
      css/style.css
  2. 297 0
      docs/research-eye-features-and-gaze.md
  3. 10 1944
      index.html
  4. 444 0
      js/calibration.js
  5. 93 0
      js/config.js
  6. 351 0
      js/gaze.js
  7. 121 0
      js/kalman.js
  8. 330 0
      js/main.js
  9. 273 0
      js/math.js
  10. 298 0
      js/renderer.js
  11. 81 0
      js/utils.js

+ 498 - 0
css/style.css

@@ -0,0 +1,498 @@
+:root {
+    --bg: #0a0a1a;
+    --grid: rgba(0, 255, 255, 0.04);
+    --cyan: #00e5ff;
+    --cyan-dim: #00b8d4;
+    --text: #e0f7fa;
+    --text-dim: #80deea;
+    --danger: #ff5252;
+    --ok: #00e676;
+    --warn: #ffb74d;
+    --panel: rgba(10, 20, 40, 0.55);
+    --panel-border: rgba(0, 229, 255, 0.35);
+  }
+
+  * { box-sizing: border-box; margin: 0; padding: 0; }
+
+  html, body {
+    width: 100%;
+    height: 100%;
+    overflow: hidden;
+    background: var(--bg);
+    color: var(--text);
+    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "SF Mono", "Roboto Mono", Menlo, Consolas, monospace;
+    -webkit-font-smoothing: antialiased;
+    user-select: none;
+  }
+
+  body {
+    background-color: var(--bg);
+    background-image:
+      linear-gradient(var(--grid) 1px, transparent 1px),
+      linear-gradient(90deg, var(--grid) 1px, transparent 1px);
+    background-size: 40px 40px;
+    background-position: -1px -1px;
+  }
+
+  /* Subtle radial vignette */
+  body::before {
+    content: "";
+    position: fixed;
+    inset: 0;
+    pointer-events: none;
+    background: radial-gradient(ellipse at center, transparent 0%, rgba(0,0,0,0.6) 100%);
+    z-index: 1;
+  }
+
+  #stage {
+    position: fixed;
+    inset: 0;
+    z-index: 2;
+    cursor: crosshair;
+  }
+
+  /* ---------- Webcam preview ---------- */
+  #preview-wrap {
+    position: fixed;
+    left: 24px;
+    bottom: 64px;
+    width: 240px;
+    height: 180px;
+    border-radius: 14px;
+    overflow: hidden;
+    background: #000;
+    border: 1px solid var(--panel-border);
+    box-shadow:
+      0 0 0 1px rgba(0, 229, 255, 0.08) inset,
+      0 8px 32px rgba(0, 229, 255, 0.12),
+      0 2px 8px rgba(0, 0, 0, 0.6);
+    z-index: 10;
+    backdrop-filter: blur(4px);
+  }
+
+  #preview-wrap::before {
+    content: "LIVE · IRIS";
+    position: absolute;
+    top: 8px;
+    left: 10px;
+    font-size: 10px;
+    letter-spacing: 0.15em;
+    color: var(--cyan);
+    text-shadow: 0 0 8px rgba(0, 229, 255, 0.7);
+    z-index: 12;
+    pointer-events: none;
+  }
+
+  #preview-wrap::after {
+    content: "";
+    position: absolute;
+    inset: 0;
+    border-radius: 14px;
+    pointer-events: none;
+    box-shadow: 0 0 24px rgba(0, 229, 255, 0.18) inset;
+    z-index: 11;
+  }
+
+  #webcam, #overlay {
+    position: absolute;
+    inset: 0;
+    width: 100%;
+    height: 100%;
+  }
+
+  #webcam {
+    object-fit: cover;
+    transform: scaleX(-1); /* mirrored */
+    z-index: 1;
+  }
+
+  #overlay {
+    z-index: 2;
+    pointer-events: none;
+  }
+
+  /* ---------- Status bar ---------- */
+  #status-bar {
+    position: fixed;
+    left: 0;
+    right: 0;
+    bottom: 0;
+    height: 48px;
+    display: flex;
+    align-items: center;
+    gap: 24px;
+    padding: 0 20px;
+    background: var(--panel);
+    border-top: 1px solid var(--panel-border);
+    backdrop-filter: blur(8px);
+    font-size: 12px;
+    letter-spacing: 0.05em;
+    z-index: 20;
+    color: var(--text-dim);
+  }
+
+  .stat {
+    display: flex;
+    align-items: center;
+    gap: 8px;
+  }
+
+  .stat .label {
+    color: rgba(128, 222, 234, 0.55);
+    text-transform: uppercase;
+    font-size: 10px;
+    letter-spacing: 0.18em;
+  }
+
+  .stat .value {
+    color: var(--cyan);
+    text-shadow: 0 0 8px rgba(0, 229, 255, 0.5);
+    font-variant-numeric: tabular-nums;
+    min-width: 60px;
+  }
+
+  .stat .value.ok { color: var(--ok); text-shadow: 0 0 8px rgba(0, 230, 118, 0.4); }
+  .stat .value.warn { color: #ffb74d; text-shadow: 0 0 8px rgba(255, 183, 77, 0.4); }
+  .stat .value.err { color: var(--danger); text-shadow: 0 0 8px rgba(255, 82, 82, 0.4); }
+
+  .dot {
+    width: 8px;
+    height: 8px;
+    border-radius: 50%;
+    background: var(--cyan-dim);
+    box-shadow: 0 0 8px var(--cyan-dim);
+    animation: pulse 1.6s ease-in-out infinite;
+  }
+  .dot.ok { background: var(--ok); box-shadow: 0 0 10px var(--ok); }
+  .dot.warn { background: #ffb74d; box-shadow: 0 0 10px #ffb74d; }
+  .dot.err { background: var(--danger); box-shadow: 0 0 10px var(--danger); animation: none; }
+
+  @keyframes pulse {
+    0%, 100% { opacity: 1; transform: scale(1); }
+    50% { opacity: 0.4; transform: scale(0.8); }
+  }
+
+  /* Small inline button (used for "Recalibrate" in the status bar) */
+  .btn-mini {
+    font-family: inherit;
+    font-size: 10px;
+    letter-spacing: 0.18em;
+    text-transform: uppercase;
+    color: var(--cyan);
+    background: transparent;
+    border: 1px solid var(--panel-border);
+    border-radius: 4px;
+    padding: 4px 10px;
+    cursor: pointer;
+    transition: background 0.2s, box-shadow 0.2s, color 0.2s;
+  }
+  .btn-mini:hover {
+    background: rgba(0, 229, 255, 0.1);
+    box-shadow: 0 0 10px rgba(0, 229, 255, 0.3);
+    color: #ffffff;
+  }
+  .btn-mini:disabled {
+    color: rgba(128, 222, 234, 0.35);
+    border-color: rgba(0, 229, 255, 0.15);
+    cursor: not-allowed;
+    background: transparent;
+    box-shadow: none;
+  }
+
+  /* ---------- Title ---------- */
+  #title {
+    position: fixed;
+    top: 18px;
+    left: 24px;
+    z-index: 15;
+    font-size: 11px;
+    letter-spacing: 0.3em;
+    color: rgba(0, 229, 255, 0.7);
+    text-shadow: 0 0 8px rgba(0, 229, 255, 0.4);
+  }
+  #title .accent { color: var(--cyan); }
+
+  /* ---------- Loading overlay ---------- */
+  #loader {
+    position: fixed;
+    inset: 0;
+    z-index: 100;
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+    justify-content: center;
+    gap: 28px;
+    background: rgba(10, 10, 26, 0.92);
+    backdrop-filter: blur(6px);
+    transition: opacity 0.5s ease, visibility 0.5s;
+  }
+  #loader.hidden {
+    opacity: 0;
+    visibility: hidden;
+  }
+
+  .spinner {
+    width: 64px;
+    height: 64px;
+    border: 2px solid rgba(0, 229, 255, 0.15);
+    border-top-color: var(--cyan);
+    border-right-color: var(--cyan);
+    border-radius: 50%;
+    animation: spin 1s linear infinite;
+    box-shadow: 0 0 24px rgba(0, 229, 255, 0.3);
+  }
+
+  @keyframes spin {
+    to { transform: rotate(360deg); }
+  }
+
+  .loader-text {
+    font-size: 12px;
+    letter-spacing: 0.4em;
+    text-transform: uppercase;
+    color: var(--cyan);
+    text-shadow: 0 0 10px rgba(0, 229, 255, 0.6);
+  }
+  .loader-sub {
+    font-size: 11px;
+    color: var(--text-dim);
+    letter-spacing: 0.15em;
+    max-width: 320px;
+    text-align: center;
+    line-height: 1.6;
+  }
+
+  /* ---------- Error overlay ---------- */
+  #error-overlay {
+    position: fixed;
+    inset: 0;
+    z-index: 90;
+    display: none;
+    flex-direction: column;
+    align-items: center;
+    justify-content: center;
+    gap: 18px;
+    background: rgba(10, 10, 26, 0.88);
+    backdrop-filter: blur(6px);
+    padding: 40px;
+    text-align: center;
+  }
+  #error-overlay.show { display: flex; }
+
+  #error-overlay .icon {
+    font-size: 48px;
+    filter: drop-shadow(0 0 12px rgba(255, 82, 82, 0.6));
+  }
+  #error-overlay h2 {
+    font-size: 18px;
+    letter-spacing: 0.15em;
+    color: var(--danger);
+    text-transform: uppercase;
+  }
+  #error-overlay p {
+    color: var(--text-dim);
+    font-size: 13px;
+    max-width: 520px;
+    line-height: 1.7;
+  }
+  #error-overlay button {
+    margin-top: 12px;
+    padding: 10px 24px;
+    background: transparent;
+    border: 1px solid var(--cyan);
+    color: var(--cyan);
+    font-family: inherit;
+    font-size: 12px;
+    letter-spacing: 0.2em;
+    text-transform: uppercase;
+    cursor: pointer;
+    border-radius: 6px;
+    transition: background 0.2s, box-shadow 0.2s;
+  }
+  #error-overlay button:hover {
+    background: rgba(0, 229, 255, 0.1);
+    box-shadow: 0 0 16px rgba(0, 229, 255, 0.3);
+  }
+
+  /* ---------- Debug panel (top-left, collapsible) ---------- */
+  #debug-panel {
+    position: fixed;
+    top: 48px;
+    left: 24px;
+    z-index: 30;
+    width: 260px;
+    max-width: calc(100vw - 48px);
+    background: var(--panel);
+    border: 1px solid var(--panel-border);
+    border-radius: 10px;
+    backdrop-filter: blur(8px);
+    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
+    font-size: 11px;
+    color: var(--text);
+    overflow: hidden;
+    transition: max-height 0.25s ease;
+  }
+  #debug-panel.collapsed { max-height: 32px; }
+  #debug-panel.expanded { max-height: 480px; }
+
+  #debug-header {
+    display: flex;
+    align-items: center;
+    justify-content: space-between;
+    padding: 8px 12px;
+    cursor: pointer;
+    user-select: none;
+    background: rgba(0, 229, 255, 0.06);
+    border-bottom: 1px solid var(--panel-border);
+    font-size: 10px;
+    letter-spacing: 0.2em;
+    text-transform: uppercase;
+    color: var(--cyan);
+  }
+  #debug-panel.collapsed #debug-body { display: none; }
+  #debug-panel.collapsed #debug-header { border-bottom: none; }
+  #debug-toggle {
+    font-family: inherit;
+    color: var(--cyan);
+    font-size: 14px;
+    line-height: 1;
+  }
+
+  #debug-body {
+    padding: 10px 12px 12px;
+    display: flex;
+    flex-direction: column;
+    gap: 6px;
+    max-height: 440px;
+    overflow-y: auto;
+  }
+
+  .dbg-row {
+    display: flex;
+    align-items: center;
+    justify-content: space-between;
+    gap: 8px;
+    font-size: 11px;
+    line-height: 1.4;
+    word-break: break-all;
+  }
+  .dbg-row .k {
+    color: rgba(128, 222, 234, 0.7);
+    text-transform: uppercase;
+    letter-spacing: 0.1em;
+    font-size: 10px;
+    flex-shrink: 0;
+  }
+  .dbg-row .v {
+    color: var(--text);
+    text-align: right;
+    font-variant-numeric: tabular-nums;
+  }
+  .dbg-row .v.ok   { color: var(--ok); }
+  .dbg-row .v.warn { color: #ffb74d; }
+  .dbg-row .v.err  { color: var(--danger); }
+  .dbg-row .v.run  { color: var(--cyan); }
+
+  #debug-err {
+    margin-top: 6px;
+    padding: 8px 10px;
+    background: rgba(255, 82, 82, 0.08);
+    border: 1px solid rgba(255, 82, 82, 0.35);
+    border-radius: 6px;
+    color: var(--danger);
+    font-size: 10px;
+    line-height: 1.5;
+    word-break: break-word;
+    display: none;
+    max-height: 120px;
+    overflow-y: auto;
+  }
+  #debug-err.show { display: block; }
+
+  /* ---------- Calibration overlay (9-point) ---------- */
+  #calibration-overlay {
+    position: fixed;
+    inset: 0;
+    z-index: 80;
+    display: none;
+    align-items: center;
+    justify-content: center;
+    background: rgba(10, 10, 26, 0.92);
+    backdrop-filter: blur(6px);
+  }
+  #calibration-overlay.show { display: flex; }
+
+  #cal-dot {
+    position: absolute;
+    width: 36px;
+    height: 36px;
+    margin-left: -18px;
+    margin-top: -18px;
+    border-radius: 50%;
+    background: radial-gradient(circle at center,
+      rgba(255, 255, 255, 1) 0%,
+      rgba(0, 229, 255, 1) 35%,
+      rgba(0, 229, 255, 0.6) 65%,
+      rgba(0, 229, 255, 0) 100%);
+    box-shadow:
+      0 0 24px rgba(0, 229, 255, 0.9),
+      0 0 60px rgba(0, 229, 255, 0.5);
+    animation: calPulse 1s ease-in-out infinite;
+    pointer-events: none;
+    transform-origin: center;
+  }
+  #cal-dot::after {
+    content: "";
+    position: absolute;
+    inset: 12px;
+    border-radius: 50%;
+    border: 2px solid rgba(0, 229, 255, 0.6);
+  }
+  @keyframes calPulse {
+    0%, 100% { transform: scale(1);   opacity: 1; }
+    50%      { transform: scale(1.3); opacity: 0.7; }
+  }
+
+  #cal-text {
+    position: absolute;
+    top: 32px;
+    left: 50%;
+    transform: translateX(-50%);
+    font-size: 13px;
+    letter-spacing: 0.3em;
+    text-transform: uppercase;
+    color: var(--cyan);
+    text-shadow: 0 0 10px rgba(0, 229, 255, 0.7);
+    text-align: center;
+    pointer-events: none;
+  }
+  #cal-sub {
+    position: absolute;
+    top: 58px;
+    left: 50%;
+    transform: translateX(-50%);
+    font-size: 10px;
+    letter-spacing: 0.2em;
+    color: var(--text-dim);
+    text-align: center;
+    pointer-events: none;
+  }
+  #cal-cancel {
+    position: absolute;
+    bottom: 32px;
+    left: 50%;
+    transform: translateX(-50%);
+  }
+
+  /* Faint preview ghost dots for upcoming calibration points */
+  .cal-ghost {
+    position: absolute;
+    width: 14px;
+    height: 14px;
+    margin-left: -7px;
+    margin-top: -7px;
+    border-radius: 50%;
+    border: 1px solid rgba(0, 229, 255, 0.25);
+    background: rgba(0, 229, 255, 0.05);
+    pointer-events: none;
+  }

+ 297 - 0
docs/research-eye-features-and-gaze.md

@@ -0,0 +1,297 @@
+# 视线追踪研究笔记:眼部特征与注视方向的关系
+
+> 整理日期: 2026-06-19
+> 来源: arXiv 论文 + PubMed/PMC + Google Scholar + GitHub,附引用链接
+
+---
+
+## 一、核心发现汇总
+
+### 眼球转动时眼睛外观会变化(多项研究证实)
+
+1. **虹膜位置变化** — 直接反映注视方向(最核心信号)
+2. **眼睑位置/形状变化** — 上眼睑随眼球上下运动而升降,下眼睑基本不动
+3. **睑裂(palpebral fissure)尺寸变化** — 向上看时纵向增宽,向下看时纵向变窄
+4. **眼白(sclera)暴露变化** — 注视方向改变时眼白分布不对称
+
+### 各方向对眼部外观的影响(有量化数据支持)
+
+| 注视方向 | 睑裂高度 | 眼睛开合度(EAR) | 上眼睑位置 | 下眼睑位置 |
+|----------|---------|----------------|-----------|-----------|
+| 向上看 | 增大 | 增大 | 抬高 | 基本不变 |
+| 正前方 | 基准 | 基准 | 基准 | 基准 |
+| 向下看 | 减小 | 减小 | 下降 | 基本不变 |
+
+---
+
+## 二、量化数据(来自实验研究)
+
+### 2.1 睑裂高度随注视方向变化
+
+**来源: Read, Collins, Carney, Iskander (2006)**
+"The morphology of the palpebral fissure in different directions of vertical gaze"
+Optometry and Vision Science, 83(10):715-22
+PMID: 17041316
+
+**实验**: 76名年轻受试者,在正视(+0°)、下视20°、下视40°三个条件下拍摄高分辨率数字照片,测量睑裂形态。
+
+**关键数据**:
+- 正视时纵向睑裂宽度(白色受试者): **9.7 ± 1.2 mm**
+- 下视40°时: **6.4 ± 1.1 mm**
+- **下视40°时睑裂高度减少约 34%**
+- 正视时水平睑裂宽度: **27.1 ± 1.5 mm**
+- 下视40°时: **25.6 ± 1.8 mm**
+- 睑裂角度随下视增大而更加"下倾斜"
+
+**结论**: "Highly significant changes to the palpebral fissure dimensions occur in downward vertical gaze."
+
+---
+
+### 2.2 眼睛开合度随垂直眼位的量化变化
+
+**来源: Culemann, Hooge, Niehorster, Heine, Nyström (2026)**
+"Blink parameters are confounded by vertical eye orientation in video-based eye tracking"
+Behavior Research Methods, 58(4):89
+DOI: 10.3758/s13428-026-02984-4
+PMC: PMC13004733
+
+**实验**: 17名受试者,在三个垂直眼位(上视+15°、微下视-5°、下视-15°)进行自愿眨眼,用视频法同时测量瞳孔直径和眼睛开合度。
+
+**关键数据**:
+- **上视时眼睛开合度**: 12.0 mm
+- **微下视时**: 减少 0.5 mm(p < 0.001)
+- **下视时**: 减少 1.5 mm(p < 0.001)
+- 眨眼持续时间:上视到下视变化 8%(基于眼睑法)到 32%(基于瞳孔法)
+- 上视时闭合幅度更大、闭合速度更快、持续时间更短
+- 下视时闭合幅度更小、张开速度更慢、持续时间更长
+
+**原文**:
+> "Eye openness at blink onset and closing amplitude decreased with downward eye orientation. With more downward eye orientation, closing velocity increased, whereas opening velocity decreased."
+
+> "Stern et al. (1984) described that upward eye orientation can increase blink amplitude due to the elevated starting position of the upper eyelid, while downward eye orientation may attenuate blink amplitude."
+
+> "Compared to upward eye orientation (12.0 mm), openness was reduced by 0.5 mm at slightly downward (p < 0.001) and by 1.5 mm at downward eye orientation (p < 0.001)."
+
+---
+
+### 2.3 眼睑运动的生理基础
+
+**来源: Gandhi, Katnani, Liversedge et al. (2011)**
+"Interactions of eye and eyelid movements"
+Oxford Handbook of Eye Movements
+
+**关键发现**:
+> "the levator palpebrae (LP) muscle contracts and raises the upper eyelid" during upward vertical movements
+
+> "the position of the upper eyelid is yoked primarily to the vertical component of the eye movement"
+
+**来源: Helmchen, Rambold (2007)**
+"The eyelid and its contribution to eye movements"
+Developments in Ophthalmology
+
+> "Although the position of the upper eyelid is actively controlled by several muscles, eyelid [movement] during vertical eye movement"
+
+**来源: VanderWerf, Brassinga, Reits et al. (2003)**
+"Eyelid movements: behavioral studies of blinking in humans under different stimulus conditions"
+Journal of Neurophysiology, 89(4)
+DOI: 10.1152/jn.00557.2002
+
+**关键数据**:
+- 用磁搜索线圈测量眼睑运动
+- 上视导致更大的闭合幅度、更短的眨眼持续时间和更高的最大闭合速度
+- 下视产生更慢、更长的眨眼,振幅减小
+
+---
+
+### 2.4 眼球运动范围与注视方向
+
+**来源: Lee, Kim, Shin, Hwang, Lim (2019)**
+"Differences in eye movement range based on age and gaze direction"
+Eye (London), 33:1145-1151
+Nature.com
+
+**实验**: 261名健康受试者(5-91岁),拍摄各注视方向的照片,用改良 limbus test 量化眼球运动角度。
+
+**关键发现**:
+- 水平和垂直注视方向的眼球运动范围存在显著差异
+- 年龄对运动范围有显著影响
+- 测量方法(VOG vs 摄影法)会因眼睑干扰产生差异
+
+---
+
+## 三、计算机视觉方向的研究
+
+### 3.1 特征重要性评估(最新)
+
+**来源: Agostinelli et al. (2025)**
+"Is Geometry Enough? An Evaluation of Landmark-Based Gaze Estimation"
+arXiv:2603.24724
+
+**特征分组与重要性**:
+
+| 特征组 | 内容 | MediaPipe 索引 |
+|--------|------|---------------|
+| Iris | 瞳孔中心 + 虹膜轮廓极值点 | 右: 473-477, 左: 468-472 |
+| Eye contour | 眼睑极值 + 眼角 | 右: 263,362,374,386; 左: 33,133,145,159 |
+| Head anchor | 鼻尖 + 眉心 | 1, 9 |
+| Relative position | 左右眼相对位置向量 | 计算值 |
+
+**各数据集上的特征重要性排名**:
+
+| 数据集 | 最重要 | 次要 |
+|--------|--------|------|
+| GazeGene | Head anchor | Iris(偏右眼) |
+| ETH-XGaze | Iris + Eye contour 并列 | Head anchor |
+| Gaze360 | Eye contour | Iris |
+
+**核心结论**: 仅用 20 个关键点的轻量 MLP 模型,跨数据集泛化能力与 ResNet18 相当。Eye contour(眼廓/眼睑)在多个数据集中都是最重要的特征之一。
+
+---
+
+### 3.2 Appearance-based 综述
+
+**来源: Zhang et al. (2021)**
+"Appearance-based Gaze Estimation With Deep Learning: A Review and Benchmark" (GazeHub)
+arXiv:2104.12668
+
+原文:
+> "Human gaze has a strong correlation with eye appearance. Even a minor perturbation in gaze direction can result in noticeable changes in eye appearance. For instance, when the eyeball rotates, the position of the iris and the shape of the eyelid undergo alterations, leading to corresponding changes in gaze direction."
+
+---
+
+### 3.3 几何方法精度
+
+**来源: Kletsi et al. (2024)**
+"Low-cost Geometry-based Eye Gaze Detection using Facial Landmarks"
+arXiv:2401.00406
+
+> "angular error of less than 1.9 degrees, rivaling state-of-the-art systems while operating in real-time and requiring negligible computational resources"
+
+用深度学习生成 3D 关键点,提取 8 维几何描述子,线性方程预测视线方向。
+
+---
+
+### 3.4 眼廓关键点直接利用
+
+**来源: Li et al. (2021)**
+"FLAME: Facial Landmark Heatmap Activated Multimodal Gaze Estimation"
+arXiv:2110.04828
+
+用眼 landmark heatmap 提取眼部解剖信息(包括眼睑),在 ColumbiaGaze 和 EYEDIAP 上比基线提升约 10%,无需个人校准。
+
+---
+
+### 3.5 差分方法与眼睑干扰
+
+**来源: Shafi et al. (2019)**
+"A Differential Approach for Gaze Estimation"
+arXiv:1904.09459
+
+> "by allowing the comparison between two eye images, annoyance factors (alignment, eyelid closing, illumination perturbations) which usually plague single image prediction methods can be much reduced"
+
+眼睑开合被列为影响视线估计的主要干扰因素之一。
+
+---
+
+### 3.6 眼动追踪模拟中的眼睑模型
+
+**来源: Salari, Niehorster, Hansen et al. (2026)**
+"PyEtSimul: An Open-Source Python Framework for Eye-Tracking Simulation"
+ACM Proceedings
+
+> "by upper eyelid motion while the lower eyelid remains" "edge position is fixed and only the upper eyelid position"
+
+模拟框架中明确建模了上眼睑随视线方向运动、下眼睑位置固定的特征。
+
+---
+
+### 3.7 图形学中的视线重定向
+
+**来源: Wood, Baltrusaitis, Morency et al. (2018)**
+"Gazedirector: Fully articulated eye gaze redirection in video"
+Computer Graphics Forum, Wiley
+DOI: 10.1111/cgf.13355
+
+> "these methods do not move the eyelids – an important cue for vertical gaze"
+
+> "The eyelids follow eye gaze, so if the eyeball [rotates], the eyelids [move] accordingly"
+
+图形学视角直接确认了眼睑是垂直视线的重要线索。
+
+---
+
+## 四、开源工程参考
+
+### GitHub 项目
+
+| 项目 | Stars | 描述 | 链接 |
+|------|-------|------|------|
+| WebGazer.js | 3,862 | 浏览器端可扩展摄像头视线追踪 | https://github.com/brownhci/WebGazer |
+| GazeService | 4 | MediaPipe + FastAPI 实时视线追踪与 3D 空间定位服务 | https://github.com/wulongovo/GazeService |
+| LandmarkGaze | - | Landmark-based gaze estimation 代码(与论文配套) | https://github.com/daniele-agostinelli/LandmarkGaze |
+
+### GazeService 技术细节(中文项目)
+- 基于 MediaPipe FaceLandmarker(478个关键点 + 虹膜)
+- FastAPI REST API 输出: 视线方向、头部姿态(Pitch/Yaw/Roll)、3D空间坐标、屏幕注视点
+- 虹膜中心定位 + 视线方向计算
+
+---
+
+## 五、标注数据集
+
+| 数据集 | 规模 | 标注内容 | 论文 |
+|--------|------|----------|------|
+| TEyeD | 2000万+张 | 瞳孔/眼睑/虹膜 2D+3D 分割、3D 眼球、视线向量 | arXiv:2102.02115 |
+| MPIIGaze | 213,659张 | 全脸 + 屏幕坐标 | arXiv:1711.09017 |
+| ETH-XGaze | 大规模 | 高精度像素级标注 | GazeHub |
+| Gaze360 | 全方向 | 360度视线 | GazeHub |
+| GazeGene | 合成数据 | 多样化生成 | arXiv:2603.24724 |
+| ColumbiaGaze | - | 标准基准 | arXiv:2110.04828 |
+| EYEDIAP | - | 标准基准 | arXiv:2110.04828 |
+
+TEyeD 下载: https://es-cloud.cs.uni-tuebingen.de/d/8e2ab8c3fdd444e1a135/?p=%2FTEyeDS&mode=list
+
+---
+
+## 六、对本项目(eye-tracking-demo)的启示
+
+### 当前项目使用的特征
+`gaze.js` 使用虹膜位置计算 ratioX/ratioY — 这是论文验证过的最有效特征。
+
+### 可以考虑增加的特征
+
+1. **眼廓关键点** — "Is Geometry Enough?" 证明 eye contour 与 iris 一样重要,MediaPipe 已提供
+2. **上眼睑位置作为垂直辅助信号** — Read 2006 证明睑裂高度变化可达 34%,Culemann 2026 量化了 12.0mm→10.5mm 的变化
+3. **头部姿态** — 所有关键论文都包含
+4. **EAR 作为数据质量过滤器** — 向下看时 EAR 减小可能误判为眨眼
+
+### 已验证的精度参考
+- 仅关键点 MLP: 接近 ResNet18 级别(跨数据集)
+- 几何方法 + 线性方程: < 1.9度角误差(2024)
+- 差分方法: 减少个体差异(2019)
+
+---
+
+## 七、参考文献
+
+### 生理学/眼科学方向
+1. Read SA, Collins MJ, Carney LG, Iskander DR. "The morphology of the palpebral fissure in different directions of vertical gaze." Optom Vis Sci, 83(10):715-22, 2006. PMID: 17041316
+2. Culemann W, Hooge ITC, Niehorster DC, Heine A, Nyström M. "Blink parameters are confounded by vertical eye orientation in video-based eye tracking." Behav Res Methods, 58(4):89, 2026. DOI: 10.3758/s13428-026-02984-4 / PMC: PMC13004733
+3. VanderWerf F, Brassinga P, Reits D, Aramideh M, Ongerboer de Visser B. "Eyelid movements: behavioral studies of blinking in humans under different stimulus conditions." J Neurophysiol, 89(4), 2003. DOI: 10.1152/jn.00557.2002
+4. Gandhi NJ, Katnani HA, Liversedge SP. "Interactions of eye and eyelid movements." Oxford Handbook of Eye Movements, 2011.
+5. Helmchen C, Rambold H. "The eyelid and its contribution to eye movements." Dev Ophthalmol, 2007.
+6. Lee WJ, Kim JH, Shin YU, Hwang S, Lim HW. "Differences in eye movement range based on age and gaze direction." Eye, 33:1145-1151, 2019. Nature.com
+7. Pansell T, Porsblad M, Abdi S. "The effect of vertical gaze position on ocular tear film stability." Clin Exp Optom, 2007.
+8. Stern JA, Walrath LC, Goldstein R. "The endogenous eyeblink." Psychophysiology, 21(1):22-33, 1984.
+
+### 计算机视觉/机器学习方向
+9. Zhang X, et al. "Appearance-based Gaze Estimation With Deep Learning: A Review and Benchmark." arXiv:2104.12668 (2021).
+10. Agostinelli D, et al. "Is Geometry Enough? An Evaluation of Landmark-Based Gaze Estimation." arXiv:2603.24724 (2025).
+11. Kletsi D, et al. "Low-cost Geometry-based Eye Gaze Detection using Facial Landmarks." arXiv:2401.00406 (2024).
+12. Shafi A, et al. "A Differential Approach for Gaze Estimation." arXiv:1904.09459 (2019).
+13. Li M, et al. "FLAME: Facial Landmark Heatmap Activated Multimodal Gaze Estimation." arXiv:2110.04828 (2021).
+14. Fuhl W, et al. "TEyeD: Over 20 million real-world eye images..." arXiv:2102.02115 (2021).
+15. Zhang X, et al. "MPIIGaze: Real-World Dataset and Deep Appearance-Based Gaze Estimation." arXiv:1711.09017 (2017).
+16. Salari M, Niehorster DC, Hansen DW, et al. "PyEtSimul: An Open-Source Python Framework for Eye-Tracking Simulation." ACM Proceedings, 2026.
+17. Wood E, Baltrusaitis T, Morency LP, et al. "Gazedirector: Fully articulated eye gaze redirection in video." Computer Graphics Forum, 2018. DOI: 10.1111/cgf.13355
+18. Soukupova T, Cech J. "Real-Time Eye Blink Detection Using Facial Landmarks." ECML PKDD, 2016.

+ 10 - 1944
index.html

@@ -4,506 +4,7 @@
 <meta charset="UTF-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 <title>Eye Tracking Demo · MediaPipe Iris</title>
-<style>
-  :root {
-    --bg: #0a0a1a;
-    --grid: rgba(0, 255, 255, 0.04);
-    --cyan: #00e5ff;
-    --cyan-dim: #00b8d4;
-    --text: #e0f7fa;
-    --text-dim: #80deea;
-    --danger: #ff5252;
-    --ok: #00e676;
-    --warn: #ffb74d;
-    --panel: rgba(10, 20, 40, 0.55);
-    --panel-border: rgba(0, 229, 255, 0.35);
-  }
-
-  * { box-sizing: border-box; margin: 0; padding: 0; }
-
-  html, body {
-    width: 100%;
-    height: 100%;
-    overflow: hidden;
-    background: var(--bg);
-    color: var(--text);
-    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "SF Mono", "Roboto Mono", Menlo, Consolas, monospace;
-    -webkit-font-smoothing: antialiased;
-    user-select: none;
-  }
-
-  body {
-    background-color: var(--bg);
-    background-image:
-      linear-gradient(var(--grid) 1px, transparent 1px),
-      linear-gradient(90deg, var(--grid) 1px, transparent 1px);
-    background-size: 40px 40px;
-    background-position: -1px -1px;
-  }
-
-  /* Subtle radial vignette */
-  body::before {
-    content: "";
-    position: fixed;
-    inset: 0;
-    pointer-events: none;
-    background: radial-gradient(ellipse at center, transparent 0%, rgba(0,0,0,0.6) 100%);
-    z-index: 1;
-  }
-
-  #stage {
-    position: fixed;
-    inset: 0;
-    z-index: 2;
-    cursor: crosshair;
-  }
-
-  /* ---------- Webcam preview ---------- */
-  #preview-wrap {
-    position: fixed;
-    left: 24px;
-    bottom: 64px;
-    width: 240px;
-    height: 180px;
-    border-radius: 14px;
-    overflow: hidden;
-    background: #000;
-    border: 1px solid var(--panel-border);
-    box-shadow:
-      0 0 0 1px rgba(0, 229, 255, 0.08) inset,
-      0 8px 32px rgba(0, 229, 255, 0.12),
-      0 2px 8px rgba(0, 0, 0, 0.6);
-    z-index: 10;
-    backdrop-filter: blur(4px);
-  }
-
-  #preview-wrap::before {
-    content: "LIVE · IRIS";
-    position: absolute;
-    top: 8px;
-    left: 10px;
-    font-size: 10px;
-    letter-spacing: 0.15em;
-    color: var(--cyan);
-    text-shadow: 0 0 8px rgba(0, 229, 255, 0.7);
-    z-index: 12;
-    pointer-events: none;
-  }
-
-  #preview-wrap::after {
-    content: "";
-    position: absolute;
-    inset: 0;
-    border-radius: 14px;
-    pointer-events: none;
-    box-shadow: 0 0 24px rgba(0, 229, 255, 0.18) inset;
-    z-index: 11;
-  }
-
-  #webcam, #overlay {
-    position: absolute;
-    inset: 0;
-    width: 100%;
-    height: 100%;
-  }
-
-  #webcam {
-    object-fit: cover;
-    transform: scaleX(-1); /* mirrored */
-    z-index: 1;
-  }
-
-  #overlay {
-    z-index: 2;
-    pointer-events: none;
-  }
-
-  /* ---------- Status bar ---------- */
-  #status-bar {
-    position: fixed;
-    left: 0;
-    right: 0;
-    bottom: 0;
-    height: 48px;
-    display: flex;
-    align-items: center;
-    gap: 24px;
-    padding: 0 20px;
-    background: var(--panel);
-    border-top: 1px solid var(--panel-border);
-    backdrop-filter: blur(8px);
-    font-size: 12px;
-    letter-spacing: 0.05em;
-    z-index: 20;
-    color: var(--text-dim);
-  }
-
-  .stat {
-    display: flex;
-    align-items: center;
-    gap: 8px;
-  }
-
-  .stat .label {
-    color: rgba(128, 222, 234, 0.55);
-    text-transform: uppercase;
-    font-size: 10px;
-    letter-spacing: 0.18em;
-  }
-
-  .stat .value {
-    color: var(--cyan);
-    text-shadow: 0 0 8px rgba(0, 229, 255, 0.5);
-    font-variant-numeric: tabular-nums;
-    min-width: 60px;
-  }
-
-  .stat .value.ok { color: var(--ok); text-shadow: 0 0 8px rgba(0, 230, 118, 0.4); }
-  .stat .value.warn { color: #ffb74d; text-shadow: 0 0 8px rgba(255, 183, 77, 0.4); }
-  .stat .value.err { color: var(--danger); text-shadow: 0 0 8px rgba(255, 82, 82, 0.4); }
-
-  .dot {
-    width: 8px;
-    height: 8px;
-    border-radius: 50%;
-    background: var(--cyan-dim);
-    box-shadow: 0 0 8px var(--cyan-dim);
-    animation: pulse 1.6s ease-in-out infinite;
-  }
-  .dot.ok { background: var(--ok); box-shadow: 0 0 10px var(--ok); }
-  .dot.warn { background: #ffb74d; box-shadow: 0 0 10px #ffb74d; }
-  .dot.err { background: var(--danger); box-shadow: 0 0 10px var(--danger); animation: none; }
-
-  @keyframes pulse {
-    0%, 100% { opacity: 1; transform: scale(1); }
-    50% { opacity: 0.4; transform: scale(0.8); }
-  }
-
-  /* Small inline button (used for "Recalibrate" in the status bar) */
-  .btn-mini {
-    font-family: inherit;
-    font-size: 10px;
-    letter-spacing: 0.18em;
-    text-transform: uppercase;
-    color: var(--cyan);
-    background: transparent;
-    border: 1px solid var(--panel-border);
-    border-radius: 4px;
-    padding: 4px 10px;
-    cursor: pointer;
-    transition: background 0.2s, box-shadow 0.2s, color 0.2s;
-  }
-  .btn-mini:hover {
-    background: rgba(0, 229, 255, 0.1);
-    box-shadow: 0 0 10px rgba(0, 229, 255, 0.3);
-    color: #ffffff;
-  }
-  .btn-mini:disabled {
-    color: rgba(128, 222, 234, 0.35);
-    border-color: rgba(0, 229, 255, 0.15);
-    cursor: not-allowed;
-    background: transparent;
-    box-shadow: none;
-  }
-
-  /* ---------- Title ---------- */
-  #title {
-    position: fixed;
-    top: 18px;
-    left: 24px;
-    z-index: 15;
-    font-size: 11px;
-    letter-spacing: 0.3em;
-    color: rgba(0, 229, 255, 0.7);
-    text-shadow: 0 0 8px rgba(0, 229, 255, 0.4);
-  }
-  #title .accent { color: var(--cyan); }
-
-  /* ---------- Loading overlay ---------- */
-  #loader {
-    position: fixed;
-    inset: 0;
-    z-index: 100;
-    display: flex;
-    flex-direction: column;
-    align-items: center;
-    justify-content: center;
-    gap: 28px;
-    background: rgba(10, 10, 26, 0.92);
-    backdrop-filter: blur(6px);
-    transition: opacity 0.5s ease, visibility 0.5s;
-  }
-  #loader.hidden {
-    opacity: 0;
-    visibility: hidden;
-  }
-
-  .spinner {
-    width: 64px;
-    height: 64px;
-    border: 2px solid rgba(0, 229, 255, 0.15);
-    border-top-color: var(--cyan);
-    border-right-color: var(--cyan);
-    border-radius: 50%;
-    animation: spin 1s linear infinite;
-    box-shadow: 0 0 24px rgba(0, 229, 255, 0.3);
-  }
-
-  @keyframes spin {
-    to { transform: rotate(360deg); }
-  }
-
-  .loader-text {
-    font-size: 12px;
-    letter-spacing: 0.4em;
-    text-transform: uppercase;
-    color: var(--cyan);
-    text-shadow: 0 0 10px rgba(0, 229, 255, 0.6);
-  }
-  .loader-sub {
-    font-size: 11px;
-    color: var(--text-dim);
-    letter-spacing: 0.15em;
-    max-width: 320px;
-    text-align: center;
-    line-height: 1.6;
-  }
-
-  /* ---------- Error overlay ---------- */
-  #error-overlay {
-    position: fixed;
-    inset: 0;
-    z-index: 90;
-    display: none;
-    flex-direction: column;
-    align-items: center;
-    justify-content: center;
-    gap: 18px;
-    background: rgba(10, 10, 26, 0.88);
-    backdrop-filter: blur(6px);
-    padding: 40px;
-    text-align: center;
-  }
-  #error-overlay.show { display: flex; }
-
-  #error-overlay .icon {
-    font-size: 48px;
-    filter: drop-shadow(0 0 12px rgba(255, 82, 82, 0.6));
-  }
-  #error-overlay h2 {
-    font-size: 18px;
-    letter-spacing: 0.15em;
-    color: var(--danger);
-    text-transform: uppercase;
-  }
-  #error-overlay p {
-    color: var(--text-dim);
-    font-size: 13px;
-    max-width: 520px;
-    line-height: 1.7;
-  }
-  #error-overlay button {
-    margin-top: 12px;
-    padding: 10px 24px;
-    background: transparent;
-    border: 1px solid var(--cyan);
-    color: var(--cyan);
-    font-family: inherit;
-    font-size: 12px;
-    letter-spacing: 0.2em;
-    text-transform: uppercase;
-    cursor: pointer;
-    border-radius: 6px;
-    transition: background 0.2s, box-shadow 0.2s;
-  }
-  #error-overlay button:hover {
-    background: rgba(0, 229, 255, 0.1);
-    box-shadow: 0 0 16px rgba(0, 229, 255, 0.3);
-  }
-
-  /* ---------- Debug panel (top-left, collapsible) ---------- */
-  #debug-panel {
-    position: fixed;
-    top: 48px;
-    left: 24px;
-    z-index: 30;
-    width: 260px;
-    max-width: calc(100vw - 48px);
-    background: var(--panel);
-    border: 1px solid var(--panel-border);
-    border-radius: 10px;
-    backdrop-filter: blur(8px);
-    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
-    font-size: 11px;
-    color: var(--text);
-    overflow: hidden;
-    transition: max-height 0.25s ease;
-  }
-  #debug-panel.collapsed { max-height: 32px; }
-  #debug-panel.expanded { max-height: 480px; }
-
-  #debug-header {
-    display: flex;
-    align-items: center;
-    justify-content: space-between;
-    padding: 8px 12px;
-    cursor: pointer;
-    user-select: none;
-    background: rgba(0, 229, 255, 0.06);
-    border-bottom: 1px solid var(--panel-border);
-    font-size: 10px;
-    letter-spacing: 0.2em;
-    text-transform: uppercase;
-    color: var(--cyan);
-  }
-  #debug-panel.collapsed #debug-body { display: none; }
-  #debug-panel.collapsed #debug-header { border-bottom: none; }
-  #debug-toggle {
-    font-family: inherit;
-    color: var(--cyan);
-    font-size: 14px;
-    line-height: 1;
-  }
-
-  #debug-body {
-    padding: 10px 12px 12px;
-    display: flex;
-    flex-direction: column;
-    gap: 6px;
-    max-height: 440px;
-    overflow-y: auto;
-  }
-
-  .dbg-row {
-    display: flex;
-    align-items: center;
-    justify-content: space-between;
-    gap: 8px;
-    font-size: 11px;
-    line-height: 1.4;
-    word-break: break-all;
-  }
-  .dbg-row .k {
-    color: rgba(128, 222, 234, 0.7);
-    text-transform: uppercase;
-    letter-spacing: 0.1em;
-    font-size: 10px;
-    flex-shrink: 0;
-  }
-  .dbg-row .v {
-    color: var(--text);
-    text-align: right;
-    font-variant-numeric: tabular-nums;
-  }
-  .dbg-row .v.ok   { color: var(--ok); }
-  .dbg-row .v.warn { color: #ffb74d; }
-  .dbg-row .v.err  { color: var(--danger); }
-  .dbg-row .v.run  { color: var(--cyan); }
-
-  #debug-err {
-    margin-top: 6px;
-    padding: 8px 10px;
-    background: rgba(255, 82, 82, 0.08);
-    border: 1px solid rgba(255, 82, 82, 0.35);
-    border-radius: 6px;
-    color: var(--danger);
-    font-size: 10px;
-    line-height: 1.5;
-    word-break: break-word;
-    display: none;
-    max-height: 120px;
-    overflow-y: auto;
-  }
-  #debug-err.show { display: block; }
-
-  /* ---------- Calibration overlay (9-point) ---------- */
-  #calibration-overlay {
-    position: fixed;
-    inset: 0;
-    z-index: 80;
-    display: none;
-    align-items: center;
-    justify-content: center;
-    background: rgba(10, 10, 26, 0.92);
-    backdrop-filter: blur(6px);
-  }
-  #calibration-overlay.show { display: flex; }
-
-  #cal-dot {
-    position: absolute;
-    width: 36px;
-    height: 36px;
-    margin-left: -18px;
-    margin-top: -18px;
-    border-radius: 50%;
-    background: radial-gradient(circle at center,
-      rgba(255, 255, 255, 1) 0%,
-      rgba(0, 229, 255, 1) 35%,
-      rgba(0, 229, 255, 0.6) 65%,
-      rgba(0, 229, 255, 0) 100%);
-    box-shadow:
-      0 0 24px rgba(0, 229, 255, 0.9),
-      0 0 60px rgba(0, 229, 255, 0.5);
-    animation: calPulse 1s ease-in-out infinite;
-    pointer-events: none;
-    transform-origin: center;
-  }
-  #cal-dot::after {
-    content: "";
-    position: absolute;
-    inset: 12px;
-    border-radius: 50%;
-    border: 2px solid rgba(0, 229, 255, 0.6);
-  }
-  @keyframes calPulse {
-    0%, 100% { transform: scale(1);   opacity: 1; }
-    50%      { transform: scale(1.3); opacity: 0.7; }
-  }
-
-  #cal-text {
-    position: absolute;
-    top: 32px;
-    left: 50%;
-    transform: translateX(-50%);
-    font-size: 13px;
-    letter-spacing: 0.3em;
-    text-transform: uppercase;
-    color: var(--cyan);
-    text-shadow: 0 0 10px rgba(0, 229, 255, 0.7);
-    text-align: center;
-    pointer-events: none;
-  }
-  #cal-sub {
-    position: absolute;
-    top: 58px;
-    left: 50%;
-    transform: translateX(-50%);
-    font-size: 10px;
-    letter-spacing: 0.2em;
-    color: var(--text-dim);
-    text-align: center;
-    pointer-events: none;
-  }
-  #cal-cancel {
-    position: absolute;
-    bottom: 32px;
-    left: 50%;
-    transform: translateX(-50%);
-  }
-
-  /* Faint preview ghost dots for upcoming calibration points */
-  .cal-ghost {
-    position: absolute;
-    width: 14px;
-    height: 14px;
-    margin-left: -7px;
-    margin-top: -7px;
-    border-radius: 50%;
-    border: 1px solid rgba(0, 229, 255, 0.25);
-    background: rgba(0, 229, 255, 0.05);
-    pointer-events: none;
-  }
-</style>
+<link rel="stylesheet" href="css/style.css">
 </head>
 <body>
 
@@ -574,6 +75,10 @@
     <div class="dbg-row"><span class="k">stage</span><span class="v" id="dbg-stage">…</span></div>
     <div class="dbg-row"><span class="k">calibration</span><span class="v" id="dbg-cal">…</span></div>
     <div class="dbg-row"><span class="k">frame ms</span><span class="v" id="dbg-frame">--</span></div>
+    <div class="dbg-row"><span class="k">EAR</span><span class="v" id="dbg-ear">--</span></div>
+    <div class="dbg-row"><span class="k">blink</span><span class="v" id="dbg-blink">--</span></div>
+    <div class="dbg-row"><span class="k">pitch</span><span class="v" id="dbg-pitch">--</span></div>
+    <div class="dbg-row"><span class="k">yaw</span><span class="v" id="dbg-yaw">--</span></div>
     <div class="dbg-row"><span class="k">downloaded</span><span class="v" id="dbg-bytes">0 KB</span></div>
     <div id="debug-err"></div>
   </div>
@@ -593,7 +98,8 @@
   <button class="btn-mini" id="cal-cancel">Cancel</button>
 </div>
 
-<!-- MediaPipe CDN -->
+<!-- MediaPipe CDN: these are UMD globals (window.FaceMesh / window.Camera / window.drawConnectors),
+     so they stay as classic <script> tags and are NOT imported as ES modules. -->
 <script>
   // Mark CDN load state on the global scope so the inline app can read it.
   window.__cdnStatus = window.__cdnStatus || {};
@@ -628,1447 +134,7 @@
         onload="__cdnOk('face_mesh')"
         onerror="__cdnErr('face_mesh', this.src)"></script>
 
-<script>
-(function () {
-  'use strict';
-
-  // ============================================================
-  //  Config
-  // ============================================================
-  const TRAIL_LENGTH = 30;            // # of trail points
-  const ORB_RADIUS = 40;              // px
-  const GRID_DRAW_INTERVAL_MS = 33;   // ~30fps redraw
-
-  // Kalman filter (replaces EMA + outlier threshold — Kalman handles noise naturally via R)
-  // No constant needed here; see kalUpdate / kalInit below.
-
-  // Calibration config
-  const CAL_SAMPLES_PER_POINT = 30;   // samples per point (first 3 are discarded)
-  const CAL_SAMPLE_INTERVAL_MS = 50; // ms between samples
-  const CAL_MARGIN = 0.15;            // 15% margin on each edge
-  const CAL_STORAGE_KEY = 'eye-tracking-calibration';
-  const CAL_VERSION = 2;  // bump when ratioY normalization or coef layout changes; old payloads are discarded
-
-  // Iris / eye landmark indices (MediaPipe Face Mesh)
-  // Left eye
-  const L_OUTER = 33,   L_INNER = 133;
-  const L_TOP   = 159,  L_BOT   = 145;
-  const L_IRIS  = 468;
-  // Right eye
-  const R_OUTER = 362,  R_INNER = 263;
-  const R_TOP   = 386,  R_BOT   = 374;
-  const R_IRIS  = 473;
-  // Iris contour points
-  const IRIS_LANDMARKS = [
-    468, 469, 470, 471, 472,   // left iris
-    473, 474, 475, 476, 477    // right iris
-  ];
-
-  // Face mesh tesselation connection subsets (subset of FACE_TESSELATION)
-  // Use eye / brow / lip / nose silhouettes to keep it light
-  const FACE_OVAL = [10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288, 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136, 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109];
-  const LIPS      = [61, 146, 91, 181, 84, 17, 314, 405, 321, 375, 291, 308, 324, 318, 402, 317, 14, 87, 178, 88, 95, 78];
-  const L_EYE     = [33, 7, 163, 144, 145, 153, 154, 155, 133, 173, 157, 158, 159, 160, 161, 246];
-  const R_EYE     = [362, 382, 381, 380, 374, 373, 390, 249, 263, 466, 388, 387, 386, 385, 384, 398];
-  const L_BROW    = [46, 53, 52, 65, 55, 107, 66, 105, 63, 70];
-  const R_BROW    = [276, 283, 282, 295, 285, 336, 296, 334, 293, 300];
-
-  // 13-point calibration grid (center + 4 corners + 4 edges + 4 mid-diagonal)
-  // The drawing is mirrored via CSS scaleX(-1), so these coords are
-  // intentionally in the *displayed* (mirrored) frame of reference.
-  // 5 rows × variable cols (5+3 cols) — center column used in rows 0,2,4 only.
-  const CAL_GRID = [
-    // row 0 (top)
-    { x: 0.1,                    y: 0.1                    }, // TL
-    { x: 0.5,                    y: 0.1                    }, // TM
-    { x: 0.9,                    y: 0.1                    }, // TR
-    // row 1 (upper mid)
-    { x: 0.1,                    y: 0.3                    }, // UL-mid
-    { x: 0.9,                    y: 0.3                    }, // UR-mid
-    // row 2 (middle)
-    { x: 0.1,                    y: 0.5                    }, // ML
-    { x: 0.5,                    y: 0.5                    }, // MM (center)
-    { x: 0.9,                    y: 0.5                    }, // MR
-    // row 3 (lower mid)
-    { x: 0.1,                    y: 0.7                    }, // LL-mid
-    { x: 0.9,                    y: 0.7                    }, // LR-mid
-    // row 4 (bottom)
-    { x: 0.1,                    y: 0.9                    }, // BL
-    { x: 0.5,                    y: 0.9                    }, // BM
-    { x: 0.9,                    y: 0.9                    }  // BR
-  ];
-  // Order: row-major traversal
-  const CAL_ORDER = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
-
-  // ============================================================
-  //  DOM
-  // ============================================================
-  const stage      = document.getElementById('stage');
-  const ctx        = stage.getContext('2d');
-  const video      = document.getElementById('webcam');
-  const overlay    = document.getElementById('overlay');
-  const octx       = overlay.getContext('2d');
-  const loader     = document.getElementById('loader');
-  const loaderText = document.getElementById('loader-text');
-  const loaderSub  = document.getElementById('loader-sub');
-  const errOverlay = document.getElementById('error-overlay');
-  const errTitle   = document.getElementById('err-title');
-  const errMsg     = document.getElementById('err-msg');
-  const errRetry   = document.getElementById('err-retry');
-  const statusDot  = document.getElementById('status-dot');
-  const statusText = document.getElementById('status-text');
-  const fpsEl      = document.getElementById('fps');
-  const gxEl       = document.getElementById('gaze-x');
-  const gyEl       = document.getElementById('gaze-y');
-  const ilEl       = document.getElementById('iris-l');
-  const irEl       = document.getElementById('iris-r');
-  const calDotStatus = document.getElementById('cal-dot-status');
-  const calStatusText = document.getElementById('cal-status-text');
-  const recalibrateBtn = document.getElementById('recalibrate-btn');
-
-  // Debug panel
-  const dbgPanel   = document.getElementById('debug-panel');
-  const dbgHeader  = document.getElementById('debug-header');
-  const dbgToggle  = document.getElementById('debug-toggle');
-  const dbgCdn1    = document.getElementById('dbg-cdn1');
-  const dbgCdn2    = document.getElementById('dbg-cdn2');
-  const dbgCdn3    = document.getElementById('dbg-cdn3');
-  const dbgModel   = document.getElementById('dbg-model');
-  const dbgCamera  = document.getElementById('dbg-camera');
-  const dbgStage   = document.getElementById('dbg-stage');
-  const dbgCal     = document.getElementById('dbg-cal');
-  const dbgFrame   = document.getElementById('dbg-frame');
-  const dbgBytes   = document.getElementById('dbg-bytes');
-  const dbgErr     = document.getElementById('debug-err');
-
-  // Calibration overlay
-  const calOverlay  = document.getElementById('calibration-overlay');
-  const calDot      = document.getElementById('cal-dot');
-  const calText     = document.getElementById('cal-text');
-  const calSub      = document.getElementById('cal-sub');
-  const calCancel   = document.getElementById('cal-cancel');
-
-  // ============================================================
-  //  Debug panel helpers
-  // ============================================================
-  function dbgSet(el, text, cls) {
-    if (!el) return;
-    el.textContent = text;
-    el.className = 'v' + (cls ? ' ' + cls : '');
-  }
-  function dbgSetError(msg) {
-    if (!dbgErr) return;
-    if (!msg) { dbgErr.classList.remove('show'); dbgErr.textContent = ''; return; }
-    dbgErr.textContent = msg;
-    dbgErr.classList.add('show');
-  }
-  if (dbgHeader) {
-    dbgHeader.addEventListener('click', () => {
-      const collapsed = dbgPanel.classList.toggle('collapsed');
-      dbgPanel.classList.toggle('expanded', !collapsed);
-      dbgToggle.textContent = collapsed ? '+' : '–';
-    });
-  }
-  // Initialize CDN cells from the global status that the loader scripts set
-  try {
-    const s = (window.__cdnStatus) || {};
-    dbgSet(dbgCdn1, s.camera_utils || (s.camera_utils === 'error' ? 'FAIL' : '…'),
-                  s.camera_utils === 'ok' ? 'ok' : s.camera_utils === 'error' ? 'err' : 'run');
-    dbgSet(dbgCdn2, s.drawing_utils || (s.drawing_utils === 'error' ? 'FAIL' : '…'),
-                  s.drawing_utils === 'ok' ? 'ok' : s.drawing_utils === 'error' ? 'err' : 'run');
-    dbgSet(dbgCdn3, s.face_mesh    || (s.face_mesh    === 'error' ? 'FAIL' : '…'),
-                  s.face_mesh    === 'ok' ? 'ok' : s.face_mesh    === 'error' ? 'err' : 'run');
-  } catch (e) { /* no-op */ }
-  // Live-update on CDN load / failure events
-  window.addEventListener('cdnOk', (e) => {
-    const n = e && e.detail && e.detail.name;
-    if (n === 'camera_utils') dbgSet(dbgCdn1, 'OK', 'ok');
-    if (n === 'drawing_utils') dbgSet(dbgCdn2, 'OK', 'ok');
-    if (n === 'face_mesh')    dbgSet(dbgCdn3, 'OK', 'ok');
-  });
-  window.addEventListener('cdnError', (e) => {
-    const n = e && e.detail && e.detail.name;
-    if (n === 'camera_utils') { dbgSet(dbgCdn1, 'FAIL', 'err'); dbgSetError('CDN camera_utils failed to load'); }
-    if (n === 'drawing_utils') { dbgSet(dbgCdn2, 'FAIL', 'err'); dbgSetError('CDN drawing_utils failed to load'); }
-    if (n === 'face_mesh')    { dbgSet(dbgCdn3, 'FAIL', 'err'); dbgSetError('CDN face_mesh failed to load'); }
-  });
-
-  function setLoaderText(main, sub) {
-    if (loaderText) loaderText.textContent = main;
-    if (loaderSub)  loaderSub.textContent  = sub;
-    console.log('[loader]', main, '—', sub);
-  }
-
-  // ============================================================
-  //  Utilities
-  // ============================================================
-  function clamp(v, lo, hi) { return Math.min(hi, Math.max(lo, v)); }
-
-  // ============================================================
-  //  State
-  // ============================================================
-  let W = 0, H = 0;
-  let smoothedX = 0.5, smoothedY = 0.5;     // Kalman-smoothed gaze (0..1)
-  // Kalman state replaces emaX/emaY
-  let rawX = 0.5, rawY = 0.5;               // raw gaze (0..1) from regression
-  let rawXValid = false;                    // whether raw gaze has a fresh, valid measurement
-  let trail = [];                           // array of {x, y}
-  let faceMesh = null;
-  let camera   = null;
-  let lastResults = null;
-  let lastTime = performance.now();
-  let fpsSmooth = 0;
-  let irisVisible = { l: false, r: false };
-  let trackingLocked = false;
-  let lastFrameMs = 0;        // last face-mesh processing time in ms
-  let lastMeshSendAt = 0;
-  let frameCount = 0;         // for frame skipping (process every 2nd frame)
-  let lastDebugLogMs = 0;     // throttles the per-second onResults debug print
-
-  // Calibration state
-  let calibrationData = null;            // { coefX:[a0..a5], coefY:[b0..b5], timestamp }
-  let calActive = false;                 // true while a calibration session is in progress
-  let calPaused = false;                 // true while in the calibration overlay (raw gaze is ignored)
-  let calCurrentIdx = 0;                 // index into CAL_ORDER
-  let calSamples = [];                   // collected {ratioX, ratioY} for the active point
-  let calAllPoints = [];                 // accumulated {screenX, screenY, samples:[…]} for all 13 points
-  let calCollectTimer = null;            // setInterval id for sample collection
-  let pointSampleCount = 0;              // per-point sample counter (discard first 3)
-
-  // Kalman Filter for 2D gaze tracking with velocity prediction
-  // State: [x, y, vx, vy], Measurement: [x, y]
-  var kalX = [0.5, 0.5, 0, 0];  // [x, y, vx, vy] in normalized screen coords
-  var kalP = [1, 0, 0, 0,
-              0, 1, 0, 0,
-              0, 0, 1, 0,
-              0, 0, 0, 1];  // 4x4 covariance matrix (flat: P[i*4+j])
-  // Q bumped up (0.001→0.01 for position, 0.01→0.05 for velocity) so the
-  // Kalman filter trusts new measurements more and responds more quickly to
-  // genuine eye motion.  With the old Q the filter over-trusted its own
-  // motion model and the orb lagged noticeably behind saccades.
-  var kalQ = [0.01, 0, 0, 0,
-              0, 0.01, 0, 0,
-              0, 0, 0.05, 0,
-              0, 0, 0, 0.05];  // process noise (symmetric diagonal)
-  var kalR = [0.04, 0,  // measurement noise (flat 2x2: [R00,R01,R10,R11])
-              0, 0.04];
-  // NOTE: measurement matrix H = [[1,0,0,0],[0,1,0,0]] is hardcoded in kalUpdate
-  // (it never changes), so no separate kalH array is needed.
-
-  // ============================================================
-  //  Calibration: 13-point collection + 6-dim polynomial regression (OLS)
-  // ============================================================
-  //
-  //   We model screen position as a quadratic polynomial of iris ratios:
-  //     screenX = a0 + a1*rX + a2*rY + a3*rX² + a4*rY² + a5*rX*rY
-  //     screenY = b0 + b1*rX + b2*rY + b3*rX² + b4*rY² + b5*rX*rY
-  //
-  //   We fit screenX and screenY independently using ordinary least
-  //   squares on the N=13 calibration points (≈ 13 × 27 = 351 effective
-  //   samples after discarding the first 3 per point). We average each
-  //   point's samples first to make one (ratioX, ratioY) per grid
-  //   location, then solve the 6×6 normal equation directly (Cramer's
-  //   rule — we only have 6 unknowns).
-  // ============================================================
-
-  // Average a point's raw samples down to a single (ratioX, ratioY).
-  function averageSamples(samples) {
-    if (!samples.length) return { ratioX: 0.5, ratioY: 0.5 };
-    let sx = 0, sy = 0;
-    for (let i = 0; i < samples.length; i++) {
-      sx += samples[i].ratioX;
-      sy += samples[i].ratioY;
-    }
-    return { ratioX: sx / samples.length, ratioY: sy / samples.length };
-  }
-
-  // Solve a 3×3 linear system A x = b via Cramer's rule.
-  // Returns [x0, x1, x2] or null if A is singular.
-  function solve3x3(A, b) {
-    const det = (
-      A[0][0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) -
-      A[0][1] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) +
-      A[0][2] * (A[1][0] * A[2][1] - A[1][1] * A[2][0])
-    );
-    if (Math.abs(det) < 1e-9) return null;
-
-    const det0 = (
-      b[0]    * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) -
-      A[0][1] * (b[1]    * A[2][2] - A[1][2] * b[2])    +
-      A[0][2] * (b[1]    * A[2][1] - A[1][1] * b[2])
-    );
-    const det1 = (
-      A[0][0] * (b[1]    * A[2][2] - A[1][2] * b[2])    -
-      b[0]    * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) +
-      A[0][2] * (A[1][0] * b[2]    - b[1]    * A[2][0])
-    );
-    const det2 = (
-      A[0][0] * (A[1][1] * b[2]    - b[1]    * A[2][1]) -
-      A[0][1] * (A[1][0] * b[2]    - b[1]    * A[2][0]) +
-      b[0]    * (A[1][0] * A[2][1] - A[1][1] * A[2][0])
-    );
-
-    return [det0 / det, det1 / det, det2 / det];
-  }
-
-  // 6x6 Cramer's rule: solve Ax=b where A is 6x6, b is 6x1
-  // A is passed as array of 6 rows, each row is [a0..a5]
-  function solve6x6(A, b) {
-    function det6(m) {
-      // Compute 6x6 determinant via cofactor expansion along first row
-      let d = 0;
-      for (let j = 0; j < 6; j++) {
-        const minor = [];
-        for (let i = 1; i < 6; i++) {
-          const row = [];
-          for (let k = 0; k < 6; k++) {
-            if (k !== j) row.push(m[i][k]);
-          }
-          minor.push(row);
-        }
-        const sign = (j % 2 === 0) ? 1 : -1;
-        d += sign * m[0][j] * det5(minor);
-      }
-      return d;
-    }
-    function det5(m) {
-      let d = 0;
-      for (let j = 0; j < 5; j++) {
-        const minor = [];
-        for (let i = 1; i < 5; i++) {
-          const row = [];
-          for (let k = 0; k < 5; k++) {
-            if (k !== j) row.push(m[i][k]);
-          }
-          minor.push(row);
-        }
-        const sign = (j % 2 === 0) ? 1 : -1;
-        d += sign * m[0][j] * det4(minor);
-      }
-      return d;
-    }
-    function det4(m) {
-      // 4x4 determinant via cofactor expansion
-      let d = 0;
-      for (let j = 0; j < 4; j++) {
-        const minor = [];
-        for (let i = 1; i < 4; i++) {
-          const row = [];
-          for (let k = 0; k < 4; k++) {
-            if (k !== j) row.push(m[i][k]);
-          }
-          minor.push(row);
-        }
-        const sign = (j % 2 === 0) ? 1 : -1;
-        d += sign * m[0][j] * det3(minor);
-      }
-      return d;
-    }
-    function det3(m) {
-      return m[0][0]*(m[1][1]*m[2][2]-m[1][2]*m[2][1])
-           - m[0][1]*(m[1][0]*m[2][2]-m[1][2]*m[2][0])
-           + m[0][2]*(m[1][0]*m[2][1]-m[1][1]*m[2][0]);
-    }
-    const D = det6(A);
-    if (Math.abs(D) < 1e-12) return null; // singular
-    const x = [];
-    for (let j = 0; j < 6; j++) {
-      const Aj = A.map((row, i) => {
-        const r = row.slice();
-        r[j] = b[i];
-        return r;
-      });
-      x.push(det6(Aj) / D);
-    }
-    return x;
-  }
-
-  // Build 6-dim polynomial design row from iris ratios
-  function buildPolyFeatures(rX, rY) {
-    return [1, rX, rY, rX*rX, rY*rY, rX*rY];
-  }
-
-  // Build the design matrix for [a0, a1, …, a5] with rows [1, rX, rY, rX², rY², rX*rY].
-  function buildDesignMatrix(points) {
-    const M = [];
-    for (let i = 0; i < points.length; i++) {
-      M.push(buildPolyFeatures(points[i].ratioX, points[i].ratioY));
-    }
-    return M;
-  }
-
-  // Ordinary least squares for y = X * beta. Returns beta = [b0, …, b5]
-  // (we use Cramer's rule on X^T X and X^T y — small, dense, exact).
-  function olsFit(X, y) {
-    const n = X.length;
-    // X^T X   (6x6)
-    const A = [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]];
-    // X^T y   (6x1)
-    const b = [0, 0, 0, 0, 0, 0];
-    for (let i = 0; i < n; i++) {
-      const xi = X[i];
-      for (let r = 0; r < 6; r++) {
-        for (let c = 0; c < 6; c++) A[r][c] += xi[r] * xi[c];
-        b[r] += xi[r] * y[i];
-      }
-    }
-    return solve6x6(A, b);
-  }
-
-  // RANSAC-style outlier rejection on ratio features per calibration point.
-  // For each point's samples, drop those whose (ratioX, ratioY) lies > 2.5 std
-  // from the per-point mean. This catches blinks, mid-saccade samples, and
-  // points where the user briefly looked elsewhere while the dot was moving.
-  function ransacCleanPerPoint(point) {
-    if (!point.samples || point.samples.length <= 5) return point.samples || [];
-    const sams = point.samples;
-    const meanX = sams.reduce((a, s) => a + s.ratioX, 0) / sams.length;
-    const meanY = sams.reduce((a, s) => a + s.ratioY, 0) / sams.length;
-    const stdX = Math.sqrt(sams.reduce((a, s) => a + (s.ratioX - meanX) * (s.ratioX - meanX), 0) / sams.length);
-    const stdY = Math.sqrt(sams.reduce((a, s) => a + (s.ratioY - meanY) * (s.ratioY - meanY), 0) / sams.length);
-    // If std is essentially 0 (perfectly steady) just return everything.
-    if (stdX < 1e-6 && stdY < 1e-6) return sams.slice();
-    const kept = [];
-    for (let i = 0; i < sams.length; i++) {
-      const sx = (Math.abs(sams[i].ratioX - meanX) < 2.5 * Math.max(stdX, 1e-6));
-      const sy = (Math.abs(sams[i].ratioY - meanY) < 2.5 * Math.max(stdY, 1e-6));
-      if (sx && sy) kept.push(sams[i]);
-    }
-    // Don't drop more than 40% of samples — std may be underestimated.
-    if (kept.length < sams.length * 0.6) return sams.slice();
-    return kept;
-  }
-
-  function fitCalibration(allPoints) {
-    // allPoints: [{ screenX, screenY, samples:[…] }, …]
-    // 1) Per-point outlier rejection (RANSAC).
-    // 2) Average remaining samples per point.
-    let totalSamples = 0, totalKept = 0;
-    const pts = allPoints.map(p => {
-      const cleaned = ransacCleanPerPoint(p);
-      totalSamples += (p.samples || []).length;
-      totalKept += cleaned.length;
-      const avg = averageSamples(cleaned);
-      return {
-        screenX: p.screenX,
-        screenY: p.screenY,
-        ratioX:  avg.ratioX,
-        ratioY:  avg.ratioY
-      };
-    });
-
-    const X = buildDesignMatrix(pts);
-    const ysx = pts.map(p => p.screenX);
-    const ysy = pts.map(p => p.screenY);
-
-    const coefX = olsFit(X, ysx);
-    const coefY = olsFit(X, ysy);
-    if (!coefX || !coefY) return null;
-
-    // Optional debug log of fit quality.
-    let sseX = 0, sseY = 0;
-    for (let i = 0; i < pts.length; i++) {
-      const px = coefX[0] + coefX[1]*pts[i].ratioX + coefX[2]*pts[i].ratioY + coefX[3]*pts[i].ratioX*pts[i].ratioX + coefX[4]*pts[i].ratioY*pts[i].ratioY + coefX[5]*pts[i].ratioX*pts[i].ratioY;
-      const py = coefY[0] + coefY[1]*pts[i].ratioX + coefY[2]*pts[i].ratioY + coefY[3]*pts[i].ratioX*pts[i].ratioX + coefY[4]*pts[i].ratioY*pts[i].ratioY + coefY[5]*pts[i].ratioX*pts[i].ratioY;
-      sseX += (pts[i].screenX - px) * (pts[i].screenX - px);
-      sseY += (pts[i].screenY - py) * (pts[i].screenY - py);
-    }
-    console.log('[cal] fit quality  kept=' + totalKept + '/' + totalSamples +
-                '  RMSE X=' + Math.sqrt(sseX / pts.length).toFixed(4) +
-                '  RMSE Y=' + Math.sqrt(sseY / pts.length).toFixed(4));
-
-    return {
-      coefX: [coefX[0], coefX[1], coefX[2], coefX[3], coefX[4], coefX[5]],
-      coefY: [coefY[0], coefY[1], coefY[2], coefY[3], coefY[4], coefY[5]]
-    };
-  }
-
-  function applyRegression(ratioX, ratioY) {
-    if (!calibrationData) return { x: 0.5, y: 0.5 };
-    const cx = calibrationData.coefX;
-    const cy = calibrationData.coefY;
-    const f = buildPolyFeatures(ratioX, ratioY);
-    const x = cx[0] + cx[1]*f[1] + cx[2]*f[2] + cx[3]*f[3] + cx[4]*f[4] + cx[5]*f[5];
-    const y = cy[0] + cy[1]*f[1] + cy[2]*f[2] + cy[3]*f[3] + cy[4]*f[4] + cy[5]*f[5];
-    return { x: clamp(x, -0.05, 1.05), y: clamp(y, -0.05, 1.05) };
-  }
-
-  function saveCalibration(cal) {
-    try {
-      const payload = {
-        version: CAL_VERSION,
-        coefX: cal.coefX,
-        coefY: cal.coefY,
-        timestamp: Date.now()
-      };
-      localStorage.setItem(CAL_STORAGE_KEY, JSON.stringify(payload));
-    } catch (e) {
-      console.warn('[cal] localStorage save failed', e && e.message);
-    }
-  }
-
-  function loadCalibration() {
-    try {
-      const raw = localStorage.getItem(CAL_STORAGE_KEY);
-      if (!raw) return null;
-      const obj = JSON.parse(raw);
-      if (!obj || !Array.isArray(obj.coefX) || !Array.isArray(obj.coefY)) return null;
-      if (obj.coefX.length !== 6 || obj.coefY.length !== 6) return null;
-      if (obj.version !== CAL_VERSION) {
-        console.warn('[cal] stored calibration version mismatch (got', obj.version, 'expected', CAL_VERSION + '); discarding');
-        return null;
-      }
-      return {
-        coefX: obj.coefX.slice(0, 6),
-        coefY: obj.coefY.slice(0, 6),
-        timestamp: obj.timestamp || 0
-      };
-    } catch (e) {
-      console.warn('[cal] localStorage load failed', e && e.message);
-      return null;
-    }
-  }
-
-  function clearCalibration() {
-    try { localStorage.removeItem(CAL_STORAGE_KEY); } catch (e) { /* no-op */ }
-    calibrationData = null;
-    // Reset Kalman so the orb returns to the center after a recalibration.
-    kalInit();
-    smoothedX = 0.5; smoothedY = 0.5;
-    rawXValid = false;
-    updateCalStatus('uncalibrated');
-  }
-
-  function updateCalStatus(state) {
-    // state: 'uncalibrated' | 'calibrating' | 'calibrated'
-    if (!calDotStatus || !calStatusText) return;
-    if (state === 'uncalibrated') {
-      calDotStatus.className = 'dot';
-      calStatusText.className = 'value warn';
-      calStatusText.textContent = 'UNCAL';
-      if (recalibrateBtn) recalibrateBtn.disabled = false;
-      dbgSet(dbgCal, 'uncalibrated', 'warn');
-    } else if (state === 'calibrating') {
-      calDotStatus.className = 'dot warn';
-      calStatusText.className = 'value';
-      calStatusText.textContent = 'CAL…';
-      if (recalibrateBtn) recalibrateBtn.disabled = true;
-      dbgSet(dbgCal, 'running', 'run');
-    } else if (state === 'calibrated') {
-      calDotStatus.className = 'dot ok';
-      calStatusText.className = 'value ok';
-      calStatusText.textContent = 'OK';
-      if (recalibrateBtn) recalibrateBtn.disabled = false;
-      dbgSet(dbgCal, 'ready', 'ok');
-    }
-  }
-
-  // ============================================================
-  //  Calibration UI flow
-  // ============================================================
-  function positionCalDot(idx) {
-    if (!calDot) return;
-    const p = CAL_GRID[CAL_ORDER[idx]];
-    // The body / stage is mirrored via CSS scaleX(-1) (webcam preview only);
-    // the canvas (#stage) is NOT mirrored, so we use window coordinates directly.
-    const cx = p.x * window.innerWidth;
-    const cy = p.y * window.innerHeight;
-    calDot.style.left = cx + 'px';
-    calDot.style.top  = cy + 'px';
-  }
-
-  function showCalibrationUI(show) {
-    if (!calOverlay) return;
-    if (show) {
-      calOverlay.classList.add('show');
-      calOverlay.setAttribute('aria-hidden', 'false');
-    } else {
-      calOverlay.classList.remove('show');
-      calOverlay.setAttribute('aria-hidden', 'true');
-    }
-  }
-
-  function startCalibration() {
-    if (calActive) return;
-    calActive = true;
-    calPaused = true;            // don't let the orb move while we collect
-    calAllPoints = [];
-    calCurrentIdx = 0;
-    calSamples = [];
-    pointSampleCount = 0;
-    updateCalStatus('calibrating');
-    showCalibrationUI(true);
-    gotoNextCalPoint();
-  }
-
-  function gotoNextCalPoint() {
-    if (!calActive) return;
-    if (calCurrentIdx >= CAL_ORDER.length) {
-      finishCalibration();
-      return;
-    }
-    positionCalDot(calCurrentIdx);
-    if (calText) {
-      calText.textContent = 'Calibrating (' + (calCurrentIdx + 1) + '/' + CAL_ORDER.length + ')';
-    }
-    if (calSub) {
-      calSub.textContent = 'Follow the dot with your eyes';
-    }
-    calSamples = [];
-    pointSampleCount = 0;        // reset per-point counter (first 3 are discarded)
-    startSampleCollection();
-  }
-
-  function startSampleCollection() {
-    if (calCollectTimer) clearInterval(calCollectTimer);
-    calCollectTimer = setInterval(() => {
-      if (!calActive) return;
-      // Discard the first 3 samples so the user has time to fixate on the dot.
-      if (pointSampleCount < 3) { pointSampleCount++; return; }
-      const gaze = lastGaze;   // most recent raw iris ratio (see onResults)
-      if (gaze && gaze.visible) {
-        calSamples.push({ ratioX: gaze.ratioX, ratioY: gaze.ratioY });
-      }
-      if (calSamples.length >= CAL_SAMPLES_PER_POINT) {
-        clearInterval(calCollectTimer);
-        calCollectTimer = null;
-        commitCurrentPoint();
-      }
-    }, CAL_SAMPLE_INTERVAL_MS);
-  }
-
-  function commitCurrentPoint() {
-    const p = CAL_GRID[CAL_ORDER[calCurrentIdx]];
-    calAllPoints.push({
-      screenX: p.x,
-      screenY: p.y,
-      samples: calSamples.slice()
-    });
-    calCurrentIdx++;
-    if (calCurrentIdx >= CAL_ORDER.length) {
-      finishCalibration();
-    } else {
-      // Brief pause between points so the user can re-target.
-      setTimeout(gotoNextCalPoint, 150);
-    }
-  }
-
-  function finishCalibration() {
-    if (calCollectTimer) { clearInterval(calCollectTimer); calCollectTimer = null; }
-    const fit = fitCalibration(calAllPoints);
-    if (!fit) {
-      console.warn('[cal] OLS fit failed');
-      calActive = false;
-      calPaused = false;
-      showCalibrationUI(false);
-      updateCalStatus(calibrationData ? 'calibrated' : 'uncalibrated');
-      return;
-    }
-    calibrationData = { coefX: fit.coefX, coefY: fit.coefY, timestamp: Date.now() };
-    saveCalibration(calibrationData);
-    console.log('[cal] saved', calibrationData);
-    // Reset Kalman so stale state doesn't bleed into the new calibration.
-    kalInit();
-    calActive = false;
-    calPaused = false;
-    showCalibrationUI(false);
-    updateCalStatus('calibrated');
-  }
-
-  function cancelCalibration() {
-    if (calCollectTimer) { clearInterval(calCollectTimer); calCollectTimer = null; }
-    calActive = false;
-    calPaused = false;
-    showCalibrationUI(false);
-    updateCalStatus(calibrationData ? 'calibrated' : 'uncalibrated');
-  }
-
-  if (calCancel) {
-    calCancel.addEventListener('click', cancelCalibration);
-  }
-  if (recalibrateBtn) {
-    recalibrateBtn.addEventListener('click', () => {
-      if (!faceMesh) return;        // need the model to be running
-      clearCalibration();
-      startCalibration();
-    });
-  }
-
-  // Try to restore a previously-saved calibration as soon as the script runs.
-  (function tryRestoreCalibration() {
-    const saved = loadCalibration();
-    if (saved) {
-      calibrationData = saved;
-      updateCalStatus('calibrated');
-      console.log('[cal] restored from localStorage');
-    } else {
-      updateCalStatus('uncalibrated');
-    }
-  })();
-
-  // ============================================================
-  //  Kalman filter (replaces EMA + outlier threshold)
-  // ============================================================
-  //   The state is [x, y, vx, vy] in normalized screen coords; the
-  //   measurement is [x, y] (from applyRegression). The process model
-  //   assumes constant velocity with small random accelerations (Q),
-  //   and the measurement model assumes the regression output is
-  //   noisy but unbiased (R). This naturally handles gaze noise,
-  //   outliers (large innovations get down-weighted), and saccades
-  //   (velocity prediction reduces lag).
-  // ============================================================
-  function kalUpdate(zx, zy) {
-    // Prediction: x = F*x, P = F*P*F' + Q
-    // F = [[1,0,dt,0],[0,1,0,dt],[0,0,1,0],[0,0,0,1]], dt=1
-    var dt = 1;
-    // Predict state
-    var px = kalX[0] + kalX[2] * dt;
-    var py = kalX[1] + kalX[3] * dt;
-    // Predict P: F*P
-    // F*P where F adds velocity*dt to position rows
-    var pP = new Float64Array(16);
-    for (var i = 0; i < 4; i++) {
-      for (var j = 0; j < 4; j++) {
-        var sum = 0;
-        for (var k = 0; k < 4; k++) {
-          var fik = (i < 2 && k === i + 2) ? dt : (i === k ? 1 : 0); // F[i][k]
-          sum += fik * kalP[k * 4 + j];
-        }
-        pP[i * 4 + j] = sum;
-      }
-    }
-    // pP * F' + Q
-    for (var i = 0; i < 4; i++) {
-      for (var j = 0; j < 4; j++) {
-        var sum = 0;
-        for (var k = 0; k < 4; k++) {
-          var fkj = (k < 2 && j === k + 2) ? dt : (k === j ? 1 : 0); // F'[k][j] = F[j][k]
-          sum += pP[i * 4 + k] * fkj;
-        }
-        kalP[i * 4 + j] = sum + kalQ[i * 4 + j];
-      }
-    }
-    // Innovation: y = z - H*x
-    var yx = zx - px;
-    var yy = zy - py;
-    // S = H*P*H' + R  (2x2)
-    // H = [[1,0,0,0],[0,1,0,0]], so H*P*H' extracts the 2x2 top-left block of P:
-    //   [P00 P01]   plus R (flat: [R00,R01,R10,R11])
-    //   [P10 P11]
-    var s00 = kalP[0]  + kalR[0];
-    var s01 = kalP[1]  + kalR[1];
-    var s10 = kalP[4]  + kalR[2];
-    var s11 = kalP[5]  + kalR[3];
-    var sDet = s00 * s11 - s01 * s10;
-    if (Math.abs(sDet) < 1e-12) { kalX = [zx, zy, 0, 0]; return {x: zx, y: zy}; }
-    var sInv00 =  s11 / sDet;
-    var sInv01 = -s01 / sDet;
-    var sInv10 = -s10 / sDet;
-    var sInv11 =  s00 / sDet;
-    // K = P * H' * S^-1  (4x2 matrix, stored flat as K[i*2+row])
-    // With H = [[1,0,0,0],[0,1,0,0]], H' has 1s at (0,0) and (1,1) only,
-    // so P*H' picks the first two columns of P, then multiplied by S^-1 (2x2).
-    var K = new Float64Array(8); // 4x2
-    for (var i = 0; i < 4; i++) {
-      K[i*2+0] = kalP[i*4+0] * sInv00 + kalP[i*4+1] * sInv10;
-      K[i*2+1] = kalP[i*4+0] * sInv01 + kalP[i*4+1] * sInv11;
-    }
-    // x = px + K*y
-    kalX[0] = px + K[0] * yx + K[1] * yy;
-    kalX[1] = py + K[2] * yx + K[3] * yy;
-    kalX[2] = kalX[2] + K[4] * yx + K[5] * yy;
-    kalX[3] = kalX[3] + K[6] * yx + K[7] * yy;
-    // P = (I - K*H) * P   (Joseph form: numerical stability)
-    // With H = [[1,0,0,0],[0,1,0,0]], only columns 0,1 of K matter:
-    //   (I-KH)[i][j] = δ(i,j) - K[i*2+0]*(j==0) - K[i*2+1]*(j==1)
-    // So (I-KH)*P simplifies to:
-    //   newP[i][k] = P[i][k] - K[i*2+0]*P[0][k] - K[i*2+1]*P[1][k]
-    var newP = new Float64Array(16);
-    for (var i = 0; i < 4; i++) {
-      for (var k = 0; k < 4; k++) {
-        newP[i*4+k] = kalP[i*4+k] - K[i*2+0]*kalP[k] - K[i*2+1]*kalP[4+k];
-      }
-    }
-    // Symmetrize P to prevent numerical drift
-    for (var i = 0; i < 4; i++) {
-      for (var j = i + 1; j < 4; j++) {
-        var avg = (newP[i*4+j] + newP[j*4+i]) * 0.5;
-        newP[i*4+j] = avg;
-        newP[j*4+i] = avg;
-      }
-    }
-    for (var i = 0; i < 16; i++) kalP[i] = newP[i];
-
-    return {x: kalX[0], y: kalX[1]};
-  }
-
-  function kalInit() {
-    kalX = [0.5, 0.5, 0, 0];
-    for (var i = 0; i < 16; i++) kalP[i] = (i % 5 === 0) ? 1 : 0;
-  }
-
-  // ============================================================
-  //  Canvas sizing
-  // ============================================================
-  function resize() {
-    const dpr = Math.min(window.devicePixelRatio || 1, 2);
-    W = window.innerWidth;
-    H = window.innerHeight;
-    stage.width  = W * dpr;
-    stage.height = H * dpr;
-    stage.style.width  = W + 'px';
-    stage.style.height = H + 'px';
-    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
-  }
-  window.addEventListener('resize', () => {
-    resize();
-    // Re-position the calibration dot if one is currently active
-    if (calActive && calCurrentIdx < CAL_ORDER.length) {
-      positionCalDot(calCurrentIdx);
-    }
-  });
-  resize();
-
-  // ============================================================
-  //  Gaze math: iris-ratio only
-  //  Pure eye-in-socket direction. The regression model (fit during
-  //  calibration) maps this raw ratio onto screen coordinates.
-  //
-  //  Both eyes use the SAME effective sign convention for ratioX (both INCREASE
-  //  when the user looks to the right):
-  //    • Left eye:  ratioX = (iris - inner) / (outer - inner)  → increases naturally
-  //    • Right eye: raw ratio = (iris - outer) / (inner - outer) → DECREASES when looking right,
-  //                  so we apply `1 - raw_ratio` to flip it back to the same sign.
-  // ============================================================
-  function computeIrisGaze(landmarks) {
-    // Left eye: normal (outer=33, inner=133)
-    const l_outer = landmarks[L_OUTER];
-    const l_inner = landmarks[L_INNER];
-    const l_top   = landmarks[L_TOP];
-    const l_bot   = landmarks[L_BOT];
-    const _l_c    = landmarks[L_IRIS];
-    // Average the 5 left iris contour points for a more stable reading
-    const l_iris  = {
-      x: [468,469,470,471,472].reduce((s,i) => s + (landmarks[i]?.x || 0), 0) / 5,
-      y: [468,469,470,471,472].reduce((s,i) => s + (landmarks[i]?.y || 0), 0) / 5
-    };
-    const left = (l_outer && l_inner && _l_c &&
-                  !(_l_c.x === 0 && _l_c.y === 0) &&
-                  !Number.isNaN(_l_c.x) && !Number.isNaN(_l_c.y) &&
-                  Math.abs(l_outer.x - l_inner.x) > 1e-6)
-      ? (() => {
-          const eyeW = l_outer.x - l_inner.x;
-          const ratioX = (l_iris.x - l_inner.x) / eyeW;
-          const midY = (l_top.y + l_bot.y) * 0.5;
-          const ratioY = (l_iris.y - midY) / (Math.abs(eyeW) || 1e-6);
-          return { ratioX, ratioY };
-        })()
-      : null;
-
-    // Right eye: same formula structure as left eye (no flip needed because
-    // MediaPipe landmarks in the raw frame already give same-sign ratios for
-    // both eyes — both ratioX values DECREASE when the user looks RIGHT).
-    // Using R_OUTER (which is to the RIGHT in the un-mirrored raw frame) as
-    // the denominator reference yields a ratio in the same [0,1]-ish range
-    // and, crucially, the same sign as the left eye so that the average of
-    // both eyes does NOT collapse to ~0.5.
-    const r_outer = landmarks[R_OUTER];
-    const r_inner = landmarks[R_INNER];
-    const r_top   = landmarks[R_TOP];
-    const r_bot   = landmarks[R_BOT];
-    const _r_c    = landmarks[R_IRIS];
-    // Average the 5 right iris contour points for a more stable reading
-    const r_iris  = {
-      x: [473,474,475,476,477].reduce((s,i) => s + (landmarks[i]?.x || 0), 0) / 5,
-      y: [473,474,475,476,477].reduce((s,i) => s + (landmarks[i]?.y || 0), 0) / 5
-    };
-    const right = (r_outer && r_inner && _r_c &&
-                   !(_r_c.x === 0 && _r_c.y === 0) &&
-                   !Number.isNaN(_r_c.x) && !Number.isNaN(_r_c.y) &&
-                   Math.abs(r_inner.x - r_outer.x) > 1e-6)
-      ? (() => {
-          // Same formula shape as the left eye, but using R_OUTER (right side
-          // in raw frame) as the "outer" anchor.  eyeW = inner - outer is
-          // NEGATIVE here, and (iris - outer)/eyeW is therefore also
-          // negative of the naive (iris - inner)/eyeW — but that's the
-          // correct sign for the right eye, so both eyes agree when the
-          // user looks right.  No `1 -` flip is applied.
-          const r_eyeW = r_inner.x - r_outer.x;
-          const r_ratioX = 1 - (r_iris.x - r_outer.x) / r_eyeW;
-          const r_midY = (r_top.y + r_bot.y) * 0.5;
-          const r_ratioY = (r_iris.y - r_midY) / (Math.abs(r_eyeW) || 1e-6);
-          return { ratioX: r_ratioX, ratioY: r_ratioY };
-        })()
-      : null;
-
-    irisVisible.l = !!left;
-    irisVisible.r = !!right;
-
-    if (!left && !right) return { ratioX: 0.5, ratioY: 0.5, visible: false };
-
-    let rx, ry;
-    if (left && right) {
-      rx = (left.ratioX + right.ratioX) * 0.5;
-      ry = (left.ratioY + right.ratioY) * 0.5;
-    } else {
-      const s = left || right;
-      rx = s.ratioX; ry = s.ratioY;
-    }
-
-    return { ratioX: rx, ratioY: ry, visible: true };
-  }
-
-  // ============================================================
-  //  Render: full-screen orb + trail
-  // ============================================================
-  function drawOrb() {
-    // Clear with very slight motion blur for the trail
-    ctx.fillStyle = 'rgba(10, 10, 26, 0.35)';
-    ctx.fillRect(0, 0, W, H);
-
-    // Map smoothed gaze to screen coordinates (with margin so orb stays on screen)
-    const margin = 60;
-    const sx = margin + smoothedX * (W - margin * 2);
-    const sy = margin + smoothedY * (H - margin * 2);
-
-    // Push trail
-    trail.push({ x: sx, y: sy });
-    if (trail.length > TRAIL_LENGTH) trail.shift();
-
-    // Draw trail (oldest -> newest, fading in opacity & shrinking radius)
-    // Cheap: simple filled circles, no radialGradient per point.
-    for (let i = 0; i < trail.length; i++) {
-      const t = trail[i];
-      const tNorm = (i + 1) / trail.length;   // 0..1
-      const r = ORB_RADIUS * 0.12 * tNorm;
-      const a = 0.03 + 0.25 * tNorm;
-      ctx.fillStyle = 'rgba(0, 229, 255, ' + a + ')';
-      ctx.beginPath();
-      ctx.arc(t.x, t.y, r, 0, Math.PI * 2);
-      ctx.fill();
-    }
-
-    // Main orb - layered radial gradients for glow
-    const cx = sx, cy = sy;
-
-    // Outer halo
-    let g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS * 4);
-    g.addColorStop(0,    'rgba(0, 229, 255, 0.35)');
-    g.addColorStop(0.25, 'rgba(0, 229, 255, 0.18)');
-    g.addColorStop(0.6,  'rgba(0, 184, 212, 0.05)');
-    g.addColorStop(1,    'rgba(0, 229, 255, 0)');
-    ctx.fillStyle = g;
-    ctx.beginPath();
-    ctx.arc(cx, cy, ORB_RADIUS * 4, 0, Math.PI * 2);
-    ctx.fill();
-
-    // Mid glow
-    g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS * 1.8);
-    g.addColorStop(0,    'rgba(180, 255, 255, 0.95)');
-    g.addColorStop(0.25, 'rgba(0, 229, 255, 0.85)');
-    g.addColorStop(0.65, 'rgba(0, 184, 212, 0.5)');
-    g.addColorStop(1,    'rgba(0, 229, 255, 0)');
-    ctx.fillStyle = g;
-    ctx.beginPath();
-    ctx.arc(cx, cy, ORB_RADIUS * 1.8, 0, Math.PI * 2);
-    ctx.fill();
-
-    // Core
-    g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS);
-    g.addColorStop(0,   'rgba(255, 255, 255, 1)');
-    g.addColorStop(0.3, 'rgba(180, 255, 255, 1)');
-    g.addColorStop(0.7, 'rgba(0, 229, 255, 0.95)');
-    g.addColorStop(1,   'rgba(0, 184, 212, 0.7)');
-    ctx.fillStyle = g;
-    ctx.beginPath();
-    ctx.arc(cx, cy, ORB_RADIUS, 0, Math.PI * 2);
-    ctx.fill();
-
-    // Inner sparkle
-    ctx.fillStyle = 'rgba(255, 255, 255, 0.85)';
-    ctx.beginPath();
-    ctx.arc(cx - ORB_RADIUS * 0.25, cy - ORB_RADIUS * 0.25, ORB_RADIUS * 0.18, 0, Math.PI * 2);
-    ctx.fill();
-  }
-
-  // ============================================================
-  //  Render: face mesh overlay on webcam preview
-  // ============================================================
-  function drawOverlay(results) {
-    const w = overlay.width;
-    const h = overlay.height;
-    octx.clearRect(0, 0, w, h);
-
-    if (!results || !results.multiFaceLandmarks || results.multiFaceLandmarks.length === 0) {
-      // Subtle "no face" indicator
-      octx.strokeStyle = 'rgba(0, 229, 255, 0.25)';
-      octx.setLineDash([4, 4]);
-      octx.lineWidth = 1;
-      octx.strokeRect(8, 8, w - 16, h - 16);
-      octx.setLineDash([]);
-      octx.fillStyle = 'rgba(0, 229, 255, 0.7)';
-      octx.font = '10px monospace';
-      octx.fillText('NO FACE DETECTED', 12, h - 12);
-      return;
-    }
-
-    const lm = results.multiFaceLandmarks[0];
-    // Note: the video is mirrored visually via CSS, so we mirror X here
-    // to keep the mesh aligned with what the user sees.
-    const pt = (i) => ({ x: (1 - lm[i].x) * w, y: lm[i].y * h });
-
-    // Draw mesh lines
-    octx.lineWidth = 0.6;
-    octx.strokeStyle = 'rgba(0, 229, 255, 0.45)';
-    octx.beginPath();
-    [FACE_OVAL, LIPS, L_EYE, R_EYE, L_BROW, R_BROW].forEach(connections => {
-      for (let i = 0; i < connections.length; i++) {
-        const a = pt(connections[i]);
-        const b = pt(connections[(i + 1) % connections.length]);
-        octx.moveTo(a.x, a.y);
-        octx.lineTo(b.x, b.y);
-      }
-    });
-    octx.stroke();
-
-    // Subtle face dots (subsample every 6th point for performance)
-    octx.fillStyle = 'rgba(0, 229, 255, 0.4)';
-    for (let i = 0; i < lm.length; i++) {
-      if (i % 6 !== 0) continue;   // was % 3 — doubled the stride to halve the work
-      const p = pt(i);
-      octx.fillRect(p.x, p.y, 1, 1);
-    }
-
-    // Iris highlight (big + bright)
-    octx.fillStyle = '#ffeb3b';
-    IRIS_LANDMARKS.forEach(idx => {
-      const p = pt(idx);
-      octx.beginPath();
-      octx.arc(p.x, p.y, 1.6, 0, Math.PI * 2);
-      octx.fill();
-    });
-
-    // Iris center (468 / 473) - extra large
-    [L_IRIS, R_IRIS].forEach(idx => {
-      const p = pt(idx);
-      octx.fillStyle = '#ffffff';
-      octx.beginPath();
-      octx.arc(p.x, p.y, 2.6, 0, Math.PI * 2);
-      octx.fill();
-    });
-  }
-
-  // ============================================================
-  //  Animation loop
-  // ============================================================
-  function loop(now) {
-    // FPS
-    const dt = now - lastTime;
-    lastTime = now;
-    const instFps = 1000 / Math.max(dt, 1);
-    fpsSmooth = fpsSmooth === 0 ? instFps : (fpsSmooth * 0.9 + instFps * 0.1);
-
-    // Kalman filter: feed raw gaze through the Kalman filter.
-    // rawX/rawY are already screen-coords (applyRegression when calibrated,
-    // or raw iris ratio clamped to [0,1] before calibration is ready).
-    // No update when no iris is visible, so the orb holds its position
-    // instead of drifting back to center.
-    if (rawXValid && !calPaused) {
-      var kf = kalUpdate(rawX, rawY);
-      smoothedX = kf.x;
-      smoothedY = kf.y;
-    }
-
-    drawOrb();
-    if (lastResults) drawOverlay(lastResults);
-
-    // Status text — overall pipeline state
-    const visible = irisVisible.l || irisVisible.r;
-    if (visible) {
-      statusDot.className = 'dot ok';
-      statusText.className = 'value ok';
-      statusText.textContent = 'TRACKING';
-      dbgSet(dbgStage, 'tracking', 'ok');
-    } else if (faceMesh) {
-      statusDot.className = 'dot warn';
-      statusText.className = 'value warn';
-      statusText.textContent = 'NO IRIS';
-      dbgSet(dbgStage, 'no face', 'warn');
-    } else {
-      statusDot.className = 'dot';
-      statusText.className = 'value';
-      statusText.textContent = 'INIT';
-      dbgSet(dbgStage, 'init', 'run');
-    }
-    fpsEl.textContent = Math.round(fpsSmooth);
-    gxEl.textContent  = smoothedX.toFixed(3);
-    gyEl.textContent  = smoothedY.toFixed(3);
-    ilEl.textContent  = irisVisible.l ? '●' : '○';
-    irEl.textContent  = irisVisible.r ? '●' : '○';
-    ilEl.className    = 'value ' + (irisVisible.l ? 'ok' : 'warn');
-    irEl.className    = 'value ' + (irisVisible.r ? 'ok' : 'warn');
-    dbgSet(dbgFrame, lastFrameMs > 0 ? (lastFrameMs.toFixed(1) + ' ms') : '--');
-
-    requestAnimationFrame(loop);
-  }
-  requestAnimationFrame(loop);
-
-  // ============================================================
-  //  MediaPipe setup
-  // ============================================================
-  function showError(title, msg) {
-    console.error('[error]', title, '—', msg);
-    errTitle.textContent = title;
-    errMsg.textContent   = msg;
-    errOverlay.classList.add('show');
-    loader.classList.add('hidden');
-    statusDot.className  = 'dot err';
-    statusText.className = 'value err';
-    statusText.textContent = 'ERROR';
-    dbgSetError((title ? title + ': ' : '') + (msg || ''));
-    dbgSet(dbgStage, 'error', 'err');
-  }
-
-  errRetry.addEventListener('click', () => {
-    errOverlay.classList.remove('show');
-    location.reload();
-  });
-
-  // Format bytes for the debug panel / loader text
-  function fmtBytes(n) {
-    if (n < 1024) return n + ' B';
-    if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
-    return (n / (1024 * 1024)).toFixed(2) + ' MB';
-  }
-
-  // Pre-fetch a list of MediaPipe WASM / data files with byte-level progress.
-  // Returns a map { filename -> blob: URL } suitable for locateFile().
-  // If any file fails, the function still resolves with whatever succeeded
-  // (MediaPipe will retry from the network as a fallback).
-  async function prefetchAssets(files) {
-    console.log('[model] pre-fetching', files.length, 'asset(s)…');
-    dbgSet(dbgModel, 'loading…', 'run');
-    const out = {};
-    let totalBytes = 0;
-    for (let i = 0; i < files.length; i++) {
-      const file = files[i];
-      const url = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/' + file;
-      setLoaderText(
-        'Downloading model (' + (i + 1) + '/' + files.length + ')',
-        file + '  (0 MB)'
-      );
-      console.log('[model] GET', file);
-      try {
-        const resp = await fetch(url, { mode: 'cors', cache: 'force-cache' });
-        if (!resp.ok) throw new Error('HTTP ' + resp.status);
-        const len = parseInt(resp.headers.get('content-length') || '0', 10);
-        // Stream the body so we can show incremental progress.
-        const reader = resp.body && resp.body.getReader ? resp.body.getReader() : null;
-        const chunks = [];
-        let received = 0;
-        if (reader) {
-          // eslint-disable-next-line no-constant-condition
-          while (true) {
-            const { done, value } = await reader.read();
-            if (done) break;
-            chunks.push(value);
-            received += value.byteLength;
-            totalBytes += value.byteLength;
-            const pct = len ? Math.round((received / len) * 100) : 0;
-            setLoaderText(
-              'Downloading model (' + (i + 1) + '/' + files.length + ' · ' + pct + '%)',
-              file + '  —  ' + fmtBytes(received) + (len ? ' / ' + fmtBytes(len) : '')
-            );
-            dbgSet(dbgBytes, fmtBytes(totalBytes));
-          }
-          const blob = new Blob(chunks, { type: resp.headers.get('content-type') || 'application/octet-stream' });
-          out[file] = URL.createObjectURL(blob);
-        } else {
-          const blob = await resp.blob();
-          out[file] = URL.createObjectURL(blob);
-          totalBytes += blob.size;
-          dbgSet(dbgBytes, fmtBytes(totalBytes));
-        }
-        console.log('[model] OK', file, fmtBytes(received || (out[file] ? 0 : 0)));
-      } catch (e) {
-        console.warn('[model] pre-fetch failed for', file, e && e.message);
-        // leave out[file] undefined → MediaPipe will fall back to the URL
-      }
-    }
-    dbgSet(dbgModel, 'ready (' + fmtBytes(totalBytes) + ')', 'ok');
-    console.log('[model] pre-fetch done, total', fmtBytes(totalBytes));
-    return out;
-  }
-
-  async function initFaceMesh() {
-    console.log('[init] initFaceMesh start');
-    setLoaderText(
-      'Initializing face mesh…',
-      'Preparing the iris-tracking model. This may take a moment.'
-    );
-    dbgSet(dbgModel, 'init…', 'run');
-    try {
-      // 1) Pre-fetch the big WASM / data files so the user can see progress
-      //    instead of a silent stall. The list mirrors the files MediaPipe
-      //    requests at runtime when refineLandmarks is enabled.
-      const assetMap = await prefetchAssets([
-        'face_mesh_solution_simd_wasm_bin.js',
-        'face_mesh_solution_simd_wasm_bin.wasm',
-        'face_mesh_solution_packed_assets.data'
-      ]);
-
-      setLoaderText(
-        'Initializing face mesh…',
-        'WASM runtime ready. Constructing the model.'
-      );
-
-      // 2) Construct FaceMesh. If we pre-fetched a file, serve it from the
-      //    blob URL so the browser uses the cached bytes; otherwise let
-      //    MediaPipe fall back to the CDN.
-      faceMesh = new FaceMesh({
-        locateFile: (file) => {
-          if (assetMap[file]) {
-            console.log('[model] locateFile (cached)', file);
-            return assetMap[file];
-          }
-          const url = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/' + file;
-          console.log('[model] locateFile (remote)', file);
-          return url;
-        }
-      });
-      faceMesh.setOptions({
-        maxNumFaces: 1,
-        refineLandmarks: true,        // gives 468-477 iris
-        minDetectionConfidence: 0.5,
-        minTrackingConfidence: 0.5
-      });
-      faceMesh.onResults(onResults);
-
-      console.log('[init] FaceMesh constructed, calling .initialize()');
-      setLoaderText(
-        'Initializing face mesh…',
-        'Calling MediaPipe .initialize() — finalizing WASM.'
-      );
-      if (typeof faceMesh.initialize === 'function') {
-        await faceMesh.initialize();
-      }
-      console.log('[init] FaceMesh ready');
-      dbgSet(dbgModel, 'ready', 'ok');
-
-      startCamera();
-    } catch (e) {
-      console.error('FaceMesh init failed:', e);
-      dbgSetError('FaceMesh init failed: ' + (e && e.message ? e.message : e));
-      dbgSet(dbgModel, 'failed', 'err');
-      showError(
-        'Initialization Failed',
-        'Could not load MediaPipe Face Mesh (' + ((e && e.message) || 'unknown error') +
-        '). Check your network connection and reload the page.'
-      );
-    }
-  }
-
-  // The most recent iris ratio (used by the calibration collector).
-  let lastGaze = { ratioX: 0.5, ratioY: 0.5, visible: false };
-
-  function onResults(results) {
-    const t1 = performance.now();
-    lastResults = results;
-
-    if (!results.multiFaceLandmarks || results.multiFaceLandmarks.length === 0) {
-      // No face - hold last smoothed position, don't drift
-      lastGaze.visible = false;
-      lastFrameMs = performance.now() - t1;
-      return;
-    }
-
-    const lm = results.multiFaceLandmarks[0];
-    const gaze = computeIrisGaze(lm);
-    lastGaze = gaze;
-
-    if (gaze.visible && calibrationData && !calPaused) {
-      // Map raw iris ratio → screen coordinates via the OLS model
-      const mapped = applyRegression(gaze.ratioX, gaze.ratioY);
-      rawX = mapped.x;
-      rawY = mapped.y;
-      rawXValid = true;
-    } else if (gaze.visible && !calPaused) {
-      // No calibration yet — approximate screen position from iris ratio.
-      // ratioX (eyeW-normalized) lives roughly in [0.2, 0.8] with the center
-      // near 0.5; recenter at 0.5 and stretch x3 to fill the screen without
-      // saturating.
-      // ratioY is eyeW-normalized and signed (look-up → negative, look-down
-      // → positive); recenter at 0.5 and stretch x3.  The calibration
-      // regression will fix the exact direction/orientation afterward — this
-      // fallback just needs to produce values that span [0, 1] without
-      // clipping at 1 the moment the user blinks or moves their head.
-      rawX = clamp(0.5 + (gaze.ratioX - 0.5) * 3, 0, 1);
-      rawY = clamp(0.5 + gaze.ratioY * 3, 0, 1);
-      rawXValid = true;
-    } else {
-      // No iris detected, or calibration is paused
-      rawXValid = false;
-    }
-    lastFrameMs = performance.now() - t1;
-
-    // Debug log: once per second, print the current iris ratios + mapped
-    // screen coordinates.  Throttled with lastDebugLogMs so we don't flood
-    // the console at ~30 fps.  Helpful for diagnosing "why is the orb
-    // stuck?" — open DevTools and watch the values as you move your eyes.
-    if (rawXValid) {
-      const nowMs = performance.now();
-      if (nowMs - lastDebugLogMs >= 1000) {
-        lastDebugLogMs = nowMs;
-        console.log(
-          '[gaze] ratioX=' + gaze.ratioX.toFixed(3) +
-          ' ratioY=' + gaze.ratioY.toFixed(3) +
-          ' | mappedX=' + rawX.toFixed(3) +
-          ' mappedY=' + rawY.toFixed(3) +
-          ' | calibrated=' + (calibrationData ? 'yes' : 'no') +
-          ' | irisVisible=' + irisVisible.l + '/' + irisVisible.r
-        );
-      }
-    }
-  }
-
-  function startCamera() {
-    console.log('[camera] startCamera');
-    setLoaderText(
-      'Connecting camera…',
-      'Requesting webcam access. Please click "Allow" in the browser prompt.'
-    );
-    dbgSet(dbgCamera, 'requesting…', 'run');
-    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
-      dbgSet(dbgCamera, 'unsupported', 'err');
-      showError(
-        'Browser Not Supported',
-        'Your browser does not support getUserMedia. Please use a modern browser (Chrome, Firefox, Edge, Safari).'
-      );
-      return;
-    }
-
-    camera = new Camera(video, {
-      onFrame: async () => {
-        // Frame-skip: only send every 2nd frame to MediaPipe.  This roughly
-        // halves CPU usage on the face-mesh pass and noticeably improves
-        // responsiveness on mid-range laptops.
-        frameCount++;
-        if (frameCount % 2 !== 0) return;
-        if (faceMesh) {
-          const t0 = performance.now();
-          try {
-            await faceMesh.send({ image: video });
-          } catch (e) {
-            // swallow individual frame errors
-            console.warn('[frame] send error', e && e.message);
-          } finally {
-            lastMeshSendAt = performance.now() - t0;
-            if (lastMeshSendAt > 5) {
-              // Only log slow frames to keep the console quiet
-              // console.log('[frame] send', lastMeshSendAt.toFixed(1), 'ms');
-            }
-          }
-        }
-      },
-      width:  640,
-      height: 480
-    });
-
-    camera.start()
-      .then(() => {
-        // wait for metadata
-        return new Promise(resolve => {
-          if (video.readyState >= 1) return resolve();
-          video.addEventListener('loadedmetadata', resolve, { once: true });
-        });
-      })
-      .then(() => {
-        console.log('[camera] stream ready, hiding loader');
-        loader.classList.add('hidden');
-        statusText.textContent = 'READY';
-        dbgSet(dbgCamera, 'streaming', 'ok');
-        dbgSet(dbgStage, 'live', 'ok');
-
-        // First-time calibration: no localStorage → kick off the 9-point flow
-        if (!calibrationData && !calActive) {
-          // small delay so the user can settle in front of the camera
-          setTimeout(() => { if (!calibrationData && !calActive) startCalibration(); }, 800);
-        }
-      })
-      .catch(err => {
-        console.error('Camera error:', err);
-        dbgSet(dbgCamera, 'error', 'err');
-        const name = err && err.name;
-        if (name === 'NotAllowedError' || name === 'PermissionDeniedError' || name === 'SecurityError') {
-          showError(
-            'Camera Access Denied',
-            'We need your camera to track your gaze. Please click the camera icon in your browser\'s address bar, grant permission, then click Retry.'
-          );
-        } else if (name === 'NotFoundError' || name === 'OverconstrainedError') {
-          showError(
-            'No Camera Found',
-            'No webcam was detected on this device. Please connect a camera and reload the page.'
-          );
-        } else if (name === 'NotReadableError' || name === 'TrackStartError') {
-          showError(
-            'Camera Busy',
-            'Your camera appears to be in use by another application. Please close other apps (Zoom, Skype, etc.) and try again.'
-          );
-        } else {
-          showError(
-            'Camera Error',
-            (err && err.message) || 'An unknown error occurred while accessing the camera.'
-          );
-        }
-      });
-  }
-
-  // Wait for the global FaceMesh symbol to be available
-  function waitFor(predicate, timeout = 20000) {
-    return new Promise((resolve, reject) => {
-      const start = performance.now();
-      (function check() {
-        if (predicate()) return resolve();
-        if (performance.now() - start > timeout) return reject(new Error('Timeout waiting for MediaPipe'));
-        requestAnimationFrame(check);
-      })();
-    });
-  }
-
-  // Kick off: stage 1 = wait for the CDN script to register window.FaceMesh
-  setLoaderText(
-    'Loading MediaPipe JS…',
-    'Downloading the MediaPipe scripts from the CDN.'
-  );
-  console.log('[boot] waiting for window.FaceMesh…');
-  waitFor(() => typeof window.FaceMesh === 'function', 20000)
-    .then(() => {
-      console.log('[boot] window.FaceMesh available');
-      initFaceMesh();
-    })
-    .catch((e) => {
-      console.error('[boot] FaceMesh never appeared:', e && e.message);
-      dbgSet(dbgCdn3, 'TIMEOUT', 'err');
-      dbgSetError('Timed out waiting for MediaPipe JS. The CDN may be blocked.');
-      showError(
-        'Failed to Load MediaPipe',
-        'The MediaPipe library could not be loaded (timeout). The CDN may be blocked in your region — try a VPN or a different network, then reload.'
-      );
-    });
-
-  // Safety: if a CDN script failed before waitFor() could resolve, bail out
-  // promptly with a clear message instead of waiting for the timeout.
-  window.addEventListener('cdnError', () => {
-    if (typeof window.FaceMesh !== 'function') {
-      console.error('[boot] CDN error before FaceMesh became available');
-      showError(
-        'CDN Load Failed',
-        'Could not download the MediaPipe library from the CDN. The CDN may be blocked in your region — try a VPN, a different network, or self-host the files, then reload.'
-      );
-    }
-  });
-
-})();
-</script>
+<!-- Application entry point (ES module) -->
+<script type="module" src="js/main.js"></script>
 </body>
-</html>
+</html>

+ 444 - 0
js/calibration.js

@@ -0,0 +1,444 @@
+// calibration.js
+// 13-point calibration: collection + 9-dim polynomial regression (OLS) with
+// Gaussian elimination (solveNxN) + RANSAC-style per-point outlier rejection
+// + localStorage persistence + UI flow (start / step / commit / finish / cancel).
+//
+//   V2 model — 9 features per dimension (screenX and screenY fit independently):
+//     screenX = a0 + a1*rX + a2*rY + a3*ear + a4*pitch + a5*yaw
+//                       + a6*rX² + a7*rY² + a8*rX*rY
+//     screenY = b0 + b1*rX + b2*rY + b3*ear + b4*pitch + b5*yaw
+//                       + b6*rX² + b7*rY² + b8*rX*rY
+//
+//   We fit screenX and screenY independently using ordinary least squares
+//   on the N=13 calibration points (≈ 13 × 27 = 351 effective samples after
+//   discarding the first 3 per point). We average each point's samples first
+//   to make one (ratioX, ratioY, ear, pitch, yaw) per grid location, then
+//   solve the 9×9 normal equation directly (Gaussian elimination with
+//   partial pivoting — Cramer's rule is too slow / numerically unstable
+//   past ~6×6).
+//
+//   Old 6-coef payloads are rejected by loadCalibration() because CAL_VERSION
+//   is now 4 (was 3).  This forces a one-time re-calibration on first run
+//   after the upgrade, which is correct: the V2 model has different
+//   feature semantics and shouldn't try to read V1 coefficients.
+
+import {
+  CAL_GRID, CAL_ORDER, CAL_SAMPLES_PER_POINT,
+  CAL_SAMPLE_INTERVAL_MS, CAL_STORAGE_KEY, CAL_VERSION
+} from './config.js';
+import { clamp, dbgSet, dbgSetError } from './utils.js';
+import {
+  averageSamples, buildPolyFeatures, buildDesignMatrix, olsFit,
+  buildPolyFeaturesV2, buildDesignMatrixV2, olsFitV2, N_FEATURES_V2
+} from './math.js';
+import { kalInit } from './kalman.js';
+
+// ---- DOM references ----
+const calOverlay  = document.getElementById('calibration-overlay');
+const calDot      = document.getElementById('cal-dot');
+const calText     = document.getElementById('cal-text');
+const calSub      = document.getElementById('cal-sub');
+const calCancel   = document.getElementById('cal-cancel');
+const calDotStatus = document.getElementById('cal-dot-status');
+const calStatusText = document.getElementById('cal-status-text');
+const recalibrateBtn = document.getElementById('recalibrate-btn');
+const dbgCal      = document.getElementById('dbg-cal');
+
+// ---- Mutable state exported as `let` (live bindings) ----
+// `calibrationData` is the live OLS fit: { coefX:[a0..a8], coefY:[b0..b8], timestamp }.
+// 9 coefficients per axis, not 6.
+export let calibrationData = null;
+// True while a calibration session is in progress.
+export let calActive = false;
+// True while in the calibration overlay (raw gaze is ignored by the renderer).
+export let calPaused = false;
+// Index into CAL_ORDER.
+export let calCurrentIdx = 0;
+
+// Internal-only state (not exported because no other module needs to mutate it)
+let calSamples = [];                   // collected V2 samples for the active point
+let calAllPoints = [];                 // accumulated {screenX, screenY, samples:[…]} for all 13 points
+let calCollectTimer = null;            // setInterval id for sample collection
+let pointSampleCount = 0;              // per-point sample counter (discard first 3)
+
+// ============================================================
+//  RANSAC + regression
+// ============================================================
+
+// RANSAC-style outlier rejection on the V2 features per calibration point.
+// For each point's samples, drop those whose (ratioX, ratioY) lies > 2.5
+// std from the per-point mean.  We also drop samples whose EAR is far from
+// the per-point median — those are mid-blink samples that slipped past
+// the per-frame blink filter, and they're poison for the regression
+// because the iris ratio is unstable while the eyelid covers the iris.
+//
+// This catches blinks, mid-saccade samples, and points where the user
+// briefly looked elsewhere while the dot was moving.
+function ransacCleanPerPoint(point) {
+  if (!point.samples || point.samples.length <= 5) return point.samples || [];
+  const sams = point.samples;
+  const meanX = sams.reduce((a, s) => a + s.ratioX, 0) / sams.length;
+  const meanY = sams.reduce((a, s) => a + s.ratioY, 0) / sams.length;
+  const stdX = Math.sqrt(sams.reduce((a, s) => a + (s.ratioX - meanX) * (s.ratioX - meanX), 0) / sams.length);
+  const stdY = Math.sqrt(sams.reduce((a, s) => a + (s.ratioY - meanY) * (s.ratioY - meanY), 0) / sams.length);
+  // Median EAR (sorted copy) — robust to a few mid-blink samples.
+  const ears = sams.map(s => (s.ear != null ? s.ear : 0)).slice().sort((a, b) => a - b);
+  const earMedian = ears[Math.floor(ears.length / 2)];
+  // If std is essentially 0 (perfectly steady) just return everything.
+  if (stdX < 1e-6 && stdY < 1e-6) return sams.slice();
+  const kept = [];
+  for (let i = 0; i < sams.length; i++) {
+    const s = sams[i];
+    const sx = (Math.abs(s.ratioX - meanX) < 2.5 * Math.max(stdX, 1e-6));
+    const sy = (Math.abs(s.ratioY - meanY) < 2.5 * Math.max(stdY, 1e-6));
+    // EAR: drop samples whose EAR is more than 0.10 below the median.
+    // 0.10 is roughly half the open-eye range, so it triggers on closed
+    // eyes but tolerates normal micro-variation.
+    const e = s.ear != null ? s.ear : 0;
+    const se = (e === 0) || (e >= earMedian - 0.10);
+    if (sx && sy && se) kept.push(s);
+  }
+  // Don't drop more than 40% of samples — std may be underestimated.
+  if (kept.length < sams.length * 0.6) return sams.slice();
+  return kept;
+}
+
+export function fitCalibration(allPoints) {
+  // allPoints: [{ screenX, screenY, samples:[…] }, …]
+  // 1) Per-point outlier rejection (RANSAC).
+  // 2) Average remaining samples per point.
+  let totalSamples = 0, totalKept = 0;
+  const pts = allPoints.map(p => {
+    const cleaned = ransacCleanPerPoint(p);
+    totalSamples += (p.samples || []).length;
+    totalKept += cleaned.length;
+    const avg = averageSamples(cleaned);
+    return {
+      screenX: p.screenX,
+      screenY: p.screenY,
+      ratioX:  avg.ratioX,
+      ratioY:  avg.ratioY,
+      ear:     avg.ear,
+      pitch:   avg.pitch,
+      yaw:     avg.yaw
+    };
+  });
+
+  // 9-dim design matrix: [1, rX, rY, ear, pitch, yaw, rX², rY², rX*rY]
+  const X = buildDesignMatrixV2(pts);
+  const ysx = pts.map(p => p.screenX);
+  const ysy = pts.map(p => p.screenY);
+
+  const coefX = olsFitV2(X, ysx, N_FEATURES_V2);
+  const coefY = olsFitV2(X, ysy, N_FEATURES_V2);
+  if (!coefX || !coefY) return null;
+
+  // Fit-quality debug: re-evaluate the model at each averaged point and
+  // report per-axis RMSE.  We do this against the averaged points (one
+  // per grid location) so the metric is independent of how many raw
+  // samples we collected; the per-point RANSAC above already trims
+  // gross outliers.
+  let sseX = 0, sseY = 0;
+  for (let i = 0; i < pts.length; i++) {
+    const f = X[i];   // already the 9-dim feature row
+    let px = 0, py = 0;
+    for (let k = 0; k < N_FEATURES_V2; k++) {
+      px += coefX[k] * f[k];
+      py += coefY[k] * f[k];
+    }
+    sseX += (pts[i].screenX - px) * (pts[i].screenX - px);
+    sseY += (pts[i].screenY - py) * (pts[i].screenY - py);
+  }
+  console.log('[cal] V2 fit quality  kept=' + totalKept + '/' + totalSamples +
+              '  RMSE X=' + Math.sqrt(sseX / pts.length).toFixed(4) +
+              '  RMSE Y=' + Math.sqrt(sseY / pts.length).toFixed(4));
+
+  return {
+    coefX: coefX.slice(0, N_FEATURES_V2),
+    coefY: coefY.slice(0, N_FEATURES_V2)
+  };
+}
+
+// Apply the V2 (9-coef) regression.  Accepts ear/pitch/yaw; they go
+// through unused if the model's coefficient for that feature happens
+// to be 0 (e.g. a user's particular head pose has no effect on their
+// gaze mapping).  Output is clamped to a slight overshoot of [0, 1]
+// so the orb can briefly travel to the screen edge.
+export function applyRegression(ratioX, ratioY, ear, pitch, yaw) {
+  if (!calibrationData) return { x: 0.5, y: 0.5 };
+  const cx = calibrationData.coefX;
+  const cy = calibrationData.coefY;
+  // Inline the V2 feature row — avoids a small allocation per frame.
+  // Layout: [1, rX, rY, ear, pitch, yaw, rX², rY², rX*rY]
+  const e  = (ear   != null) ? ear   : 0;
+  const pi = (pitch != null) ? pitch : 0;
+  const w  = (yaw   != null) ? yaw   : 0;
+  const r2x = ratioX * ratioX;
+  const r2y = ratioY * ratioY;
+  const rxy = ratioX * ratioY;
+  const f = [1, ratioX, ratioY, e, pi, w, r2x, r2y, rxy];
+  let x = 0, y = 0;
+  for (let k = 0; k < N_FEATURES_V2; k++) {
+    x += cx[k] * f[k];
+    y += cy[k] * f[k];
+  }
+  return { x: clamp(x, -0.05, 1.05), y: clamp(y, -0.05, 1.05) };
+}
+
+export function saveCalibration(cal) {
+  try {
+    const payload = {
+      version: CAL_VERSION,
+      coefX: cal.coefX,
+      coefY: cal.coefY,
+      timestamp: Date.now()
+    };
+    localStorage.setItem(CAL_STORAGE_KEY, JSON.stringify(payload));
+  } catch (e) {
+    console.warn('[cal] localStorage save failed', e && e.message);
+  }
+}
+
+export function loadCalibration() {
+  try {
+    const raw = localStorage.getItem(CAL_STORAGE_KEY);
+    if (!raw) return null;
+    const obj = JSON.parse(raw);
+    if (!obj || !Array.isArray(obj.coefX) || !Array.isArray(obj.coefY)) return null;
+    // V2: 9 coefficients per axis (was 6 in the V1 6-dim model).
+    if (obj.coefX.length !== N_FEATURES_V2 || obj.coefY.length !== N_FEATURES_V2) return null;
+    if (obj.version !== CAL_VERSION) {
+      console.warn('[cal] stored calibration version mismatch (got', obj.version, 'expected', CAL_VERSION + '); discarding');
+      return null;
+    }
+    return {
+      coefX: obj.coefX.slice(0, N_FEATURES_V2),
+      coefY: obj.coefY.slice(0, N_FEATURES_V2),
+      timestamp: obj.timestamp || 0
+    };
+  } catch (e) {
+    console.warn('[cal] localStorage load failed', e && e.message);
+    return null;
+  }
+}
+
+export function clearCalibration() {
+  try { localStorage.removeItem(CAL_STORAGE_KEY); } catch (e) { /* no-op */ }
+  calibrationData = null;
+  // Reset Kalman so the orb returns to the center after a recalibration.
+  kalInit();
+  // Mirror the IIFE's `rawXValid = false` so the renderer stops feeding
+  // stale samples into the Kalman filter. The local mirror is also kept
+  // in sync by gaze.js via setRawXValid().
+  _rawXValid = false;
+  // Notify the renderer that it should snap smoothed values back to center.
+  _resetSmoothed && _resetSmoothed();
+  updateCalStatus('uncalibrated');
+}
+
+// ============================================================
+//  Calibration UI flow
+// ============================================================
+
+// Imported lazily to avoid a circular import (gaze.js imports
+// calibration.js, and calibration.js reads lastGaze from gaze.js).
+// We access it through a dynamic getter that gaze.js registers
+// once it's initialized.
+let _lastGazeGetter = () => ({
+  ratioX: 0.5, ratioY: 0.5,
+  ear: 0, pitch: 0, yaw: 0,
+  visible: false
+});
+export function registerLastGazeGetter(fn) { _lastGazeGetter = fn; }
+
+// Same pattern for the renderer's smoothed-gaze reset hook (called on
+// clearCalibration / finishCalibration). Renderer.js registers this.
+let _resetSmoothed = null;
+export function registerResetSmoothed(fn) { _resetSmoothed = fn; }
+
+// `rawXValid` is mirrored here too (renderer reads it; gaze writes to it).
+// We expose getters/setters so gaze.js doesn't need to import this module.
+let _rawXValid = false;
+export function getRawXValid() { return _rawXValid; }
+export function setRawXValid(v) { _rawXValid = v; }
+// Back-compat: some old callers referenced `rawXValid` directly.
+// We use `getRawXValid()`/`setRawXValid()` from gaze.js instead.
+
+export function updateCalStatus(state) {
+  // state: 'uncalibrated' | 'calibrating' | 'calibrated'
+  if (!calDotStatus || !calStatusText) return;
+  if (state === 'uncalibrated') {
+    calDotStatus.className = 'dot';
+    calStatusText.className = 'value warn';
+    calStatusText.textContent = 'UNCAL';
+    if (recalibrateBtn) recalibrateBtn.disabled = false;
+    dbgSet(dbgCal, 'uncalibrated', 'warn');
+  } else if (state === 'calibrating') {
+    calDotStatus.className = 'dot warn';
+    calStatusText.className = 'value';
+    calStatusText.textContent = 'CAL…';
+    if (recalibrateBtn) recalibrateBtn.disabled = true;
+    dbgSet(dbgCal, 'running', 'run');
+  } else if (state === 'calibrated') {
+    calDotStatus.className = 'dot ok';
+    calStatusText.className = 'value ok';
+    calStatusText.textContent = 'OK';
+    if (recalibrateBtn) recalibrateBtn.disabled = false;
+    dbgSet(dbgCal, 'ready', 'ok');
+  }
+}
+
+export function positionCalDot(idx) {
+  if (!calDot) return;
+  const p = CAL_GRID[CAL_ORDER[idx]];
+  // The body / stage is mirrored via CSS scaleX(-1) (webcam preview only);
+  // the canvas (#stage) is NOT mirrored, so we use window coordinates directly.
+  const cx = p.x * window.innerWidth;
+  const cy = p.y * window.innerHeight;
+  calDot.style.left = cx + 'px';
+  calDot.style.top  = cy + 'px';
+}
+
+export function showCalibrationUI(show) {
+  if (!calOverlay) return;
+  if (show) {
+    calOverlay.classList.add('show');
+    calOverlay.setAttribute('aria-hidden', 'false');
+  } else {
+    calOverlay.classList.remove('show');
+    calOverlay.setAttribute('aria-hidden', 'true');
+  }
+}
+
+export function startCalibration() {
+  if (calActive) return;
+  calActive = true;
+  calPaused = true;            // don't let the orb move while we collect
+  calAllPoints = [];
+  calCurrentIdx = 0;
+  calSamples = [];
+  pointSampleCount = 0;
+  updateCalStatus('calibrating');
+  showCalibrationUI(true);
+  gotoNextCalPoint();
+}
+
+export function gotoNextCalPoint() {
+  if (!calActive) return;
+  if (calCurrentIdx >= CAL_ORDER.length) {
+    finishCalibration();
+    return;
+  }
+  positionCalDot(calCurrentIdx);
+  if (calText) {
+    calText.textContent = 'Calibrating (' + (calCurrentIdx + 1) + '/' + CAL_ORDER.length + ')';
+  }
+  if (calSub) {
+    calSub.textContent = 'Follow the dot with your eyes';
+  }
+  calSamples = [];
+  pointSampleCount = 0;        // reset per-point counter (first 3 are discarded)
+  startSampleCollection();
+}
+
+export function startSampleCollection() {
+  if (calCollectTimer) clearInterval(calCollectTimer);
+  calCollectTimer = setInterval(() => {
+    if (!calActive) return;
+    // Discard the first 3 samples so the user has time to fixate on the dot.
+    if (pointSampleCount < 3) { pointSampleCount++; return; }
+    const gaze = _lastGazeGetter();   // most recent V2 sample (see onResults)
+    if (gaze && gaze.visible) {
+      // V2 sample: ratioX/ratioY + ear/pitch/yaw.  We don't separately
+      // skip blink frames here — the onResults blink filter in gaze.js
+      // means the gaze is already only being updated on non-blink frames,
+      // and the per-point RANSAC below will catch any leakage.
+      calSamples.push({
+        ratioX: gaze.ratioX,
+        ratioY: gaze.ratioY,
+        ear:    gaze.ear    != null ? gaze.ear    : 0,
+        pitch:  gaze.pitch  != null ? gaze.pitch  : 0,
+        yaw:    gaze.yaw    != null ? gaze.yaw    : 0
+      });
+    }
+    if (calSamples.length >= CAL_SAMPLES_PER_POINT) {
+      clearInterval(calCollectTimer);
+      calCollectTimer = null;
+      commitCurrentPoint();
+    }
+  }, CAL_SAMPLE_INTERVAL_MS);
+}
+
+export function commitCurrentPoint() {
+  const p = CAL_GRID[CAL_ORDER[calCurrentIdx]];
+  calAllPoints.push({
+    screenX: p.x,
+    screenY: p.y,
+    samples: calSamples.slice()
+  });
+  calCurrentIdx++;
+  if (calCurrentIdx >= CAL_ORDER.length) {
+    finishCalibration();
+  } else {
+    // Brief pause between points so the user can re-target.
+    setTimeout(gotoNextCalPoint, 150);
+  }
+}
+
+export function finishCalibration() {
+  if (calCollectTimer) { clearInterval(calCollectTimer); calCollectTimer = null; }
+  const fit = fitCalibration(calAllPoints);
+  if (!fit) {
+    console.warn('[cal] OLS fit failed');
+    calActive = false;
+    calPaused = false;
+    showCalibrationUI(false);
+    updateCalStatus(calibrationData ? 'calibrated' : 'uncalibrated');
+    return;
+  }
+  calibrationData = { coefX: fit.coefX, coefY: fit.coefY, timestamp: Date.now() };
+  saveCalibration(calibrationData);
+  console.log('[cal] saved', calibrationData);
+  // Reset Kalman so stale state doesn't bleed into the new calibration.
+  kalInit();
+  calActive = false;
+  calPaused = false;
+  showCalibrationUI(false);
+  updateCalStatus('calibrated');
+}
+
+export function cancelCalibration() {
+  if (calCollectTimer) { clearInterval(calCollectTimer); calCollectTimer = null; }
+  calActive = false;
+  calPaused = false;
+  showCalibrationUI(false);
+  updateCalStatus(calibrationData ? 'calibrated' : 'uncalibrated');
+}
+
+// ---- Wire up buttons ----
+if (calCancel) {
+  calCancel.addEventListener('click', cancelCalibration);
+}
+
+// Recalibrate button is wired by main.js (it needs to know whether
+// faceMesh is ready before kicking off a new calibration).
+export function bindRecalibrateButton(isFaceMeshReady) {
+  if (!recalibrateBtn) return;
+  recalibrateBtn.addEventListener('click', () => {
+    if (!isFaceMeshReady()) return;        // need the model to be running
+    clearCalibration();
+    startCalibration();
+  });
+}
+
+// Try to restore a previously-saved calibration as soon as the script runs.
+export function tryRestoreCalibration() {
+  const saved = loadCalibration();
+  if (saved) {
+    calibrationData = saved;
+    updateCalStatus('calibrated');
+    console.log('[cal] restored from localStorage');
+  } else {
+    updateCalStatus('uncalibrated');
+  }
+}

+ 93 - 0
js/config.js

@@ -0,0 +1,93 @@
+// config.js
+// Pure constants: landmark indices, calibration grid, parameters, connections.
+// No imports; no DOM access; no side effects.
+
+export const TRAIL_LENGTH = 30;            // # of trail points
+export const ORB_RADIUS = 40;              // px
+export const GRID_DRAW_INTERVAL_MS = 33;   // ~30fps redraw
+
+// Kalman filter (replaces EMA + outlier threshold — Kalman handles noise naturally via R)
+// No constant needed here; see kalUpdate / kalInit below.
+
+// Calibration config
+export const CAL_SAMPLES_PER_POINT = 30;   // samples per point (first 3 are discarded)
+export const CAL_SAMPLE_INTERVAL_MS = 50; // ms between samples
+export const CAL_MARGIN = 0.15;            // 15% margin on each edge
+export const CAL_STORAGE_KEY = 'eye-tracking-calibration';
+// Bumped to 4: regression now uses 9-dim features (rX, rY, ear, pitch, yaw, rX², rY², rX*rY).
+// Old 6-coef payloads are rejected by loadCalibration() so the user re-calibrates once.
+export const CAL_VERSION = 4;
+
+// ---- Eye-state features (V2 model) ----
+// EAR (Eye Aspect Ratio) thresholds.
+//   EAR = vertical eye-opening / horizontal eye-width.
+//   An open eye is typically ~0.28–0.35; a fully closed eye is ~0.0.
+//   A blink is a transient dip below ~0.22 (Soukupová & Čech, 2016).
+export const EAR_BLINK_THRESHOLD = 0.22;  // < this value => blink frame; skip raw gaze update
+export const EAR_CLOSED_THRESHOLD = 0.15; // < this value => considered "eye closed"
+
+// ---- Head-pose feature switch ----
+// When true, the regression model includes simple geometric head-pitch / head-yaw
+// estimates (derived from nose vs. eye-corners / chin / forehead).  The 9-dim
+// model below already wires them in; this flag is a documentation/extension
+// hook so we can later add features (e.g. roll) or fall back to 6-dim if needed.
+export const HEAD_POSE_FEATURES = true;
+
+// ---- Head-pose landmark indices (MediaPipe Face Mesh) ----
+// We use a simple geometric estimate (not full PnP).  See computeHeadPose() in gaze.js.
+export const NOSE_TIP         = 1;   // tip of the nose
+export const CHIN             = 152; // bottom of the chin
+export const FOREHEAD         = 10;  // top of the forehead (between brows)
+export const LEFT_EYE_CORNER  = 33;  // outer corner of the left eye (in raw frame)
+export const RIGHT_EYE_CORNER = 263; // outer corner of the right eye (in raw frame)
+
+// Iris / eye landmark indices (MediaPipe Face Mesh)
+// Left eye
+export const L_OUTER = 33,   L_INNER = 133;
+export const L_TOP   = 159,  L_BOT   = 145;
+export const L_IRIS  = 468;
+// Right eye
+export const R_OUTER = 362,  R_INNER = 263;
+export const R_TOP   = 386,  R_BOT   = 374;
+export const R_IRIS  = 473;
+// Iris contour points
+export const IRIS_LANDMARKS = [
+  468, 469, 470, 471, 472,   // left iris
+  473, 474, 475, 476, 477    // right iris
+];
+
+// Face mesh tesselation connection subsets (subset of FACE_TESSELATION)
+// Use eye / brow / lip / nose silhouettes to keep it light
+export const FACE_OVAL = [10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288, 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136, 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109];
+export const LIPS      = [61, 146, 91, 181, 84, 17, 314, 405, 321, 375, 291, 308, 324, 318, 402, 317, 14, 87, 178, 88, 95, 78];
+export const L_EYE     = [33, 7, 163, 144, 145, 153, 154, 155, 133, 173, 157, 158, 159, 160, 161, 246];
+export const R_EYE     = [362, 382, 381, 380, 374, 373, 390, 249, 263, 466, 388, 387, 386, 385, 384, 398];
+export const L_BROW    = [46, 53, 52, 65, 55, 107, 66, 105, 63, 70];
+export const R_BROW    = [276, 283, 282, 295, 285, 336, 296, 334, 293, 300];
+
+// 13-point calibration grid (center + 4 corners + 4 edges + 4 mid-diagonal)
+// The drawing is mirrored via CSS scaleX(-1), so these coords are
+// intentionally in the *displayed* (mirrored) frame of reference.
+// 5 rows × variable cols (5+3 cols) — center column used in rows 0,2,4 only.
+export const CAL_GRID = [
+  // row 0 (top)
+  { x: 0.1,                    y: 0.1                    }, // TL
+  { x: 0.5,                    y: 0.1                    }, // TM
+  { x: 0.9,                    y: 0.1                    }, // TR
+  // row 1 (upper mid)
+  { x: 0.1,                    y: 0.3                    }, // UL-mid
+  { x: 0.9,                    y: 0.3                    }, // UR-mid
+  // row 2 (middle)
+  { x: 0.1,                    y: 0.5                    }, // ML
+  { x: 0.5,                    y: 0.5                    }, // MM (center)
+  { x: 0.9,                    y: 0.5                    }, // MR
+  // row 3 (lower mid)
+  { x: 0.1,                    y: 0.7                    }, // LL-mid
+  { x: 0.9,                    y: 0.7                    }, // LR-mid
+  // row 4 (bottom)
+  { x: 0.1,                    y: 0.9                    }, // BL
+  { x: 0.5,                    y: 0.9                    }, // BM
+  { x: 0.9,                    y: 0.9                    }  // BR
+];
+// Order: row-major traversal
+export const CAL_ORDER = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

+ 351 - 0
js/gaze.js

@@ -0,0 +1,351 @@
+// gaze.js
+// Per-frame MediaPipe FaceMesh result handler.
+// Owns: lastGaze, irisVisible, lastResults, lastFrameMs, lastDebugLogMs, rawX, rawY,
+//       lastEAR, lastBlinking, lastHeadPose.
+
+import {
+  L_OUTER, L_INNER, L_TOP, L_BOT, L_IRIS,
+  R_OUTER, R_INNER, R_TOP, R_BOT, R_IRIS,
+  NOSE_TIP, CHIN, FOREHEAD,
+  LEFT_EYE_CORNER, RIGHT_EYE_CORNER,
+  EAR_BLINK_THRESHOLD, EAR_CLOSED_THRESHOLD
+} from './config.js';
+import { clamp } from './utils.js';
+import {
+  applyRegression, calibrationData, calPaused,
+  getRawXValid, setRawXValid,
+  registerLastGazeGetter
+} from './calibration.js';
+
+// ---- Iris visibility flags ----
+export const irisVisible = { l: false, r: false };
+
+// ---- Most recent iris-ratio gaze sample (consumed by the calibration collector) ----
+// Extended with ear / pitch / yaw for the V2 regression model and the
+// per-frame blink filter.  The `visible` flag still indicates whether the
+// iris was actually detected this frame; ear/pitch/yaw are computed only
+// when the face landmarks are present and are otherwise zero.
+export let lastGaze = {
+  ratioX: 0.5, ratioY: 0.5,
+  ear: 0, pitch: 0, yaw: 0,
+  visible: false
+};
+
+// ---- Latest raw screen-coordinate gaze (set by onResults, consumed by renderer loop) ----
+export let rawX = 0.5;
+export let rawY = 0.5;
+
+// ---- Most recent FaceMesh results (consumed by renderer.drawOverlay) ----
+export let lastResults = null;
+
+// ---- Per-frame timing / debug throttling ----
+export let lastFrameMs = 0;
+let lastDebugLogMs = 0;
+
+// ---- New V2 state: blink filter + head-pose ----
+// lastEAR      — most recent EAR value (averaged across the two eyes)
+// lastBlinking — true while EAR is below the blink threshold (the renderer
+//                dims the orb to show the user that their blink was registered)
+// lastHeadPose — { pitch, yaw } geometric estimate; both are roughly in
+//                [-0.5, +0.5] for natural head rotations and 0 when the
+//                user faces the camera squarely.
+export let lastEAR = 0;
+export let lastBlinking = false;
+export let lastHeadPose = { pitch: 0, yaw: 0 };
+
+// Internal setters (the `let` bindings above are only mutated from within
+// this module, so we keep the setters file-local rather than exporting them).
+function setLastGaze(v) { lastGaze = v; }
+function setRawX(v)     { rawX = v; }
+function setRawY(v)     { rawY = v; }
+function setLastResults(v) { lastResults = v; }
+function setLastFrameMs(v) { lastFrameMs = v; }
+function setLastEAR(v) { lastEAR = v; }
+function setLastBlinking(v) { lastBlinking = v; }
+function setLastHeadPose(v) { lastHeadPose = v; }
+
+// ============================================================
+//  Helpers: eye state features
+// ============================================================
+
+// Euclidean distance between two landmarks (both are MediaPipe-style
+// {x, y, z} points in normalized [0, 1] coordinates).
+function dist2D(a, b) {
+  const dx = a.x - b.x;
+  const dy = a.y - b.y;
+  return Math.sqrt(dx * dx + dy * dy);
+}
+
+// Eye Aspect Ratio (Soukupová & Čech, 2016) — a 4-point approximation
+// using the inner-corner, outer-corner, and the top/bottom mid-points:
+//   EAR = ||top - bot|| / ||outer - inner||
+// We average across both eyes because (a) blinks are usually synchronous
+// and (b) averaging stabilises the estimate against single-eye noise.
+//
+// Returns 0 if any landmark is missing (caller should treat that as
+// "eye state unknown" — we still attempt to keep the rest of the pipeline
+// running rather than throwing).
+function earForEye(landmarks, outerIdx, topIdx, botIdx, innerIdx) {
+  const o = landmarks[outerIdx];
+  const t = landmarks[topIdx];
+  const b = landmarks[botIdx];
+  const i = landmarks[innerIdx];
+  if (!o || !t || !b || !i) return 0;
+  const horiz = dist2D(o, i);
+  if (horiz < 1e-6) return 0;
+  return dist2D(t, b) / horiz;
+}
+
+// Compute the mean Eye Aspect Ratio across both eyes.
+export function computeEAR(landmarks) {
+  if (!landmarks) return 0;
+  // Left eye:  outer=33, top=159, bot=145, inner=133
+  // Right eye: outer=362, top=386, bot=374, inner=263
+  const l = earForEye(landmarks, L_OUTER, L_TOP, L_BOT, L_INNER);
+  const r = earForEye(landmarks, R_OUTER, R_TOP, R_BOT, R_INNER);
+  // If only one eye is detected, use it; otherwise average.
+  if (l > 0 && r > 0) return (l + r) * 0.5;
+  if (l > 0) return l;
+  if (r > 0) return r;
+  return 0;
+}
+
+// Simple geometric head-pose estimate (no PnP solve needed).
+//   yaw   — horizontal nose offset, normalised by inter-eye distance.
+//           Positive => head turned left (the nose moves toward the
+//           right of the eye-line), negative => head turned right.
+//   pitch — vertical nose offset, normalised by forehead-to-chin
+//           distance.  Positive => head tilted down (nose below the
+//           geometric centre of the face), negative => head tilted up.
+//
+// We deliberately do NOT invert for screen mirroring here; head pose is
+// a property of the *face*, not of the screen, so the same value is
+// valid whether or not the preview is mirrored.
+export function computeHeadPose(landmarks) {
+  if (!landmarks) return { pitch: 0, yaw: 0 };
+  const nose = landmarks[NOSE_TIP];
+  const chin = landmarks[CHIN];
+  const forehead = landmarks[FOREHEAD];
+  const lEye = landmarks[LEFT_EYE_CORNER];
+  const rEye = landmarks[RIGHT_EYE_CORNER];
+  if (!nose || !chin || !forehead || !lEye || !rEye) {
+    return { pitch: 0, yaw: 0 };
+  }
+  // Eye centre: midpoint of the two outer eye corners.
+  const eyeMidX = (lEye.x + rEye.x) * 0.5;
+  const eyeMidY = (lEye.y + rEye.y) * 0.5;
+  // Inter-eye horizontal distance — our yaw normaliser.  Falls back to
+  // a small epsilon to avoid division by zero if eyes happen to coincide.
+  const eyeW = Math.abs(rEye.x - lEye.x) || 1e-6;
+  // Yaw: how far the nose is offset horizontally from the eye line.
+  // Positive yaw => the nose is to the right of the eye line in the
+  // raw frame, which (because the raw frame is un-mirrored) means the
+  // user has turned their head to their own LEFT.  We leave the sign
+  // raw here; the regression can fit whichever sign it likes.
+  const yaw = (nose.x - eyeMidX) / eyeW;
+  // Face height: forehead to chin (vertical span of the face).
+  const faceH = (chin.y - forehead.y) || 1e-6;
+  // Face vertical centre: midway between forehead and chin.
+  const faceMidY = (forehead.y + chin.y) * 0.5;
+  // Pitch: how far the nose sits above/below the face centre, normalised
+  // by face height.  In the raw frame y increases downward, so a nose
+  // ABOVE the centre gives a NEGATIVE pitch (head tilted up) and a
+  // nose BELOW the centre gives a POSITIVE pitch (head tilted down).
+  const pitch = (nose.y - faceMidY) / faceH;
+  return { pitch, yaw };
+}
+
+// ============================================================
+//  Gaze math: iris-ratio only
+//  Pure eye-in-socket direction. The regression model (fit during
+//  calibration) maps this raw ratio onto screen coordinates.
+//
+//  Both eyes use the SAME effective sign convention for ratioX (both INCREASE
+//  when the user looks to the right):
+//    • Left eye:  ratioX = (iris - inner) / (outer - inner)  → increases naturally
+//    • Right eye: raw ratio = (iris - outer) / (inner - outer) → DECREASES when looking right,
+//                  so we apply `1 - raw_ratio` to flip it back to the same sign.
+// ============================================================
+export function computeIrisGaze(landmarks) {
+  // Left eye: normal (outer=33, inner=133)
+  const l_outer = landmarks[L_OUTER];
+  const l_inner = landmarks[L_INNER];
+  const l_top   = landmarks[L_TOP];
+  const l_bot   = landmarks[L_BOT];
+  const _l_c    = landmarks[L_IRIS];
+  // Average the 5 left iris contour points for a more stable reading
+  const l_iris  = {
+    x: [468,469,470,471,472].reduce((s,i) => s + (landmarks[i]?.x || 0), 0) / 5,
+    y: [468,469,470,471,472].reduce((s,i) => s + (landmarks[i]?.y || 0), 0) / 5
+  };
+  const left = (l_outer && l_inner && _l_c &&
+                !(_l_c.x === 0 && _l_c.y === 0) &&
+                !Number.isNaN(_l_c.x) && !Number.isNaN(_l_c.y) &&
+                Math.abs(l_outer.x - l_inner.x) > 1e-6)
+    ? (() => {
+        const eyeW = l_outer.x - l_inner.x;
+        const ratioX = (l_iris.x - l_inner.x) / eyeW;
+        const midY = (l_top.y + l_bot.y) * 0.5;
+        const ratioY = (l_iris.y - midY) / (Math.abs(eyeW) || 1e-6);
+        return { ratioX, ratioY };
+      })()
+    : null;
+
+  // Right eye: same formula structure as left eye (no flip needed because
+  // MediaPipe landmarks in the raw frame already give same-sign ratios for
+  // both eyes — both ratioX values DECREASE when the user looks RIGHT).
+  // Using R_OUTER (which is to the RIGHT in the un-mirrored raw frame) as
+  // the denominator reference yields a ratio in the same [0,1]-ish range
+  // and, crucially, the same sign as the left eye so that the average of
+  // both eyes does NOT collapse to ~0.5.
+  const r_outer = landmarks[R_OUTER];
+  const r_inner = landmarks[R_INNER];
+  const r_top   = landmarks[R_TOP];
+  const r_bot   = landmarks[R_BOT];
+  const _r_c    = landmarks[R_IRIS];
+  // Average the 5 right iris contour points for a more stable reading
+  const r_iris  = {
+    x: [473,474,475,476,477].reduce((s,i) => s + (landmarks[i]?.x || 0), 0) / 5,
+    y: [473,474,475,476,477].reduce((s,i) => s + (landmarks[i]?.y || 0), 0) / 5
+  };
+  const right = (r_outer && r_inner && _r_c &&
+                 !(_r_c.x === 0 && _r_c.y === 0) &&
+                 !Number.isNaN(_r_c.x) && !Number.isNaN(_r_c.y) &&
+                 Math.abs(r_inner.x - r_outer.x) > 1e-6)
+    ? (() => {
+        // Same formula shape as the left eye, but using R_OUTER (right side
+        // in raw frame) as the "outer" anchor.  eyeW = inner - outer is
+        // NEGATIVE here, and (iris - outer)/eyeW is therefore also
+        // negative of the naive (iris - inner)/eyeW — but that's the
+        // correct sign for the right eye, so both eyes agree when the
+        // user looks right.  No `1 -` flip is applied.
+        const r_eyeW = r_inner.x - r_outer.x;
+        const r_ratioX = 1 - (r_iris.x - r_outer.x) / r_eyeW;
+        const r_midY = (r_top.y + r_bot.y) * 0.5;
+        const r_ratioY = (r_iris.y - r_midY) / (Math.abs(r_eyeW) || 1e-6);
+        return { ratioX: r_ratioX, ratioY: r_ratioY };
+      })()
+    : null;
+
+  irisVisible.l = !!left;
+  irisVisible.r = !!right;
+
+  if (!left && !right) {
+    return { ratioX: 0.5, ratioY: 0.5, visible: false };
+  }
+
+  let rx, ry;
+  if (left && right) {
+    rx = (left.ratioX + right.ratioX) * 0.5;
+    ry = (left.ratioY + right.ratioY) * 0.5;
+  } else {
+    const s = left || right;
+    rx = s.ratioX; ry = s.ratioY;
+  }
+
+  return { ratioX: rx, ratioY: ry, visible: true };
+}
+
+export function onResults(results) {
+  const t1 = performance.now();
+  setLastResults(results);
+
+  if (!results.multiFaceLandmarks || results.multiFaceLandmarks.length === 0) {
+    // No face - hold last smoothed position, don't drift.
+    // Clear the blink flag too (we can't really know, but assume the
+    // user isn't actively blinking while no face is visible).
+    setLastGaze({ ...lastGaze, visible: false });
+    setLastBlinking(false);
+    setLastFrameMs(performance.now() - t1);
+    return;
+  }
+
+  const lm = results.multiFaceLandmarks[0];
+
+  // V2 features: blink + head pose, computed once per frame before
+  // the iris-ratio path so we can use EAR to gate that path.
+  const ear = computeEAR(lm);
+  const headPose = computeHeadPose(lm);
+  setLastEAR(ear);
+  setLastHeadPose(headPose);
+
+  // Blink detection: if the eyes are closed enough, mark the frame as
+  // a blink and DO NOT update the raw gaze position.  The orb will
+  // keep its current Kalman-smoothed position so it doesn't jump.
+  // The blink flag is sticky across the entire closed-eyes interval
+  // (we don't return early until EAR recovers), but we only ever skip
+  // the raw-gaze update — we still want lastGaze / lastFrameMs etc.
+  // refreshed.
+  const isBlink = ear > 0 && ear < EAR_BLINK_THRESHOLD;
+  setLastBlinking(isBlink);
+
+  const gaze = computeIrisGaze(lm);
+  // Attach the V2 features to lastGaze so calibration.js can sample them.
+  setLastGaze({ ...gaze, ear, pitch: headPose.pitch, yaw: headPose.yaw });
+
+  if (isBlink) {
+    // Keep the orb parked where it is.  Crucially we do NOT call
+    // setRawXValid(false) here — that would cause the renderer to
+    // hold the last *valid* position too, which is what we want.
+    // We also don't write to rawX/rawY; they keep their previous
+    // values, and the Kalman filter continues to predict from them.
+    setLastFrameMs(performance.now() - t1);
+  } else if (gaze.visible && calibrationData && !calPaused) {
+    // Map raw iris ratio (+ ear/pitch/yaw) → screen coordinates via the
+    // 9-dim OLS model.  applyRegression accepts the V2 features and
+    // will use whichever coefficients are non-zero; for a freshly-
+    // fitted model on 13 points all 9 are non-zero.
+    const mapped = applyRegression(
+      gaze.ratioX, gaze.ratioY,
+      ear, headPose.pitch, headPose.yaw
+    );
+    setRawX(mapped.x);
+    setRawY(mapped.y);
+    setRawXValid(true);
+  } else if (gaze.visible && !calPaused) {
+    // No calibration yet — approximate screen position from iris ratio.
+    // ratioX (eyeW-normalized) lives roughly in [0.2, 0.8] with the center
+    // near 0.5; recenter at 0.5 and stretch x3 to fill the screen without
+    // saturating.
+    // ratioY is eyeW-normalized and signed (look-up → negative, look-down
+    // → positive); recenter at 0.5 and stretch x3.  The calibration
+    // regression will fix the exact direction/orientation afterward — this
+    // fallback just needs to produce values that span [0, 1] without
+    // clipping at 1 the moment the user blinks or moves their head.
+    setRawX(clamp(0.5 + (gaze.ratioX - 0.5) * 3, 0, 1));
+    setRawY(clamp(0.5 + (gaze.ratioY + 0.03) * 6, 0, 1));
+    setRawXValid(true);
+  } else {
+    // No iris detected, or calibration is paused
+    setRawXValid(false);
+  }
+  setLastFrameMs(performance.now() - t1);
+
+  // Debug log: once per second, print the current iris ratios + mapped
+  // screen coordinates + blink/head-pose state.  Throttled with
+  // lastDebugLogMs so we don't flood the console at ~30 fps.  Helpful
+  // for diagnosing "why is the orb stuck?" — open DevTools and watch
+  // the values as you move your eyes / tilt your head.
+  if (getRawXValid()) {
+    const nowMs = performance.now();
+    if (nowMs - lastDebugLogMs >= 1000) {
+      lastDebugLogMs = nowMs;
+      console.log(
+        '[gaze] ratioX=' + gaze.ratioX.toFixed(3) +
+        ' ratioY=' + gaze.ratioY.toFixed(3) +
+        ' EAR=' + ear.toFixed(3) +
+        (isBlink ? ' (BLINK)' : '') +
+        ' pitch=' + headPose.pitch.toFixed(3) +
+        ' yaw=' + headPose.yaw.toFixed(3) +
+        ' | mappedX=' + rawX.toFixed(3) +
+        ' mappedY=' + rawY.toFixed(3) +
+        ' | calibrated=' + (calibrationData ? 'yes' : 'no') +
+        ' | irisVisible=' + irisVisible.l + '/' + irisVisible.r
+      );
+    }
+  }
+}
+
+// Wire up the late-binding hook so calibration.js can read lastGaze
+// without creating a circular import.
+registerLastGazeGetter(() => lastGaze);

+ 121 - 0
js/kalman.js

@@ -0,0 +1,121 @@
+// kalman.js
+// Kalman filter for 2D gaze tracking with velocity prediction.
+// State: [x, y, vx, vy], Measurement: [x, y].
+// The process model assumes constant velocity with small random
+// accelerations (Q); measurement model assumes the regression output
+// is noisy but unbiased (R). This naturally handles gaze noise,
+// outliers, and saccades (velocity prediction reduces lag).
+
+// Kalman state replaces emaX/emaY.
+// NOTE: measurement matrix H = [[1,0,0,0],[0,1,0,0]] is hardcoded in kalUpdate
+// (it never changes), so no separate kalH array is needed.
+
+// Exported `let` bindings — mutating modules can re-assign kalX / kalP
+// (e.g. kalInit), and readers always see the current values.
+export var kalX = [0.5, 0.5, 0, 0];  // [x, y, vx, vy] in normalized screen coords
+export var kalP = [1, 0, 0, 0,
+                   0, 1, 0, 0,
+                   0, 0, 1, 0,
+                   0, 0, 0, 1];  // 4x4 covariance matrix (flat: P[i*4+j])
+
+// Q bumped up (0.001→0.01 for position, 0.01→0.05 for velocity) so the
+// Kalman filter trusts new measurements more and responds more quickly to
+// genuine eye motion.  With the old Q the filter over-trusted its own
+// motion model and the orb lagged noticeably behind saccades.
+export var kalQ = [0.01, 0, 0, 0,
+                   0, 0.01, 0, 0,
+                   0, 0, 0.05, 0,
+                   0, 0, 0, 0.05];  // process noise (symmetric diagonal)
+
+export var kalR = [0.04, 0,  // measurement noise (flat 2x2: [R00,R01,R10,R11])
+                   0, 0.04];
+
+export function kalUpdate(zx, zy) {
+  // Prediction: x = F*x, P = F*P*F' + Q
+  // F = [[1,0,dt,0],[0,1,0,dt],[0,0,1,0],[0,0,0,1]], dt=1
+  var dt = 1;
+  // Predict state
+  var px = kalX[0] + kalX[2] * dt;
+  var py = kalX[1] + kalX[3] * dt;
+  // Predict P: F*P
+  // F*P where F adds velocity*dt to position rows
+  var pP = new Float64Array(16);
+  for (var i = 0; i < 4; i++) {
+    for (var j = 0; j < 4; j++) {
+      var sum = 0;
+      for (var k = 0; k < 4; k++) {
+        var fik = (i < 2 && k === i + 2) ? dt : (i === k ? 1 : 0); // F[i][k]
+        sum += fik * kalP[k * 4 + j];
+      }
+      pP[i * 4 + j] = sum;
+    }
+  }
+  // pP * F' + Q
+  for (var i = 0; i < 4; i++) {
+    for (var j = 0; j < 4; j++) {
+      var sum = 0;
+      for (var k = 0; k < 4; k++) {
+        var fkj = (k < 2 && j === k + 2) ? dt : (k === j ? 1 : 0); // F'[k][j] = F[j][k]
+        sum += pP[i * 4 + k] * fkj;
+      }
+      kalP[i * 4 + j] = sum + kalQ[i * 4 + j];
+    }
+  }
+  // Innovation: y = z - H*x
+  var yx = zx - px;
+  var yy = zy - py;
+  // S = H*P*H' + R  (2x2)
+  // H = [[1,0,0,0],[0,1,0,0]], so H*P*H' extracts the 2x2 top-left block of P:
+  //   [P00 P01]   plus R (flat: [R00,R01,R10,R11])
+  //   [P10 P11]
+  var s00 = kalP[0]  + kalR[0];
+  var s01 = kalP[1]  + kalR[1];
+  var s10 = kalP[4]  + kalR[2];
+  var s11 = kalP[5]  + kalR[3];
+  var sDet = s00 * s11 - s01 * s10;
+  if (Math.abs(sDet) < 1e-12) { kalX = [zx, zy, 0, 0]; return {x: zx, y: zy}; }
+  var sInv00 =  s11 / sDet;
+  var sInv01 = -s01 / sDet;
+  var sInv10 = -s10 / sDet;
+  var sInv11 =  s00 / sDet;
+  // K = P * H' * S^-1  (4x2 matrix, stored flat as K[i*2+row])
+  // With H = [[1,0,0,0],[0,1,0,0]], H' has 1s at (0,0) and (1,1) only,
+  // so P*H' picks the first two columns of P, then multiplied by S^-1 (2x2).
+  var K = new Float64Array(8); // 4x2
+  for (var i = 0; i < 4; i++) {
+    K[i*2+0] = kalP[i*4+0] * sInv00 + kalP[i*4+1] * sInv10;
+    K[i*2+1] = kalP[i*4+0] * sInv01 + kalP[i*4+1] * sInv11;
+  }
+  // x = px + K*y
+  kalX[0] = px + K[0] * yx + K[1] * yy;
+  kalX[1] = py + K[2] * yx + K[3] * yy;
+  kalX[2] = kalX[2] + K[4] * yx + K[5] * yy;
+  kalX[3] = kalX[3] + K[6] * yx + K[7] * yy;
+  // P = (I - K*H) * P   (Joseph form: numerical stability)
+  // With H = [[1,0,0,0],[0,1,0,0]], only columns 0,1 of K matter:
+  //   (I-KH)[i][j] = δ(i,j) - K[i*2+0]*(j==0) - K[i*2+1]*(j==1)
+  // So (I-KH)*P simplifies to:
+  //   newP[i][k] = P[i][k] - K[i*2+0]*P[0][k] - K[i*2+1]*P[1][k]
+  var newP = new Float64Array(16);
+  for (var i = 0; i < 4; i++) {
+    for (var k = 0; k < 4; k++) {
+      newP[i*4+k] = kalP[i*4+k] - K[i*2+0]*kalP[k] - K[i*2+1]*kalP[4+k];
+    }
+  }
+  // Symmetrize P to prevent numerical drift
+  for (var i = 0; i < 4; i++) {
+    for (var j = i + 1; j < 4; j++) {
+      var avg = (newP[i*4+j] + newP[j*4+i]) * 0.5;
+      newP[i*4+j] = avg;
+      newP[j*4+i] = avg;
+    }
+  }
+  for (var i = 0; i < 16; i++) kalP[i] = newP[i];
+
+  return {x: kalX[0], y: kalX[1]};
+}
+
+export function kalInit() {
+  kalX = [0.5, 0.5, 0, 0];
+  for (var i = 0; i < 16; i++) kalP[i] = (i % 5 === 0) ? 1 : 0;
+}

+ 330 - 0
js/main.js

@@ -0,0 +1,330 @@
+// main.js
+// Entry point. Wires up MediaPipe FaceMesh initialization, the Camera,
+// the "Retry" button on the error overlay, the CDN-timeout fallback, and
+// the first-time auto-calibration trigger. All DOM bindings and runtime
+// state live in the other modules; this file just stitches them together.
+
+import { dbgSet, dbgSetError, setLoaderText, fmtBytes } from './utils.js';
+import { onResults } from './gaze.js';
+import {
+  bindRecalibrateButton, tryRestoreCalibration,
+  startCalibration, calibrationData, calActive
+} from './calibration.js';
+import { setFaceMeshRef } from './renderer.js';
+
+// ---- DOM references ----
+const video      = document.getElementById('webcam');
+const loader     = document.getElementById('loader');
+const loaderText = document.getElementById('loader-text');
+const loaderSub  = document.getElementById('loader-sub');
+const errOverlay = document.getElementById('error-overlay');
+const errTitle   = document.getElementById('err-title');
+const errMsg     = document.getElementById('err-msg');
+const errRetry   = document.getElementById('err-retry');
+const statusDot  = document.getElementById('status-dot');
+const statusText = document.getElementById('status-text');
+
+// Debug panel
+const dbgModel   = document.getElementById('dbg-model');
+const dbgCamera  = document.getElementById('dbg-camera');
+const dbgBytes   = document.getElementById('dbg-bytes');
+const dbgCdn3    = document.getElementById('dbg-cdn3');
+
+// ---- Shared runtime state ----
+let faceMesh = null;
+let camera   = null;
+let frameCount = 0;         // for frame skipping (process every 2nd frame)
+let lastMeshSendAt = 0;
+
+// ---- Error overlay ----
+function showError(title, msg) {
+  console.error('[error]', title, '—', msg);
+  errTitle.textContent = title;
+  errMsg.textContent   = msg;
+  errOverlay.classList.add('show');
+  loader.classList.add('hidden');
+  statusDot.className  = 'dot err';
+  statusText.className = 'value err';
+  statusText.textContent = 'ERROR';
+  dbgSetError((title ? title + ' — ' : '') + (msg || ''));
+  // Renderer also writes its own stage row; update here for consistency.
+  const dbgStage = document.getElementById('dbg-stage');
+  dbgSet(dbgStage, 'error', 'err');
+}
+
+errRetry.addEventListener('click', () => {
+  errOverlay.classList.remove('show');
+  location.reload();
+});
+
+// ---- Model asset pre-fetch with byte-level progress ----
+// Pre-fetch a list of MediaPipe WASM / data files with byte-level progress.
+// Returns a map { filename -> blob: URL } suitable for locateFile().
+// If any file fails, the function still resolves with whatever succeeded
+// (MediaPipe will retry from the network as a fallback).
+async function prefetchAssets(files) {
+  console.log('[model] pre-fetching', files.length, 'asset(s)…');
+  dbgSet(dbgModel, 'loading…', 'run');
+  const out = {};
+  let totalBytes = 0;
+  for (let i = 0; i < files.length; i++) {
+    const file = files[i];
+    const url = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/' + file;
+    setLoaderText(
+      'Downloading model (' + (i + 1) + '/' + files.length + ')',
+      file + '  (0 MB)'
+    );
+    console.log('[model] GET', file);
+    try {
+      const resp = await fetch(url, { mode: 'cors', cache: 'force-cache' });
+      if (!resp.ok) throw new Error('HTTP ' + resp.status);
+      const len = parseInt(resp.headers.get('content-length') || '0', 10);
+      // Stream the body so we can show incremental progress.
+      const reader = resp.body && resp.body.getReader ? resp.body.getReader() : null;
+      const chunks = [];
+      let received = 0;
+      if (reader) {
+        // eslint-disable-next-line no-constant-condition
+        while (true) {
+          const { done, value } = await reader.read();
+          if (done) break;
+          chunks.push(value);
+          received += value.byteLength;
+          totalBytes += value.byteLength;
+          const pct = len ? Math.round((received / len) * 100) : 0;
+          setLoaderText(
+            'Downloading model (' + (i + 1) + '/' + files.length + ' · ' + pct + '%)',
+            file + '  —  ' + fmtBytes(received) + (len ? ' / ' + fmtBytes(len) : '')
+          );
+          dbgSet(dbgBytes, fmtBytes(totalBytes));
+        }
+        const blob = new Blob(chunks, { type: resp.headers.get('content-type') || 'application/octet-stream' });
+        out[file] = URL.createObjectURL(blob);
+      } else {
+        const blob = await resp.blob();
+        out[file] = URL.createObjectURL(blob);
+        totalBytes += blob.size;
+        dbgSet(dbgBytes, fmtBytes(totalBytes));
+      }
+      console.log('[model] OK', file, fmtBytes(received || (out[file] ? 0 : 0)));
+    } catch (e) {
+      console.warn('[model] pre-fetch failed for', file, e && e.message);
+      // leave out[file] undefined → MediaPipe will fall back to the URL
+    }
+  }
+  dbgSet(dbgModel, 'ready (' + fmtBytes(totalBytes) + ')', 'ok');
+  console.log('[model] pre-fetch done, total', fmtBytes(totalBytes));
+  return out;
+}
+
+async function initFaceMesh() {
+  console.log('[init] initFaceMesh start');
+  setLoaderText(
+    'Initializing face mesh…',
+    'Preparing the iris-tracking model. This may take a moment.'
+  );
+  dbgSet(dbgModel, 'init…', 'run');
+  try {
+    // 1) Pre-fetch the big WASM / data files so the user can see progress
+    //    instead of a silent stall. The list mirrors the files MediaPipe
+    //    requests at runtime when refineLandmarks is enabled.
+    const assetMap = await prefetchAssets([
+      'face_mesh_solution_simd_wasm_bin.js',
+      'face_mesh_solution_simd_wasm_bin.wasm',
+      'face_mesh_solution_packed_assets.data'
+    ]);
+
+    setLoaderText(
+      'Initializing face mesh…',
+      'WASM runtime ready. Constructing the model.'
+    );
+
+    // 2) Construct FaceMesh. If we pre-fetched a file, serve it from the
+    //    blob URL so the browser uses the cached bytes; otherwise let
+    //    MediaPipe fall back to the CDN.
+    faceMesh = new FaceMesh({
+      locateFile: (file) => {
+        if (assetMap[file]) {
+          console.log('[model] locateFile (cached)', file);
+          return assetMap[file];
+        }
+        const url = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/' + file;
+        console.log('[model] locateFile (remote)', file);
+        return url;
+      }
+    });
+    faceMesh.setOptions({
+      maxNumFaces: 1,
+      refineLandmarks: true,        // gives 468-477 iris
+      minDetectionConfidence: 0.5,
+      minTrackingConfidence: 0.5
+    });
+    faceMesh.onResults(onResults);
+    setFaceMeshRef(faceMesh);
+
+    console.log('[init] FaceMesh constructed, calling .initialize()');
+    setLoaderText(
+      'Initializing face mesh…',
+      'Calling MediaPipe .initialize() — finalizing WASM.'
+    );
+    if (typeof faceMesh.initialize === 'function') {
+      await faceMesh.initialize();
+    }
+    console.log('[init] FaceMesh ready');
+    dbgSet(dbgModel, 'ready', 'ok');
+
+    startCamera();
+  } catch (e) {
+    console.error('FaceMesh init failed:', e);
+    dbgSetError('FaceMesh init failed: ' + (e && e.message ? e.message : e));
+    dbgSet(dbgModel, 'failed', 'err');
+    showError(
+      'Initialization Failed',
+      'Could not load MediaPipe Face Mesh (' + ((e && e.message) || 'unknown error') +
+      '). Check your network connection and reload the page.'
+    );
+  }
+}
+
+function startCamera() {
+  console.log('[camera] startCamera');
+  setLoaderText(
+    'Connecting camera…',
+    'Requesting webcam access. Please click "Allow" in the browser prompt.'
+  );
+  dbgSet(dbgCamera, 'requesting…', 'run');
+  if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
+    dbgSet(dbgCamera, 'unsupported', 'err');
+    showError(
+      'Browser Not Supported',
+      'Your browser does not support getUserMedia. Please use a modern browser (Chrome, Firefox, Edge, Safari).'
+    );
+    return;
+  }
+
+  camera = new Camera(video, {
+    onFrame: async () => {
+      // Frame-skip: only send every 2nd frame to MediaPipe.  This roughly
+      // halves CPU usage on the face-mesh pass and noticeably improves
+      // responsiveness on mid-range laptops.
+      frameCount++;
+      if (frameCount % 2 !== 0) return;
+      if (faceMesh) {
+        const t0 = performance.now();
+        try {
+          await faceMesh.send({ image: video });
+        } catch (e) {
+          // swallow individual frame errors
+          console.warn('[frame] send error', e && e.message);
+        } finally {
+          lastMeshSendAt = performance.now() - t0;
+          if (lastMeshSendAt > 5) {
+            // Only log slow frames to keep the console quiet
+            // console.log('[frame] send', lastMeshSendAt.toFixed(1), 'ms');
+          }
+        }
+      }
+    },
+    width:  640,
+    height: 480
+  });
+
+  camera.start()
+    .then(() => {
+      // wait for metadata
+      return new Promise(resolve => {
+        if (video.readyState >= 1) return resolve();
+        video.addEventListener('loadedmetadata', resolve, { once: true });
+      });
+    })
+    .then(() => {
+      console.log('[camera] stream ready, hiding loader');
+      loader.classList.add('hidden');
+      statusText.textContent = 'READY';
+      dbgSet(dbgCamera, 'streaming', 'ok');
+      const dbgStage = document.getElementById('dbg-stage');
+      dbgSet(dbgStage, 'live', 'ok');
+
+      // First-time calibration: no localStorage → kick off the 9-point flow
+      if (!calibrationData && !calActive) {
+        // small delay so the user can settle in front of the camera
+        setTimeout(() => { if (!calibrationData && !calActive) startCalibration(); }, 800);
+      }
+    })
+    .catch(err => {
+      console.error('Camera error:', err);
+      dbgSet(dbgCamera, 'error', 'err');
+      const name = err && err.name;
+      if (name === 'NotAllowedError' || name === 'PermissionDeniedError' || name === 'SecurityError') {
+        showError(
+          'Camera Access Denied',
+          'We need your camera to track your gaze. Please click the camera icon in your browser\'s address bar, grant permission, then click Retry.'
+        );
+      } else if (name === 'NotFoundError' || name === 'OverconstrainedError') {
+        showError(
+          'No Camera Found',
+          'No webcam was detected on this device. Please connect a camera and reload the page.'
+        );
+      } else if (name === 'NotReadableError' || name === 'TrackStartError') {
+        showError(
+          'Camera Busy',
+          'Your camera appears to be in use by another application. Please close other apps (Zoom, Skype, etc.) and try again.'
+        );
+      } else {
+        showError(
+          'Camera Error',
+          (err && err.message) || 'An unknown error occurred while accessing the camera.'
+        );
+      }
+    });
+}
+
+// Wait for the global FaceMesh symbol to be available
+function waitFor(predicate, timeout = 20000) {
+  return new Promise((resolve, reject) => {
+    const start = performance.now();
+    (function check() {
+      if (predicate()) return resolve();
+      if (performance.now() - start > timeout) return reject(new Error('Timeout waiting for MediaPipe'));
+      requestAnimationFrame(check);
+    })();
+  });
+}
+
+// ---- Boot sequence ----
+// 1) Restore any previously-saved calibration (synchronous, before camera).
+tryRestoreCalibration();
+// 2) Wire up the "Recalibrate" button so it's ready once the model is up.
+bindRecalibrateButton(() => !!faceMesh);
+// 3) Wait for the MediaPipe CDN script to register window.FaceMesh.
+setLoaderText(
+  'Loading MediaPipe JS…',
+  'Downloading the MediaPipe scripts from the CDN.'
+);
+console.log('[boot] waiting for window.FaceMesh…');
+waitFor(() => typeof window.FaceMesh === 'function', 20000)
+  .then(() => {
+    console.log('[boot] window.FaceMesh available');
+    initFaceMesh();
+  })
+  .catch((e) => {
+    console.error('[boot] FaceMesh never appeared:', e && e.message);
+    dbgSet(dbgCdn3, 'TIMEOUT', 'err');
+    dbgSetError('Timed out waiting for MediaPipe JS. The CDN may be blocked.');
+    showError(
+      'Failed to Load MediaPipe',
+      'The MediaPipe library could not be loaded (timeout). The CDN may be blocked in your region — try a VPN or a different network, then reload.'
+    );
+  });
+
+// Safety: if a CDN script failed before waitFor() could resolve, bail out
+// promptly with a clear message instead of waiting for the timeout.
+window.addEventListener('cdnError', () => {
+  if (typeof window.FaceMesh !== 'function') {
+    console.error('[boot] CDN error before FaceMesh became available');
+    showError(
+      'CDN Load Failed',
+      'Could not download the MediaPipe library from the CDN. The CDN may be blocked in your region — try a VPN, a different network, or self-host the files, then reload.'
+    );
+  }
+});

+ 273 - 0
js/math.js

@@ -0,0 +1,273 @@
+// math.js
+// Linear-algebra helpers + sample averaging.
+// Pure functions; no DOM; no side effects.
+
+// ---- Sample averaging (V2) ----
+// Averages all the per-frame features collected during calibration.  Old samples
+// without ear/pitch/yaw simply contribute 0 to the corresponding sums (we
+// branch on the field being defined), so the function degrades gracefully if
+// it's ever called on a partially-populated sample batch.
+export function averageSamples(samples) {
+  if (!samples.length) {
+    return { ratioX: 0.5, ratioY: 0.5, ear: 0, pitch: 0, yaw: 0 };
+  }
+  let sx = 0, sy = 0;
+  let eSum = 0, eN = 0;
+  let pSum = 0, pN = 0;
+  let wSum = 0, wN = 0;
+  for (let i = 0; i < samples.length; i++) {
+    const s = samples[i];
+    sx += s.ratioX;
+    sy += s.ratioY;
+    if (s.ear   !== undefined && s.ear   !== null) { eSum += s.ear;   eN++; }
+    if (s.pitch !== undefined && s.pitch !== null) { pSum += s.pitch; pN++; }
+    if (s.yaw   !== undefined && s.yaw   !== null) { wSum += s.yaw;   wN++; }
+  }
+  const n = samples.length;
+  return {
+    ratioX: sx / n,
+    ratioY: sy / n,
+    ear:    eN ? eSum / eN : 0,
+    pitch:  pN ? pSum / pN : 0,
+    yaw:    wN ? wSum / wN : 0
+  };
+}
+
+// ---- NxN linear solver (Gaussian elimination with partial pivoting) ----
+// Replaces the old Cramer's-rule 6x6 solver when we need a 9x9 (or any other
+// size) normal equation.  Cramer's is O(n!) and becomes both slow and
+// numerically unstable past ~6x6, so we switch to LU-with-pivoting here.
+//
+//   A is an n×n matrix (array of n row-arrays of length n).
+//   b is an n-vector.
+//   Returns the n-vector x such that A·x = b, or null if A is singular
+//   (rank-deficient to machine precision, |pivot| < 1e-12).
+export function solveNxN(n, A, b) {
+  // Build the augmented [A|b] matrix in row-major form.
+  const M = new Array(n);
+  for (let i = 0; i < n; i++) {
+    const row = new Array(n + 1);
+    for (let j = 0; j < n; j++) row[j] = A[i][j];
+    row[n] = b[i];
+    M[i] = row;
+  }
+
+  // Forward elimination.
+  for (let k = 0; k < n; k++) {
+    // Partial pivoting: pick the row with the largest |M[i][k]| for i >= k.
+    let maxVal = Math.abs(M[k][k]);
+    let maxRow = k;
+    for (let i = k + 1; i < n; i++) {
+      const v = Math.abs(M[i][k]);
+      if (v > maxVal) { maxVal = v; maxRow = i; }
+    }
+    if (maxVal < 1e-12) return null;            // singular
+    if (maxRow !== k) {                        // swap rows
+      const tmp = M[k]; M[k] = M[maxRow]; M[maxRow] = tmp;
+    }
+    // Eliminate below the pivot.
+    for (let i = k + 1; i < n; i++) {
+      const factor = M[i][k] / M[k][k];
+      if (factor === 0) continue;
+      for (let j = k; j <= n; j++) {
+        M[i][j] -= factor * M[k][j];
+      }
+    }
+  }
+
+  // Back substitution.
+  const x = new Array(n);
+  for (let i = n - 1; i >= 0; i--) {
+    let sum = M[i][n];
+    for (let j = i + 1; j < n; j++) sum -= M[i][j] * x[j];
+    x[i] = sum / M[i][i];
+  }
+  return x;
+}
+
+// ============================================================
+//  Old 6-dim helpers (kept for back-compat / regression testing)
+// ============================================================
+
+// Solve a 3×3 linear system A x = b via Cramer's rule.
+// Returns [x0, x1, x2] or null if A is singular.
+export function solve3x3(A, b) {
+  const det = (
+    A[0][0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) -
+    A[0][1] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) +
+    A[0][2] * (A[1][0] * A[2][1] - A[1][1] * A[2][0])
+  );
+  if (Math.abs(det) < 1e-9) return null;
+
+  const det0 = (
+    b[0]    * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) -
+    A[0][1] * (b[1]    * A[2][2] - A[1][2] * b[2])    +
+    A[0][2] * (b[1]    * A[2][1] - A[1][1] * b[2])
+  );
+  const det1 = (
+    A[0][0] * (b[1]    * A[2][2] - A[1][2] * b[2])    -
+    b[0]    * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) +
+    A[0][2] * (A[1][0] * b[2]    - b[1]    * A[2][0])
+  );
+  const det2 = (
+    A[0][0] * (A[1][1] * b[2]    - b[1]    * A[2][1]) -
+    A[0][1] * (A[1][0] * b[2]    - b[1]    * A[2][0]) +
+    b[0]    * (A[1][0] * A[2][1] - A[1][1] * A[2][0])
+  );
+
+  return [det0 / det, det1 / det, det2 / det];
+}
+
+// 6x6 Cramer's rule: solve Ax=b where A is 6x6, b is 6x1
+// A is passed as array of 6 rows, each row is [a0..a5]
+export function solve6x6(A, b) {
+  function det6(m) {
+    // Compute 6x6 determinant via cofactor expansion along first row
+    let d = 0;
+    for (let j = 0; j < 6; j++) {
+      const minor = [];
+      for (let i = 1; i < 6; i++) {
+        const row = [];
+        for (let k = 0; k < 6; k++) {
+          if (k !== j) row.push(m[i][k]);
+        }
+        minor.push(row);
+      }
+      const sign = (j % 2 === 0) ? 1 : -1;
+      d += sign * m[0][j] * det5(minor);
+    }
+    return d;
+  }
+  function det5(m) {
+    let d = 0;
+    for (let j = 0; j < 5; j++) {
+      const minor = [];
+      for (let i = 1; i < 5; i++) {
+        const row = [];
+        for (let k = 0; k < 5; k++) {
+          if (k !== j) row.push(m[i][k]);
+        }
+        minor.push(row);
+      }
+      const sign = (j % 2 === 0) ? 1 : -1;
+      d += sign * m[0][j] * det4(minor);
+    }
+    return d;
+  }
+  function det4(m) {
+    // 4x4 determinant via cofactor expansion
+    let d = 0;
+    for (let j = 0; j < 4; j++) {
+      const minor = [];
+      for (let i = 1; i < 4; i++) {
+        const row = [];
+        for (let k = 0; k < 4; k++) {
+          if (k !== j) row.push(m[i][k]);
+        }
+        minor.push(row);
+      }
+      const sign = (j % 2 === 0) ? 1 : -1;
+      d += sign * m[0][j] * det3(minor);
+    }
+    return d;
+  }
+  function det3(m) {
+    return m[0][0]*(m[1][1]*m[2][2]-m[1][2]*m[2][1])
+         - m[0][1]*(m[1][0]*m[2][2]-m[1][2]*m[2][0])
+         + m[0][2]*(m[1][0]*m[2][1]-m[1][1]*m[2][0]);
+  }
+  const D = det6(A);
+  if (Math.abs(D) < 1e-12) return null; // singular
+  const x = [];
+  for (let j = 0; j < 6; j++) {
+    const Aj = A.map((row, i) => {
+      const r = row.slice();
+      r[j] = b[i];
+      return r;
+    });
+    x.push(det6(Aj) / D);
+  }
+  return x;
+}
+
+// Build 6-dim polynomial design row from iris ratios
+export function buildPolyFeatures(rX, rY) {
+  return [1, rX, rY, rX*rX, rY*rY, rX*rY];
+}
+
+// Build the design matrix for [a0, a1, …, a5] with rows [1, rX, rY, rX², rY², rX*rY].
+export function buildDesignMatrix(points) {
+  const M = [];
+  for (let i = 0; i < points.length; i++) {
+    M.push(buildPolyFeatures(points[i].ratioX, points[i].ratioY));
+  }
+  return M;
+}
+
+// Ordinary least squares for y = X * beta. Returns beta = [b0, …, b5]
+// (we use Cramer's rule on X^T X and X^T y — small, dense, exact).
+export function olsFit(X, y) {
+  const n = X.length;
+  // X^T X   (6x6)
+  const A = [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]];
+  // X^T y   (6x1)
+  const b = [0, 0, 0, 0, 0, 0];
+  for (let i = 0; i < n; i++) {
+    const xi = X[i];
+    for (let r = 0; r < 6; r++) {
+      for (let c = 0; c < 6; c++) A[r][c] += xi[r] * xi[c];
+      b[r] += xi[r] * y[i];
+    }
+  }
+  return solve6x6(A, b);
+}
+
+// ============================================================
+//  V2 (9-dim) helpers:  [1, rX, rY, ear, pitch, yaw, rX², rY², rX*rY]
+// ============================================================
+// The V2 feature layout.  Head-pose features (ear, pitch, yaw) enter
+// linearly; the polynomial cross-terms (rX², rY², rX*rY) only involve
+// the iris ratios, which is what the literature converges on (eye-contour
+// + iris is dominant, with head pose as an auxiliary).
+export const N_FEATURES_V2 = 9;
+
+// Build one 9-dim design row from a (rX, rY, ear, pitch, yaw) sample.
+export function buildPolyFeaturesV2(rX, rY, ear, pitch, yaw) {
+  return [1, rX, rY, ear, pitch, yaw, rX*rX, rY*rY, rX*rY];
+}
+
+// Build a 9-dim design matrix from a list of points that carry the V2 features.
+// `points` is expected to be [{ ratioX, ratioY, ear, pitch, yaw }, ...].
+export function buildDesignMatrixV2(points) {
+  const M = [];
+  for (let i = 0; i < points.length; i++) {
+    const p = points[i];
+    M.push(buildPolyFeaturesV2(
+      p.ratioX, p.ratioY,
+      p.ear   != null ? p.ear   : 0,
+      p.pitch != null ? p.pitch : 0,
+      p.yaw   != null ? p.yaw   : 0
+    ));
+  }
+  return M;
+}
+
+// Ordinary least squares for an arbitrary-dim design matrix.
+//   X is m × nFeatures (m >= nFeatures), y is m × 1.
+//   Solves (X^T X) beta = X^T y via Gaussian elimination with partial pivoting.
+export function olsFitV2(X, y, nFeatures) {
+  const n = X.length;
+  // X^T X   (nFeatures x nFeatures)
+  const A = new Array(nFeatures);
+  for (let r = 0; r < nFeatures; r++) A[r] = new Array(nFeatures).fill(0);
+  // X^T y   (nFeatures x 1)
+  const b = new Array(nFeatures).fill(0);
+  for (let i = 0; i < n; i++) {
+    const xi = X[i];
+    for (let r = 0; r < nFeatures; r++) {
+      for (let c = 0; c < nFeatures; c++) A[r][c] += xi[r] * xi[c];
+      b[r] += xi[r] * y[i];
+    }
+  }
+  return solveNxN(nFeatures, A, b);
+}

+ 298 - 0
js/renderer.js

@@ -0,0 +1,298 @@
+// renderer.js
+// Canvas rendering: stage canvas (orb + trail) + overlay canvas (face mesh on preview).
+// Owns: W, H, ctx, octx, stage, overlay, smoothedX, smoothedY, trail, fpsSmooth, lastTime.
+
+import { TRAIL_LENGTH, ORB_RADIUS, FACE_OVAL, LIPS, L_EYE, R_EYE, L_BROW, R_BROW, IRIS_LANDMARKS, L_IRIS, R_IRIS, CAL_ORDER } from './config.js';
+import { dbgSet } from './utils.js';
+import { kalUpdate } from './kalman.js';
+import {
+  rawX, rawY, lastResults, lastFrameMs,
+  irisVisible, lastEAR, lastBlinking, lastHeadPose
+} from './gaze.js';
+import { calActive, calPaused, calCurrentIdx, getRawXValid, registerResetSmoothed, positionCalDot } from './calibration.js';
+
+// ---- DOM references ----
+const stage    = document.getElementById('stage');
+const ctx      = stage.getContext('2d');
+const overlay  = document.getElementById('overlay');
+const octx     = overlay.getContext('2d');
+
+// Status bar elements
+const statusDot  = document.getElementById('status-dot');
+const statusText = document.getElementById('status-text');
+const fpsEl      = document.getElementById('fps');
+const gxEl       = document.getElementById('gaze-x');
+const gyEl       = document.getElementById('gaze-y');
+const ilEl       = document.getElementById('iris-l');
+const irEl       = document.getElementById('iris-r');
+
+// Debug panel stage row
+const dbgStage   = document.getElementById('dbg-stage');
+const dbgFrame   = document.getElementById('dbg-frame');
+// V2 debug panel rows (EAR, blink flag, pitch, yaw) — set in the animation loop.
+const dbgEar     = document.getElementById('dbg-ear');
+const dbgBlink   = document.getElementById('dbg-blink');
+const dbgPitch   = document.getElementById('dbg-pitch');
+const dbgYaw     = document.getElementById('dbg-yaw');
+
+// ---- Renderer state ----
+export let W = 0, H = 0;
+let smoothedX = 0.5, smoothedY = 0.5;     // Kalman-smoothed gaze (0..1)
+let trail = [];                           // array of {x, y}
+let lastTime = performance.now();
+let fpsSmooth = 0;
+
+export function resetSmoothed() {
+  smoothedX = 0.5;
+  smoothedY = 0.5;
+}
+
+// ============================================================
+//  Canvas sizing
+// ============================================================
+function resize() {
+  const dpr = Math.min(window.devicePixelRatio || 1, 2);
+  W = window.innerWidth;
+  H = window.innerHeight;
+  stage.width  = W * dpr;
+  stage.height = H * dpr;
+  stage.style.width  = W + 'px';
+  stage.style.height = H + 'px';
+  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+}
+window.addEventListener('resize', () => {
+  resize();
+  // Re-position the calibration dot if one is currently active
+  if (calActive && calCurrentIdx < CAL_ORDER.length) {
+    positionCalDot(calCurrentIdx);
+  }
+});
+
+// Register the smoothed-reset hook so calibration.clearCalibration() can
+// snap the orb back to the center after a recalibration.
+registerResetSmoothed(resetSmoothed);
+
+resize();
+
+// ============================================================
+//  Render: full-screen orb + trail
+// ============================================================
+function drawOrb() {
+  // Clear with very slight motion blur for the trail
+  ctx.fillStyle = 'rgba(10, 10, 26, 0.35)';
+  ctx.fillRect(0, 0, W, H);
+
+  // Map smoothed gaze to screen coordinates (with margin so orb stays on screen)
+  const margin = 60;
+  const sx = margin + smoothedX * (W - margin * 2);
+  const sy = margin + smoothedY * (H - margin * 2);
+
+  // Push trail
+  trail.push({ x: sx, y: sy });
+  if (trail.length > TRAIL_LENGTH) trail.shift();
+
+  // Draw trail (oldest -> newest, fading in opacity & shrinking radius)
+  // Cheap: simple filled circles, no radialGradient per point.
+  for (let i = 0; i < trail.length; i++) {
+    const t = trail[i];
+    const tNorm = (i + 1) / trail.length;   // 0..1
+    const r = ORB_RADIUS * 0.12 * tNorm;
+    const a = 0.03 + 0.25 * tNorm;
+    ctx.fillStyle = 'rgba(0, 229, 255, ' + a + ')';
+    ctx.beginPath();
+    ctx.arc(t.x, t.y, r, 0, Math.PI * 2);
+    ctx.fill();
+  }
+
+  // Main orb - layered radial gradients for glow.
+  // During a blink we dim the orb (~55% intensity) so the user gets
+  // visual feedback that the blink was registered, but we keep it on
+  // screen so its position is unambiguous.  The dim also hides the
+  // brief artifacts that some webcams produce at the moment of lid closure.
+  const blink = lastBlinking;
+  // Alpha multipliers: halo and mid-glow dim more aggressively than the
+  // core so the orb still has a recognisable shape at low alpha.
+  const haloMul = blink ? 0.55 : 1.0;
+  const midMul  = blink ? 0.60 : 1.0;
+  const coreMul = blink ? 0.70 : 1.0;
+  // Optional tint shift: when blinking we mix a touch of warm magenta
+  // into the orb so it reads as "muted" rather than just "faded".  We
+  // shift the highlight stop to a slightly pinker cyan.
+  const highlightR = blink ? 200 : 180;
+  const highlightG = blink ? 180 : 255;
+  const highlightB = blink ? 255 : 255;
+
+  const cx = sx, cy = sy;
+
+  // Outer halo
+  let g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS * 4);
+  g.addColorStop(0,    'rgba(0, 229, 255, ' + (0.35 * haloMul).toFixed(3) + ')');
+  g.addColorStop(0.25, 'rgba(0, 229, 255, ' + (0.18 * haloMul).toFixed(3) + ')');
+  g.addColorStop(0.6,  'rgba(0, 184, 212, ' + (0.05 * haloMul).toFixed(3) + ')');
+  g.addColorStop(1,    'rgba(0, 229, 255, 0)');
+  ctx.fillStyle = g;
+  ctx.beginPath();
+  ctx.arc(cx, cy, ORB_RADIUS * 4, 0, Math.PI * 2);
+  ctx.fill();
+
+  // Mid glow
+  g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS * 1.8);
+  g.addColorStop(0,    'rgba(' + highlightR + ', ' + highlightG + ', ' + highlightB + ', ' + (0.95 * midMul).toFixed(3) + ')');
+  g.addColorStop(0.25, 'rgba(0, 229, 255, ' + (0.85 * midMul).toFixed(3) + ')');
+  g.addColorStop(0.65, 'rgba(0, 184, 212, ' + (0.5  * midMul).toFixed(3) + ')');
+  g.addColorStop(1,    'rgba(0, 229, 255, 0)');
+  ctx.fillStyle = g;
+  ctx.beginPath();
+  ctx.arc(cx, cy, ORB_RADIUS * 1.8, 0, Math.PI * 2);
+  ctx.fill();
+
+  // Core
+  g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS);
+  g.addColorStop(0,   'rgba(255, 255, 255, ' + (1.0  * coreMul).toFixed(3) + ')');
+  g.addColorStop(0.3, 'rgba(' + highlightR + ', ' + highlightG + ', ' + highlightB + ', ' + (1.0 * coreMul).toFixed(3) + ')');
+  g.addColorStop(0.7, 'rgba(0, 229, 255, ' + (0.95 * coreMul).toFixed(3) + ')');
+  g.addColorStop(1,   'rgba(0, 184, 212, ' + (0.7  * coreMul).toFixed(3) + ')');
+  ctx.fillStyle = g;
+  ctx.beginPath();
+  ctx.arc(cx, cy, ORB_RADIUS, 0, Math.PI * 2);
+  ctx.fill();
+
+  // Inner sparkle
+  ctx.fillStyle = 'rgba(255, 255, 255, ' + (0.85 * coreMul).toFixed(3) + ')';
+  ctx.beginPath();
+  ctx.arc(cx - ORB_RADIUS * 0.25, cy - ORB_RADIUS * 0.25, ORB_RADIUS * 0.18, 0, Math.PI * 2);
+  ctx.fill();
+}
+
+// ============================================================
+//  Render: face mesh overlay on webcam preview
+// ============================================================
+function drawOverlay(results) {
+  const w = overlay.width;
+  const h = overlay.height;
+  octx.clearRect(0, 0, w, h);
+
+  if (!results || !results.multiFaceLandmarks || results.multiFaceLandmarks.length === 0) {
+    // Subtle "no face" indicator
+    octx.strokeStyle = 'rgba(0, 229, 255, 0.25)';
+    octx.setLineDash([4, 4]);
+    octx.lineWidth = 1;
+    octx.strokeRect(8, 8, w - 16, h - 16);
+    octx.setLineDash([]);
+    octx.fillStyle = 'rgba(0, 229, 255, 0.7)';
+    octx.font = '10px monospace';
+    octx.fillText('NO FACE DETECTED', 12, h - 12);
+    return;
+  }
+
+  const lm = results.multiFaceLandmarks[0];
+  // Note: the video is mirrored visually via CSS, so we mirror X here
+  // to keep the mesh aligned with what the user sees.
+  const pt = (i) => ({ x: (1 - lm[i].x) * w, y: lm[i].y * h });
+
+  // Draw mesh lines
+  octx.lineWidth = 0.6;
+  octx.strokeStyle = 'rgba(0, 229, 255, 0.45)';
+  octx.beginPath();
+  [FACE_OVAL, LIPS, L_EYE, R_EYE, L_BROW, R_BROW].forEach(connections => {
+    for (let i = 0; i < connections.length; i++) {
+      const a = pt(connections[i]);
+      const b = pt(connections[(i + 1) % connections.length]);
+      octx.moveTo(a.x, a.y);
+      octx.lineTo(b.x, b.y);
+    }
+  });
+  octx.stroke();
+
+  // Subtle face dots (subsample every 6th point for performance)
+  octx.fillStyle = 'rgba(0, 229, 255, 0.4)';
+  for (let i = 0; i < lm.length; i++) {
+    if (i % 6 !== 0) continue;   // was % 3 — doubled the stride to halve the work
+    const p = pt(i);
+    octx.fillRect(p.x, p.y, 1, 1);
+  }
+
+  // Iris highlight (big + bright)
+  octx.fillStyle = '#ffeb3b';
+  IRIS_LANDMARKS.forEach(idx => {
+    const p = pt(idx);
+    octx.beginPath();
+    octx.arc(p.x, p.y, 1.6, 0, Math.PI * 2);
+    octx.fill();
+  });
+
+  // Iris center (468 / 473) - extra large
+  [L_IRIS, R_IRIS].forEach(idx => {
+    const p = pt(idx);
+    octx.fillStyle = '#ffffff';
+    octx.beginPath();
+    octx.arc(p.x, p.y, 2.6, 0, Math.PI * 2);
+    octx.fill();
+  });
+}
+
+// ============================================================
+//  Animation loop
+// ============================================================
+let faceMesh = null;
+export function setFaceMeshRef(v) { faceMesh = v; }
+
+function loop(now) {
+  // FPS
+  const dt = now - lastTime;
+  lastTime = now;
+  const instFps = 1000 / Math.max(dt, 1);
+  fpsSmooth = fpsSmooth === 0 ? instFps : (fpsSmooth * 0.9 + instFps * 0.1);
+
+  // Kalman filter: feed raw gaze through the Kalman filter.
+  // rawX/rawY are already screen-coords (applyRegression when calibrated,
+  // or raw iris ratio clamped to [0,1] before calibration is ready).
+  // No update when no iris is visible, so the orb holds its position
+  // instead of drifting back to center.
+  if (getRawXValid() && !calPaused) {
+    const kf = kalUpdate(rawX, rawY);
+    smoothedX = kf.x;
+    smoothedY = kf.y;
+  }
+
+  drawOrb();
+  if (lastResults) drawOverlay(lastResults);
+
+  // Status text — overall pipeline state
+  const visible = irisVisible.l || irisVisible.r;
+  if (visible) {
+    statusDot.className = 'dot ok';
+    statusText.className = 'value ok';
+    statusText.textContent = 'TRACKING';
+    dbgSet(dbgStage, 'tracking', 'ok');
+  } else if (faceMesh) {
+    statusDot.className = 'dot warn';
+    statusText.className = 'value warn';
+    statusText.textContent = 'NO IRIS';
+    dbgSet(dbgStage, 'no face', 'warn');
+  } else {
+    statusDot.className = 'dot';
+    statusText.className = 'value';
+    statusText.textContent = 'INIT';
+    dbgSet(dbgStage, 'init', 'run');
+  }
+  fpsEl.textContent = Math.round(fpsSmooth);
+  gxEl.textContent  = smoothedX.toFixed(3);
+  gyEl.textContent  = smoothedY.toFixed(3);
+  ilEl.textContent  = irisVisible.l ? '●' : '○';
+  irEl.textContent  = irisVisible.r ? '●' : '○';
+  ilEl.className    = 'value ' + (irisVisible.l ? 'ok' : 'warn');
+  irEl.className    = 'value ' + (irisVisible.r ? 'ok' : 'warn');
+  dbgSet(dbgFrame, lastFrameMs > 0 ? (lastFrameMs.toFixed(1) + ' ms') : '--');
+
+  // V2 debug rows: EAR, blink flag, pitch, yaw.  The blink row gets
+  // a warn class so the user can see at a glance that a blink was
+  // filtered this frame.
+  if (dbgEar)   dbgSet(dbgEar,   lastEAR > 0 ? lastEAR.toFixed(3) : '--');
+  if (dbgBlink) dbgSet(dbgBlink, lastBlinking ? 'YES' : 'no', lastBlinking ? 'warn' : null);
+  if (dbgPitch) dbgSet(dbgPitch, lastHeadPose.pitch.toFixed(3));
+  if (dbgYaw)   dbgSet(dbgYaw,   lastHeadPose.yaw.toFixed(3));
+
+  requestAnimationFrame(loop);
+}
+requestAnimationFrame(loop);

+ 81 - 0
js/utils.js

@@ -0,0 +1,81 @@
+// utils.js
+// Generic utilities: clamp, dbgSet (debug panel), setLoaderText, fmtBytes.
+// Also wires up the debug-panel CDN status listeners using window-level
+// CDN status (the MediaPipe CDN <script> tags in index.html set
+// window.__cdnStatus + dispatch cdnOk / cdnError events).
+
+// ---- Debug-panel element references ----
+const dbgPanel   = document.getElementById('debug-panel');
+const dbgHeader  = document.getElementById('debug-header');
+const dbgToggle  = document.getElementById('debug-toggle');
+const dbgCdn1    = document.getElementById('dbg-cdn1');
+const dbgCdn2    = document.getElementById('dbg-cdn2');
+const dbgCdn3    = document.getElementById('dbg-cdn3');
+const dbgErr     = document.getElementById('debug-err');
+
+// Loader text elements
+const loaderText = document.getElementById('loader-text');
+const loaderSub  = document.getElementById('loader-sub');
+
+// ---- Generic utilities ----
+export function clamp(v, lo, hi) { return Math.min(hi, Math.max(lo, v)); }
+
+export function dbgSet(el, text, cls) {
+  if (!el) return;
+  el.textContent = text;
+  el.className = 'v' + (cls ? ' ' + cls : '');
+}
+
+export function dbgSetError(msg) {
+  if (!dbgErr) return;
+  if (!msg) { dbgErr.classList.remove('show'); dbgErr.textContent = ''; return; }
+  dbgErr.textContent = msg;
+  dbgErr.classList.add('show');
+}
+
+export function setLoaderText(main, sub) {
+  if (loaderText) loaderText.textContent = main;
+  if (loaderSub)  loaderSub.textContent  = sub;
+  console.log('[loader]', main, '—', sub);
+}
+
+// Format bytes for the debug panel / loader text
+export function fmtBytes(n) {
+  if (n < 1024) return n + ' B';
+  if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
+  return (n / (1024 * 1024)).toFixed(2) + ' MB';
+}
+
+// ---- Debug panel: collapse/expand + CDN status wiring ----
+if (dbgHeader) {
+  dbgHeader.addEventListener('click', () => {
+    const collapsed = dbgPanel.classList.toggle('collapsed');
+    dbgPanel.classList.toggle('expanded', !collapsed);
+    dbgToggle.textContent = collapsed ? '+' : '–';
+  });
+}
+
+// Initialize CDN cells from the global status that the loader scripts set
+try {
+  const s = (window.__cdnStatus) || {};
+  dbgSet(dbgCdn1, s.camera_utils || (s.camera_utils === 'error' ? 'FAIL' : '…'),
+                s.camera_utils === 'ok' ? 'ok' : s.camera_utils === 'error' ? 'err' : 'run');
+  dbgSet(dbgCdn2, s.drawing_utils || (s.drawing_utils === 'error' ? 'FAIL' : '…'),
+                s.drawing_utils === 'ok' ? 'ok' : s.drawing_utils === 'error' ? 'err' : 'run');
+  dbgSet(dbgCdn3, s.face_mesh    || (s.face_mesh    === 'error' ? 'FAIL' : '…'),
+                s.face_mesh    === 'ok' ? 'ok' : s.face_mesh    === 'error' ? 'err' : 'run');
+} catch (e) { /* no-op */ }
+
+// Live-update on CDN load / failure events
+window.addEventListener('cdnOk', (e) => {
+  const n = e && e.detail && e.detail.name;
+  if (n === 'camera_utils') dbgSet(dbgCdn1, 'OK', 'ok');
+  if (n === 'drawing_utils') dbgSet(dbgCdn2, 'OK', 'ok');
+  if (n === 'face_mesh')    dbgSet(dbgCdn3, 'OK', 'ok');
+});
+window.addEventListener('cdnError', (e) => {
+  const n = e && e.detail && e.detail.name;
+  if (n === 'camera_utils') { dbgSet(dbgCdn1, 'FAIL', 'err'); dbgSetError('CDN camera_utils failed to load'); }
+  if (n === 'drawing_utils') { dbgSet(dbgCdn2, 'FAIL', 'err'); dbgSetError('CDN drawing_utils failed to load'); }
+  if (n === 'face_mesh')    { dbgSet(dbgCdn3, 'FAIL', 'err'); dbgSetError('CDN face_mesh failed to load'); }
+});