// 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);