Realistic watercolor drawings
Add hand-tracking mode with dwell gestures and overlay
Maksim9526a97317af
diff --git a/.gitignore b/.gitignoreindex f06235c..06e6038 100644--- a/.gitignore+++ b/.gitignore@@ -1,2 +1,3 @@node_modulesdist+*.tsbuildinfodiff --git a/package-lock.json b/package-lock.jsonindex 4ac43b4..2cc6893 100644--- a/package-lock.json+++ b/package-lock.json@@ -8,6 +8,7 @@"name": "watercolor","version": "0.1.0","dependencies": {+ "@mediapipe/tasks-vision": "^1.0.1","@preact/signals": "^2.11.3","heic-to": "^1.6.5","preact": "^11.0.0",@@ -385,6 +386,12 @@"@jridgewell/sourcemap-codec": "^1.4.14"}},+ "node_modules/@mediapipe/tasks-vision": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@mediapipe/tasks-vision/-/tasks-vision-1.0.1.tgz",+ "integrity": "sha512-rvRE2FmAZ6ZxKSw7wq+e+jQDpN3t1B/tD2mJz9SmAzb1msoDkd4dMoE4wAh8Z30Um0PQwLiHr9QtomhmXk3aUQ==",+ "license": "Apache-2.0"+ },"node_modules/@oxc-project/types": {"version": "0.152.0","resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.152.0.tgz",diff --git a/package.json b/package.jsonindex d5a5e81..346015d 100644--- a/package.json+++ b/package.json@@ -15,6 +15,7 @@"vite": "^8.3.2"},"dependencies": {+ "@mediapipe/tasks-vision": "^1.0.1","@preact/signals": "^2.11.3","heic-to": "^1.6.5","preact": "^11.0.0",diff --git a/src/app/App.tsx b/src/app/App.tsxindex d9f66ac..c87d4be 100644--- a/src/app/App.tsx+++ b/src/app/App.tsx@@ -1,6 +1,7 @@import { useEffect, useState } from 'preact/hooks';import { ActionBar } from '../components/ActionBar';import { BrushLibrary } from '../components/BrushLibrary';+import { HandOverlay } from '../components/HandOverlay';import { HistoryPanel } from '../components/HistoryPanel';import { DropChoice, FillChoice, Ghost, Toast } from '../components/Overlays';import { Palette } from '../components/Palette';@@ -42,6 +43,7 @@ function Chrome() {<Ghost /><DropChoice /><FillChoice />+ <HandOverlay /></>;}diff --git a/src/app/store.ts b/src/app/store.tsindex eec690d..e19a12a 100644--- a/src/app/store.ts+++ b/src/app/store.ts@@ -4,6 +4,8 @@ import { clampDocSize, DEFAULT_PARAMS, MAX_ZOOM, MIN_ZOOM, WatercolorEngine, typimport type { StepInfo } from '../engine/history';import { DEFAULT_PAPER, PAPER_SIZES, PAPERS, type PaperPreset } from '../engine/papers';import { ExportStore } from '../export/ExportStore';+import type { HandMode } from '../hand/HandMode';+import { HAND_IDLE, type HandCursor, type HandStatus } from '../hand/types';import { customEntry, PALETTE, type PaletteEntry } from '../palette';import { isProjectFile, type ProjectData } from '../project/format';import { ProjectStore } from '../project/ProjectStore';@@ -39,6 +41,12 @@ const sanitizeSize = (v: PaperSizeChoice): PaperSizeChoice => {return { preset, w, h };};const isEngineTool = (t: UiTool): t is Tool => ENGINE_TOOLS.some(e => e.id === t);+const handErrorText = (e: unknown) => {+ const name = e instanceof Error ? e.name : '';+ if (name === 'NotAllowedError' || name === 'SecurityError') return 'Camera access was denied';+ if (name === 'NotFoundError' || name === 'OverconstrainedError') return 'No camera found';+ return 'Could not start hand tracking';+};/*** All UI state as signals, plus the actions that change it. Owns the engine and the@@ -82,6 +90,11 @@ export class AppStore {readonly zoom = signal(1);/** A dropped image waiting for the user to say what it is for. */readonly dropped = signal<{ file: File; x: number; y: number } | null>(null);+ /** Hand painting (camera + MediaPipe): the switch, where it is in loading, and what the hand is doing. Not remembered: it needs the camera. */+ readonly handEnabled = signal(false);+ readonly handStatus = signal<HandStatus>('off');+ readonly hand = signal<HandCursor>(HAND_IDLE);+ readonly handStream = signal<MediaStream | null>(null);readonly panelTools = new Map<string, { def: PanelToolDef; tool: PanelTool }>();readonly reference: ReferenceStore;@@ -91,6 +104,8 @@ export class AppStore {readonly activePanelTool = computed(() => this.panelTools.get(this.tool.value)?.tool ?? null);private confirmTimer = 0;+ private handMode: HandMode | null = null;+ private handStarting: Promise<void> | null = null;private textureBefore: DocState | null = null;private readonly navigation: Navigation;@@ -293,6 +308,45 @@ export class AppStore {this.closePopovers();}+ /**+ * Switch hand painting on or off. Switching on pulls in MediaPipe (its own chunk), asks for the+ * camera and loads the model; a failure shows a toast and flips the switch back.+ */+ async setHandMode(on: boolean) {+ this.handEnabled.value = on;+ if (on) {+ if (this.handMode || this.handStarting) return;+ this.handStatus.value = 'loading';+ this.handStarting = (async () => {+ const { HandMode } = await import('../hand');+ const mode = new HandMode({+ engine: this.engine,+ paintTool: () => { const t = this.tool.peek(); return isEngineTool(t) && this.engine.interactive ? t : null; },+ setCursor: c => { this.hand.value = c; },+ setStream: s => { this.handStream.value = s; },+ });+ await mode.start();+ if (!this.handEnabled.peek()) { mode.stop(); return; } // switched off while loading+ this.handMode = mode;+ this.handStatus.value = 'on';+ if (import.meta.env.DEV) (window as unknown as { hand: HandMode }).hand = mode;+ })().catch((e: unknown) => {+ this.handStatus.value = 'error';+ this.handEnabled.value = false;+ this.hand.value = HAND_IDLE;+ this.handStream.value = null;+ showToast(handErrorText(e));+ }).finally(() => { this.handStarting = null; });+ } else {+ // a start still under way sees the switch off and stops itself when it finishes+ this.handMode?.stop();+ this.handMode = null;+ this.handStatus.value = 'off';+ this.hand.value = HAND_IDLE;+ this.handStream.value = null;+ }+ }+/** First press arms the button ("Sure?"), a second press within 2.5 s clears. */clear() {clearTimeout(this.confirmTimer);@@ -348,5 +402,5 @@ export class AppStore {this.reference.syncRect();}- destroy() { this.navigation.destroy(); this.engine.destroy(); }+ destroy() { void this.setHandMode(false); this.navigation.destroy(); this.engine.destroy(); }}diff --git a/src/components/HandOverlay.tsx b/src/components/HandOverlay.tsxnew file mode 100644index 0000000..63523fd--- /dev/null+++ b/src/components/HandOverlay.tsx@@ -0,0 +1,36 @@+import { useEffect, useRef } from 'preact/hooks';+import { useApp } from '../app/context';+import type { HandRect } from '../hand/types';++const R = 14, SIZE = 40, C = 2 * Math.PI * R;+const rectStyle = (r: HandRect) => ({ left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px` });++/** Hand mode on screen: the hand cursor with its dwell ring, the control it rests on, and the camera picture. */+export function HandOverlay() {+ const app = useApp();+ const status = app.handStatus.value;+ const stream = app.handStream.value;+ const video = useRef<HTMLVideoElement>(null);+ useEffect(() => { if (video.current) video.current.srcObject = stream; }, [stream, status]);+ if (status !== 'loading' && status !== 'on') return null;+ const c = app.hand.value;+ const box = c.grab ?? c.target;+ return <>+ <div class="hand-overlay">+ {box && <div class={`hand-target${c.grab ? ' grab' : ''}`} style={rectStyle(box)} />}+ {c.visible && (+ <svg class={`hand-cursor${c.pinching ? ' pinch' : ''}${c.painting ? ' paint' : ''}`} width={SIZE} height={SIZE}+ style={{ transform: `translate(${c.x - SIZE / 2}px, ${c.y - SIZE / 2}px)` }}>+ <circle class="base" cx={SIZE / 2} cy={SIZE / 2} r={R} />+ <circle class="dwell" cx={SIZE / 2} cy={SIZE / 2} r={R} stroke-dasharray={C} stroke-dashoffset={C * (1 - c.dwell)} />+ <circle class="dot" cx={SIZE / 2} cy={SIZE / 2} r={c.pinching ? 5 : 2.5} />+ </svg>+ )}+ </div>+ <div class="hand-pip" title="Your camera. Move inside the box; pinch to paint, rest on a button to press it.">+ <video ref={video} muted autoPlay playsInline />+ <div class="box" />+ {status === 'loading' && <span>{stream ? 'Loading the hand model…' : 'Starting camera…'}</span>}+ </div>+ </>;+}diff --git a/src/components/SettingsPanel.tsx b/src/components/SettingsPanel.tsxindex 65466cf..4a33669 100644--- a/src/components/SettingsPanel.tsx+++ b/src/components/SettingsPanel.tsx@@ -1,6 +1,7 @@import { useApp } from '../app/context';import { DEFAULT_PARAMS, type Params } from '../engine/Engine';import { Panel } from '../ui/Panel';+import { Seg } from '../ui/Seg';import { SliderRows, type SliderSpec } from '../ui/Slider';const SLIDERS: SliderSpec<Params>[] = [@@ -18,6 +19,12 @@ export function SettingsPanel() {const app = useApp();return (<Panel class="settings" open={app.popover.value === 'settings'}>+ <div class="slider hand-row" title="Paint with your hand in front of the camera: pinch to paint, rest on a button to press it">+ <span>Hand</span>+ <Seg label="Hand painting" options={[{ id: false, label: 'Off' }, { id: true, label: 'On' }]}+ value={app.handEnabled.value} onChange={v => void app.setHandMode(v)} />+ </div>+ {app.handStatus.value === 'loading' && <span class="note">Starting the camera and loading the hand model…</span>}<SliderRows spec={SLIDERS} settings={app.params.value} onChange={p => app.setParams(p)} /><button class="reset" onClick={() => app.setParams(DEFAULT_PARAMS)}>Reset</button></Panel>diff --git a/src/hand/HandMode.ts b/src/hand/HandMode.tsnew file mode 100644index 0000000..6320a86--- /dev/null+++ b/src/hand/HandMode.ts@@ -0,0 +1,198 @@+import type { NormalizedLandmark } from '@mediapipe/tasks-vision';+import { Dwell, sliderInput, toRect } from './dwell';+import { Ema, Hysteresis, OneEuro } from './filter';+import { HandTracker, type Frame } from './tracker';+import { HAND_IDLE, type HandHost, type HandRect } from './types';++/** Rest on a control this long to press it. */+const DWELL_MS = 1500;+/** Pressure of every hand stroke (there is no stylus to read it from). */+const PRESSURE = 0.6;+/** The part of the camera frame that maps to the whole screen, so the corners need no reaching. */+const BOX_LO = 0.15, BOX_HI = 0.85;+/** How long the cursor stays where it was once the hand is lost. */+const LOST_MS = 150;+/** Pinch thresholds on thumb-tip to index-tip distance over palm size (wrist to middle knuckle). */+const PINCH_ENTER = 0.35, PINCH_EXIT = 0.5;+/** How far up or down the hand may wander while sliding before the slider is let go, in row heights. */+const GRAB_LEEWAY = 2.5;++const THUMB_TIP = 4, INDEX_TIP = 8, WRIST = 0, MIDDLE_MCP = 9;+const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));++interface Grab { input: HTMLInputElement; track: HandRect; row: HandRect; last: number }++/**+ * Paints and operates the UI from camera hand landmarks: the midpoint of thumb and index+ * tip is the cursor, a pinch is the brush on the paper, resting on a control presses it,+ * and resting on a slider grabs it so sideways motion sets its value.+ */+export class HandMode {+ private readonly tracker: HandTracker;+ private readonly fx = new OneEuro();+ private readonly fy = new OneEuro();+ private readonly pinchRatio = new Ema(0.5);+ private readonly pinch = new Hysteresis(PINCH_ENTER, PINCH_EXIT);+ private readonly dwell = new Dwell(DWELL_MS);+ private mode: 'idle' | 'paint' | 'grab' = 'idle';+ private grab: Grab | null = null;+ private wasPinching = false;+ private seenAt = -Infinity;+ private stopped = false;++ constructor(private host: HandHost) {+ this.tracker = new HandTracker(f => this.onFrame(f), s => host.setStream(s));+ }++ async start(): Promise<void> {+ document.addEventListener('visibilitychange', this.onVisibility);+ try {+ await this.tracker.start();+ } catch (e) {+ this.stop();+ throw e;+ }+ }++ stop() {+ if (this.stopped) return;+ this.stopped = true;+ document.removeEventListener('visibilitychange', this.onVisibility);+ this.endStroke();+ this.tracker.stop();+ this.host.setStream(null);+ this.host.setCursor(HAND_IDLE);+ }++ /** Feed a frame by hand (tests, no camera): 21 landmarks in camera space, or null for "no hand". */+ inject(landmarks: NormalizedLandmark[] | null, t = performance.now(), aspect = 4 / 3) {+ this.onFrame({ landmarks, t, aspect });+ }++ private onVisibility = () => {+ if (document.visibilityState !== 'hidden') return;+ this.rest();+ this.fx.reset(); this.fy.reset(); this.pinchRatio.reset(); this.pinch.reset();+ this.seenAt = -Infinity;+ this.host.setCursor(HAND_IDLE);+ };++ /** Let go of everything: the stroke, the slider, the dwell. */+ private rest() {+ this.endStroke();+ this.releaseGrab();+ this.dwell.reset();+ this.mode = 'idle';+ this.wasPinching = false;+ }++ private endStroke() {+ if (this.host.engine.scripting) this.host.engine.scriptEnd();+ if (this.mode === 'paint') this.mode = 'idle';+ }++ private releaseGrab() {+ const g = this.grab;+ if (!g) return;+ this.grab = null;+ // sliders that record an undo step per adjustment listen for `change`+ g.input.dispatchEvent(new Event('change', { bubbles: true }));+ if (this.mode === 'grab') this.mode = 'idle';+ }++ private onFrame(f: Frame) {+ if (this.stopped) return;+ const lm = f.landmarks;+ if (!lm) {+ if (f.t - this.seenAt > LOST_MS) {+ this.rest();+ this.host.setCursor(HAND_IDLE);+ }+ return;+ }+ this.seenAt = f.t;++ // the cursor: between thumb and index tip, mirrored, the middle of the frame spread over the screen+ const px = (lm[THUMB_TIP].x + lm[INDEX_TIP].x) / 2, py = (lm[THUMB_TIP].y + lm[INDEX_TIP].y) / 2;+ const u = this.fx.filter(1 - px, f.t), v = this.fy.filter(py, f.t);+ const x = clamp((u - BOX_LO) / (BOX_HI - BOX_LO), 0, 1) * window.innerWidth;+ const y = clamp((v - BOX_LO) / (BOX_HI - BOX_LO), 0, 1) * window.innerHeight;++ // the pinch: tip distance relative to the palm, so it works at any distance from the camera+ const d = (i: number, j: number) => Math.hypot((lm[i].x - lm[j].x) * f.aspect, lm[i].y - lm[j].y);+ const ratio = this.pinchRatio.update(d(THUMB_TIP, INDEX_TIP) / Math.max(d(WRIST, MIDDLE_MCP), 1e-3));+ const pinching = this.pinch.update(ratio);+ const rose = pinching && !this.wasPinching, fell = !pinching && this.wasPinching;+ this.wasPinching = pinching;++ let dwell = 0, target: HandRect | null = null;+ const engine = this.host.engine;++ if (this.mode === 'paint') {+ if (fell) {+ engine.scriptEnd();+ this.mode = 'idle';+ } else if (pinching) {+ const [dx, dy] = engine.clientToDoc(x, y);+ if (!engine.scriptMove(dx, dy, PRESSURE, f.t)) this.mode = 'idle'; // undone or cleared under us+ } else {+ this.mode = 'idle';+ }+ } else if (this.mode === 'grab') {+ const g = this.grab!;+ const rowMid = g.row.top + g.row.height / 2;+ if (pinching || Math.abs(y - rowMid) > GRAB_LEEWAY * g.row.height) {+ this.releaseGrab();+ this.dwell.reset();+ } else {+ this.slide(g, x);+ target = g.row;+ }+ }++ if (this.mode === 'idle') {+ if (pinching) {+ // a pinch over the paper starts a stroke; over a panel it is ignored (dwell is the way to press things)+ const tool = this.host.paintTool();+ const overUi = !!document.elementFromPoint(x, y)?.closest('.panel');+ if (tool && !overUi && (rose || this.wasPinching)) {+ const [dx, dy] = engine.clientToDoc(x, y);+ if (engine.scriptBegin(tool, dx, dy, PRESSURE, 'Hand stroke')) this.mode = 'paint';+ // else a pointer stroke is still on the paper: try again next frame+ }+ this.dwell.reset();+ } else {+ const r = this.dwell.update(x, y, f.t);+ dwell = r.progress; target = r.rect;+ if (r.fired?.kind === 'button') {+ r.fired.el.click();+ if (this.stopped) return; // the hand pressed "Off"+ } else if (r.fired?.kind === 'slider') {+ const input = sliderInput(r.fired.el);+ if (input) {+ this.grab = { input, track: toRect(input.getBoundingClientRect()), row: r.rect!, last: Number(input.value) };+ this.mode = 'grab';+ this.slide(this.grab, x);+ }+ }+ }+ }++ this.host.setCursor({+ visible: true, x, y, pinching, painting: this.mode === 'paint', dwell, target,+ grab: this.mode === 'grab' ? this.grab!.row : null,+ });+ }++ /** Set a grabbed slider from the cursor's position along its track. */+ private slide(g: Grab, x: number) {+ const input = g.input;+ const min = Number(input.min) || 0, max = input.max === '' ? 1 : Number(input.max), step = Number(input.step) || 0.01;+ const f = clamp((x - g.track.left) / Math.max(g.track.width, 1), 0, 1);+ const v = clamp(min + Math.round((f * (max - min)) / step) * step, min, max);+ if (Math.abs(v - g.last) < step / 2) return;+ g.last = v;+ input.value = String(v);+ input.dispatchEvent(new Event('input', { bubbles: true }));+ }+}diff --git a/src/hand/dwell.ts b/src/hand/dwell.tsnew file mode 100644index 0000000..38e7cbc--- /dev/null+++ b/src/hand/dwell.ts@@ -0,0 +1,46 @@+import type { HandRect } from './types';++/** Controls the hand can rest on. Hidden panels are not hit, and disabled buttons are skipped. */+const TARGETS = '.panel button:not(:disabled), .panel label.slider';++export interface DwellFire { kind: 'button' | 'slider'; el: HTMLElement }+export interface DwellResult { progress: number; rect: HandRect | null; fired: DwellFire | null }++export const toRect = (r: DOMRect): HandRect => ({ left: r.left, top: r.top, width: r.width, height: r.height });++/** The range input of a slider row, if it can be adjusted. */+export const sliderInput = (row: HTMLElement): HTMLInputElement | null => {+ const input = row.querySelector<HTMLInputElement>('input[type=range]');+ return input && !input.disabled ? input : null;+};++/**+ * Hover-to-activate: resting the cursor on a control for `ms` fires it once. Moving to another+ * control restarts the timer; staying on the same one after it fired does nothing more, so a+ * long rest on Undo undoes once.+ */+export class Dwell {+ private current: HTMLElement | null = null;+ private since = 0;+ private fired = false;++ constructor(private ms: number) {}++ reset() { this.current = null; this.fired = false; }++ /** `t` in ms. */+ update(x: number, y: number, t: number): DwellResult {+ let el = (document.elementFromPoint(x, y) as HTMLElement | null)?.closest<HTMLElement>(TARGETS) ?? null;+ const slider = !!el && el.matches('label.slider');+ if (slider && !sliderInput(el!)) el = null;+ if (el !== this.current) { this.current = el; this.since = t; this.fired = false; }+ if (!el) return { progress: 0, rect: null, fired: null };+ const progress = Math.min(1, (t - this.since) / this.ms);+ const rect = toRect(el.getBoundingClientRect());+ if (progress >= 1 && !this.fired) {+ this.fired = true;+ return { progress, rect, fired: { kind: slider ? 'slider' : 'button', el } };+ }+ return { progress, rect, fired: null };+ }+}diff --git a/src/hand/filter.ts b/src/hand/filter.tsnew file mode 100644index 0000000..15ee13b--- /dev/null+++ b/src/hand/filter.ts@@ -0,0 +1,67 @@+/** Smoothing for noisy landmark streams. */++const alpha = (dt: number, cutoff: number) => {+ const tau = 1 / (2 * Math.PI * cutoff);+ return 1 / (1 + tau / dt);+};++/**+ * One Euro filter (Casiez et al.): heavy smoothing while the value rests, light smoothing+ * while it moves fast, so a still hand does not jitter and a sweep does not lag.+ */+export class OneEuro {+ private x: number | null = null;+ private dx = 0;+ private t = 0;++ constructor(private minCutoff = 1.2, private beta = 0.02, private dCutoff = 1.0) {}++ reset() { this.x = null; this.dx = 0; }++ /** `t` in ms. */+ filter(v: number, t: number): number {+ if (this.x === null) { this.x = v; this.t = t; return v; }+ const dt = Math.max((t - this.t) / 1000, 1e-3);+ this.t = t;+ const rate = (v - this.x) / dt;+ this.dx += (rate - this.dx) * alpha(dt, this.dCutoff);+ const cutoff = this.minCutoff + this.beta * Math.abs(this.dx);+ this.x += (v - this.x) * alpha(dt, cutoff);+ return this.x;+ }+}++/** Exponential moving average. */+export class Ema {+ private v: number | null = null;+ constructor(private a: number) {}+ reset() { this.v = null; }+ update(x: number): number {+ this.v = this.v === null ? x : this.v + (x - this.v) * this.a;+ return this.v;+ }+}++/**+ * A boolean with two thresholds and a frame count: turns on once the value has been below+ * `enter` for `frames` frames, off once it has been above `exit` for as many. Between the+ * two it keeps its state.+ */+export class Hysteresis {+ private on = false;+ private run = 0;++ constructor(private enter: number, private exit: number, private frames = 2) {}++ reset() { this.on = false; this.run = 0; }++ update(v: number): boolean {+ const want = this.on ? !(v > this.exit) : v < this.enter;+ if (want !== this.on) {+ if (++this.run >= this.frames) { this.on = want; this.run = 0; }+ } else {+ this.run = 0;+ }+ return this.on;+ }+}diff --git a/src/hand/index.ts b/src/hand/index.tsnew file mode 100644index 0000000..ac0cc65--- /dev/null+++ b/src/hand/index.ts@@ -0,0 +1,2 @@+/** Lazy entry: everything behind this import (MediaPipe included) loads only when hand mode is switched on. */+export { HandMode } from './HandMode';diff --git a/src/hand/tracker.ts b/src/hand/tracker.tsnew file mode 100644index 0000000..5bd1cff--- /dev/null+++ b/src/hand/tracker.ts@@ -0,0 +1,97 @@+import { FilesetResolver, HandLandmarker, type NormalizedLandmark } from '@mediapipe/tasks-vision';++// Keep in step with the installed @mediapipe/tasks-vision version (package.json): the wasm must match the JS.+const VERSION = '1.0.1';+const WASM_URL = `https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@${VERSION}/wasm`;+// To serve these yourself, copy node_modules/@mediapipe/tasks-vision/wasm/* and the model into public/ and point the two URLs there.+const MODEL_URL = 'https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/latest/hand_landmarker.task';++export interface Frame {+ /** The 21 landmarks of the first hand (x, y normalised to the camera frame), or null when no hand is seen. */+ landmarks: NormalizedLandmark[] | null;+ /** performance.now() of the frame. */+ t: number;+ /** Camera frame width / height, for distances in frame space. */+ aspect: number;+}++/** The webcam and the MediaPipe hand landmarker, feeding one callback per video frame. */+export class HandTracker {+ private stream: MediaStream | null = null;+ private video: HTMLVideoElement | null = null;+ private landmarker: HandLandmarker | null = null;+ private handle = 0;+ private useVfc = false;+ private stopped = false;+ private lastTs = -1;++ constructor(private onFrame: (f: Frame) => void, private onStream: (s: MediaStream) => void) {}++ /** The camera first (so a denied permission shows before the download), then the model. Throws on either failure. */+ async start(): Promise<void> {+ const stream = await navigator.mediaDevices.getUserMedia({+ video: { facingMode: 'user', width: { ideal: 640 }, height: { ideal: 480 } }, audio: false,+ });+ if (this.stopped) { stream.getTracks().forEach(t => t.stop()); return; }+ this.stream = stream;+ this.onStream(stream);+ const v = document.createElement('video');+ v.muted = true; v.playsInline = true; v.autoplay = true;+ v.srcObject = stream;+ // not awaited: a camera that sends no frames yet would hold up the start; `tick` waits for readyState instead+ void v.play().catch(() => { /* autoplay refused; the frames still arrive */ });+ this.video = v;++ const vision = await FilesetResolver.forVisionTasks(WASM_URL);+ const create = (delegate: 'GPU' | 'CPU') => HandLandmarker.createFromOptions(vision, {+ baseOptions: { modelAssetPath: MODEL_URL, delegate },+ runningMode: 'VIDEO', numHands: 1,+ });+ try { this.landmarker = await create('GPU'); } catch { this.landmarker = await create('CPU'); }+ if (this.stopped) { this.release(); return; }++ this.useVfc = 'requestVideoFrameCallback' in v;+ this.schedule();+ }++ stop() {+ this.stopped = true;+ this.release();+ }++ private schedule() {+ const v = this.video!;+ this.handle = this.useVfc ? v.requestVideoFrameCallback(this.tick) : requestAnimationFrame(this.tick);+ }++ private tick = () => {+ this.handle = 0;+ if (this.stopped || !this.video || !this.landmarker) return;+ const v = this.video;+ if (v.readyState >= 2 && v.videoWidth > 0) {+ // MediaPipe wants strictly increasing timestamps+ const ts = Math.max(performance.now(), this.lastTs + 1);+ this.lastTs = ts;+ let landmarks: NormalizedLandmark[] | null = null;+ try {+ const res = this.landmarker.detectForVideo(v, ts);+ landmarks = res.landmarks[0] ?? null;+ } catch { /* a dropped frame */ }+ this.onFrame({ landmarks, t: ts, aspect: v.videoWidth / v.videoHeight });+ }+ if (!this.stopped) this.schedule();+ };++ private release() {+ if (this.handle) {+ if (this.useVfc) this.video?.cancelVideoFrameCallback(this.handle);+ else cancelAnimationFrame(this.handle);+ this.handle = 0;+ }+ this.landmarker?.close();+ this.landmarker = null;+ this.stream?.getTracks().forEach(t => t.stop());+ this.stream = null;+ if (this.video) { this.video.pause(); this.video.srcObject = null; this.video = null; }+ }+}diff --git a/src/hand/types.ts b/src/hand/types.tsnew file mode 100644index 0000000..7a45e59--- /dev/null+++ b/src/hand/types.ts@@ -0,0 +1,33 @@+import type { Tool, WatercolorEngine } from '../engine/Engine';++export type HandStatus = 'off' | 'loading' | 'on' | 'error';++/** A screen rectangle in client px (a plain object, so it can live in a signal). */+export interface HandRect { left: number; top: number; width: number; height: number }++/** Where the hand is and what it is doing, for the overlay. */+export interface HandCursor {+ visible: boolean;+ /** Client px. */+ x: number; y: number;+ pinching: boolean;+ /** A scripted stroke is open. */+ painting: boolean;+ /** 0..1 progress of the dwell on the hovered control. */+ dwell: number;+ /** The hovered control. */+ target: HandRect | null;+ /** The slider row being slid. */+ grab: HandRect | null;+}++export const HAND_IDLE: HandCursor = { visible: false, x: 0, y: 0, pinching: false, painting: false, dwell: 0, target: null, grab: null };++/** What the hand mode needs from the app. The store satisfies it, so the store keeps owning the engine. */+export interface HandHost {+ engine: WatercolorEngine;+ /** The engine tool to paint with, or null while painting is not allowed (panel tool active, reference being moved). */+ paintTool(): Tool | null;+ setCursor(c: HandCursor): void;+ setStream(s: MediaStream | null): void;+}diff --git a/src/styles.css b/src/styles.cssindex f67b53a..59a2cd4 100644--- a/src/styles.css+++ b/src/styles.css@@ -394,3 +394,33 @@ body.space-pan .cursor, body.panning .cursor { opacity: 0 !important; }@media (max-width: 640px) {.zoom { right: auto; left: calc(10px + env(safe-area-inset-left)); bottom: calc(96px + env(safe-area-inset-bottom)); }}++/* hand painting: the hand cursor, its dwell ring, the hovered control and the camera picture */+.hand-overlay { position: fixed; inset: 0; z-index: 8; pointer-events: none; }+.hand-target {+ position: absolute; box-sizing: border-box; border-radius: 9px;+ border: 1.5px solid rgba(42, 42, 51, 0.35); background: rgba(42, 42, 51, 0.04);+ transition: left 0.08s, top 0.08s, width 0.08s, height 0.08s;+}+.hand-target.grab { border-color: rgba(60, 90, 160, 0.8); background: rgba(60, 90, 160, 0.08); }+.hand-cursor { position: absolute; left: 0; top: 0; overflow: visible; }+.hand-cursor .base { fill: rgba(255, 255, 255, 0.35); stroke: rgba(42, 42, 51, 0.5); stroke-width: 1.5; }+.hand-cursor .dwell { fill: none; stroke: var(--ink); stroke-width: 3; stroke-linecap: round; transform: rotate(-90deg); transform-origin: 50% 50%; }+.hand-cursor .dot { fill: rgba(42, 42, 51, 0.7); transition: r 0.1s; }+.hand-cursor.pinch .base { stroke: var(--ink); fill: rgba(42, 42, 51, 0.12); }+.hand-cursor.paint .base { stroke: rgba(60, 90, 160, 0.9); fill: rgba(60, 90, 160, 0.14); }+.hand-cursor.paint .dot { fill: rgba(60, 90, 160, 0.9); }+.hand-pip {+ position: fixed; z-index: 5; pointer-events: none;+ right: calc(14px + env(safe-area-inset-right)); bottom: calc(66px + env(safe-area-inset-bottom)); /* above the zoom control */+ width: 160px; aspect-ratio: 4 / 3; border-radius: var(--radius); overflow: hidden;+ background: rgba(42, 42, 51, 0.85); border: 1px solid var(--line); box-shadow: 0 6px 24px rgba(40, 35, 25, 0.12);+}+.hand-pip video { width: 100%; height: 100%; object-fit: cover; transform: scaleX(-1); display: block; }+.hand-pip .box { position: absolute; left: 15%; top: 15%; width: 70%; height: 70%; border: 1px dashed rgba(255, 255, 255, 0.55); border-radius: 6px; }+.hand-pip span {+ position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; text-align: center; padding: 0 12px;+ font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; color: #f6f3ec; background: rgba(42, 42, 51, 0.5);+}+.settings .hand-row .seg { flex: 1; }+.settings .note { font-size: 10px; color: var(--ink-faint); line-height: 1.4; margin-top: -4px; }