// renderer.js // Canvas rendering: stage canvas (orb + trail) + overlay canvas (face mesh on preview). // Owns: W, H, ctx, octx, stage, overlay, smoothedX, smoothedY, trail, fpsSmooth, lastTime. import { TRAIL_LENGTH, ORB_RADIUS, FACE_OVAL, LIPS, L_EYE, R_EYE, L_BROW, R_BROW, IRIS_LANDMARKS, L_IRIS, R_IRIS, CAL_ORDER } from './config.js'; import { dbgSet } from './utils.js'; import { kalUpdate } from './kalman.js'; import { rawX, rawY, lastResults, lastFrameMs, irisVisible, lastEAR, lastBlinking, lastHeadPose } from './gaze.js'; import { calActive, calPaused, calCurrentIdx, getRawXValid, registerResetSmoothed, positionCalDot } from './calibration.js'; // ---- DOM references ---- const stage = document.getElementById('stage'); const ctx = stage.getContext('2d'); const overlay = document.getElementById('overlay'); const octx = overlay.getContext('2d'); // Status bar elements const statusDot = document.getElementById('status-dot'); const statusText = document.getElementById('status-text'); const fpsEl = document.getElementById('fps'); const gxEl = document.getElementById('gaze-x'); const gyEl = document.getElementById('gaze-y'); const ilEl = document.getElementById('iris-l'); const irEl = document.getElementById('iris-r'); // Debug panel stage row const dbgStage = document.getElementById('dbg-stage'); const dbgFrame = document.getElementById('dbg-frame'); // V2 debug panel rows (EAR, blink flag, pitch, yaw) — set in the animation loop. const dbgEar = document.getElementById('dbg-ear'); const dbgBlink = document.getElementById('dbg-blink'); const dbgPitch = document.getElementById('dbg-pitch'); const dbgYaw = document.getElementById('dbg-yaw'); // ---- Renderer state ---- export let W = 0, H = 0; let smoothedX = 0.5, smoothedY = 0.5; // Kalman-smoothed gaze (0..1) let trail = []; // array of {x, y} let lastTime = performance.now(); let fpsSmooth = 0; export function resetSmoothed() { smoothedX = 0.5; smoothedY = 0.5; } // ============================================================ // Canvas sizing // ============================================================ function resize() { const dpr = Math.min(window.devicePixelRatio || 1, 2); W = window.innerWidth; H = window.innerHeight; stage.width = W * dpr; stage.height = H * dpr; stage.style.width = W + 'px'; stage.style.height = H + 'px'; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); } window.addEventListener('resize', () => { resize(); // Re-position the calibration dot if one is currently active if (calActive && calCurrentIdx < CAL_ORDER.length) { positionCalDot(calCurrentIdx); } }); // Register the smoothed-reset hook so calibration.clearCalibration() can // snap the orb back to the center after a recalibration. registerResetSmoothed(resetSmoothed); resize(); // ============================================================ // Render: full-screen orb + trail // ============================================================ function drawOrb() { // Clear with very slight motion blur for the trail ctx.fillStyle = 'rgba(10, 10, 26, 0.35)'; ctx.fillRect(0, 0, W, H); // Map smoothed gaze to screen coordinates (with margin so orb stays on screen) const margin = 60; const sx = margin + smoothedX * (W - margin * 2); const sy = margin + smoothedY * (H - margin * 2); // Push trail trail.push({ x: sx, y: sy }); if (trail.length > TRAIL_LENGTH) trail.shift(); // Draw trail (oldest -> newest, fading in opacity & shrinking radius) // Cheap: simple filled circles, no radialGradient per point. for (let i = 0; i < trail.length; i++) { const t = trail[i]; const tNorm = (i + 1) / trail.length; // 0..1 const r = ORB_RADIUS * 0.12 * tNorm; const a = 0.03 + 0.25 * tNorm; ctx.fillStyle = 'rgba(0, 229, 255, ' + a + ')'; ctx.beginPath(); ctx.arc(t.x, t.y, r, 0, Math.PI * 2); ctx.fill(); } // Main orb - layered radial gradients for glow. // During a blink we dim the orb (~55% intensity) so the user gets // visual feedback that the blink was registered, but we keep it on // screen so its position is unambiguous. The dim also hides the // brief artifacts that some webcams produce at the moment of lid closure. const blink = lastBlinking; // Alpha multipliers: halo and mid-glow dim more aggressively than the // core so the orb still has a recognisable shape at low alpha. const haloMul = blink ? 0.55 : 1.0; const midMul = blink ? 0.60 : 1.0; const coreMul = blink ? 0.70 : 1.0; // Optional tint shift: when blinking we mix a touch of warm magenta // into the orb so it reads as "muted" rather than just "faded". We // shift the highlight stop to a slightly pinker cyan. const highlightR = blink ? 200 : 180; const highlightG = blink ? 180 : 255; const highlightB = blink ? 255 : 255; const cx = sx, cy = sy; // Outer halo let g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS * 4); g.addColorStop(0, 'rgba(0, 229, 255, ' + (0.35 * haloMul).toFixed(3) + ')'); g.addColorStop(0.25, 'rgba(0, 229, 255, ' + (0.18 * haloMul).toFixed(3) + ')'); g.addColorStop(0.6, 'rgba(0, 184, 212, ' + (0.05 * haloMul).toFixed(3) + ')'); g.addColorStop(1, 'rgba(0, 229, 255, 0)'); ctx.fillStyle = g; ctx.beginPath(); ctx.arc(cx, cy, ORB_RADIUS * 4, 0, Math.PI * 2); ctx.fill(); // Mid glow g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS * 1.8); g.addColorStop(0, 'rgba(' + highlightR + ', ' + highlightG + ', ' + highlightB + ', ' + (0.95 * midMul).toFixed(3) + ')'); g.addColorStop(0.25, 'rgba(0, 229, 255, ' + (0.85 * midMul).toFixed(3) + ')'); g.addColorStop(0.65, 'rgba(0, 184, 212, ' + (0.5 * midMul).toFixed(3) + ')'); g.addColorStop(1, 'rgba(0, 229, 255, 0)'); ctx.fillStyle = g; ctx.beginPath(); ctx.arc(cx, cy, ORB_RADIUS * 1.8, 0, Math.PI * 2); ctx.fill(); // Core g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS); g.addColorStop(0, 'rgba(255, 255, 255, ' + (1.0 * coreMul).toFixed(3) + ')'); g.addColorStop(0.3, 'rgba(' + highlightR + ', ' + highlightG + ', ' + highlightB + ', ' + (1.0 * coreMul).toFixed(3) + ')'); g.addColorStop(0.7, 'rgba(0, 229, 255, ' + (0.95 * coreMul).toFixed(3) + ')'); g.addColorStop(1, 'rgba(0, 184, 212, ' + (0.7 * coreMul).toFixed(3) + ')'); ctx.fillStyle = g; ctx.beginPath(); ctx.arc(cx, cy, ORB_RADIUS, 0, Math.PI * 2); ctx.fill(); // Inner sparkle ctx.fillStyle = 'rgba(255, 255, 255, ' + (0.85 * coreMul).toFixed(3) + ')'; ctx.beginPath(); ctx.arc(cx - ORB_RADIUS * 0.25, cy - ORB_RADIUS * 0.25, ORB_RADIUS * 0.18, 0, Math.PI * 2); ctx.fill(); } // ============================================================ // Render: face mesh overlay on webcam preview // ============================================================ function drawOverlay(results) { const w = overlay.width; const h = overlay.height; octx.clearRect(0, 0, w, h); if (!results || !results.multiFaceLandmarks || results.multiFaceLandmarks.length === 0) { // Subtle "no face" indicator octx.strokeStyle = 'rgba(0, 229, 255, 0.25)'; octx.setLineDash([4, 4]); octx.lineWidth = 1; octx.strokeRect(8, 8, w - 16, h - 16); octx.setLineDash([]); octx.fillStyle = 'rgba(0, 229, 255, 0.7)'; octx.font = '10px monospace'; octx.fillText('NO FACE DETECTED', 12, h - 12); return; } const lm = results.multiFaceLandmarks[0]; // Note: the video is mirrored visually via CSS, so we mirror X here // to keep the mesh aligned with what the user sees. const pt = (i) => ({ x: (1 - lm[i].x) * w, y: lm[i].y * h }); // Draw mesh lines octx.lineWidth = 0.6; octx.strokeStyle = 'rgba(0, 229, 255, 0.45)'; octx.beginPath(); [FACE_OVAL, LIPS, L_EYE, R_EYE, L_BROW, R_BROW].forEach(connections => { for (let i = 0; i < connections.length; i++) { const a = pt(connections[i]); const b = pt(connections[(i + 1) % connections.length]); octx.moveTo(a.x, a.y); octx.lineTo(b.x, b.y); } }); octx.stroke(); // Subtle face dots (subsample every 6th point for performance) octx.fillStyle = 'rgba(0, 229, 255, 0.4)'; for (let i = 0; i < lm.length; i++) { if (i % 6 !== 0) continue; // was % 3 — doubled the stride to halve the work const p = pt(i); octx.fillRect(p.x, p.y, 1, 1); } // Iris highlight (big + bright) octx.fillStyle = '#ffeb3b'; IRIS_LANDMARKS.forEach(idx => { const p = pt(idx); octx.beginPath(); octx.arc(p.x, p.y, 1.6, 0, Math.PI * 2); octx.fill(); }); // Iris center (468 / 473) - extra large [L_IRIS, R_IRIS].forEach(idx => { const p = pt(idx); octx.fillStyle = '#ffffff'; octx.beginPath(); octx.arc(p.x, p.y, 2.6, 0, Math.PI * 2); octx.fill(); }); } // ============================================================ // Animation loop // ============================================================ let faceMesh = null; export function setFaceMeshRef(v) { faceMesh = v; } function loop(now) { // FPS const dt = now - lastTime; lastTime = now; const instFps = 1000 / Math.max(dt, 1); fpsSmooth = fpsSmooth === 0 ? instFps : (fpsSmooth * 0.9 + instFps * 0.1); // Kalman filter: feed raw gaze through the Kalman filter. // rawX/rawY are already screen-coords (applyRegression when calibrated, // or raw iris ratio clamped to [0,1] before calibration is ready). // No update when no iris is visible, so the orb holds its position // instead of drifting back to center. if (getRawXValid() && !calPaused) { const kf = kalUpdate(rawX, rawY); smoothedX = kf.x; smoothedY = kf.y; } drawOrb(); if (lastResults) drawOverlay(lastResults); // Status text — overall pipeline state const visible = irisVisible.l || irisVisible.r; if (visible) { statusDot.className = 'dot ok'; statusText.className = 'value ok'; statusText.textContent = 'TRACKING'; dbgSet(dbgStage, 'tracking', 'ok'); } else if (faceMesh) { statusDot.className = 'dot warn'; statusText.className = 'value warn'; statusText.textContent = 'NO IRIS'; dbgSet(dbgStage, 'no face', 'warn'); } else { statusDot.className = 'dot'; statusText.className = 'value'; statusText.textContent = 'INIT'; dbgSet(dbgStage, 'init', 'run'); } fpsEl.textContent = Math.round(fpsSmooth); gxEl.textContent = smoothedX.toFixed(3); gyEl.textContent = smoothedY.toFixed(3); ilEl.textContent = irisVisible.l ? '●' : '○'; irEl.textContent = irisVisible.r ? '●' : '○'; ilEl.className = 'value ' + (irisVisible.l ? 'ok' : 'warn'); irEl.className = 'value ' + (irisVisible.r ? 'ok' : 'warn'); dbgSet(dbgFrame, lastFrameMs > 0 ? (lastFrameMs.toFixed(1) + ' ms') : '--'); // V2 debug rows: EAR, blink flag, pitch, yaw. The blink row gets // a warn class so the user can see at a glance that a blink was // filtered this frame. if (dbgEar) dbgSet(dbgEar, lastEAR > 0 ? lastEAR.toFixed(3) : '--'); if (dbgBlink) dbgSet(dbgBlink, lastBlinking ? 'YES' : 'no', lastBlinking ? 'warn' : null); if (dbgPitch) dbgSet(dbgPitch, lastHeadPose.pitch.toFixed(3)); if (dbgYaw) dbgSet(dbgYaw, lastHeadPose.yaw.toFixed(3)); requestAnimationFrame(loop); } requestAnimationFrame(loop);