| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444 |
- // 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');
- }
- }
|