index.html 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  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. --panel: rgba(10, 20, 40, 0.55);
  18. --panel-border: rgba(0, 229, 255, 0.35);
  19. }
  20. * { box-sizing: border-box; margin: 0; padding: 0; }
  21. html, body {
  22. width: 100%;
  23. height: 100%;
  24. overflow: hidden;
  25. background: var(--bg);
  26. color: var(--text);
  27. font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "SF Mono", "Roboto Mono", Menlo, Consolas, monospace;
  28. -webkit-font-smoothing: antialiased;
  29. user-select: none;
  30. }
  31. body {
  32. background-color: var(--bg);
  33. background-image:
  34. linear-gradient(var(--grid) 1px, transparent 1px),
  35. linear-gradient(90deg, var(--grid) 1px, transparent 1px);
  36. background-size: 40px 40px;
  37. background-position: -1px -1px;
  38. }
  39. /* Subtle radial vignette */
  40. body::before {
  41. content: "";
  42. position: fixed;
  43. inset: 0;
  44. pointer-events: none;
  45. background: radial-gradient(ellipse at center, transparent 0%, rgba(0,0,0,0.6) 100%);
  46. z-index: 1;
  47. }
  48. #stage {
  49. position: fixed;
  50. inset: 0;
  51. z-index: 2;
  52. cursor: crosshair;
  53. }
  54. /* ---------- Webcam preview ---------- */
  55. #preview-wrap {
  56. position: fixed;
  57. left: 24px;
  58. bottom: 64px;
  59. width: 240px;
  60. height: 180px;
  61. border-radius: 14px;
  62. overflow: hidden;
  63. background: #000;
  64. border: 1px solid var(--panel-border);
  65. box-shadow:
  66. 0 0 0 1px rgba(0, 229, 255, 0.08) inset,
  67. 0 8px 32px rgba(0, 229, 255, 0.12),
  68. 0 2px 8px rgba(0, 0, 0, 0.6);
  69. z-index: 10;
  70. backdrop-filter: blur(4px);
  71. }
  72. #preview-wrap::before {
  73. content: "LIVE · IRIS";
  74. position: absolute;
  75. top: 8px;
  76. left: 10px;
  77. font-size: 10px;
  78. letter-spacing: 0.15em;
  79. color: var(--cyan);
  80. text-shadow: 0 0 8px rgba(0, 229, 255, 0.7);
  81. z-index: 12;
  82. pointer-events: none;
  83. }
  84. #preview-wrap::after {
  85. content: "";
  86. position: absolute;
  87. inset: 0;
  88. border-radius: 14px;
  89. pointer-events: none;
  90. box-shadow: 0 0 24px rgba(0, 229, 255, 0.18) inset;
  91. z-index: 11;
  92. }
  93. #webcam, #overlay {
  94. position: absolute;
  95. inset: 0;
  96. width: 100%;
  97. height: 100%;
  98. }
  99. #webcam {
  100. object-fit: cover;
  101. transform: scaleX(-1); /* mirrored */
  102. z-index: 1;
  103. }
  104. #overlay {
  105. z-index: 2;
  106. pointer-events: none;
  107. }
  108. /* ---------- Status bar ---------- */
  109. #status-bar {
  110. position: fixed;
  111. left: 0;
  112. right: 0;
  113. bottom: 0;
  114. height: 48px;
  115. display: flex;
  116. align-items: center;
  117. gap: 24px;
  118. padding: 0 20px;
  119. background: var(--panel);
  120. border-top: 1px solid var(--panel-border);
  121. backdrop-filter: blur(8px);
  122. font-size: 12px;
  123. letter-spacing: 0.05em;
  124. z-index: 20;
  125. color: var(--text-dim);
  126. }
  127. .stat {
  128. display: flex;
  129. align-items: center;
  130. gap: 8px;
  131. }
  132. .stat .label {
  133. color: rgba(128, 222, 234, 0.55);
  134. text-transform: uppercase;
  135. font-size: 10px;
  136. letter-spacing: 0.18em;
  137. }
  138. .stat .value {
  139. color: var(--cyan);
  140. text-shadow: 0 0 8px rgba(0, 229, 255, 0.5);
  141. font-variant-numeric: tabular-nums;
  142. min-width: 60px;
  143. }
  144. .stat .value.ok { color: var(--ok); text-shadow: 0 0 8px rgba(0, 230, 118, 0.4); }
  145. .stat .value.warn { color: #ffb74d; text-shadow: 0 0 8px rgba(255, 183, 77, 0.4); }
  146. .stat .value.err { color: var(--danger); text-shadow: 0 0 8px rgba(255, 82, 82, 0.4); }
  147. .dot {
  148. width: 8px;
  149. height: 8px;
  150. border-radius: 50%;
  151. background: var(--cyan-dim);
  152. box-shadow: 0 0 8px var(--cyan-dim);
  153. animation: pulse 1.6s ease-in-out infinite;
  154. }
  155. .dot.ok { background: var(--ok); box-shadow: 0 0 10px var(--ok); }
  156. .dot.warn { background: #ffb74d; box-shadow: 0 0 10px #ffb74d; }
  157. .dot.err { background: var(--danger); box-shadow: 0 0 10px var(--danger); animation: none; }
  158. @keyframes pulse {
  159. 0%, 100% { opacity: 1; transform: scale(1); }
  160. 50% { opacity: 0.4; transform: scale(0.8); }
  161. }
  162. /* ---------- Title ---------- */
  163. #title {
  164. position: fixed;
  165. top: 18px;
  166. left: 24px;
  167. z-index: 15;
  168. font-size: 11px;
  169. letter-spacing: 0.3em;
  170. color: rgba(0, 229, 255, 0.7);
  171. text-shadow: 0 0 8px rgba(0, 229, 255, 0.4);
  172. }
  173. #title .accent { color: var(--cyan); }
  174. /* ---------- Loading overlay ---------- */
  175. #loader {
  176. position: fixed;
  177. inset: 0;
  178. z-index: 100;
  179. display: flex;
  180. flex-direction: column;
  181. align-items: center;
  182. justify-content: center;
  183. gap: 28px;
  184. background: rgba(10, 10, 26, 0.92);
  185. backdrop-filter: blur(6px);
  186. transition: opacity 0.5s ease, visibility 0.5s;
  187. }
  188. #loader.hidden {
  189. opacity: 0;
  190. visibility: hidden;
  191. }
  192. .spinner {
  193. width: 64px;
  194. height: 64px;
  195. border: 2px solid rgba(0, 229, 255, 0.15);
  196. border-top-color: var(--cyan);
  197. border-right-color: var(--cyan);
  198. border-radius: 50%;
  199. animation: spin 1s linear infinite;
  200. box-shadow: 0 0 24px rgba(0, 229, 255, 0.3);
  201. }
  202. @keyframes spin {
  203. to { transform: rotate(360deg); }
  204. }
  205. .loader-text {
  206. font-size: 12px;
  207. letter-spacing: 0.4em;
  208. text-transform: uppercase;
  209. color: var(--cyan);
  210. text-shadow: 0 0 10px rgba(0, 229, 255, 0.6);
  211. }
  212. .loader-sub {
  213. font-size: 11px;
  214. color: var(--text-dim);
  215. letter-spacing: 0.15em;
  216. max-width: 320px;
  217. text-align: center;
  218. line-height: 1.6;
  219. }
  220. /* ---------- Error overlay ---------- */
  221. #error-overlay {
  222. position: fixed;
  223. inset: 0;
  224. z-index: 90;
  225. display: none;
  226. flex-direction: column;
  227. align-items: center;
  228. justify-content: center;
  229. gap: 18px;
  230. background: rgba(10, 10, 26, 0.88);
  231. backdrop-filter: blur(6px);
  232. padding: 40px;
  233. text-align: center;
  234. }
  235. #error-overlay.show { display: flex; }
  236. #error-overlay .icon {
  237. font-size: 48px;
  238. filter: drop-shadow(0 0 12px rgba(255, 82, 82, 0.6));
  239. }
  240. #error-overlay h2 {
  241. font-size: 18px;
  242. letter-spacing: 0.15em;
  243. color: var(--danger);
  244. text-transform: uppercase;
  245. }
  246. #error-overlay p {
  247. color: var(--text-dim);
  248. font-size: 13px;
  249. max-width: 520px;
  250. line-height: 1.7;
  251. }
  252. #error-overlay button {
  253. margin-top: 12px;
  254. padding: 10px 24px;
  255. background: transparent;
  256. border: 1px solid var(--cyan);
  257. color: var(--cyan);
  258. font-family: inherit;
  259. font-size: 12px;
  260. letter-spacing: 0.2em;
  261. text-transform: uppercase;
  262. cursor: pointer;
  263. border-radius: 6px;
  264. transition: background 0.2s, box-shadow 0.2s;
  265. }
  266. #error-overlay button:hover {
  267. background: rgba(0, 229, 255, 0.1);
  268. box-shadow: 0 0 16px rgba(0, 229, 255, 0.3);
  269. }
  270. /* ---------- Debug panel (top-left, collapsible) ---------- */
  271. #debug-panel {
  272. position: fixed;
  273. top: 48px;
  274. left: 24px;
  275. z-index: 30;
  276. width: 260px;
  277. max-width: calc(100vw - 48px);
  278. background: var(--panel);
  279. border: 1px solid var(--panel-border);
  280. border-radius: 10px;
  281. backdrop-filter: blur(8px);
  282. box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
  283. font-size: 11px;
  284. color: var(--text);
  285. overflow: hidden;
  286. transition: max-height 0.25s ease;
  287. }
  288. #debug-panel.collapsed { max-height: 32px; }
  289. #debug-panel.expanded { max-height: 480px; }
  290. #debug-header {
  291. display: flex;
  292. align-items: center;
  293. justify-content: space-between;
  294. padding: 8px 12px;
  295. cursor: pointer;
  296. user-select: none;
  297. background: rgba(0, 229, 255, 0.06);
  298. border-bottom: 1px solid var(--panel-border);
  299. font-size: 10px;
  300. letter-spacing: 0.2em;
  301. text-transform: uppercase;
  302. color: var(--cyan);
  303. }
  304. #debug-panel.collapsed #debug-body { display: none; }
  305. #debug-panel.collapsed #debug-header { border-bottom: none; }
  306. #debug-toggle {
  307. font-family: inherit;
  308. color: var(--cyan);
  309. font-size: 14px;
  310. line-height: 1;
  311. }
  312. #debug-body {
  313. padding: 10px 12px 12px;
  314. display: flex;
  315. flex-direction: column;
  316. gap: 6px;
  317. max-height: 440px;
  318. overflow-y: auto;
  319. }
  320. .dbg-row {
  321. display: flex;
  322. align-items: center;
  323. justify-content: space-between;
  324. gap: 8px;
  325. font-size: 11px;
  326. line-height: 1.4;
  327. word-break: break-all;
  328. }
  329. .dbg-row .k {
  330. color: rgba(128, 222, 234, 0.7);
  331. text-transform: uppercase;
  332. letter-spacing: 0.1em;
  333. font-size: 10px;
  334. flex-shrink: 0;
  335. }
  336. .dbg-row .v {
  337. color: var(--text);
  338. text-align: right;
  339. font-variant-numeric: tabular-nums;
  340. }
  341. .dbg-row .v.ok { color: var(--ok); }
  342. .dbg-row .v.warn { color: #ffb74d; }
  343. .dbg-row .v.err { color: var(--danger); }
  344. .dbg-row .v.run { color: var(--cyan); }
  345. #debug-err {
  346. margin-top: 6px;
  347. padding: 8px 10px;
  348. background: rgba(255, 82, 82, 0.08);
  349. border: 1px solid rgba(255, 82, 82, 0.35);
  350. border-radius: 6px;
  351. color: var(--danger);
  352. font-size: 10px;
  353. line-height: 1.5;
  354. word-break: break-word;
  355. display: none;
  356. max-height: 120px;
  357. overflow-y: auto;
  358. }
  359. #debug-err.show { display: block; }
  360. </style>
  361. </head>
  362. <body>
  363. <canvas id="stage"></canvas>
  364. <div id="title">
  365. EYE · TRACK <span class="accent">//</span> PUPIL GAZE
  366. </div>
  367. <div id="preview-wrap" aria-label="Webcam preview with face mesh overlay">
  368. <video id="webcam" autoplay playsinline muted></video>
  369. <canvas id="overlay" width="240" height="180"></canvas>
  370. </div>
  371. <div id="status-bar">
  372. <div class="stat">
  373. <span class="dot" id="status-dot"></span>
  374. <span class="label">Status</span>
  375. <span class="value" id="status-text">INIT</span>
  376. </div>
  377. <div class="stat">
  378. <span class="label">FPS</span>
  379. <span class="value" id="fps">--</span>
  380. </div>
  381. <div class="stat">
  382. <span class="label">Gaze X</span>
  383. <span class="value" id="gaze-x">0.000</span>
  384. </div>
  385. <div class="stat">
  386. <span class="label">Gaze Y</span>
  387. <span class="value" id="gaze-y">0.000</span>
  388. </div>
  389. <div class="stat">
  390. <span class="label">Iris L</span>
  391. <span class="value" id="iris-l">--</span>
  392. </div>
  393. <div class="stat">
  394. <span class="label">Iris R</span>
  395. <span class="value" id="iris-r">--</span>
  396. </div>
  397. </div>
  398. <div id="loader">
  399. <div class="spinner"></div>
  400. <div class="loader-text" id="loader-text">Loading MediaPipe</div>
  401. <div class="loader-sub" id="loader-sub">Initializing WASM runtime &amp; face mesh model. Please allow camera access when prompted.</div>
  402. </div>
  403. <div id="debug-panel" class="collapsed">
  404. <div id="debug-header" title="Click to expand/collapse">
  405. <span>DEBUG</span>
  406. <span id="debug-toggle">+</span>
  407. </div>
  408. <div id="debug-body">
  409. <div class="dbg-row"><span class="k">camera_utils</span><span class="v" id="dbg-cdn1">…</span></div>
  410. <div class="dbg-row"><span class="k">drawing_utils</span><span class="v" id="dbg-cdn2">…</span></div>
  411. <div class="dbg-row"><span class="k">face_mesh</span><span class="v" id="dbg-cdn3">…</span></div>
  412. <div class="dbg-row"><span class="k">model</span><span class="v" id="dbg-model">…</span></div>
  413. <div class="dbg-row"><span class="k">camera</span><span class="v" id="dbg-camera">…</span></div>
  414. <div class="dbg-row"><span class="k">stage</span><span class="v" id="dbg-stage">…</span></div>
  415. <div class="dbg-row"><span class="k">frame ms</span><span class="v" id="dbg-frame">--</span></div>
  416. <div class="dbg-row"><span class="k">downloaded</span><span class="v" id="dbg-bytes">0 KB</span></div>
  417. <div id="debug-err"></div>
  418. </div>
  419. </div>
  420. <div id="error-overlay">
  421. <div class="icon">⚠</div>
  422. <h2 id="err-title">Camera Access Denied</h2>
  423. <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>
  424. <button id="err-retry">Retry</button>
  425. </div>
  426. <!-- MediaPipe CDN -->
  427. <script>
  428. // Mark CDN load state on the global scope so the inline app can read it.
  429. window.__cdnStatus = window.__cdnStatus || {};
  430. function __cdnErr(name, src) {
  431. window.__cdnStatus[name] = 'error';
  432. console.error('[CDN] failed to load', name, src);
  433. // Surface the failure as a visible loader message immediately.
  434. var lt = document.getElementById('loader-text');
  435. var ls = document.getElementById('loader-sub');
  436. if (lt) lt.textContent = 'CDN load failed';
  437. if (ls) ls.textContent = 'Could not download ' + name + ' from the CDN. Check your network and reload.';
  438. try {
  439. var evt = new CustomEvent('cdnError', { detail: { name: name, src: src } });
  440. window.dispatchEvent(evt);
  441. } catch (e) { /* no-op */ }
  442. }
  443. function __cdnOk(name) {
  444. window.__cdnStatus[name] = 'ok';
  445. console.log('[CDN] loaded', name);
  446. try {
  447. window.dispatchEvent(new CustomEvent('cdnOk', { detail: { name: name } }));
  448. } catch (e) { /* no-op */ }
  449. }
  450. </script>
  451. <script src="https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils/camera_utils.js" crossorigin="anonymous"
  452. onload="__cdnOk('camera_utils')"
  453. onerror="__cdnErr('camera_utils', this.src)"></script>
  454. <script src="https://cdn.jsdelivr.net/npm/@mediapipe/drawing_utils/drawing_utils.js" crossorigin="anonymous"
  455. onload="__cdnOk('drawing_utils')"
  456. onerror="__cdnErr('drawing_utils', this.src)"></script>
  457. <script src="https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/face_mesh.js" crossorigin="anonymous"
  458. onload="__cdnOk('face_mesh')"
  459. onerror="__cdnErr('face_mesh', this.src)"></script>
  460. <script>
  461. (function () {
  462. 'use strict';
  463. // ============================================================
  464. // Config
  465. // ============================================================
  466. const TRAIL_LENGTH = 50; // # of trail points
  467. const ORB_RADIUS = 40; // px
  468. const GRID_DRAW_INTERVAL_MS = 33; // ~30fps redraw
  469. // Kalman filter parameters (tuned for responsiveness, not smoothness)
  470. const KALMAN_R = 0.015; // measurement noise (LOW = trust raw data more = faster response)
  471. const KALMAN_Q = 0.006; // process noise (HIGHER = less smoothing = more responsive)
  472. // No fixed sensitivity — iris ratio already maps to [0,1] natively
  473. // Iris / eye landmark indices (MediaPipe Face Mesh)
  474. // Left eye
  475. const L_OUTER = 33, L_INNER = 133;
  476. const L_TOP = 159, L_BOT = 145;
  477. const L_IRIS = 468;
  478. // Right eye
  479. const R_OUTER = 362, R_INNER = 263;
  480. const R_TOP = 386, R_BOT = 374;
  481. const R_IRIS = 473;
  482. // Iris contour points
  483. const IRIS_LANDMARKS = [
  484. 468, 469, 470, 471, 472, // left iris
  485. 473, 474, 475, 476, 477 // right iris
  486. ];
  487. // Face mesh tesselation connection subsets (subset of FACE_TESSELATION)
  488. // Use eye / brow / lip / nose silhouettes to keep it light
  489. 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];
  490. const LIPS = [61, 146, 91, 181, 84, 17, 314, 405, 321, 375, 291, 308, 324, 318, 402, 317, 14, 87, 178, 88, 95, 78];
  491. const L_EYE = [33, 7, 163, 144, 145, 153, 154, 155, 133, 173, 157, 158, 159, 160, 161, 246];
  492. const R_EYE = [362, 382, 381, 380, 374, 373, 390, 249, 263, 466, 388, 387, 386, 385, 384, 398];
  493. const L_BROW = [46, 53, 52, 65, 55, 107, 66, 105, 63, 70];
  494. const R_BROW = [276, 283, 282, 295, 285, 336, 296, 334, 293, 300];
  495. // ============================================================
  496. // DOM
  497. // ============================================================
  498. const stage = document.getElementById('stage');
  499. const ctx = stage.getContext('2d');
  500. const video = document.getElementById('webcam');
  501. const overlay = document.getElementById('overlay');
  502. const octx = overlay.getContext('2d');
  503. const loader = document.getElementById('loader');
  504. const loaderText = document.getElementById('loader-text');
  505. const loaderSub = document.getElementById('loader-sub');
  506. const errOverlay = document.getElementById('error-overlay');
  507. const errTitle = document.getElementById('err-title');
  508. const errMsg = document.getElementById('err-msg');
  509. const errRetry = document.getElementById('err-retry');
  510. const statusDot = document.getElementById('status-dot');
  511. const statusText = document.getElementById('status-text');
  512. const fpsEl = document.getElementById('fps');
  513. const gxEl = document.getElementById('gaze-x');
  514. const gyEl = document.getElementById('gaze-y');
  515. const ilEl = document.getElementById('iris-l');
  516. const irEl = document.getElementById('iris-r');
  517. // Debug panel
  518. const dbgPanel = document.getElementById('debug-panel');
  519. const dbgHeader = document.getElementById('debug-header');
  520. const dbgToggle = document.getElementById('debug-toggle');
  521. const dbgCdn1 = document.getElementById('dbg-cdn1');
  522. const dbgCdn2 = document.getElementById('dbg-cdn2');
  523. const dbgCdn3 = document.getElementById('dbg-cdn3');
  524. const dbgModel = document.getElementById('dbg-model');
  525. const dbgCamera = document.getElementById('dbg-camera');
  526. const dbgStage = document.getElementById('dbg-stage');
  527. const dbgFrame = document.getElementById('dbg-frame');
  528. const dbgBytes = document.getElementById('dbg-bytes');
  529. const dbgErr = document.getElementById('debug-err');
  530. // ============================================================
  531. // Debug panel helpers
  532. // ============================================================
  533. function dbgSet(el, text, cls) {
  534. if (!el) return;
  535. el.textContent = text;
  536. el.className = 'v' + (cls ? ' ' + cls : '');
  537. }
  538. function dbgSetError(msg) {
  539. if (!dbgErr) return;
  540. if (!msg) { dbgErr.classList.remove('show'); dbgErr.textContent = ''; return; }
  541. dbgErr.textContent = msg;
  542. dbgErr.classList.add('show');
  543. }
  544. if (dbgHeader) {
  545. dbgHeader.addEventListener('click', () => {
  546. const collapsed = dbgPanel.classList.toggle('collapsed');
  547. dbgPanel.classList.toggle('expanded', !collapsed);
  548. dbgToggle.textContent = collapsed ? '+' : '–';
  549. });
  550. }
  551. // Initialize CDN cells from the global status that the loader scripts set
  552. try {
  553. const s = (window.__cdnStatus) || {};
  554. dbgSet(dbgCdn1, s.camera_utils || (s.camera_utils === 'error' ? 'FAIL' : '…'),
  555. s.camera_utils === 'ok' ? 'ok' : s.camera_utils === 'error' ? 'err' : 'run');
  556. dbgSet(dbgCdn2, s.drawing_utils || (s.drawing_utils === 'error' ? 'FAIL' : '…'),
  557. s.drawing_utils === 'ok' ? 'ok' : s.drawing_utils === 'error' ? 'err' : 'run');
  558. dbgSet(dbgCdn3, s.face_mesh || (s.face_mesh === 'error' ? 'FAIL' : '…'),
  559. s.face_mesh === 'ok' ? 'ok' : s.face_mesh === 'error' ? 'err' : 'run');
  560. } catch (e) { /* no-op */ }
  561. // Live-update on CDN load / failure events
  562. window.addEventListener('cdnOk', (e) => {
  563. const n = e && e.detail && e.detail.name;
  564. if (n === 'camera_utils') dbgSet(dbgCdn1, 'OK', 'ok');
  565. if (n === 'drawing_utils') dbgSet(dbgCdn2, 'OK', 'ok');
  566. if (n === 'face_mesh') dbgSet(dbgCdn3, 'OK', 'ok');
  567. });
  568. window.addEventListener('cdnError', (e) => {
  569. const n = e && e.detail && e.detail.name;
  570. if (n === 'camera_utils') { dbgSet(dbgCdn1, 'FAIL', 'err'); dbgSetError('CDN camera_utils failed to load'); }
  571. if (n === 'drawing_utils') { dbgSet(dbgCdn2, 'FAIL', 'err'); dbgSetError('CDN drawing_utils failed to load'); }
  572. if (n === 'face_mesh') { dbgSet(dbgCdn3, 'FAIL', 'err'); dbgSetError('CDN face_mesh failed to load'); }
  573. });
  574. function setLoaderText(main, sub) {
  575. if (loaderText) loaderText.textContent = main;
  576. if (loaderSub) loaderSub.textContent = sub;
  577. console.log('[loader]', main, '—', sub);
  578. }
  579. // ============================================================
  580. // State
  581. // ============================================================
  582. let W = 0, H = 0;
  583. let smoothedX = 0.5, smoothedY = 0.5; // Kalman-smoothed gaze (0..1)
  584. let rawX = 0.5, rawY = 0.5; // raw gaze (0..1)
  585. let rawXValid = false; // whether raw gaze has a fresh, valid measurement
  586. let trail = []; // array of {x, y}
  587. let faceMesh = null;
  588. let camera = null;
  589. let lastResults = null;
  590. let lastTime = performance.now();
  591. let fpsSmooth = 0;
  592. let irisVisible = { l: false, r: false };
  593. let trackingLocked = false;
  594. let lastFrameMs = 0; // last face-mesh processing time in ms
  595. let lastMeshSendAt = 0;
  596. // ============================================================
  597. // Simple 1D Kalman filter
  598. // ============================================================
  599. class SimpleKalman {
  600. constructor(R, Q) {
  601. this.R = R; // measurement noise covariance
  602. this.Q = Q; // process noise covariance
  603. this.P = 1; // estimation error covariance
  604. this.X = 0.5; // state estimate
  605. this.K = 0; // Kalman gain
  606. }
  607. update(measurement) {
  608. // Predict: covariance grows by process noise
  609. this.P = this.P + this.Q;
  610. // Update: compute Kalman gain and incorporate measurement
  611. this.K = this.P / (this.P + this.R);
  612. this.X = this.X + this.K * (measurement - this.X);
  613. this.P = (1 - this.K) * this.P;
  614. return this.X;
  615. }
  616. reset(v = 0.5) {
  617. this.P = 1; this.X = v; this.K = 0;
  618. }
  619. }
  620. const kalmanX = new SimpleKalman(KALMAN_R, KALMAN_Q);
  621. const kalmanY = new SimpleKalman(KALMAN_R, KALMAN_Q);
  622. // ============================================================
  623. // Canvas sizing
  624. // ============================================================
  625. function resize() {
  626. const dpr = Math.min(window.devicePixelRatio || 1, 2);
  627. W = window.innerWidth;
  628. H = window.innerHeight;
  629. stage.width = W * dpr;
  630. stage.height = H * dpr;
  631. stage.style.width = W + 'px';
  632. stage.style.height = H + 'px';
  633. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  634. }
  635. window.addEventListener('resize', resize);
  636. resize();
  637. // ============================================================
  638. // Gaze math: iris-ratio + head-pose hybrid
  639. // iris ratio gives fine eye-in-socket direction;
  640. // face/nose position in the frame captures head movement (which
  641. // naturally accompanies gaze shifts). Blending both = much larger
  642. // usable range, especially vertically.
  643. // ============================================================
  644. // Weight: how much iris vs head contributes (0=all head, 1=all iris)
  645. const IRIS_WEIGHT_X = 0.65;
  646. const IRIS_WEIGHT_Y = 0.30; // give head even more weight vertically → bigger range
  647. function computeIrisGaze(landmarks) {
  648. function eyeData(outerIdx, innerIdx, topIdx, botIdx, irisIdx) {
  649. const outer = landmarks[outerIdx];
  650. const inner = landmarks[innerIdx];
  651. const top = landmarks[topIdx];
  652. const bot = landmarks[botIdx];
  653. const iris = landmarks[irisIdx];
  654. if (!outer || !inner || !iris) return null;
  655. if ((iris.x === 0 && iris.y === 0) || Number.isNaN(iris.x) || Number.isNaN(iris.y)) return null;
  656. const eyeW = outer.x - inner.x;
  657. if (Math.abs(eyeW) < 1e-6) return null;
  658. const ratioX = (iris.x - inner.x) / eyeW;
  659. const midY = (top.y + bot.y) * 0.5;
  660. const ratioY = (iris.y - midY) / Math.abs(eyeW);
  661. return { ratioX, ratioY };
  662. }
  663. const left = eyeData(L_OUTER, L_INNER, L_TOP, L_BOT, L_IRIS);
  664. const right = eyeData(R_OUTER, R_INNER, R_TOP, R_BOT, R_IRIS);
  665. irisVisible.l = !!left;
  666. irisVisible.r = !!right;
  667. if (!left && !right) return { x: 0.5, y: 0.5, visible: false };
  668. // --- Iris ratio (eye-in-socket signal) ---
  669. let rx, ry;
  670. if (left && right) {
  671. rx = (left.ratioX + right.ratioX) * 0.5;
  672. ry = (left.ratioY + right.ratioY) * 0.5;
  673. } else {
  674. const s = left || right;
  675. rx = s.ratioX; ry = s.ratioY;
  676. }
  677. // --- Head pose signal (nose tip position in frame) ---
  678. // Nose tip = landmark 1, face center = average of landmarks 10(top) + 152(bottom)
  679. const nose = landmarks[1];
  680. const fTop = landmarks[10];
  681. const fBot = landmarks[152];
  682. const faceMidY = (fTop.y + fBot.y) * 0.5;
  683. // headX: nose x relative to image center. ~0.5 when centered.
  684. // headY: nose y relative to face vertical center, normalized by face height.
  685. const faceH = Math.abs(fBot.y - fTop.y) || 1e-6;
  686. const headOffY = (nose.y - faceMidY) / faceH; // negative=looking up, positive=looking down
  687. // --- Blend iris + head ---
  688. // Iris X already [0,1]. Head X = nose.x (also ~[0,1], invert because raw is mirror).
  689. const irisScreenX = rx * 1.8 - 0.4; // amplify & recenter
  690. const headScreenX = 0.5 + (0.5 - nose.x) * 3.0; // amplify head horizontal by 3x
  691. const irisScreenY = 0.5 - ry * 2.0; // amplify iris vertical by 2x
  692. const headScreenY = 0.5 + headOffY * 2.5; // amplify head vertical by 2.5x
  693. const screenX = IRIS_WEIGHT_X * irisScreenX + (1 - IRIS_WEIGHT_X) * headScreenX;
  694. const screenY = IRIS_WEIGHT_Y * irisScreenY + (1 - IRIS_WEIGHT_Y) * headScreenY;
  695. return {
  696. x: Math.min(1, Math.max(0, screenX)),
  697. y: Math.min(1, Math.max(0, screenY)),
  698. visible: true
  699. };
  700. }
  701. // ============================================================
  702. // Render: full-screen orb + trail
  703. // ============================================================
  704. function drawOrb() {
  705. // Clear with very slight motion blur for the trail
  706. ctx.fillStyle = 'rgba(10, 10, 26, 0.35)';
  707. ctx.fillRect(0, 0, W, H);
  708. // Map smoothed gaze to screen coordinates (with margin so orb stays on screen)
  709. // No extra mirror needed — computeIrisGaze already handles it
  710. const margin = 60;
  711. const sx = margin + smoothedX * (W - margin * 2);
  712. const sy = margin + smoothedY * (H - margin * 2);
  713. // Push trail
  714. trail.push({ x: sx, y: sy });
  715. if (trail.length > TRAIL_LENGTH) trail.shift();
  716. // Draw trail (oldest -> newest, fading in opacity & shrinking radius)
  717. for (let i = 0; i < trail.length; i++) {
  718. const t = trail[i];
  719. const tNorm = (i + 1) / trail.length; // 0..1
  720. const r = ORB_RADIUS * 0.15 * tNorm;
  721. const a = 0.05 + 0.45 * tNorm;
  722. const grad = ctx.createRadialGradient(t.x, t.y, 0, t.x, t.y, r * 2.5);
  723. grad.addColorStop(0, `rgba(0, 229, 255, ${a})`);
  724. grad.addColorStop(0.4, `rgba(0, 184, 212, ${a * 0.6})`);
  725. grad.addColorStop(1, 'rgba(0, 229, 255, 0)');
  726. ctx.fillStyle = grad;
  727. ctx.beginPath();
  728. ctx.arc(t.x, t.y, r * 2.5, 0, Math.PI * 2);
  729. ctx.fill();
  730. }
  731. // Connect trail points with a smooth fading line
  732. if (trail.length > 1) {
  733. ctx.lineCap = 'round';
  734. ctx.lineJoin = 'round';
  735. for (let i = 1; i < trail.length; i++) {
  736. const tNorm = i / trail.length;
  737. ctx.strokeStyle = `rgba(0, 229, 255, ${0.05 + 0.35 * tNorm})`;
  738. ctx.lineWidth = 2 + 2 * tNorm;
  739. ctx.beginPath();
  740. ctx.moveTo(trail[i - 1].x, trail[i - 1].y);
  741. ctx.lineTo(trail[i].x, trail[i].y);
  742. ctx.stroke();
  743. }
  744. }
  745. // Main orb - layered radial gradients for glow
  746. const cx = sx, cy = sy;
  747. // Outer halo
  748. let g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS * 4);
  749. g.addColorStop(0, 'rgba(0, 229, 255, 0.35)');
  750. g.addColorStop(0.25, 'rgba(0, 229, 255, 0.18)');
  751. g.addColorStop(0.6, 'rgba(0, 184, 212, 0.05)');
  752. g.addColorStop(1, 'rgba(0, 229, 255, 0)');
  753. ctx.fillStyle = g;
  754. ctx.beginPath();
  755. ctx.arc(cx, cy, ORB_RADIUS * 4, 0, Math.PI * 2);
  756. ctx.fill();
  757. // Mid glow
  758. g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS * 1.8);
  759. g.addColorStop(0, 'rgba(180, 255, 255, 0.95)');
  760. g.addColorStop(0.25, 'rgba(0, 229, 255, 0.85)');
  761. g.addColorStop(0.65, 'rgba(0, 184, 212, 0.5)');
  762. g.addColorStop(1, 'rgba(0, 229, 255, 0)');
  763. ctx.fillStyle = g;
  764. ctx.beginPath();
  765. ctx.arc(cx, cy, ORB_RADIUS * 1.8, 0, Math.PI * 2);
  766. ctx.fill();
  767. // Core
  768. g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS);
  769. g.addColorStop(0, 'rgba(255, 255, 255, 1)');
  770. g.addColorStop(0.3, 'rgba(180, 255, 255, 1)');
  771. g.addColorStop(0.7, 'rgba(0, 229, 255, 0.95)');
  772. g.addColorStop(1, 'rgba(0, 184, 212, 0.7)');
  773. ctx.fillStyle = g;
  774. ctx.beginPath();
  775. ctx.arc(cx, cy, ORB_RADIUS, 0, Math.PI * 2);
  776. ctx.fill();
  777. // Inner sparkle
  778. ctx.fillStyle = 'rgba(255, 255, 255, 0.85)';
  779. ctx.beginPath();
  780. ctx.arc(cx - ORB_RADIUS * 0.25, cy - ORB_RADIUS * 0.25, ORB_RADIUS * 0.18, 0, Math.PI * 2);
  781. ctx.fill();
  782. }
  783. // ============================================================
  784. // Render: face mesh overlay on webcam preview
  785. // ============================================================
  786. function drawOverlay(results) {
  787. const w = overlay.width;
  788. const h = overlay.height;
  789. octx.clearRect(0, 0, w, h);
  790. if (!results || !results.multiFaceLandmarks || results.multiFaceLandmarks.length === 0) {
  791. // Subtle "no face" indicator
  792. octx.strokeStyle = 'rgba(0, 229, 255, 0.25)';
  793. octx.setLineDash([4, 4]);
  794. octx.lineWidth = 1;
  795. octx.strokeRect(8, 8, w - 16, h - 16);
  796. octx.setLineDash([]);
  797. octx.fillStyle = 'rgba(0, 229, 255, 0.7)';
  798. octx.font = '10px monospace';
  799. octx.fillText('NO FACE DETECTED', 12, h - 12);
  800. return;
  801. }
  802. const lm = results.multiFaceLandmarks[0];
  803. // Note: the video is mirrored visually via CSS, so we mirror X here
  804. // to keep the mesh aligned with what the user sees.
  805. const pt = (i) => ({ x: (1 - lm[i].x) * w, y: lm[i].y * h });
  806. // Draw mesh lines
  807. octx.lineWidth = 0.6;
  808. octx.strokeStyle = 'rgba(0, 229, 255, 0.45)';
  809. octx.beginPath();
  810. [FACE_OVAL, LIPS, L_EYE, R_EYE, L_BROW, R_BROW].forEach(connections => {
  811. for (let i = 0; i < connections.length; i++) {
  812. const a = pt(connections[i]);
  813. const b = pt(connections[(i + 1) % connections.length]);
  814. octx.moveTo(a.x, a.y);
  815. octx.lineTo(b.x, b.y);
  816. }
  817. });
  818. octx.stroke();
  819. // Subtle face dots
  820. octx.fillStyle = 'rgba(0, 229, 255, 0.4)';
  821. for (let i = 0; i < lm.length; i++) {
  822. if (i % 3 !== 0) continue; // subsample
  823. const p = pt(i);
  824. octx.fillRect(p.x, p.y, 1, 1);
  825. }
  826. // Iris highlight (big + bright)
  827. octx.fillStyle = '#ffeb3b';
  828. octx.shadowColor = '#ffeb3b';
  829. octx.shadowBlur = 10;
  830. IRIS_LANDMARKS.forEach(idx => {
  831. const p = pt(idx);
  832. octx.beginPath();
  833. octx.arc(p.x, p.y, 1.6, 0, Math.PI * 2);
  834. octx.fill();
  835. });
  836. // Iris center (468 / 473) - extra large
  837. octx.shadowBlur = 14;
  838. [L_IRIS, R_IRIS].forEach(idx => {
  839. const p = pt(idx);
  840. octx.fillStyle = '#ffffff';
  841. octx.beginPath();
  842. octx.arc(p.x, p.y, 2.6, 0, Math.PI * 2);
  843. octx.fill();
  844. });
  845. octx.shadowBlur = 0;
  846. }
  847. // ============================================================
  848. // Animation loop
  849. // ============================================================
  850. function loop(now) {
  851. // FPS
  852. const dt = now - lastTime;
  853. lastTime = now;
  854. const instFps = 1000 / Math.max(dt, 1);
  855. fpsSmooth = fpsSmooth === 0 ? instFps : (fpsSmooth * 0.9 + instFps * 0.1);
  856. // Kalman smoothing: feed raw gaze through the per-axis Kalman filters.
  857. // No update when no iris is visible, so the orb holds its last position
  858. // instead of drifting back toward the center.
  859. if (rawXValid) {
  860. smoothedX = kalmanX.update(rawX);
  861. smoothedY = kalmanY.update(rawY);
  862. }
  863. drawOrb();
  864. if (lastResults) drawOverlay(lastResults);
  865. // Status text
  866. const visible = irisVisible.l || irisVisible.r;
  867. if (visible) {
  868. statusDot.className = 'dot ok';
  869. statusText.className = 'value ok';
  870. statusText.textContent = 'TRACKING';
  871. dbgSet(dbgStage, 'tracking', 'ok');
  872. } else if (faceMesh) {
  873. statusDot.className = 'dot warn';
  874. statusText.className = 'value warn';
  875. statusText.textContent = 'NO IRIS';
  876. dbgSet(dbgStage, 'no face', 'warn');
  877. } else {
  878. statusDot.className = 'dot';
  879. statusText.className = 'value';
  880. statusText.textContent = 'INIT';
  881. dbgSet(dbgStage, 'init', 'run');
  882. }
  883. fpsEl.textContent = Math.round(fpsSmooth);
  884. gxEl.textContent = smoothedX.toFixed(3);
  885. gyEl.textContent = smoothedY.toFixed(3);
  886. ilEl.textContent = irisVisible.l ? '●' : '○';
  887. irEl.textContent = irisVisible.r ? '●' : '○';
  888. ilEl.className = 'value ' + (irisVisible.l ? 'ok' : 'warn');
  889. irEl.className = 'value ' + (irisVisible.r ? 'ok' : 'warn');
  890. dbgSet(dbgFrame, lastFrameMs > 0 ? (lastFrameMs.toFixed(1) + ' ms') : '--');
  891. requestAnimationFrame(loop);
  892. }
  893. requestAnimationFrame(loop);
  894. // ============================================================
  895. // MediaPipe setup
  896. // ============================================================
  897. function showError(title, msg) {
  898. console.error('[error]', title, '—', msg);
  899. errTitle.textContent = title;
  900. errMsg.textContent = msg;
  901. errOverlay.classList.add('show');
  902. loader.classList.add('hidden');
  903. statusDot.className = 'dot err';
  904. statusText.className = 'value err';
  905. statusText.textContent = 'ERROR';
  906. dbgSetError((title ? title + ': ' : '') + (msg || ''));
  907. dbgSet(dbgStage, 'error', 'err');
  908. }
  909. errRetry.addEventListener('click', () => {
  910. errOverlay.classList.remove('show');
  911. location.reload();
  912. });
  913. // Format bytes for the debug panel / loader text
  914. function fmtBytes(n) {
  915. if (n < 1024) return n + ' B';
  916. if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
  917. return (n / (1024 * 1024)).toFixed(2) + ' MB';
  918. }
  919. // Pre-fetch a list of MediaPipe WASM / data files with byte-level progress.
  920. // Returns a map { filename -> blob: URL } suitable for locateFile().
  921. // If any file fails, the function still resolves with whatever succeeded
  922. // (MediaPipe will retry from the network as a fallback).
  923. async function prefetchAssets(files) {
  924. console.log('[model] pre-fetching', files.length, 'asset(s)…');
  925. dbgSet(dbgModel, 'loading…', 'run');
  926. const out = {};
  927. let totalBytes = 0;
  928. for (let i = 0; i < files.length; i++) {
  929. const file = files[i];
  930. const url = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/' + file;
  931. setLoaderText(
  932. 'Downloading model (' + (i + 1) + '/' + files.length + ')',
  933. file + ' (0 MB)'
  934. );
  935. console.log('[model] GET', file);
  936. try {
  937. const resp = await fetch(url, { mode: 'cors', cache: 'force-cache' });
  938. if (!resp.ok) throw new Error('HTTP ' + resp.status);
  939. const len = parseInt(resp.headers.get('content-length') || '0', 10);
  940. // Stream the body so we can show incremental progress.
  941. const reader = resp.body && resp.body.getReader ? resp.body.getReader() : null;
  942. const chunks = [];
  943. let received = 0;
  944. if (reader) {
  945. // eslint-disable-next-line no-constant-condition
  946. while (true) {
  947. const { done, value } = await reader.read();
  948. if (done) break;
  949. chunks.push(value);
  950. received += value.byteLength;
  951. totalBytes += value.byteLength;
  952. const pct = len ? Math.round((received / len) * 100) : 0;
  953. setLoaderText(
  954. 'Downloading model (' + (i + 1) + '/' + files.length + ' · ' + pct + '%)',
  955. file + ' — ' + fmtBytes(received) + (len ? ' / ' + fmtBytes(len) : '')
  956. );
  957. dbgSet(dbgBytes, fmtBytes(totalBytes));
  958. }
  959. const blob = new Blob(chunks, { type: resp.headers.get('content-type') || 'application/octet-stream' });
  960. out[file] = URL.createObjectURL(blob);
  961. } else {
  962. const blob = await resp.blob();
  963. out[file] = URL.createObjectURL(blob);
  964. totalBytes += blob.size;
  965. dbgSet(dbgBytes, fmtBytes(totalBytes));
  966. }
  967. console.log('[model] OK', file, fmtBytes(received || (out[file] ? 0 : 0)));
  968. } catch (e) {
  969. console.warn('[model] pre-fetch failed for', file, e && e.message);
  970. // leave out[file] undefined → MediaPipe will fall back to the URL
  971. }
  972. }
  973. dbgSet(dbgModel, 'ready (' + fmtBytes(totalBytes) + ')', 'ok');
  974. console.log('[model] pre-fetch done, total', fmtBytes(totalBytes));
  975. return out;
  976. }
  977. async function initFaceMesh() {
  978. console.log('[init] initFaceMesh start');
  979. setLoaderText(
  980. 'Initializing face mesh…',
  981. 'Preparing the iris-tracking model. This may take a moment.'
  982. );
  983. dbgSet(dbgModel, 'init…', 'run');
  984. try {
  985. // 1) Pre-fetch the big WASM / data files so the user can see progress
  986. // instead of a silent stall. The list mirrors the files MediaPipe
  987. // requests at runtime when refineLandmarks is enabled.
  988. const assetMap = await prefetchAssets([
  989. 'face_mesh_solution_simd_wasm_bin.js',
  990. 'face_mesh_solution_simd_wasm_bin.wasm',
  991. 'face_mesh_solution_packed_assets.data'
  992. ]);
  993. setLoaderText(
  994. 'Initializing face mesh…',
  995. 'WASM runtime ready. Constructing the model.'
  996. );
  997. // 2) Construct FaceMesh. If we pre-fetched a file, serve it from the
  998. // blob URL so the browser uses the cached bytes; otherwise let
  999. // MediaPipe fall back to the CDN.
  1000. faceMesh = new FaceMesh({
  1001. locateFile: (file) => {
  1002. if (assetMap[file]) {
  1003. console.log('[model] locateFile (cached)', file);
  1004. return assetMap[file];
  1005. }
  1006. const url = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/' + file;
  1007. console.log('[model] locateFile (remote)', file);
  1008. return url;
  1009. }
  1010. });
  1011. faceMesh.setOptions({
  1012. maxNumFaces: 1,
  1013. refineLandmarks: true, // gives 468-477 iris
  1014. minDetectionConfidence: 0.5,
  1015. minTrackingConfidence: 0.5
  1016. });
  1017. faceMesh.onResults(onResults);
  1018. console.log('[init] FaceMesh constructed, calling .initialize()');
  1019. setLoaderText(
  1020. 'Initializing face mesh…',
  1021. 'Calling MediaPipe .initialize() — finalizing WASM.'
  1022. );
  1023. if (typeof faceMesh.initialize === 'function') {
  1024. await faceMesh.initialize();
  1025. }
  1026. console.log('[init] FaceMesh ready');
  1027. dbgSet(dbgModel, 'ready', 'ok');
  1028. startCamera();
  1029. } catch (e) {
  1030. console.error('FaceMesh init failed:', e);
  1031. dbgSetError('FaceMesh init failed: ' + (e && e.message ? e.message : e));
  1032. dbgSet(dbgModel, 'failed', 'err');
  1033. showError(
  1034. 'Initialization Failed',
  1035. 'Could not load MediaPipe Face Mesh (' + ((e && e.message) || 'unknown error') +
  1036. '). Check your network connection and reload the page.'
  1037. );
  1038. }
  1039. }
  1040. function onResults(results) {
  1041. const t1 = performance.now();
  1042. lastResults = results;
  1043. if (!results.multiFaceLandmarks || results.multiFaceLandmarks.length === 0) {
  1044. // No face - hold last smoothed position, don't drift
  1045. lastFrameMs = performance.now() - t1;
  1046. return;
  1047. }
  1048. const lm = results.multiFaceLandmarks[0];
  1049. const gaze = computeIrisGaze(lm);
  1050. if (gaze.visible) {
  1051. rawX = gaze.x;
  1052. rawY = gaze.y;
  1053. rawXValid = true;
  1054. } else {
  1055. rawXValid = false;
  1056. }
  1057. lastFrameMs = performance.now() - t1;
  1058. }
  1059. function startCamera() {
  1060. console.log('[camera] startCamera');
  1061. setLoaderText(
  1062. 'Connecting camera…',
  1063. 'Requesting webcam access. Please click "Allow" in the browser prompt.'
  1064. );
  1065. dbgSet(dbgCamera, 'requesting…', 'run');
  1066. if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
  1067. dbgSet(dbgCamera, 'unsupported', 'err');
  1068. showError(
  1069. 'Browser Not Supported',
  1070. 'Your browser does not support getUserMedia. Please use a modern browser (Chrome, Firefox, Edge, Safari).'
  1071. );
  1072. return;
  1073. }
  1074. camera = new Camera(video, {
  1075. onFrame: async () => {
  1076. if (faceMesh) {
  1077. const t0 = performance.now();
  1078. try {
  1079. await faceMesh.send({ image: video });
  1080. } catch (e) {
  1081. // swallow individual frame errors
  1082. console.warn('[frame] send error', e && e.message);
  1083. } finally {
  1084. lastMeshSendAt = performance.now() - t0;
  1085. if (lastMeshSendAt > 5) {
  1086. // Only log slow frames to keep the console quiet
  1087. // console.log('[frame] send', lastMeshSendAt.toFixed(1), 'ms');
  1088. }
  1089. }
  1090. }
  1091. },
  1092. width: 640,
  1093. height: 480
  1094. });
  1095. camera.start()
  1096. .then(() => {
  1097. // wait for metadata
  1098. return new Promise(resolve => {
  1099. if (video.readyState >= 1) return resolve();
  1100. video.addEventListener('loadedmetadata', resolve, { once: true });
  1101. });
  1102. })
  1103. .then(() => {
  1104. console.log('[camera] stream ready, hiding loader');
  1105. loader.classList.add('hidden');
  1106. statusText.textContent = 'READY';
  1107. dbgSet(dbgCamera, 'streaming', 'ok');
  1108. dbgSet(dbgStage, 'live', 'ok');
  1109. })
  1110. .catch(err => {
  1111. console.error('Camera error:', err);
  1112. dbgSet(dbgCamera, 'error', 'err');
  1113. const name = err && err.name;
  1114. if (name === 'NotAllowedError' || name === 'PermissionDeniedError' || name === 'SecurityError') {
  1115. showError(
  1116. 'Camera Access Denied',
  1117. 'We need your camera to track your gaze. Please click the camera icon in your browser\'s address bar, grant permission, then click Retry.'
  1118. );
  1119. } else if (name === 'NotFoundError' || name === 'OverconstrainedError') {
  1120. showError(
  1121. 'No Camera Found',
  1122. 'No webcam was detected on this device. Please connect a camera and reload the page.'
  1123. );
  1124. } else if (name === 'NotReadableError' || name === 'TrackStartError') {
  1125. showError(
  1126. 'Camera Busy',
  1127. 'Your camera appears to be in use by another application. Please close other apps (Zoom, Skype, etc.) and try again.'
  1128. );
  1129. } else {
  1130. showError(
  1131. 'Camera Error',
  1132. (err && err.message) || 'An unknown error occurred while accessing the camera.'
  1133. );
  1134. }
  1135. });
  1136. }
  1137. // Wait for the global FaceMesh symbol to be available
  1138. function waitFor(predicate, timeout = 20000) {
  1139. return new Promise((resolve, reject) => {
  1140. const start = performance.now();
  1141. (function check() {
  1142. if (predicate()) return resolve();
  1143. if (performance.now() - start > timeout) return reject(new Error('Timeout waiting for MediaPipe'));
  1144. requestAnimationFrame(check);
  1145. })();
  1146. });
  1147. }
  1148. // Kick off: stage 1 = wait for the CDN script to register window.FaceMesh
  1149. setLoaderText(
  1150. 'Loading MediaPipe JS…',
  1151. 'Downloading the MediaPipe scripts from the CDN.'
  1152. );
  1153. console.log('[boot] waiting for window.FaceMesh…');
  1154. waitFor(() => typeof window.FaceMesh === 'function', 20000)
  1155. .then(() => {
  1156. console.log('[boot] window.FaceMesh available');
  1157. initFaceMesh();
  1158. })
  1159. .catch((e) => {
  1160. console.error('[boot] FaceMesh never appeared:', e && e.message);
  1161. dbgSet(dbgCdn3, 'TIMEOUT', 'err');
  1162. dbgSetError('Timed out waiting for MediaPipe JS. The CDN may be blocked.');
  1163. showError(
  1164. 'Failed to Load MediaPipe',
  1165. '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.'
  1166. );
  1167. });
  1168. // Safety: if a CDN script failed before waitFor() could resolve, bail out
  1169. // promptly with a clear message instead of waiting for the timeout.
  1170. window.addEventListener('cdnError', () => {
  1171. if (typeof window.FaceMesh !== 'function') {
  1172. console.error('[boot] CDN error before FaceMesh became available');
  1173. showError(
  1174. 'CDN Load Failed',
  1175. '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.'
  1176. );
  1177. }
  1178. });
  1179. })();
  1180. </script>
  1181. </body>
  1182. </html>