gaze.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. // gaze.js
  2. // Per-frame MediaPipe FaceMesh result handler.
  3. // Owns: lastGaze, irisVisible, lastResults, lastFrameMs, lastDebugLogMs, rawX, rawY,
  4. // lastEAR, lastBlinking, lastHeadPose.
  5. import {
  6. L_OUTER, L_INNER, L_TOP, L_BOT, L_IRIS,
  7. R_OUTER, R_INNER, R_TOP, R_BOT, R_IRIS,
  8. NOSE_TIP, CHIN, FOREHEAD,
  9. LEFT_EYE_CORNER, RIGHT_EYE_CORNER,
  10. EAR_BLINK_THRESHOLD, EAR_CLOSED_THRESHOLD
  11. } from './config.js';
  12. import { clamp } from './utils.js';
  13. import {
  14. applyRegression, calibrationData, calPaused,
  15. getRawXValid, setRawXValid,
  16. registerLastGazeGetter
  17. } from './calibration.js';
  18. // ---- Iris visibility flags ----
  19. export const irisVisible = { l: false, r: false };
  20. // ---- Most recent iris-ratio gaze sample (consumed by the calibration collector) ----
  21. // Extended with ear / pitch / yaw for the V2 regression model and the
  22. // per-frame blink filter. The `visible` flag still indicates whether the
  23. // iris was actually detected this frame; ear/pitch/yaw are computed only
  24. // when the face landmarks are present and are otherwise zero.
  25. export let lastGaze = {
  26. ratioX: 0.5, ratioY: 0.5,
  27. ear: 0, pitch: 0, yaw: 0,
  28. visible: false
  29. };
  30. // ---- Latest raw screen-coordinate gaze (set by onResults, consumed by renderer loop) ----
  31. export let rawX = 0.5;
  32. export let rawY = 0.5;
  33. // ---- Most recent FaceMesh results (consumed by renderer.drawOverlay) ----
  34. export let lastResults = null;
  35. // ---- Per-frame timing / debug throttling ----
  36. export let lastFrameMs = 0;
  37. let lastDebugLogMs = 0;
  38. // ---- New V2 state: blink filter + head-pose ----
  39. // lastEAR — most recent EAR value (averaged across the two eyes)
  40. // lastBlinking — true while EAR is below the blink threshold (the renderer
  41. // dims the orb to show the user that their blink was registered)
  42. // lastHeadPose — { pitch, yaw } geometric estimate; both are roughly in
  43. // [-0.5, +0.5] for natural head rotations and 0 when the
  44. // user faces the camera squarely.
  45. export let lastEAR = 0;
  46. export let lastBlinking = false;
  47. export let lastHeadPose = { pitch: 0, yaw: 0 };
  48. // Internal setters (the `let` bindings above are only mutated from within
  49. // this module, so we keep the setters file-local rather than exporting them).
  50. function setLastGaze(v) { lastGaze = v; }
  51. function setRawX(v) { rawX = v; }
  52. function setRawY(v) { rawY = v; }
  53. function setLastResults(v) { lastResults = v; }
  54. function setLastFrameMs(v) { lastFrameMs = v; }
  55. function setLastEAR(v) { lastEAR = v; }
  56. function setLastBlinking(v) { lastBlinking = v; }
  57. function setLastHeadPose(v) { lastHeadPose = v; }
  58. // ============================================================
  59. // Helpers: eye state features
  60. // ============================================================
  61. // Euclidean distance between two landmarks (both are MediaPipe-style
  62. // {x, y, z} points in normalized [0, 1] coordinates).
  63. function dist2D(a, b) {
  64. const dx = a.x - b.x;
  65. const dy = a.y - b.y;
  66. return Math.sqrt(dx * dx + dy * dy);
  67. }
  68. // Eye Aspect Ratio (Soukupová & Čech, 2016) — a 4-point approximation
  69. // using the inner-corner, outer-corner, and the top/bottom mid-points:
  70. // EAR = ||top - bot|| / ||outer - inner||
  71. // We average across both eyes because (a) blinks are usually synchronous
  72. // and (b) averaging stabilises the estimate against single-eye noise.
  73. //
  74. // Returns 0 if any landmark is missing (caller should treat that as
  75. // "eye state unknown" — we still attempt to keep the rest of the pipeline
  76. // running rather than throwing).
  77. function earForEye(landmarks, outerIdx, topIdx, botIdx, innerIdx) {
  78. const o = landmarks[outerIdx];
  79. const t = landmarks[topIdx];
  80. const b = landmarks[botIdx];
  81. const i = landmarks[innerIdx];
  82. if (!o || !t || !b || !i) return 0;
  83. const horiz = dist2D(o, i);
  84. if (horiz < 1e-6) return 0;
  85. return dist2D(t, b) / horiz;
  86. }
  87. // Compute the mean Eye Aspect Ratio across both eyes.
  88. export function computeEAR(landmarks) {
  89. if (!landmarks) return 0;
  90. // Left eye: outer=33, top=159, bot=145, inner=133
  91. // Right eye: outer=362, top=386, bot=374, inner=263
  92. const l = earForEye(landmarks, L_OUTER, L_TOP, L_BOT, L_INNER);
  93. const r = earForEye(landmarks, R_OUTER, R_TOP, R_BOT, R_INNER);
  94. // If only one eye is detected, use it; otherwise average.
  95. if (l > 0 && r > 0) return (l + r) * 0.5;
  96. if (l > 0) return l;
  97. if (r > 0) return r;
  98. return 0;
  99. }
  100. // Simple geometric head-pose estimate (no PnP solve needed).
  101. // yaw — horizontal nose offset, normalised by inter-eye distance.
  102. // Positive => head turned left (the nose moves toward the
  103. // right of the eye-line), negative => head turned right.
  104. // pitch — vertical nose offset, normalised by forehead-to-chin
  105. // distance. Positive => head tilted down (nose below the
  106. // geometric centre of the face), negative => head tilted up.
  107. //
  108. // We deliberately do NOT invert for screen mirroring here; head pose is
  109. // a property of the *face*, not of the screen, so the same value is
  110. // valid whether or not the preview is mirrored.
  111. export function computeHeadPose(landmarks) {
  112. if (!landmarks) return { pitch: 0, yaw: 0 };
  113. const nose = landmarks[NOSE_TIP];
  114. const chin = landmarks[CHIN];
  115. const forehead = landmarks[FOREHEAD];
  116. const lEye = landmarks[LEFT_EYE_CORNER];
  117. const rEye = landmarks[RIGHT_EYE_CORNER];
  118. if (!nose || !chin || !forehead || !lEye || !rEye) {
  119. return { pitch: 0, yaw: 0 };
  120. }
  121. // Eye centre: midpoint of the two outer eye corners.
  122. const eyeMidX = (lEye.x + rEye.x) * 0.5;
  123. const eyeMidY = (lEye.y + rEye.y) * 0.5;
  124. // Inter-eye horizontal distance — our yaw normaliser. Falls back to
  125. // a small epsilon to avoid division by zero if eyes happen to coincide.
  126. const eyeW = Math.abs(rEye.x - lEye.x) || 1e-6;
  127. // Yaw: how far the nose is offset horizontally from the eye line.
  128. // Positive yaw => the nose is to the right of the eye line in the
  129. // raw frame, which (because the raw frame is un-mirrored) means the
  130. // user has turned their head to their own LEFT. We leave the sign
  131. // raw here; the regression can fit whichever sign it likes.
  132. const yaw = (nose.x - eyeMidX) / eyeW;
  133. // Face height: forehead to chin (vertical span of the face).
  134. const faceH = (chin.y - forehead.y) || 1e-6;
  135. // Face vertical centre: midway between forehead and chin.
  136. const faceMidY = (forehead.y + chin.y) * 0.5;
  137. // Pitch: how far the nose sits above/below the face centre, normalised
  138. // by face height. In the raw frame y increases downward, so a nose
  139. // ABOVE the centre gives a NEGATIVE pitch (head tilted up) and a
  140. // nose BELOW the centre gives a POSITIVE pitch (head tilted down).
  141. const pitch = (nose.y - faceMidY) / faceH;
  142. return { pitch, yaw };
  143. }
  144. // ============================================================
  145. // Gaze math: iris-ratio only
  146. // Pure eye-in-socket direction. The regression model (fit during
  147. // calibration) maps this raw ratio onto screen coordinates.
  148. //
  149. // Both eyes use the SAME effective sign convention for ratioX (both INCREASE
  150. // when the user looks to the right):
  151. // • Left eye: ratioX = (iris - inner) / (outer - inner) → increases naturally
  152. // • Right eye: raw ratio = (iris - outer) / (inner - outer) → DECREASES when looking right,
  153. // so we apply `1 - raw_ratio` to flip it back to the same sign.
  154. // ============================================================
  155. export function computeIrisGaze(landmarks) {
  156. // Left eye: normal (outer=33, inner=133)
  157. const l_outer = landmarks[L_OUTER];
  158. const l_inner = landmarks[L_INNER];
  159. const l_top = landmarks[L_TOP];
  160. const l_bot = landmarks[L_BOT];
  161. const _l_c = landmarks[L_IRIS];
  162. // Average the 5 left iris contour points for a more stable reading
  163. const l_iris = {
  164. x: [468,469,470,471,472].reduce((s,i) => s + (landmarks[i]?.x || 0), 0) / 5,
  165. y: [468,469,470,471,472].reduce((s,i) => s + (landmarks[i]?.y || 0), 0) / 5
  166. };
  167. const left = (l_outer && l_inner && _l_c &&
  168. !(_l_c.x === 0 && _l_c.y === 0) &&
  169. !Number.isNaN(_l_c.x) && !Number.isNaN(_l_c.y) &&
  170. Math.abs(l_outer.x - l_inner.x) > 1e-6)
  171. ? (() => {
  172. const eyeW = l_outer.x - l_inner.x;
  173. const ratioX = (l_iris.x - l_inner.x) / eyeW;
  174. const midY = (l_top.y + l_bot.y) * 0.5;
  175. const ratioY = (l_iris.y - midY) / (Math.abs(eyeW) || 1e-6);
  176. return { ratioX, ratioY };
  177. })()
  178. : null;
  179. // Right eye: same formula structure as left eye (no flip needed because
  180. // MediaPipe landmarks in the raw frame already give same-sign ratios for
  181. // both eyes — both ratioX values DECREASE when the user looks RIGHT).
  182. // Using R_OUTER (which is to the RIGHT in the un-mirrored raw frame) as
  183. // the denominator reference yields a ratio in the same [0,1]-ish range
  184. // and, crucially, the same sign as the left eye so that the average of
  185. // both eyes does NOT collapse to ~0.5.
  186. const r_outer = landmarks[R_OUTER];
  187. const r_inner = landmarks[R_INNER];
  188. const r_top = landmarks[R_TOP];
  189. const r_bot = landmarks[R_BOT];
  190. const _r_c = landmarks[R_IRIS];
  191. // Average the 5 right iris contour points for a more stable reading
  192. const r_iris = {
  193. x: [473,474,475,476,477].reduce((s,i) => s + (landmarks[i]?.x || 0), 0) / 5,
  194. y: [473,474,475,476,477].reduce((s,i) => s + (landmarks[i]?.y || 0), 0) / 5
  195. };
  196. const right = (r_outer && r_inner && _r_c &&
  197. !(_r_c.x === 0 && _r_c.y === 0) &&
  198. !Number.isNaN(_r_c.x) && !Number.isNaN(_r_c.y) &&
  199. Math.abs(r_inner.x - r_outer.x) > 1e-6)
  200. ? (() => {
  201. // Same formula shape as the left eye, but using R_OUTER (right side
  202. // in raw frame) as the "outer" anchor. eyeW = inner - outer is
  203. // NEGATIVE here, and (iris - outer)/eyeW is therefore also
  204. // negative of the naive (iris - inner)/eyeW — but that's the
  205. // correct sign for the right eye, so both eyes agree when the
  206. // user looks right. No `1 -` flip is applied.
  207. const r_eyeW = r_inner.x - r_outer.x;
  208. const r_ratioX = 1 - (r_iris.x - r_outer.x) / r_eyeW;
  209. const r_midY = (r_top.y + r_bot.y) * 0.5;
  210. const r_ratioY = (r_iris.y - r_midY) / (Math.abs(r_eyeW) || 1e-6);
  211. return { ratioX: r_ratioX, ratioY: r_ratioY };
  212. })()
  213. : null;
  214. irisVisible.l = !!left;
  215. irisVisible.r = !!right;
  216. if (!left && !right) {
  217. return { ratioX: 0.5, ratioY: 0.5, visible: false };
  218. }
  219. let rx, ry;
  220. if (left && right) {
  221. rx = (left.ratioX + right.ratioX) * 0.5;
  222. ry = (left.ratioY + right.ratioY) * 0.5;
  223. } else {
  224. const s = left || right;
  225. rx = s.ratioX; ry = s.ratioY;
  226. }
  227. return { ratioX: rx, ratioY: ry, visible: true };
  228. }
  229. export function onResults(results) {
  230. const t1 = performance.now();
  231. setLastResults(results);
  232. if (!results.multiFaceLandmarks || results.multiFaceLandmarks.length === 0) {
  233. // No face - hold last smoothed position, don't drift.
  234. // Clear the blink flag too (we can't really know, but assume the
  235. // user isn't actively blinking while no face is visible).
  236. setLastGaze({ ...lastGaze, visible: false });
  237. setLastBlinking(false);
  238. setLastFrameMs(performance.now() - t1);
  239. return;
  240. }
  241. const lm = results.multiFaceLandmarks[0];
  242. // V2 features: blink + head pose, computed once per frame before
  243. // the iris-ratio path so we can use EAR to gate that path.
  244. const ear = computeEAR(lm);
  245. const headPose = computeHeadPose(lm);
  246. setLastEAR(ear);
  247. setLastHeadPose(headPose);
  248. // Blink detection: if the eyes are closed enough, mark the frame as
  249. // a blink and DO NOT update the raw gaze position. The orb will
  250. // keep its current Kalman-smoothed position so it doesn't jump.
  251. // The blink flag is sticky across the entire closed-eyes interval
  252. // (we don't return early until EAR recovers), but we only ever skip
  253. // the raw-gaze update — we still want lastGaze / lastFrameMs etc.
  254. // refreshed.
  255. const isBlink = ear > 0 && ear < EAR_BLINK_THRESHOLD;
  256. setLastBlinking(isBlink);
  257. const gaze = computeIrisGaze(lm);
  258. // Attach the V2 features to lastGaze so calibration.js can sample them.
  259. setLastGaze({ ...gaze, ear, pitch: headPose.pitch, yaw: headPose.yaw });
  260. if (isBlink) {
  261. // Keep the orb parked where it is. Crucially we do NOT call
  262. // setRawXValid(false) here — that would cause the renderer to
  263. // hold the last *valid* position too, which is what we want.
  264. // We also don't write to rawX/rawY; they keep their previous
  265. // values, and the Kalman filter continues to predict from them.
  266. setLastFrameMs(performance.now() - t1);
  267. } else if (gaze.visible && calibrationData && !calPaused) {
  268. // Map raw iris ratio (+ ear/pitch/yaw) → screen coordinates via the
  269. // 9-dim OLS model. applyRegression accepts the V2 features and
  270. // will use whichever coefficients are non-zero; for a freshly-
  271. // fitted model on 13 points all 9 are non-zero.
  272. const mapped = applyRegression(
  273. gaze.ratioX, gaze.ratioY,
  274. ear, headPose.pitch, headPose.yaw
  275. );
  276. setRawX(mapped.x);
  277. setRawY(mapped.y);
  278. setRawXValid(true);
  279. } else if (gaze.visible && !calPaused) {
  280. // No calibration yet — approximate screen position from iris ratio.
  281. // ratioX (eyeW-normalized) lives roughly in [0.2, 0.8] with the center
  282. // near 0.5; recenter at 0.5 and stretch x3 to fill the screen without
  283. // saturating.
  284. // ratioY is eyeW-normalized and signed (look-up → negative, look-down
  285. // → positive); recenter at 0.5 and stretch x3. The calibration
  286. // regression will fix the exact direction/orientation afterward — this
  287. // fallback just needs to produce values that span [0, 1] without
  288. // clipping at 1 the moment the user blinks or moves their head.
  289. setRawX(clamp(0.5 + (gaze.ratioX - 0.5) * 3, 0, 1));
  290. setRawY(clamp(0.5 + (gaze.ratioY + 0.03) * 6, 0, 1));
  291. setRawXValid(true);
  292. } else {
  293. // No iris detected, or calibration is paused
  294. setRawXValid(false);
  295. }
  296. setLastFrameMs(performance.now() - t1);
  297. // Debug log: once per second, print the current iris ratios + mapped
  298. // screen coordinates + blink/head-pose state. Throttled with
  299. // lastDebugLogMs so we don't flood the console at ~30 fps. Helpful
  300. // for diagnosing "why is the orb stuck?" — open DevTools and watch
  301. // the values as you move your eyes / tilt your head.
  302. if (getRawXValid()) {
  303. const nowMs = performance.now();
  304. if (nowMs - lastDebugLogMs >= 1000) {
  305. lastDebugLogMs = nowMs;
  306. console.log(
  307. '[gaze] ratioX=' + gaze.ratioX.toFixed(3) +
  308. ' ratioY=' + gaze.ratioY.toFixed(3) +
  309. ' EAR=' + ear.toFixed(3) +
  310. (isBlink ? ' (BLINK)' : '') +
  311. ' pitch=' + headPose.pitch.toFixed(3) +
  312. ' yaw=' + headPose.yaw.toFixed(3) +
  313. ' | mappedX=' + rawX.toFixed(3) +
  314. ' mappedY=' + rawY.toFixed(3) +
  315. ' | calibrated=' + (calibrationData ? 'yes' : 'no') +
  316. ' | irisVisible=' + irisVisible.l + '/' + irisVisible.r
  317. );
  318. }
  319. }
  320. }
  321. // Wire up the late-binding hook so calibration.js can read lastGaze
  322. // without creating a circular import.
  323. registerLastGazeGetter(() => lastGaze);