index.html 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>Eye Tracking Demo · MediaPipe Iris</title>
  7. <style>
  8. :root {
  9. --bg: #0a0a1a;
  10. --grid: rgba(0, 255, 255, 0.04);
  11. --cyan: #00e5ff;
  12. --cyan-dim: #00b8d4;
  13. --text: #e0f7fa;
  14. --text-dim: #80deea;
  15. --danger: #ff5252;
  16. --ok: #00e676;
  17. --warn: #ffb74d;
  18. --panel: rgba(10, 20, 40, 0.55);
  19. --panel-border: rgba(0, 229, 255, 0.35);
  20. }
  21. * { box-sizing: border-box; margin: 0; padding: 0; }
  22. html, body {
  23. width: 100%;
  24. height: 100%;
  25. overflow: hidden;
  26. background: var(--bg);
  27. color: var(--text);
  28. font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "SF Mono", "Roboto Mono", Menlo, Consolas, monospace;
  29. -webkit-font-smoothing: antialiased;
  30. user-select: none;
  31. }
  32. body {
  33. background-color: var(--bg);
  34. background-image:
  35. linear-gradient(var(--grid) 1px, transparent 1px),
  36. linear-gradient(90deg, var(--grid) 1px, transparent 1px);
  37. background-size: 40px 40px;
  38. background-position: -1px -1px;
  39. }
  40. /* Subtle radial vignette */
  41. body::before {
  42. content: "";
  43. position: fixed;
  44. inset: 0;
  45. pointer-events: none;
  46. background: radial-gradient(ellipse at center, transparent 0%, rgba(0,0,0,0.6) 100%);
  47. z-index: 1;
  48. }
  49. #stage {
  50. position: fixed;
  51. inset: 0;
  52. z-index: 2;
  53. cursor: crosshair;
  54. }
  55. /* ---------- Webcam preview ---------- */
  56. #preview-wrap {
  57. position: fixed;
  58. left: 24px;
  59. bottom: 64px;
  60. width: 240px;
  61. height: 180px;
  62. border-radius: 14px;
  63. overflow: hidden;
  64. background: #000;
  65. border: 1px solid var(--panel-border);
  66. box-shadow:
  67. 0 0 0 1px rgba(0, 229, 255, 0.08) inset,
  68. 0 8px 32px rgba(0, 229, 255, 0.12),
  69. 0 2px 8px rgba(0, 0, 0, 0.6);
  70. z-index: 10;
  71. backdrop-filter: blur(4px);
  72. }
  73. #preview-wrap::before {
  74. content: "LIVE · IRIS";
  75. position: absolute;
  76. top: 8px;
  77. left: 10px;
  78. font-size: 10px;
  79. letter-spacing: 0.15em;
  80. color: var(--cyan);
  81. text-shadow: 0 0 8px rgba(0, 229, 255, 0.7);
  82. z-index: 12;
  83. pointer-events: none;
  84. }
  85. #preview-wrap::after {
  86. content: "";
  87. position: absolute;
  88. inset: 0;
  89. border-radius: 14px;
  90. pointer-events: none;
  91. box-shadow: 0 0 24px rgba(0, 229, 255, 0.18) inset;
  92. z-index: 11;
  93. }
  94. #webcam, #overlay {
  95. position: absolute;
  96. inset: 0;
  97. width: 100%;
  98. height: 100%;
  99. }
  100. #webcam {
  101. object-fit: cover;
  102. transform: scaleX(-1); /* mirrored */
  103. z-index: 1;
  104. }
  105. #overlay {
  106. z-index: 2;
  107. pointer-events: none;
  108. }
  109. /* ---------- Status bar ---------- */
  110. #status-bar {
  111. position: fixed;
  112. left: 0;
  113. right: 0;
  114. bottom: 0;
  115. height: 48px;
  116. display: flex;
  117. align-items: center;
  118. gap: 24px;
  119. padding: 0 20px;
  120. background: var(--panel);
  121. border-top: 1px solid var(--panel-border);
  122. backdrop-filter: blur(8px);
  123. font-size: 12px;
  124. letter-spacing: 0.05em;
  125. z-index: 20;
  126. color: var(--text-dim);
  127. }
  128. .stat {
  129. display: flex;
  130. align-items: center;
  131. gap: 8px;
  132. }
  133. .stat .label {
  134. color: rgba(128, 222, 234, 0.55);
  135. text-transform: uppercase;
  136. font-size: 10px;
  137. letter-spacing: 0.18em;
  138. }
  139. .stat .value {
  140. color: var(--cyan);
  141. text-shadow: 0 0 8px rgba(0, 229, 255, 0.5);
  142. font-variant-numeric: tabular-nums;
  143. min-width: 60px;
  144. }
  145. .stat .value.ok { color: var(--ok); text-shadow: 0 0 8px rgba(0, 230, 118, 0.4); }
  146. .stat .value.warn { color: #ffb74d; text-shadow: 0 0 8px rgba(255, 183, 77, 0.4); }
  147. .stat .value.err { color: var(--danger); text-shadow: 0 0 8px rgba(255, 82, 82, 0.4); }
  148. .dot {
  149. width: 8px;
  150. height: 8px;
  151. border-radius: 50%;
  152. background: var(--cyan-dim);
  153. box-shadow: 0 0 8px var(--cyan-dim);
  154. animation: pulse 1.6s ease-in-out infinite;
  155. }
  156. .dot.ok { background: var(--ok); box-shadow: 0 0 10px var(--ok); }
  157. .dot.warn { background: #ffb74d; box-shadow: 0 0 10px #ffb74d; }
  158. .dot.err { background: var(--danger); box-shadow: 0 0 10px var(--danger); animation: none; }
  159. @keyframes pulse {
  160. 0%, 100% { opacity: 1; transform: scale(1); }
  161. 50% { opacity: 0.4; transform: scale(0.8); }
  162. }
  163. /* Small inline button (used for "Recalibrate" in the status bar) */
  164. .btn-mini {
  165. font-family: inherit;
  166. font-size: 10px;
  167. letter-spacing: 0.18em;
  168. text-transform: uppercase;
  169. color: var(--cyan);
  170. background: transparent;
  171. border: 1px solid var(--panel-border);
  172. border-radius: 4px;
  173. padding: 4px 10px;
  174. cursor: pointer;
  175. transition: background 0.2s, box-shadow 0.2s, color 0.2s;
  176. }
  177. .btn-mini:hover {
  178. background: rgba(0, 229, 255, 0.1);
  179. box-shadow: 0 0 10px rgba(0, 229, 255, 0.3);
  180. color: #ffffff;
  181. }
  182. .btn-mini:disabled {
  183. color: rgba(128, 222, 234, 0.35);
  184. border-color: rgba(0, 229, 255, 0.15);
  185. cursor: not-allowed;
  186. background: transparent;
  187. box-shadow: none;
  188. }
  189. /* ---------- Title ---------- */
  190. #title {
  191. position: fixed;
  192. top: 18px;
  193. left: 24px;
  194. z-index: 15;
  195. font-size: 11px;
  196. letter-spacing: 0.3em;
  197. color: rgba(0, 229, 255, 0.7);
  198. text-shadow: 0 0 8px rgba(0, 229, 255, 0.4);
  199. }
  200. #title .accent { color: var(--cyan); }
  201. /* ---------- Loading overlay ---------- */
  202. #loader {
  203. position: fixed;
  204. inset: 0;
  205. z-index: 100;
  206. display: flex;
  207. flex-direction: column;
  208. align-items: center;
  209. justify-content: center;
  210. gap: 28px;
  211. background: rgba(10, 10, 26, 0.92);
  212. backdrop-filter: blur(6px);
  213. transition: opacity 0.5s ease, visibility 0.5s;
  214. }
  215. #loader.hidden {
  216. opacity: 0;
  217. visibility: hidden;
  218. }
  219. .spinner {
  220. width: 64px;
  221. height: 64px;
  222. border: 2px solid rgba(0, 229, 255, 0.15);
  223. border-top-color: var(--cyan);
  224. border-right-color: var(--cyan);
  225. border-radius: 50%;
  226. animation: spin 1s linear infinite;
  227. box-shadow: 0 0 24px rgba(0, 229, 255, 0.3);
  228. }
  229. @keyframes spin {
  230. to { transform: rotate(360deg); }
  231. }
  232. .loader-text {
  233. font-size: 12px;
  234. letter-spacing: 0.4em;
  235. text-transform: uppercase;
  236. color: var(--cyan);
  237. text-shadow: 0 0 10px rgba(0, 229, 255, 0.6);
  238. }
  239. .loader-sub {
  240. font-size: 11px;
  241. color: var(--text-dim);
  242. letter-spacing: 0.15em;
  243. max-width: 320px;
  244. text-align: center;
  245. line-height: 1.6;
  246. }
  247. /* ---------- Error overlay ---------- */
  248. #error-overlay {
  249. position: fixed;
  250. inset: 0;
  251. z-index: 90;
  252. display: none;
  253. flex-direction: column;
  254. align-items: center;
  255. justify-content: center;
  256. gap: 18px;
  257. background: rgba(10, 10, 26, 0.88);
  258. backdrop-filter: blur(6px);
  259. padding: 40px;
  260. text-align: center;
  261. }
  262. #error-overlay.show { display: flex; }
  263. #error-overlay .icon {
  264. font-size: 48px;
  265. filter: drop-shadow(0 0 12px rgba(255, 82, 82, 0.6));
  266. }
  267. #error-overlay h2 {
  268. font-size: 18px;
  269. letter-spacing: 0.15em;
  270. color: var(--danger);
  271. text-transform: uppercase;
  272. }
  273. #error-overlay p {
  274. color: var(--text-dim);
  275. font-size: 13px;
  276. max-width: 520px;
  277. line-height: 1.7;
  278. }
  279. #error-overlay button {
  280. margin-top: 12px;
  281. padding: 10px 24px;
  282. background: transparent;
  283. border: 1px solid var(--cyan);
  284. color: var(--cyan);
  285. font-family: inherit;
  286. font-size: 12px;
  287. letter-spacing: 0.2em;
  288. text-transform: uppercase;
  289. cursor: pointer;
  290. border-radius: 6px;
  291. transition: background 0.2s, box-shadow 0.2s;
  292. }
  293. #error-overlay button:hover {
  294. background: rgba(0, 229, 255, 0.1);
  295. box-shadow: 0 0 16px rgba(0, 229, 255, 0.3);
  296. }
  297. /* ---------- Debug panel (top-left, collapsible) ---------- */
  298. #debug-panel {
  299. position: fixed;
  300. top: 48px;
  301. left: 24px;
  302. z-index: 30;
  303. width: 260px;
  304. max-width: calc(100vw - 48px);
  305. background: var(--panel);
  306. border: 1px solid var(--panel-border);
  307. border-radius: 10px;
  308. backdrop-filter: blur(8px);
  309. box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
  310. font-size: 11px;
  311. color: var(--text);
  312. overflow: hidden;
  313. transition: max-height 0.25s ease;
  314. }
  315. #debug-panel.collapsed { max-height: 32px; }
  316. #debug-panel.expanded { max-height: 480px; }
  317. #debug-header {
  318. display: flex;
  319. align-items: center;
  320. justify-content: space-between;
  321. padding: 8px 12px;
  322. cursor: pointer;
  323. user-select: none;
  324. background: rgba(0, 229, 255, 0.06);
  325. border-bottom: 1px solid var(--panel-border);
  326. font-size: 10px;
  327. letter-spacing: 0.2em;
  328. text-transform: uppercase;
  329. color: var(--cyan);
  330. }
  331. #debug-panel.collapsed #debug-body { display: none; }
  332. #debug-panel.collapsed #debug-header { border-bottom: none; }
  333. #debug-toggle {
  334. font-family: inherit;
  335. color: var(--cyan);
  336. font-size: 14px;
  337. line-height: 1;
  338. }
  339. #debug-body {
  340. padding: 10px 12px 12px;
  341. display: flex;
  342. flex-direction: column;
  343. gap: 6px;
  344. max-height: 440px;
  345. overflow-y: auto;
  346. }
  347. .dbg-row {
  348. display: flex;
  349. align-items: center;
  350. justify-content: space-between;
  351. gap: 8px;
  352. font-size: 11px;
  353. line-height: 1.4;
  354. word-break: break-all;
  355. }
  356. .dbg-row .k {
  357. color: rgba(128, 222, 234, 0.7);
  358. text-transform: uppercase;
  359. letter-spacing: 0.1em;
  360. font-size: 10px;
  361. flex-shrink: 0;
  362. }
  363. .dbg-row .v {
  364. color: var(--text);
  365. text-align: right;
  366. font-variant-numeric: tabular-nums;
  367. }
  368. .dbg-row .v.ok { color: var(--ok); }
  369. .dbg-row .v.warn { color: #ffb74d; }
  370. .dbg-row .v.err { color: var(--danger); }
  371. .dbg-row .v.run { color: var(--cyan); }
  372. #debug-err {
  373. margin-top: 6px;
  374. padding: 8px 10px;
  375. background: rgba(255, 82, 82, 0.08);
  376. border: 1px solid rgba(255, 82, 82, 0.35);
  377. border-radius: 6px;
  378. color: var(--danger);
  379. font-size: 10px;
  380. line-height: 1.5;
  381. word-break: break-word;
  382. display: none;
  383. max-height: 120px;
  384. overflow-y: auto;
  385. }
  386. #debug-err.show { display: block; }
  387. /* ---------- Calibration overlay (9-point) ---------- */
  388. #calibration-overlay {
  389. position: fixed;
  390. inset: 0;
  391. z-index: 80;
  392. display: none;
  393. align-items: center;
  394. justify-content: center;
  395. background: rgba(10, 10, 26, 0.92);
  396. backdrop-filter: blur(6px);
  397. }
  398. #calibration-overlay.show { display: flex; }
  399. #cal-dot {
  400. position: absolute;
  401. width: 36px;
  402. height: 36px;
  403. margin-left: -18px;
  404. margin-top: -18px;
  405. border-radius: 50%;
  406. background: radial-gradient(circle at center,
  407. rgba(255, 255, 255, 1) 0%,
  408. rgba(0, 229, 255, 1) 35%,
  409. rgba(0, 229, 255, 0.6) 65%,
  410. rgba(0, 229, 255, 0) 100%);
  411. box-shadow:
  412. 0 0 24px rgba(0, 229, 255, 0.9),
  413. 0 0 60px rgba(0, 229, 255, 0.5);
  414. animation: calPulse 1s ease-in-out infinite;
  415. pointer-events: none;
  416. transform-origin: center;
  417. }
  418. #cal-dot::after {
  419. content: "";
  420. position: absolute;
  421. inset: 12px;
  422. border-radius: 50%;
  423. border: 2px solid rgba(0, 229, 255, 0.6);
  424. }
  425. @keyframes calPulse {
  426. 0%, 100% { transform: scale(1); opacity: 1; }
  427. 50% { transform: scale(1.3); opacity: 0.7; }
  428. }
  429. #cal-text {
  430. position: absolute;
  431. top: 32px;
  432. left: 50%;
  433. transform: translateX(-50%);
  434. font-size: 13px;
  435. letter-spacing: 0.3em;
  436. text-transform: uppercase;
  437. color: var(--cyan);
  438. text-shadow: 0 0 10px rgba(0, 229, 255, 0.7);
  439. text-align: center;
  440. pointer-events: none;
  441. }
  442. #cal-sub {
  443. position: absolute;
  444. top: 58px;
  445. left: 50%;
  446. transform: translateX(-50%);
  447. font-size: 10px;
  448. letter-spacing: 0.2em;
  449. color: var(--text-dim);
  450. text-align: center;
  451. pointer-events: none;
  452. }
  453. #cal-cancel {
  454. position: absolute;
  455. bottom: 32px;
  456. left: 50%;
  457. transform: translateX(-50%);
  458. }
  459. /* Faint preview ghost dots for upcoming calibration points */
  460. .cal-ghost {
  461. position: absolute;
  462. width: 14px;
  463. height: 14px;
  464. margin-left: -7px;
  465. margin-top: -7px;
  466. border-radius: 50%;
  467. border: 1px solid rgba(0, 229, 255, 0.25);
  468. background: rgba(0, 229, 255, 0.05);
  469. pointer-events: none;
  470. }
  471. </style>
  472. </head>
  473. <body>
  474. <canvas id="stage"></canvas>
  475. <div id="title">
  476. EYE · TRACK <span class="accent">//</span> PUPIL GAZE
  477. </div>
  478. <div id="preview-wrap" aria-label="Webcam preview with face mesh overlay">
  479. <video id="webcam" autoplay playsinline muted></video>
  480. <canvas id="overlay" width="240" height="180"></canvas>
  481. </div>
  482. <div id="status-bar">
  483. <div class="stat">
  484. <span class="dot" id="status-dot"></span>
  485. <span class="label">Status</span>
  486. <span class="value" id="status-text">INIT</span>
  487. </div>
  488. <div class="stat">
  489. <span class="label">FPS</span>
  490. <span class="value" id="fps">--</span>
  491. </div>
  492. <div class="stat">
  493. <span class="label">Gaze X</span>
  494. <span class="value" id="gaze-x">0.000</span>
  495. </div>
  496. <div class="stat">
  497. <span class="label">Gaze Y</span>
  498. <span class="value" id="gaze-y">0.000</span>
  499. </div>
  500. <div class="stat">
  501. <span class="label">Iris L</span>
  502. <span class="value" id="iris-l">--</span>
  503. </div>
  504. <div class="stat">
  505. <span class="label">Iris R</span>
  506. <span class="value" id="iris-r">--</span>
  507. </div>
  508. <div class="stat">
  509. <span class="dot" id="cal-dot-status"></span>
  510. <span class="label">Cal</span>
  511. <span class="value" id="cal-status-text">--</span>
  512. </div>
  513. <div class="stat" style="margin-left: auto;">
  514. <button class="btn-mini" id="recalibrate-btn" disabled>Recalibrate</button>
  515. </div>
  516. </div>
  517. <div id="loader">
  518. <div class="spinner"></div>
  519. <div class="loader-text" id="loader-text">Loading MediaPipe</div>
  520. <div class="loader-sub" id="loader-sub">Initializing WASM runtime &amp; face mesh model. Please allow camera access when prompted.</div>
  521. </div>
  522. <div id="debug-panel" class="collapsed">
  523. <div id="debug-header" title="Click to expand/collapse">
  524. <span>DEBUG</span>
  525. <span id="debug-toggle">+</span>
  526. </div>
  527. <div id="debug-body">
  528. <div class="dbg-row"><span class="k">camera_utils</span><span class="v" id="dbg-cdn1">…</span></div>
  529. <div class="dbg-row"><span class="k">drawing_utils</span><span class="v" id="dbg-cdn2">…</span></div>
  530. <div class="dbg-row"><span class="k">face_mesh</span><span class="v" id="dbg-cdn3">…</span></div>
  531. <div class="dbg-row"><span class="k">model</span><span class="v" id="dbg-model">…</span></div>
  532. <div class="dbg-row"><span class="k">camera</span><span class="v" id="dbg-camera">…</span></div>
  533. <div class="dbg-row"><span class="k">stage</span><span class="v" id="dbg-stage">…</span></div>
  534. <div class="dbg-row"><span class="k">calibration</span><span class="v" id="dbg-cal">…</span></div>
  535. <div class="dbg-row"><span class="k">frame ms</span><span class="v" id="dbg-frame">--</span></div>
  536. <div class="dbg-row"><span class="k">downloaded</span><span class="v" id="dbg-bytes">0 KB</span></div>
  537. <div id="debug-err"></div>
  538. </div>
  539. </div>
  540. <div id="error-overlay">
  541. <div class="icon">⚠</div>
  542. <h2 id="err-title">Camera Access Denied</h2>
  543. <p id="err-msg">We need your camera to track your gaze. Please grant camera permission in your browser settings and reload the page.</p>
  544. <button id="err-retry">Retry</button>
  545. </div>
  546. <div id="calibration-overlay" aria-hidden="true">
  547. <div id="cal-text">Calibrating</div>
  548. <div id="cal-sub">Follow the dot with your eyes</div>
  549. <div id="cal-dot"></div>
  550. <button class="btn-mini" id="cal-cancel">Cancel</button>
  551. </div>
  552. <!-- MediaPipe CDN -->
  553. <script>
  554. // Mark CDN load state on the global scope so the inline app can read it.
  555. window.__cdnStatus = window.__cdnStatus || {};
  556. function __cdnErr(name, src) {
  557. window.__cdnStatus[name] = 'error';
  558. console.error('[CDN] failed to load', name, src);
  559. // Surface the failure as a visible loader message immediately.
  560. var lt = document.getElementById('loader-text');
  561. var ls = document.getElementById('loader-sub');
  562. if (lt) lt.textContent = 'CDN load failed';
  563. if (ls) ls.textContent = 'Could not download ' + name + ' from the CDN. Check your network and reload.';
  564. try {
  565. var evt = new CustomEvent('cdnError', { detail: { name: name, src: src } });
  566. window.dispatchEvent(evt);
  567. } catch (e) { /* no-op */ }
  568. }
  569. function __cdnOk(name) {
  570. window.__cdnStatus[name] = 'ok';
  571. console.log('[CDN] loaded', name);
  572. try {
  573. window.dispatchEvent(new CustomEvent('cdnOk', { detail: { name: name } }));
  574. } catch (e) { /* no-op */ }
  575. }
  576. </script>
  577. <script src="https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils/camera_utils.js" crossorigin="anonymous"
  578. onload="__cdnOk('camera_utils')"
  579. onerror="__cdnErr('camera_utils', this.src)"></script>
  580. <script src="https://cdn.jsdelivr.net/npm/@mediapipe/drawing_utils/drawing_utils.js" crossorigin="anonymous"
  581. onload="__cdnOk('drawing_utils')"
  582. onerror="__cdnErr('drawing_utils', this.src)"></script>
  583. <script src="https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/face_mesh.js" crossorigin="anonymous"
  584. onload="__cdnOk('face_mesh')"
  585. onerror="__cdnErr('face_mesh', this.src)"></script>
  586. <script>
  587. (function () {
  588. 'use strict';
  589. // ============================================================
  590. // Config
  591. // ============================================================
  592. const TRAIL_LENGTH = 30; // # of trail points
  593. const ORB_RADIUS = 40; // px
  594. const GRID_DRAW_INTERVAL_MS = 33; // ~30fps redraw
  595. // Kalman filter (replaces EMA + outlier threshold — Kalman handles noise naturally via R)
  596. // No constant needed here; see kalUpdate / kalInit below.
  597. // Calibration config
  598. const CAL_SAMPLES_PER_POINT = 30; // samples per point (first 3 are discarded)
  599. const CAL_SAMPLE_INTERVAL_MS = 50; // ms between samples
  600. const CAL_MARGIN = 0.15; // 15% margin on each edge
  601. const CAL_STORAGE_KEY = 'eye-tracking-calibration';
  602. const CAL_VERSION = 2; // bump when ratioY normalization or coef layout changes; old payloads are discarded
  603. // Iris / eye landmark indices (MediaPipe Face Mesh)
  604. // Left eye
  605. const L_OUTER = 33, L_INNER = 133;
  606. const L_TOP = 159, L_BOT = 145;
  607. const L_IRIS = 468;
  608. // Right eye
  609. const R_OUTER = 362, R_INNER = 263;
  610. const R_TOP = 386, R_BOT = 374;
  611. const R_IRIS = 473;
  612. // Iris contour points
  613. const IRIS_LANDMARKS = [
  614. 468, 469, 470, 471, 472, // left iris
  615. 473, 474, 475, 476, 477 // right iris
  616. ];
  617. // Face mesh tesselation connection subsets (subset of FACE_TESSELATION)
  618. // Use eye / brow / lip / nose silhouettes to keep it light
  619. 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];
  620. const LIPS = [61, 146, 91, 181, 84, 17, 314, 405, 321, 375, 291, 308, 324, 318, 402, 317, 14, 87, 178, 88, 95, 78];
  621. const L_EYE = [33, 7, 163, 144, 145, 153, 154, 155, 133, 173, 157, 158, 159, 160, 161, 246];
  622. const R_EYE = [362, 382, 381, 380, 374, 373, 390, 249, 263, 466, 388, 387, 386, 385, 384, 398];
  623. const L_BROW = [46, 53, 52, 65, 55, 107, 66, 105, 63, 70];
  624. const R_BROW = [276, 283, 282, 295, 285, 336, 296, 334, 293, 300];
  625. // 13-point calibration grid (center + 4 corners + 4 edges + 4 mid-diagonal)
  626. // The drawing is mirrored via CSS scaleX(-1), so these coords are
  627. // intentionally in the *displayed* (mirrored) frame of reference.
  628. // 5 rows × variable cols (5+3 cols) — center column used in rows 0,2,4 only.
  629. const CAL_GRID = [
  630. // row 0 (top)
  631. { x: 0.1, y: 0.1 }, // TL
  632. { x: 0.5, y: 0.1 }, // TM
  633. { x: 0.9, y: 0.1 }, // TR
  634. // row 1 (upper mid)
  635. { x: 0.1, y: 0.3 }, // UL-mid
  636. { x: 0.9, y: 0.3 }, // UR-mid
  637. // row 2 (middle)
  638. { x: 0.1, y: 0.5 }, // ML
  639. { x: 0.5, y: 0.5 }, // MM (center)
  640. { x: 0.9, y: 0.5 }, // MR
  641. // row 3 (lower mid)
  642. { x: 0.1, y: 0.7 }, // LL-mid
  643. { x: 0.9, y: 0.7 }, // LR-mid
  644. // row 4 (bottom)
  645. { x: 0.1, y: 0.9 }, // BL
  646. { x: 0.5, y: 0.9 }, // BM
  647. { x: 0.9, y: 0.9 } // BR
  648. ];
  649. // Order: row-major traversal
  650. const CAL_ORDER = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
  651. // ============================================================
  652. // DOM
  653. // ============================================================
  654. const stage = document.getElementById('stage');
  655. const ctx = stage.getContext('2d');
  656. const video = document.getElementById('webcam');
  657. const overlay = document.getElementById('overlay');
  658. const octx = overlay.getContext('2d');
  659. const loader = document.getElementById('loader');
  660. const loaderText = document.getElementById('loader-text');
  661. const loaderSub = document.getElementById('loader-sub');
  662. const errOverlay = document.getElementById('error-overlay');
  663. const errTitle = document.getElementById('err-title');
  664. const errMsg = document.getElementById('err-msg');
  665. const errRetry = document.getElementById('err-retry');
  666. const statusDot = document.getElementById('status-dot');
  667. const statusText = document.getElementById('status-text');
  668. const fpsEl = document.getElementById('fps');
  669. const gxEl = document.getElementById('gaze-x');
  670. const gyEl = document.getElementById('gaze-y');
  671. const ilEl = document.getElementById('iris-l');
  672. const irEl = document.getElementById('iris-r');
  673. const calDotStatus = document.getElementById('cal-dot-status');
  674. const calStatusText = document.getElementById('cal-status-text');
  675. const recalibrateBtn = document.getElementById('recalibrate-btn');
  676. // Debug panel
  677. const dbgPanel = document.getElementById('debug-panel');
  678. const dbgHeader = document.getElementById('debug-header');
  679. const dbgToggle = document.getElementById('debug-toggle');
  680. const dbgCdn1 = document.getElementById('dbg-cdn1');
  681. const dbgCdn2 = document.getElementById('dbg-cdn2');
  682. const dbgCdn3 = document.getElementById('dbg-cdn3');
  683. const dbgModel = document.getElementById('dbg-model');
  684. const dbgCamera = document.getElementById('dbg-camera');
  685. const dbgStage = document.getElementById('dbg-stage');
  686. const dbgCal = document.getElementById('dbg-cal');
  687. const dbgFrame = document.getElementById('dbg-frame');
  688. const dbgBytes = document.getElementById('dbg-bytes');
  689. const dbgErr = document.getElementById('debug-err');
  690. // Calibration overlay
  691. const calOverlay = document.getElementById('calibration-overlay');
  692. const calDot = document.getElementById('cal-dot');
  693. const calText = document.getElementById('cal-text');
  694. const calSub = document.getElementById('cal-sub');
  695. const calCancel = document.getElementById('cal-cancel');
  696. // ============================================================
  697. // Debug panel helpers
  698. // ============================================================
  699. function dbgSet(el, text, cls) {
  700. if (!el) return;
  701. el.textContent = text;
  702. el.className = 'v' + (cls ? ' ' + cls : '');
  703. }
  704. function dbgSetError(msg) {
  705. if (!dbgErr) return;
  706. if (!msg) { dbgErr.classList.remove('show'); dbgErr.textContent = ''; return; }
  707. dbgErr.textContent = msg;
  708. dbgErr.classList.add('show');
  709. }
  710. if (dbgHeader) {
  711. dbgHeader.addEventListener('click', () => {
  712. const collapsed = dbgPanel.classList.toggle('collapsed');
  713. dbgPanel.classList.toggle('expanded', !collapsed);
  714. dbgToggle.textContent = collapsed ? '+' : '–';
  715. });
  716. }
  717. // Initialize CDN cells from the global status that the loader scripts set
  718. try {
  719. const s = (window.__cdnStatus) || {};
  720. dbgSet(dbgCdn1, s.camera_utils || (s.camera_utils === 'error' ? 'FAIL' : '…'),
  721. s.camera_utils === 'ok' ? 'ok' : s.camera_utils === 'error' ? 'err' : 'run');
  722. dbgSet(dbgCdn2, s.drawing_utils || (s.drawing_utils === 'error' ? 'FAIL' : '…'),
  723. s.drawing_utils === 'ok' ? 'ok' : s.drawing_utils === 'error' ? 'err' : 'run');
  724. dbgSet(dbgCdn3, s.face_mesh || (s.face_mesh === 'error' ? 'FAIL' : '…'),
  725. s.face_mesh === 'ok' ? 'ok' : s.face_mesh === 'error' ? 'err' : 'run');
  726. } catch (e) { /* no-op */ }
  727. // Live-update on CDN load / failure events
  728. window.addEventListener('cdnOk', (e) => {
  729. const n = e && e.detail && e.detail.name;
  730. if (n === 'camera_utils') dbgSet(dbgCdn1, 'OK', 'ok');
  731. if (n === 'drawing_utils') dbgSet(dbgCdn2, 'OK', 'ok');
  732. if (n === 'face_mesh') dbgSet(dbgCdn3, 'OK', 'ok');
  733. });
  734. window.addEventListener('cdnError', (e) => {
  735. const n = e && e.detail && e.detail.name;
  736. if (n === 'camera_utils') { dbgSet(dbgCdn1, 'FAIL', 'err'); dbgSetError('CDN camera_utils failed to load'); }
  737. if (n === 'drawing_utils') { dbgSet(dbgCdn2, 'FAIL', 'err'); dbgSetError('CDN drawing_utils failed to load'); }
  738. if (n === 'face_mesh') { dbgSet(dbgCdn3, 'FAIL', 'err'); dbgSetError('CDN face_mesh failed to load'); }
  739. });
  740. function setLoaderText(main, sub) {
  741. if (loaderText) loaderText.textContent = main;
  742. if (loaderSub) loaderSub.textContent = sub;
  743. console.log('[loader]', main, '—', sub);
  744. }
  745. // ============================================================
  746. // Utilities
  747. // ============================================================
  748. function clamp(v, lo, hi) { return Math.min(hi, Math.max(lo, v)); }
  749. // ============================================================
  750. // State
  751. // ============================================================
  752. let W = 0, H = 0;
  753. let smoothedX = 0.5, smoothedY = 0.5; // Kalman-smoothed gaze (0..1)
  754. // Kalman state replaces emaX/emaY
  755. let rawX = 0.5, rawY = 0.5; // raw gaze (0..1) from regression
  756. let rawXValid = false; // whether raw gaze has a fresh, valid measurement
  757. let trail = []; // array of {x, y}
  758. let faceMesh = null;
  759. let camera = null;
  760. let lastResults = null;
  761. let lastTime = performance.now();
  762. let fpsSmooth = 0;
  763. let irisVisible = { l: false, r: false };
  764. let trackingLocked = false;
  765. let lastFrameMs = 0; // last face-mesh processing time in ms
  766. let lastMeshSendAt = 0;
  767. let frameCount = 0; // for frame skipping (process every 2nd frame)
  768. let lastDebugLogMs = 0; // throttles the per-second onResults debug print
  769. // Calibration state
  770. let calibrationData = null; // { coefX:[a0..a5], coefY:[b0..b5], timestamp }
  771. let calActive = false; // true while a calibration session is in progress
  772. let calPaused = false; // true while in the calibration overlay (raw gaze is ignored)
  773. let calCurrentIdx = 0; // index into CAL_ORDER
  774. let calSamples = []; // collected {ratioX, ratioY} for the active point
  775. let calAllPoints = []; // accumulated {screenX, screenY, samples:[…]} for all 13 points
  776. let calCollectTimer = null; // setInterval id for sample collection
  777. let pointSampleCount = 0; // per-point sample counter (discard first 3)
  778. // Kalman Filter for 2D gaze tracking with velocity prediction
  779. // State: [x, y, vx, vy], Measurement: [x, y]
  780. var kalX = [0.5, 0.5, 0, 0]; // [x, y, vx, vy] in normalized screen coords
  781. var kalP = [1, 0, 0, 0,
  782. 0, 1, 0, 0,
  783. 0, 0, 1, 0,
  784. 0, 0, 0, 1]; // 4x4 covariance matrix (flat: P[i*4+j])
  785. // Q bumped up (0.001→0.01 for position, 0.01→0.05 for velocity) so the
  786. // Kalman filter trusts new measurements more and responds more quickly to
  787. // genuine eye motion. With the old Q the filter over-trusted its own
  788. // motion model and the orb lagged noticeably behind saccades.
  789. var kalQ = [0.01, 0, 0, 0,
  790. 0, 0.01, 0, 0,
  791. 0, 0, 0.05, 0,
  792. 0, 0, 0, 0.05]; // process noise (symmetric diagonal)
  793. var kalR = [0.04, 0, // measurement noise (flat 2x2: [R00,R01,R10,R11])
  794. 0, 0.04];
  795. // NOTE: measurement matrix H = [[1,0,0,0],[0,1,0,0]] is hardcoded in kalUpdate
  796. // (it never changes), so no separate kalH array is needed.
  797. // ============================================================
  798. // Calibration: 13-point collection + 6-dim polynomial regression (OLS)
  799. // ============================================================
  800. //
  801. // We model screen position as a quadratic polynomial of iris ratios:
  802. // screenX = a0 + a1*rX + a2*rY + a3*rX² + a4*rY² + a5*rX*rY
  803. // screenY = b0 + b1*rX + b2*rY + b3*rX² + b4*rY² + b5*rX*rY
  804. //
  805. // We fit screenX and screenY independently using ordinary least
  806. // squares on the N=13 calibration points (≈ 13 × 27 = 351 effective
  807. // samples after discarding the first 3 per point). We average each
  808. // point's samples first to make one (ratioX, ratioY) per grid
  809. // location, then solve the 6×6 normal equation directly (Cramer's
  810. // rule — we only have 6 unknowns).
  811. // ============================================================
  812. // Average a point's raw samples down to a single (ratioX, ratioY).
  813. function averageSamples(samples) {
  814. if (!samples.length) return { ratioX: 0.5, ratioY: 0.5 };
  815. let sx = 0, sy = 0;
  816. for (let i = 0; i < samples.length; i++) {
  817. sx += samples[i].ratioX;
  818. sy += samples[i].ratioY;
  819. }
  820. return { ratioX: sx / samples.length, ratioY: sy / samples.length };
  821. }
  822. // Solve a 3×3 linear system A x = b via Cramer's rule.
  823. // Returns [x0, x1, x2] or null if A is singular.
  824. function solve3x3(A, b) {
  825. const det = (
  826. A[0][0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) -
  827. A[0][1] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) +
  828. A[0][2] * (A[1][0] * A[2][1] - A[1][1] * A[2][0])
  829. );
  830. if (Math.abs(det) < 1e-9) return null;
  831. const det0 = (
  832. b[0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) -
  833. A[0][1] * (b[1] * A[2][2] - A[1][2] * b[2]) +
  834. A[0][2] * (b[1] * A[2][1] - A[1][1] * b[2])
  835. );
  836. const det1 = (
  837. A[0][0] * (b[1] * A[2][2] - A[1][2] * b[2]) -
  838. b[0] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) +
  839. A[0][2] * (A[1][0] * b[2] - b[1] * A[2][0])
  840. );
  841. const det2 = (
  842. A[0][0] * (A[1][1] * b[2] - b[1] * A[2][1]) -
  843. A[0][1] * (A[1][0] * b[2] - b[1] * A[2][0]) +
  844. b[0] * (A[1][0] * A[2][1] - A[1][1] * A[2][0])
  845. );
  846. return [det0 / det, det1 / det, det2 / det];
  847. }
  848. // 6x6 Cramer's rule: solve Ax=b where A is 6x6, b is 6x1
  849. // A is passed as array of 6 rows, each row is [a0..a5]
  850. function solve6x6(A, b) {
  851. function det6(m) {
  852. // Compute 6x6 determinant via cofactor expansion along first row
  853. let d = 0;
  854. for (let j = 0; j < 6; j++) {
  855. const minor = [];
  856. for (let i = 1; i < 6; i++) {
  857. const row = [];
  858. for (let k = 0; k < 6; k++) {
  859. if (k !== j) row.push(m[i][k]);
  860. }
  861. minor.push(row);
  862. }
  863. const sign = (j % 2 === 0) ? 1 : -1;
  864. d += sign * m[0][j] * det5(minor);
  865. }
  866. return d;
  867. }
  868. function det5(m) {
  869. let d = 0;
  870. for (let j = 0; j < 5; j++) {
  871. const minor = [];
  872. for (let i = 1; i < 5; i++) {
  873. const row = [];
  874. for (let k = 0; k < 5; k++) {
  875. if (k !== j) row.push(m[i][k]);
  876. }
  877. minor.push(row);
  878. }
  879. const sign = (j % 2 === 0) ? 1 : -1;
  880. d += sign * m[0][j] * det4(minor);
  881. }
  882. return d;
  883. }
  884. function det4(m) {
  885. // 4x4 determinant via cofactor expansion
  886. let d = 0;
  887. for (let j = 0; j < 4; j++) {
  888. const minor = [];
  889. for (let i = 1; i < 4; i++) {
  890. const row = [];
  891. for (let k = 0; k < 4; k++) {
  892. if (k !== j) row.push(m[i][k]);
  893. }
  894. minor.push(row);
  895. }
  896. const sign = (j % 2 === 0) ? 1 : -1;
  897. d += sign * m[0][j] * det3(minor);
  898. }
  899. return d;
  900. }
  901. function det3(m) {
  902. return m[0][0]*(m[1][1]*m[2][2]-m[1][2]*m[2][1])
  903. - m[0][1]*(m[1][0]*m[2][2]-m[1][2]*m[2][0])
  904. + m[0][2]*(m[1][0]*m[2][1]-m[1][1]*m[2][0]);
  905. }
  906. const D = det6(A);
  907. if (Math.abs(D) < 1e-12) return null; // singular
  908. const x = [];
  909. for (let j = 0; j < 6; j++) {
  910. const Aj = A.map((row, i) => {
  911. const r = row.slice();
  912. r[j] = b[i];
  913. return r;
  914. });
  915. x.push(det6(Aj) / D);
  916. }
  917. return x;
  918. }
  919. // Build 6-dim polynomial design row from iris ratios
  920. function buildPolyFeatures(rX, rY) {
  921. return [1, rX, rY, rX*rX, rY*rY, rX*rY];
  922. }
  923. // Build the design matrix for [a0, a1, …, a5] with rows [1, rX, rY, rX², rY², rX*rY].
  924. function buildDesignMatrix(points) {
  925. const M = [];
  926. for (let i = 0; i < points.length; i++) {
  927. M.push(buildPolyFeatures(points[i].ratioX, points[i].ratioY));
  928. }
  929. return M;
  930. }
  931. // Ordinary least squares for y = X * beta. Returns beta = [b0, …, b5]
  932. // (we use Cramer's rule on X^T X and X^T y — small, dense, exact).
  933. function olsFit(X, y) {
  934. const n = X.length;
  935. // X^T X (6x6)
  936. 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]];
  937. // X^T y (6x1)
  938. const b = [0, 0, 0, 0, 0, 0];
  939. for (let i = 0; i < n; i++) {
  940. const xi = X[i];
  941. for (let r = 0; r < 6; r++) {
  942. for (let c = 0; c < 6; c++) A[r][c] += xi[r] * xi[c];
  943. b[r] += xi[r] * y[i];
  944. }
  945. }
  946. return solve6x6(A, b);
  947. }
  948. // RANSAC-style outlier rejection on ratio features per calibration point.
  949. // For each point's samples, drop those whose (ratioX, ratioY) lies > 2.5 std
  950. // from the per-point mean. This catches blinks, mid-saccade samples, and
  951. // points where the user briefly looked elsewhere while the dot was moving.
  952. function ransacCleanPerPoint(point) {
  953. if (!point.samples || point.samples.length <= 5) return point.samples || [];
  954. const sams = point.samples;
  955. const meanX = sams.reduce((a, s) => a + s.ratioX, 0) / sams.length;
  956. const meanY = sams.reduce((a, s) => a + s.ratioY, 0) / sams.length;
  957. const stdX = Math.sqrt(sams.reduce((a, s) => a + (s.ratioX - meanX) * (s.ratioX - meanX), 0) / sams.length);
  958. const stdY = Math.sqrt(sams.reduce((a, s) => a + (s.ratioY - meanY) * (s.ratioY - meanY), 0) / sams.length);
  959. // If std is essentially 0 (perfectly steady) just return everything.
  960. if (stdX < 1e-6 && stdY < 1e-6) return sams.slice();
  961. const kept = [];
  962. for (let i = 0; i < sams.length; i++) {
  963. const sx = (Math.abs(sams[i].ratioX - meanX) < 2.5 * Math.max(stdX, 1e-6));
  964. const sy = (Math.abs(sams[i].ratioY - meanY) < 2.5 * Math.max(stdY, 1e-6));
  965. if (sx && sy) kept.push(sams[i]);
  966. }
  967. // Don't drop more than 40% of samples — std may be underestimated.
  968. if (kept.length < sams.length * 0.6) return sams.slice();
  969. return kept;
  970. }
  971. function fitCalibration(allPoints) {
  972. // allPoints: [{ screenX, screenY, samples:[…] }, …]
  973. // 1) Per-point outlier rejection (RANSAC).
  974. // 2) Average remaining samples per point.
  975. let totalSamples = 0, totalKept = 0;
  976. const pts = allPoints.map(p => {
  977. const cleaned = ransacCleanPerPoint(p);
  978. totalSamples += (p.samples || []).length;
  979. totalKept += cleaned.length;
  980. const avg = averageSamples(cleaned);
  981. return {
  982. screenX: p.screenX,
  983. screenY: p.screenY,
  984. ratioX: avg.ratioX,
  985. ratioY: avg.ratioY
  986. };
  987. });
  988. const X = buildDesignMatrix(pts);
  989. const ysx = pts.map(p => p.screenX);
  990. const ysy = pts.map(p => p.screenY);
  991. const coefX = olsFit(X, ysx);
  992. const coefY = olsFit(X, ysy);
  993. if (!coefX || !coefY) return null;
  994. // Optional debug log of fit quality.
  995. let sseX = 0, sseY = 0;
  996. for (let i = 0; i < pts.length; i++) {
  997. 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;
  998. 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;
  999. sseX += (pts[i].screenX - px) * (pts[i].screenX - px);
  1000. sseY += (pts[i].screenY - py) * (pts[i].screenY - py);
  1001. }
  1002. console.log('[cal] fit quality kept=' + totalKept + '/' + totalSamples +
  1003. ' RMSE X=' + Math.sqrt(sseX / pts.length).toFixed(4) +
  1004. ' RMSE Y=' + Math.sqrt(sseY / pts.length).toFixed(4));
  1005. return {
  1006. coefX: [coefX[0], coefX[1], coefX[2], coefX[3], coefX[4], coefX[5]],
  1007. coefY: [coefY[0], coefY[1], coefY[2], coefY[3], coefY[4], coefY[5]]
  1008. };
  1009. }
  1010. function applyRegression(ratioX, ratioY) {
  1011. if (!calibrationData) return { x: 0.5, y: 0.5 };
  1012. const cx = calibrationData.coefX;
  1013. const cy = calibrationData.coefY;
  1014. const f = buildPolyFeatures(ratioX, ratioY);
  1015. const x = cx[0] + cx[1]*f[1] + cx[2]*f[2] + cx[3]*f[3] + cx[4]*f[4] + cx[5]*f[5];
  1016. const y = cy[0] + cy[1]*f[1] + cy[2]*f[2] + cy[3]*f[3] + cy[4]*f[4] + cy[5]*f[5];
  1017. return { x: clamp(x, -0.05, 1.05), y: clamp(y, -0.05, 1.05) };
  1018. }
  1019. function saveCalibration(cal) {
  1020. try {
  1021. const payload = {
  1022. version: CAL_VERSION,
  1023. coefX: cal.coefX,
  1024. coefY: cal.coefY,
  1025. timestamp: Date.now()
  1026. };
  1027. localStorage.setItem(CAL_STORAGE_KEY, JSON.stringify(payload));
  1028. } catch (e) {
  1029. console.warn('[cal] localStorage save failed', e && e.message);
  1030. }
  1031. }
  1032. function loadCalibration() {
  1033. try {
  1034. const raw = localStorage.getItem(CAL_STORAGE_KEY);
  1035. if (!raw) return null;
  1036. const obj = JSON.parse(raw);
  1037. if (!obj || !Array.isArray(obj.coefX) || !Array.isArray(obj.coefY)) return null;
  1038. if (obj.coefX.length !== 6 || obj.coefY.length !== 6) return null;
  1039. if (obj.version !== CAL_VERSION) {
  1040. console.warn('[cal] stored calibration version mismatch (got', obj.version, 'expected', CAL_VERSION + '); discarding');
  1041. return null;
  1042. }
  1043. return {
  1044. coefX: obj.coefX.slice(0, 6),
  1045. coefY: obj.coefY.slice(0, 6),
  1046. timestamp: obj.timestamp || 0
  1047. };
  1048. } catch (e) {
  1049. console.warn('[cal] localStorage load failed', e && e.message);
  1050. return null;
  1051. }
  1052. }
  1053. function clearCalibration() {
  1054. try { localStorage.removeItem(CAL_STORAGE_KEY); } catch (e) { /* no-op */ }
  1055. calibrationData = null;
  1056. // Reset Kalman so the orb returns to the center after a recalibration.
  1057. kalInit();
  1058. smoothedX = 0.5; smoothedY = 0.5;
  1059. rawXValid = false;
  1060. updateCalStatus('uncalibrated');
  1061. }
  1062. function updateCalStatus(state) {
  1063. // state: 'uncalibrated' | 'calibrating' | 'calibrated'
  1064. if (!calDotStatus || !calStatusText) return;
  1065. if (state === 'uncalibrated') {
  1066. calDotStatus.className = 'dot';
  1067. calStatusText.className = 'value warn';
  1068. calStatusText.textContent = 'UNCAL';
  1069. if (recalibrateBtn) recalibrateBtn.disabled = false;
  1070. dbgSet(dbgCal, 'uncalibrated', 'warn');
  1071. } else if (state === 'calibrating') {
  1072. calDotStatus.className = 'dot warn';
  1073. calStatusText.className = 'value';
  1074. calStatusText.textContent = 'CAL…';
  1075. if (recalibrateBtn) recalibrateBtn.disabled = true;
  1076. dbgSet(dbgCal, 'running', 'run');
  1077. } else if (state === 'calibrated') {
  1078. calDotStatus.className = 'dot ok';
  1079. calStatusText.className = 'value ok';
  1080. calStatusText.textContent = 'OK';
  1081. if (recalibrateBtn) recalibrateBtn.disabled = false;
  1082. dbgSet(dbgCal, 'ready', 'ok');
  1083. }
  1084. }
  1085. // ============================================================
  1086. // Calibration UI flow
  1087. // ============================================================
  1088. function positionCalDot(idx) {
  1089. if (!calDot) return;
  1090. const p = CAL_GRID[CAL_ORDER[idx]];
  1091. // The body / stage is mirrored via CSS scaleX(-1) (webcam preview only);
  1092. // the canvas (#stage) is NOT mirrored, so we use window coordinates directly.
  1093. const cx = p.x * window.innerWidth;
  1094. const cy = p.y * window.innerHeight;
  1095. calDot.style.left = cx + 'px';
  1096. calDot.style.top = cy + 'px';
  1097. }
  1098. function showCalibrationUI(show) {
  1099. if (!calOverlay) return;
  1100. if (show) {
  1101. calOverlay.classList.add('show');
  1102. calOverlay.setAttribute('aria-hidden', 'false');
  1103. } else {
  1104. calOverlay.classList.remove('show');
  1105. calOverlay.setAttribute('aria-hidden', 'true');
  1106. }
  1107. }
  1108. function startCalibration() {
  1109. if (calActive) return;
  1110. calActive = true;
  1111. calPaused = true; // don't let the orb move while we collect
  1112. calAllPoints = [];
  1113. calCurrentIdx = 0;
  1114. calSamples = [];
  1115. pointSampleCount = 0;
  1116. updateCalStatus('calibrating');
  1117. showCalibrationUI(true);
  1118. gotoNextCalPoint();
  1119. }
  1120. function gotoNextCalPoint() {
  1121. if (!calActive) return;
  1122. if (calCurrentIdx >= CAL_ORDER.length) {
  1123. finishCalibration();
  1124. return;
  1125. }
  1126. positionCalDot(calCurrentIdx);
  1127. if (calText) {
  1128. calText.textContent = 'Calibrating (' + (calCurrentIdx + 1) + '/' + CAL_ORDER.length + ')';
  1129. }
  1130. if (calSub) {
  1131. calSub.textContent = 'Follow the dot with your eyes';
  1132. }
  1133. calSamples = [];
  1134. pointSampleCount = 0; // reset per-point counter (first 3 are discarded)
  1135. startSampleCollection();
  1136. }
  1137. function startSampleCollection() {
  1138. if (calCollectTimer) clearInterval(calCollectTimer);
  1139. calCollectTimer = setInterval(() => {
  1140. if (!calActive) return;
  1141. // Discard the first 3 samples so the user has time to fixate on the dot.
  1142. if (pointSampleCount < 3) { pointSampleCount++; return; }
  1143. const gaze = lastGaze; // most recent raw iris ratio (see onResults)
  1144. if (gaze && gaze.visible) {
  1145. calSamples.push({ ratioX: gaze.ratioX, ratioY: gaze.ratioY });
  1146. }
  1147. if (calSamples.length >= CAL_SAMPLES_PER_POINT) {
  1148. clearInterval(calCollectTimer);
  1149. calCollectTimer = null;
  1150. commitCurrentPoint();
  1151. }
  1152. }, CAL_SAMPLE_INTERVAL_MS);
  1153. }
  1154. function commitCurrentPoint() {
  1155. const p = CAL_GRID[CAL_ORDER[calCurrentIdx]];
  1156. calAllPoints.push({
  1157. screenX: p.x,
  1158. screenY: p.y,
  1159. samples: calSamples.slice()
  1160. });
  1161. calCurrentIdx++;
  1162. if (calCurrentIdx >= CAL_ORDER.length) {
  1163. finishCalibration();
  1164. } else {
  1165. // Brief pause between points so the user can re-target.
  1166. setTimeout(gotoNextCalPoint, 150);
  1167. }
  1168. }
  1169. function finishCalibration() {
  1170. if (calCollectTimer) { clearInterval(calCollectTimer); calCollectTimer = null; }
  1171. const fit = fitCalibration(calAllPoints);
  1172. if (!fit) {
  1173. console.warn('[cal] OLS fit failed');
  1174. calActive = false;
  1175. calPaused = false;
  1176. showCalibrationUI(false);
  1177. updateCalStatus(calibrationData ? 'calibrated' : 'uncalibrated');
  1178. return;
  1179. }
  1180. calibrationData = { coefX: fit.coefX, coefY: fit.coefY, timestamp: Date.now() };
  1181. saveCalibration(calibrationData);
  1182. console.log('[cal] saved', calibrationData);
  1183. // Reset Kalman so stale state doesn't bleed into the new calibration.
  1184. kalInit();
  1185. calActive = false;
  1186. calPaused = false;
  1187. showCalibrationUI(false);
  1188. updateCalStatus('calibrated');
  1189. }
  1190. function cancelCalibration() {
  1191. if (calCollectTimer) { clearInterval(calCollectTimer); calCollectTimer = null; }
  1192. calActive = false;
  1193. calPaused = false;
  1194. showCalibrationUI(false);
  1195. updateCalStatus(calibrationData ? 'calibrated' : 'uncalibrated');
  1196. }
  1197. if (calCancel) {
  1198. calCancel.addEventListener('click', cancelCalibration);
  1199. }
  1200. if (recalibrateBtn) {
  1201. recalibrateBtn.addEventListener('click', () => {
  1202. if (!faceMesh) return; // need the model to be running
  1203. clearCalibration();
  1204. startCalibration();
  1205. });
  1206. }
  1207. // Try to restore a previously-saved calibration as soon as the script runs.
  1208. (function tryRestoreCalibration() {
  1209. const saved = loadCalibration();
  1210. if (saved) {
  1211. calibrationData = saved;
  1212. updateCalStatus('calibrated');
  1213. console.log('[cal] restored from localStorage');
  1214. } else {
  1215. updateCalStatus('uncalibrated');
  1216. }
  1217. })();
  1218. // ============================================================
  1219. // Kalman filter (replaces EMA + outlier threshold)
  1220. // ============================================================
  1221. // The state is [x, y, vx, vy] in normalized screen coords; the
  1222. // measurement is [x, y] (from applyRegression). The process model
  1223. // assumes constant velocity with small random accelerations (Q),
  1224. // and the measurement model assumes the regression output is
  1225. // noisy but unbiased (R). This naturally handles gaze noise,
  1226. // outliers (large innovations get down-weighted), and saccades
  1227. // (velocity prediction reduces lag).
  1228. // ============================================================
  1229. function kalUpdate(zx, zy) {
  1230. // Prediction: x = F*x, P = F*P*F' + Q
  1231. // F = [[1,0,dt,0],[0,1,0,dt],[0,0,1,0],[0,0,0,1]], dt=1
  1232. var dt = 1;
  1233. // Predict state
  1234. var px = kalX[0] + kalX[2] * dt;
  1235. var py = kalX[1] + kalX[3] * dt;
  1236. // Predict P: F*P
  1237. // F*P where F adds velocity*dt to position rows
  1238. var pP = new Float64Array(16);
  1239. for (var i = 0; i < 4; i++) {
  1240. for (var j = 0; j < 4; j++) {
  1241. var sum = 0;
  1242. for (var k = 0; k < 4; k++) {
  1243. var fik = (i < 2 && k === i + 2) ? dt : (i === k ? 1 : 0); // F[i][k]
  1244. sum += fik * kalP[k * 4 + j];
  1245. }
  1246. pP[i * 4 + j] = sum;
  1247. }
  1248. }
  1249. // pP * F' + Q
  1250. for (var i = 0; i < 4; i++) {
  1251. for (var j = 0; j < 4; j++) {
  1252. var sum = 0;
  1253. for (var k = 0; k < 4; k++) {
  1254. var fkj = (k < 2 && j === k + 2) ? dt : (k === j ? 1 : 0); // F'[k][j] = F[j][k]
  1255. sum += pP[i * 4 + k] * fkj;
  1256. }
  1257. kalP[i * 4 + j] = sum + kalQ[i * 4 + j];
  1258. }
  1259. }
  1260. // Innovation: y = z - H*x
  1261. var yx = zx - px;
  1262. var yy = zy - py;
  1263. // S = H*P*H' + R (2x2)
  1264. // H = [[1,0,0,0],[0,1,0,0]], so H*P*H' extracts the 2x2 top-left block of P:
  1265. // [P00 P01] plus R (flat: [R00,R01,R10,R11])
  1266. // [P10 P11]
  1267. var s00 = kalP[0] + kalR[0];
  1268. var s01 = kalP[1] + kalR[1];
  1269. var s10 = kalP[4] + kalR[2];
  1270. var s11 = kalP[5] + kalR[3];
  1271. var sDet = s00 * s11 - s01 * s10;
  1272. if (Math.abs(sDet) < 1e-12) { kalX = [zx, zy, 0, 0]; return {x: zx, y: zy}; }
  1273. var sInv00 = s11 / sDet;
  1274. var sInv01 = -s01 / sDet;
  1275. var sInv10 = -s10 / sDet;
  1276. var sInv11 = s00 / sDet;
  1277. // K = P * H' * S^-1 (4x2 matrix, stored flat as K[i*2+row])
  1278. // With H = [[1,0,0,0],[0,1,0,0]], H' has 1s at (0,0) and (1,1) only,
  1279. // so P*H' picks the first two columns of P, then multiplied by S^-1 (2x2).
  1280. var K = new Float64Array(8); // 4x2
  1281. for (var i = 0; i < 4; i++) {
  1282. K[i*2+0] = kalP[i*4+0] * sInv00 + kalP[i*4+1] * sInv10;
  1283. K[i*2+1] = kalP[i*4+0] * sInv01 + kalP[i*4+1] * sInv11;
  1284. }
  1285. // x = px + K*y
  1286. kalX[0] = px + K[0] * yx + K[1] * yy;
  1287. kalX[1] = py + K[2] * yx + K[3] * yy;
  1288. kalX[2] = kalX[2] + K[4] * yx + K[5] * yy;
  1289. kalX[3] = kalX[3] + K[6] * yx + K[7] * yy;
  1290. // P = (I - K*H) * P (Joseph form: numerical stability)
  1291. // With H = [[1,0,0,0],[0,1,0,0]], only columns 0,1 of K matter:
  1292. // (I-KH)[i][j] = δ(i,j) - K[i*2+0]*(j==0) - K[i*2+1]*(j==1)
  1293. // So (I-KH)*P simplifies to:
  1294. // newP[i][k] = P[i][k] - K[i*2+0]*P[0][k] - K[i*2+1]*P[1][k]
  1295. var newP = new Float64Array(16);
  1296. for (var i = 0; i < 4; i++) {
  1297. for (var k = 0; k < 4; k++) {
  1298. newP[i*4+k] = kalP[i*4+k] - K[i*2+0]*kalP[k] - K[i*2+1]*kalP[4+k];
  1299. }
  1300. }
  1301. // Symmetrize P to prevent numerical drift
  1302. for (var i = 0; i < 4; i++) {
  1303. for (var j = i + 1; j < 4; j++) {
  1304. var avg = (newP[i*4+j] + newP[j*4+i]) * 0.5;
  1305. newP[i*4+j] = avg;
  1306. newP[j*4+i] = avg;
  1307. }
  1308. }
  1309. for (var i = 0; i < 16; i++) kalP[i] = newP[i];
  1310. return {x: kalX[0], y: kalX[1]};
  1311. }
  1312. function kalInit() {
  1313. kalX = [0.5, 0.5, 0, 0];
  1314. for (var i = 0; i < 16; i++) kalP[i] = (i % 5 === 0) ? 1 : 0;
  1315. }
  1316. // ============================================================
  1317. // Canvas sizing
  1318. // ============================================================
  1319. function resize() {
  1320. const dpr = Math.min(window.devicePixelRatio || 1, 2);
  1321. W = window.innerWidth;
  1322. H = window.innerHeight;
  1323. stage.width = W * dpr;
  1324. stage.height = H * dpr;
  1325. stage.style.width = W + 'px';
  1326. stage.style.height = H + 'px';
  1327. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1328. }
  1329. window.addEventListener('resize', () => {
  1330. resize();
  1331. // Re-position the calibration dot if one is currently active
  1332. if (calActive && calCurrentIdx < CAL_ORDER.length) {
  1333. positionCalDot(calCurrentIdx);
  1334. }
  1335. });
  1336. resize();
  1337. // ============================================================
  1338. // Gaze math: iris-ratio only
  1339. // Pure eye-in-socket direction. The regression model (fit during
  1340. // calibration) maps this raw ratio onto screen coordinates.
  1341. //
  1342. // Both eyes use the SAME effective sign convention for ratioX (both INCREASE
  1343. // when the user looks to the right):
  1344. // • Left eye: ratioX = (iris - inner) / (outer - inner) → increases naturally
  1345. // • Right eye: raw ratio = (iris - outer) / (inner - outer) → DECREASES when looking right,
  1346. // so we apply `1 - raw_ratio` to flip it back to the same sign.
  1347. // ============================================================
  1348. function computeIrisGaze(landmarks) {
  1349. // Left eye: normal (outer=33, inner=133)
  1350. const l_outer = landmarks[L_OUTER];
  1351. const l_inner = landmarks[L_INNER];
  1352. const l_top = landmarks[L_TOP];
  1353. const l_bot = landmarks[L_BOT];
  1354. const _l_c = landmarks[L_IRIS];
  1355. // Average the 5 left iris contour points for a more stable reading
  1356. const l_iris = {
  1357. x: [468,469,470,471,472].reduce((s,i) => s + (landmarks[i]?.x || 0), 0) / 5,
  1358. y: [468,469,470,471,472].reduce((s,i) => s + (landmarks[i]?.y || 0), 0) / 5
  1359. };
  1360. const left = (l_outer && l_inner && _l_c &&
  1361. !(_l_c.x === 0 && _l_c.y === 0) &&
  1362. !Number.isNaN(_l_c.x) && !Number.isNaN(_l_c.y) &&
  1363. Math.abs(l_outer.x - l_inner.x) > 1e-6)
  1364. ? (() => {
  1365. const eyeW = l_outer.x - l_inner.x;
  1366. const ratioX = (l_iris.x - l_inner.x) / eyeW;
  1367. const midY = (l_top.y + l_bot.y) * 0.5;
  1368. const ratioY = (l_iris.y - midY) / (Math.abs(eyeW) || 1e-6);
  1369. return { ratioX, ratioY };
  1370. })()
  1371. : null;
  1372. // Right eye: same formula structure as left eye (no flip needed because
  1373. // MediaPipe landmarks in the raw frame already give same-sign ratios for
  1374. // both eyes — both ratioX values DECREASE when the user looks RIGHT).
  1375. // Using R_OUTER (which is to the RIGHT in the un-mirrored raw frame) as
  1376. // the denominator reference yields a ratio in the same [0,1]-ish range
  1377. // and, crucially, the same sign as the left eye so that the average of
  1378. // both eyes does NOT collapse to ~0.5.
  1379. const r_outer = landmarks[R_OUTER];
  1380. const r_inner = landmarks[R_INNER];
  1381. const r_top = landmarks[R_TOP];
  1382. const r_bot = landmarks[R_BOT];
  1383. const _r_c = landmarks[R_IRIS];
  1384. // Average the 5 right iris contour points for a more stable reading
  1385. const r_iris = {
  1386. x: [473,474,475,476,477].reduce((s,i) => s + (landmarks[i]?.x || 0), 0) / 5,
  1387. y: [473,474,475,476,477].reduce((s,i) => s + (landmarks[i]?.y || 0), 0) / 5
  1388. };
  1389. const right = (r_outer && r_inner && _r_c &&
  1390. !(_r_c.x === 0 && _r_c.y === 0) &&
  1391. !Number.isNaN(_r_c.x) && !Number.isNaN(_r_c.y) &&
  1392. Math.abs(r_inner.x - r_outer.x) > 1e-6)
  1393. ? (() => {
  1394. // Same formula shape as the left eye, but using R_OUTER (right side
  1395. // in raw frame) as the "outer" anchor. eyeW = inner - outer is
  1396. // NEGATIVE here, and (iris - outer)/eyeW is therefore also
  1397. // negative of the naive (iris - inner)/eyeW — but that's the
  1398. // correct sign for the right eye, so both eyes agree when the
  1399. // user looks right. No `1 -` flip is applied.
  1400. const r_eyeW = r_inner.x - r_outer.x;
  1401. const r_ratioX = 1 - (r_iris.x - r_outer.x) / r_eyeW;
  1402. const r_midY = (r_top.y + r_bot.y) * 0.5;
  1403. const r_ratioY = (r_iris.y - r_midY) / (Math.abs(r_eyeW) || 1e-6);
  1404. return { ratioX: r_ratioX, ratioY: r_ratioY };
  1405. })()
  1406. : null;
  1407. irisVisible.l = !!left;
  1408. irisVisible.r = !!right;
  1409. if (!left && !right) return { ratioX: 0.5, ratioY: 0.5, visible: false };
  1410. let rx, ry;
  1411. if (left && right) {
  1412. rx = (left.ratioX + right.ratioX) * 0.5;
  1413. ry = (left.ratioY + right.ratioY) * 0.5;
  1414. } else {
  1415. const s = left || right;
  1416. rx = s.ratioX; ry = s.ratioY;
  1417. }
  1418. return { ratioX: rx, ratioY: ry, visible: true };
  1419. }
  1420. // ============================================================
  1421. // Render: full-screen orb + trail
  1422. // ============================================================
  1423. function drawOrb() {
  1424. // Clear with very slight motion blur for the trail
  1425. ctx.fillStyle = 'rgba(10, 10, 26, 0.35)';
  1426. ctx.fillRect(0, 0, W, H);
  1427. // Map smoothed gaze to screen coordinates (with margin so orb stays on screen)
  1428. const margin = 60;
  1429. const sx = margin + smoothedX * (W - margin * 2);
  1430. const sy = margin + smoothedY * (H - margin * 2);
  1431. // Push trail
  1432. trail.push({ x: sx, y: sy });
  1433. if (trail.length > TRAIL_LENGTH) trail.shift();
  1434. // Draw trail (oldest -> newest, fading in opacity & shrinking radius)
  1435. // Cheap: simple filled circles, no radialGradient per point.
  1436. for (let i = 0; i < trail.length; i++) {
  1437. const t = trail[i];
  1438. const tNorm = (i + 1) / trail.length; // 0..1
  1439. const r = ORB_RADIUS * 0.12 * tNorm;
  1440. const a = 0.03 + 0.25 * tNorm;
  1441. ctx.fillStyle = 'rgba(0, 229, 255, ' + a + ')';
  1442. ctx.beginPath();
  1443. ctx.arc(t.x, t.y, r, 0, Math.PI * 2);
  1444. ctx.fill();
  1445. }
  1446. // Main orb - layered radial gradients for glow
  1447. const cx = sx, cy = sy;
  1448. // Outer halo
  1449. let g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS * 4);
  1450. g.addColorStop(0, 'rgba(0, 229, 255, 0.35)');
  1451. g.addColorStop(0.25, 'rgba(0, 229, 255, 0.18)');
  1452. g.addColorStop(0.6, 'rgba(0, 184, 212, 0.05)');
  1453. g.addColorStop(1, 'rgba(0, 229, 255, 0)');
  1454. ctx.fillStyle = g;
  1455. ctx.beginPath();
  1456. ctx.arc(cx, cy, ORB_RADIUS * 4, 0, Math.PI * 2);
  1457. ctx.fill();
  1458. // Mid glow
  1459. g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS * 1.8);
  1460. g.addColorStop(0, 'rgba(180, 255, 255, 0.95)');
  1461. g.addColorStop(0.25, 'rgba(0, 229, 255, 0.85)');
  1462. g.addColorStop(0.65, 'rgba(0, 184, 212, 0.5)');
  1463. g.addColorStop(1, 'rgba(0, 229, 255, 0)');
  1464. ctx.fillStyle = g;
  1465. ctx.beginPath();
  1466. ctx.arc(cx, cy, ORB_RADIUS * 1.8, 0, Math.PI * 2);
  1467. ctx.fill();
  1468. // Core
  1469. g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS);
  1470. g.addColorStop(0, 'rgba(255, 255, 255, 1)');
  1471. g.addColorStop(0.3, 'rgba(180, 255, 255, 1)');
  1472. g.addColorStop(0.7, 'rgba(0, 229, 255, 0.95)');
  1473. g.addColorStop(1, 'rgba(0, 184, 212, 0.7)');
  1474. ctx.fillStyle = g;
  1475. ctx.beginPath();
  1476. ctx.arc(cx, cy, ORB_RADIUS, 0, Math.PI * 2);
  1477. ctx.fill();
  1478. // Inner sparkle
  1479. ctx.fillStyle = 'rgba(255, 255, 255, 0.85)';
  1480. ctx.beginPath();
  1481. ctx.arc(cx - ORB_RADIUS * 0.25, cy - ORB_RADIUS * 0.25, ORB_RADIUS * 0.18, 0, Math.PI * 2);
  1482. ctx.fill();
  1483. }
  1484. // ============================================================
  1485. // Render: face mesh overlay on webcam preview
  1486. // ============================================================
  1487. function drawOverlay(results) {
  1488. const w = overlay.width;
  1489. const h = overlay.height;
  1490. octx.clearRect(0, 0, w, h);
  1491. if (!results || !results.multiFaceLandmarks || results.multiFaceLandmarks.length === 0) {
  1492. // Subtle "no face" indicator
  1493. octx.strokeStyle = 'rgba(0, 229, 255, 0.25)';
  1494. octx.setLineDash([4, 4]);
  1495. octx.lineWidth = 1;
  1496. octx.strokeRect(8, 8, w - 16, h - 16);
  1497. octx.setLineDash([]);
  1498. octx.fillStyle = 'rgba(0, 229, 255, 0.7)';
  1499. octx.font = '10px monospace';
  1500. octx.fillText('NO FACE DETECTED', 12, h - 12);
  1501. return;
  1502. }
  1503. const lm = results.multiFaceLandmarks[0];
  1504. // Note: the video is mirrored visually via CSS, so we mirror X here
  1505. // to keep the mesh aligned with what the user sees.
  1506. const pt = (i) => ({ x: (1 - lm[i].x) * w, y: lm[i].y * h });
  1507. // Draw mesh lines
  1508. octx.lineWidth = 0.6;
  1509. octx.strokeStyle = 'rgba(0, 229, 255, 0.45)';
  1510. octx.beginPath();
  1511. [FACE_OVAL, LIPS, L_EYE, R_EYE, L_BROW, R_BROW].forEach(connections => {
  1512. for (let i = 0; i < connections.length; i++) {
  1513. const a = pt(connections[i]);
  1514. const b = pt(connections[(i + 1) % connections.length]);
  1515. octx.moveTo(a.x, a.y);
  1516. octx.lineTo(b.x, b.y);
  1517. }
  1518. });
  1519. octx.stroke();
  1520. // Subtle face dots (subsample every 6th point for performance)
  1521. octx.fillStyle = 'rgba(0, 229, 255, 0.4)';
  1522. for (let i = 0; i < lm.length; i++) {
  1523. if (i % 6 !== 0) continue; // was % 3 — doubled the stride to halve the work
  1524. const p = pt(i);
  1525. octx.fillRect(p.x, p.y, 1, 1);
  1526. }
  1527. // Iris highlight (big + bright)
  1528. octx.fillStyle = '#ffeb3b';
  1529. IRIS_LANDMARKS.forEach(idx => {
  1530. const p = pt(idx);
  1531. octx.beginPath();
  1532. octx.arc(p.x, p.y, 1.6, 0, Math.PI * 2);
  1533. octx.fill();
  1534. });
  1535. // Iris center (468 / 473) - extra large
  1536. [L_IRIS, R_IRIS].forEach(idx => {
  1537. const p = pt(idx);
  1538. octx.fillStyle = '#ffffff';
  1539. octx.beginPath();
  1540. octx.arc(p.x, p.y, 2.6, 0, Math.PI * 2);
  1541. octx.fill();
  1542. });
  1543. }
  1544. // ============================================================
  1545. // Animation loop
  1546. // ============================================================
  1547. function loop(now) {
  1548. // FPS
  1549. const dt = now - lastTime;
  1550. lastTime = now;
  1551. const instFps = 1000 / Math.max(dt, 1);
  1552. fpsSmooth = fpsSmooth === 0 ? instFps : (fpsSmooth * 0.9 + instFps * 0.1);
  1553. // Kalman filter: feed raw gaze through the Kalman filter.
  1554. // rawX/rawY are already screen-coords (applyRegression when calibrated,
  1555. // or raw iris ratio clamped to [0,1] before calibration is ready).
  1556. // No update when no iris is visible, so the orb holds its position
  1557. // instead of drifting back to center.
  1558. if (rawXValid && !calPaused) {
  1559. var kf = kalUpdate(rawX, rawY);
  1560. smoothedX = kf.x;
  1561. smoothedY = kf.y;
  1562. }
  1563. drawOrb();
  1564. if (lastResults) drawOverlay(lastResults);
  1565. // Status text — overall pipeline state
  1566. const visible = irisVisible.l || irisVisible.r;
  1567. if (visible) {
  1568. statusDot.className = 'dot ok';
  1569. statusText.className = 'value ok';
  1570. statusText.textContent = 'TRACKING';
  1571. dbgSet(dbgStage, 'tracking', 'ok');
  1572. } else if (faceMesh) {
  1573. statusDot.className = 'dot warn';
  1574. statusText.className = 'value warn';
  1575. statusText.textContent = 'NO IRIS';
  1576. dbgSet(dbgStage, 'no face', 'warn');
  1577. } else {
  1578. statusDot.className = 'dot';
  1579. statusText.className = 'value';
  1580. statusText.textContent = 'INIT';
  1581. dbgSet(dbgStage, 'init', 'run');
  1582. }
  1583. fpsEl.textContent = Math.round(fpsSmooth);
  1584. gxEl.textContent = smoothedX.toFixed(3);
  1585. gyEl.textContent = smoothedY.toFixed(3);
  1586. ilEl.textContent = irisVisible.l ? '●' : '○';
  1587. irEl.textContent = irisVisible.r ? '●' : '○';
  1588. ilEl.className = 'value ' + (irisVisible.l ? 'ok' : 'warn');
  1589. irEl.className = 'value ' + (irisVisible.r ? 'ok' : 'warn');
  1590. dbgSet(dbgFrame, lastFrameMs > 0 ? (lastFrameMs.toFixed(1) + ' ms') : '--');
  1591. requestAnimationFrame(loop);
  1592. }
  1593. requestAnimationFrame(loop);
  1594. // ============================================================
  1595. // MediaPipe setup
  1596. // ============================================================
  1597. function showError(title, msg) {
  1598. console.error('[error]', title, '—', msg);
  1599. errTitle.textContent = title;
  1600. errMsg.textContent = msg;
  1601. errOverlay.classList.add('show');
  1602. loader.classList.add('hidden');
  1603. statusDot.className = 'dot err';
  1604. statusText.className = 'value err';
  1605. statusText.textContent = 'ERROR';
  1606. dbgSetError((title ? title + ': ' : '') + (msg || ''));
  1607. dbgSet(dbgStage, 'error', 'err');
  1608. }
  1609. errRetry.addEventListener('click', () => {
  1610. errOverlay.classList.remove('show');
  1611. location.reload();
  1612. });
  1613. // Format bytes for the debug panel / loader text
  1614. function fmtBytes(n) {
  1615. if (n < 1024) return n + ' B';
  1616. if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
  1617. return (n / (1024 * 1024)).toFixed(2) + ' MB';
  1618. }
  1619. // Pre-fetch a list of MediaPipe WASM / data files with byte-level progress.
  1620. // Returns a map { filename -> blob: URL } suitable for locateFile().
  1621. // If any file fails, the function still resolves with whatever succeeded
  1622. // (MediaPipe will retry from the network as a fallback).
  1623. async function prefetchAssets(files) {
  1624. console.log('[model] pre-fetching', files.length, 'asset(s)…');
  1625. dbgSet(dbgModel, 'loading…', 'run');
  1626. const out = {};
  1627. let totalBytes = 0;
  1628. for (let i = 0; i < files.length; i++) {
  1629. const file = files[i];
  1630. const url = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/' + file;
  1631. setLoaderText(
  1632. 'Downloading model (' + (i + 1) + '/' + files.length + ')',
  1633. file + ' (0 MB)'
  1634. );
  1635. console.log('[model] GET', file);
  1636. try {
  1637. const resp = await fetch(url, { mode: 'cors', cache: 'force-cache' });
  1638. if (!resp.ok) throw new Error('HTTP ' + resp.status);
  1639. const len = parseInt(resp.headers.get('content-length') || '0', 10);
  1640. // Stream the body so we can show incremental progress.
  1641. const reader = resp.body && resp.body.getReader ? resp.body.getReader() : null;
  1642. const chunks = [];
  1643. let received = 0;
  1644. if (reader) {
  1645. // eslint-disable-next-line no-constant-condition
  1646. while (true) {
  1647. const { done, value } = await reader.read();
  1648. if (done) break;
  1649. chunks.push(value);
  1650. received += value.byteLength;
  1651. totalBytes += value.byteLength;
  1652. const pct = len ? Math.round((received / len) * 100) : 0;
  1653. setLoaderText(
  1654. 'Downloading model (' + (i + 1) + '/' + files.length + ' · ' + pct + '%)',
  1655. file + ' — ' + fmtBytes(received) + (len ? ' / ' + fmtBytes(len) : '')
  1656. );
  1657. dbgSet(dbgBytes, fmtBytes(totalBytes));
  1658. }
  1659. const blob = new Blob(chunks, { type: resp.headers.get('content-type') || 'application/octet-stream' });
  1660. out[file] = URL.createObjectURL(blob);
  1661. } else {
  1662. const blob = await resp.blob();
  1663. out[file] = URL.createObjectURL(blob);
  1664. totalBytes += blob.size;
  1665. dbgSet(dbgBytes, fmtBytes(totalBytes));
  1666. }
  1667. console.log('[model] OK', file, fmtBytes(received || (out[file] ? 0 : 0)));
  1668. } catch (e) {
  1669. console.warn('[model] pre-fetch failed for', file, e && e.message);
  1670. // leave out[file] undefined → MediaPipe will fall back to the URL
  1671. }
  1672. }
  1673. dbgSet(dbgModel, 'ready (' + fmtBytes(totalBytes) + ')', 'ok');
  1674. console.log('[model] pre-fetch done, total', fmtBytes(totalBytes));
  1675. return out;
  1676. }
  1677. async function initFaceMesh() {
  1678. console.log('[init] initFaceMesh start');
  1679. setLoaderText(
  1680. 'Initializing face mesh…',
  1681. 'Preparing the iris-tracking model. This may take a moment.'
  1682. );
  1683. dbgSet(dbgModel, 'init…', 'run');
  1684. try {
  1685. // 1) Pre-fetch the big WASM / data files so the user can see progress
  1686. // instead of a silent stall. The list mirrors the files MediaPipe
  1687. // requests at runtime when refineLandmarks is enabled.
  1688. const assetMap = await prefetchAssets([
  1689. 'face_mesh_solution_simd_wasm_bin.js',
  1690. 'face_mesh_solution_simd_wasm_bin.wasm',
  1691. 'face_mesh_solution_packed_assets.data'
  1692. ]);
  1693. setLoaderText(
  1694. 'Initializing face mesh…',
  1695. 'WASM runtime ready. Constructing the model.'
  1696. );
  1697. // 2) Construct FaceMesh. If we pre-fetched a file, serve it from the
  1698. // blob URL so the browser uses the cached bytes; otherwise let
  1699. // MediaPipe fall back to the CDN.
  1700. faceMesh = new FaceMesh({
  1701. locateFile: (file) => {
  1702. if (assetMap[file]) {
  1703. console.log('[model] locateFile (cached)', file);
  1704. return assetMap[file];
  1705. }
  1706. const url = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/' + file;
  1707. console.log('[model] locateFile (remote)', file);
  1708. return url;
  1709. }
  1710. });
  1711. faceMesh.setOptions({
  1712. maxNumFaces: 1,
  1713. refineLandmarks: true, // gives 468-477 iris
  1714. minDetectionConfidence: 0.5,
  1715. minTrackingConfidence: 0.5
  1716. });
  1717. faceMesh.onResults(onResults);
  1718. console.log('[init] FaceMesh constructed, calling .initialize()');
  1719. setLoaderText(
  1720. 'Initializing face mesh…',
  1721. 'Calling MediaPipe .initialize() — finalizing WASM.'
  1722. );
  1723. if (typeof faceMesh.initialize === 'function') {
  1724. await faceMesh.initialize();
  1725. }
  1726. console.log('[init] FaceMesh ready');
  1727. dbgSet(dbgModel, 'ready', 'ok');
  1728. startCamera();
  1729. } catch (e) {
  1730. console.error('FaceMesh init failed:', e);
  1731. dbgSetError('FaceMesh init failed: ' + (e && e.message ? e.message : e));
  1732. dbgSet(dbgModel, 'failed', 'err');
  1733. showError(
  1734. 'Initialization Failed',
  1735. 'Could not load MediaPipe Face Mesh (' + ((e && e.message) || 'unknown error') +
  1736. '). Check your network connection and reload the page.'
  1737. );
  1738. }
  1739. }
  1740. // The most recent iris ratio (used by the calibration collector).
  1741. let lastGaze = { ratioX: 0.5, ratioY: 0.5, visible: false };
  1742. function onResults(results) {
  1743. const t1 = performance.now();
  1744. lastResults = results;
  1745. if (!results.multiFaceLandmarks || results.multiFaceLandmarks.length === 0) {
  1746. // No face - hold last smoothed position, don't drift
  1747. lastGaze.visible = false;
  1748. lastFrameMs = performance.now() - t1;
  1749. return;
  1750. }
  1751. const lm = results.multiFaceLandmarks[0];
  1752. const gaze = computeIrisGaze(lm);
  1753. lastGaze = gaze;
  1754. if (gaze.visible && calibrationData && !calPaused) {
  1755. // Map raw iris ratio → screen coordinates via the OLS model
  1756. const mapped = applyRegression(gaze.ratioX, gaze.ratioY);
  1757. rawX = mapped.x;
  1758. rawY = mapped.y;
  1759. rawXValid = true;
  1760. } else if (gaze.visible && !calPaused) {
  1761. // No calibration yet — approximate screen position from iris ratio.
  1762. // ratioX (eyeW-normalized) lives roughly in [0.2, 0.8] with the center
  1763. // near 0.5; recenter at 0.5 and stretch x3 to fill the screen without
  1764. // saturating.
  1765. // ratioY is eyeW-normalized and signed (look-up → negative, look-down
  1766. // → positive); recenter at 0.5 and stretch x3. The calibration
  1767. // regression will fix the exact direction/orientation afterward — this
  1768. // fallback just needs to produce values that span [0, 1] without
  1769. // clipping at 1 the moment the user blinks or moves their head.
  1770. rawX = clamp(0.5 + (gaze.ratioX - 0.5) * 3, 0, 1);
  1771. rawY = clamp(0.5 + gaze.ratioY * 3, 0, 1);
  1772. rawXValid = true;
  1773. } else {
  1774. // No iris detected, or calibration is paused
  1775. rawXValid = false;
  1776. }
  1777. lastFrameMs = performance.now() - t1;
  1778. // Debug log: once per second, print the current iris ratios + mapped
  1779. // screen coordinates. Throttled with lastDebugLogMs so we don't flood
  1780. // the console at ~30 fps. Helpful for diagnosing "why is the orb
  1781. // stuck?" — open DevTools and watch the values as you move your eyes.
  1782. if (rawXValid) {
  1783. const nowMs = performance.now();
  1784. if (nowMs - lastDebugLogMs >= 1000) {
  1785. lastDebugLogMs = nowMs;
  1786. console.log(
  1787. '[gaze] ratioX=' + gaze.ratioX.toFixed(3) +
  1788. ' ratioY=' + gaze.ratioY.toFixed(3) +
  1789. ' | mappedX=' + rawX.toFixed(3) +
  1790. ' mappedY=' + rawY.toFixed(3) +
  1791. ' | calibrated=' + (calibrationData ? 'yes' : 'no') +
  1792. ' | irisVisible=' + irisVisible.l + '/' + irisVisible.r
  1793. );
  1794. }
  1795. }
  1796. }
  1797. function startCamera() {
  1798. console.log('[camera] startCamera');
  1799. setLoaderText(
  1800. 'Connecting camera…',
  1801. 'Requesting webcam access. Please click "Allow" in the browser prompt.'
  1802. );
  1803. dbgSet(dbgCamera, 'requesting…', 'run');
  1804. if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
  1805. dbgSet(dbgCamera, 'unsupported', 'err');
  1806. showError(
  1807. 'Browser Not Supported',
  1808. 'Your browser does not support getUserMedia. Please use a modern browser (Chrome, Firefox, Edge, Safari).'
  1809. );
  1810. return;
  1811. }
  1812. camera = new Camera(video, {
  1813. onFrame: async () => {
  1814. // Frame-skip: only send every 2nd frame to MediaPipe. This roughly
  1815. // halves CPU usage on the face-mesh pass and noticeably improves
  1816. // responsiveness on mid-range laptops.
  1817. frameCount++;
  1818. if (frameCount % 2 !== 0) return;
  1819. if (faceMesh) {
  1820. const t0 = performance.now();
  1821. try {
  1822. await faceMesh.send({ image: video });
  1823. } catch (e) {
  1824. // swallow individual frame errors
  1825. console.warn('[frame] send error', e && e.message);
  1826. } finally {
  1827. lastMeshSendAt = performance.now() - t0;
  1828. if (lastMeshSendAt > 5) {
  1829. // Only log slow frames to keep the console quiet
  1830. // console.log('[frame] send', lastMeshSendAt.toFixed(1), 'ms');
  1831. }
  1832. }
  1833. }
  1834. },
  1835. width: 640,
  1836. height: 480
  1837. });
  1838. camera.start()
  1839. .then(() => {
  1840. // wait for metadata
  1841. return new Promise(resolve => {
  1842. if (video.readyState >= 1) return resolve();
  1843. video.addEventListener('loadedmetadata', resolve, { once: true });
  1844. });
  1845. })
  1846. .then(() => {
  1847. console.log('[camera] stream ready, hiding loader');
  1848. loader.classList.add('hidden');
  1849. statusText.textContent = 'READY';
  1850. dbgSet(dbgCamera, 'streaming', 'ok');
  1851. dbgSet(dbgStage, 'live', 'ok');
  1852. // First-time calibration: no localStorage → kick off the 9-point flow
  1853. if (!calibrationData && !calActive) {
  1854. // small delay so the user can settle in front of the camera
  1855. setTimeout(() => { if (!calibrationData && !calActive) startCalibration(); }, 800);
  1856. }
  1857. })
  1858. .catch(err => {
  1859. console.error('Camera error:', err);
  1860. dbgSet(dbgCamera, 'error', 'err');
  1861. const name = err && err.name;
  1862. if (name === 'NotAllowedError' || name === 'PermissionDeniedError' || name === 'SecurityError') {
  1863. showError(
  1864. 'Camera Access Denied',
  1865. 'We need your camera to track your gaze. Please click the camera icon in your browser\'s address bar, grant permission, then click Retry.'
  1866. );
  1867. } else if (name === 'NotFoundError' || name === 'OverconstrainedError') {
  1868. showError(
  1869. 'No Camera Found',
  1870. 'No webcam was detected on this device. Please connect a camera and reload the page.'
  1871. );
  1872. } else if (name === 'NotReadableError' || name === 'TrackStartError') {
  1873. showError(
  1874. 'Camera Busy',
  1875. 'Your camera appears to be in use by another application. Please close other apps (Zoom, Skype, etc.) and try again.'
  1876. );
  1877. } else {
  1878. showError(
  1879. 'Camera Error',
  1880. (err && err.message) || 'An unknown error occurred while accessing the camera.'
  1881. );
  1882. }
  1883. });
  1884. }
  1885. // Wait for the global FaceMesh symbol to be available
  1886. function waitFor(predicate, timeout = 20000) {
  1887. return new Promise((resolve, reject) => {
  1888. const start = performance.now();
  1889. (function check() {
  1890. if (predicate()) return resolve();
  1891. if (performance.now() - start > timeout) return reject(new Error('Timeout waiting for MediaPipe'));
  1892. requestAnimationFrame(check);
  1893. })();
  1894. });
  1895. }
  1896. // Kick off: stage 1 = wait for the CDN script to register window.FaceMesh
  1897. setLoaderText(
  1898. 'Loading MediaPipe JS…',
  1899. 'Downloading the MediaPipe scripts from the CDN.'
  1900. );
  1901. console.log('[boot] waiting for window.FaceMesh…');
  1902. waitFor(() => typeof window.FaceMesh === 'function', 20000)
  1903. .then(() => {
  1904. console.log('[boot] window.FaceMesh available');
  1905. initFaceMesh();
  1906. })
  1907. .catch((e) => {
  1908. console.error('[boot] FaceMesh never appeared:', e && e.message);
  1909. dbgSet(dbgCdn3, 'TIMEOUT', 'err');
  1910. dbgSetError('Timed out waiting for MediaPipe JS. The CDN may be blocked.');
  1911. showError(
  1912. 'Failed to Load MediaPipe',
  1913. '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.'
  1914. );
  1915. });
  1916. // Safety: if a CDN script failed before waitFor() could resolve, bail out
  1917. // promptly with a clear message instead of waiting for the timeout.
  1918. window.addEventListener('cdnError', () => {
  1919. if (typeof window.FaceMesh !== 'function') {
  1920. console.error('[boot] CDN error before FaceMesh became available');
  1921. showError(
  1922. 'CDN Load Failed',
  1923. '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.'
  1924. );
  1925. }
  1926. });
  1927. })();
  1928. </script>
  1929. </body>
  1930. </html>