the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Milestone 1: real-time browser instrument with MRI-style live anatomy
Jameson Hodge6a8cded23d72
diff --git a/index.html b/index.htmlnew file mode 100644index 0000000..df01234--- /dev/null+++ b/index.html@@ -0,0 +1,15 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="description" content="CHIMERA: a physically modelled voice synthesizer. Every sound comes from a simulated airway." />+ <meta name="theme-color" content="#2a3035" />+ <title>CHIMERA</title>+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='6' fill='%23000'/%3E%3Cpath d='M9 22c2-9 12-13 15-6' stroke='%23F2CF5B' stroke-width='3' fill='none' stroke-linecap='round'/%3E%3C/svg%3E" />+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/main.tsx"></script>+ </body>+</html>diff --git a/public/fonts/OFL.txt b/public/fonts/OFL.txtnew file mode 100644index 0000000..8597481--- /dev/null+++ b/public/fonts/OFL.txt@@ -0,0 +1,93 @@+Copyright 2020 The Archivo Project Authors (https://github.com/Omnibus-Type/Archivo)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/public/fonts/archivo-latin-ext.woff2 b/public/fonts/archivo-latin-ext.woff2new file mode 100644index 0000000..c0dbc07Binary files /dev/null and b/public/fonts/archivo-latin-ext.woff2 differdiff --git a/public/fonts/archivo-latin.woff2 b/public/fonts/archivo-latin.woff2new file mode 100644index 0000000..e2448d0Binary files /dev/null and b/public/fonts/archivo-latin.woff2 differdiff --git a/src/audio/AudioEngine.ts b/src/audio/AudioEngine.tsnew file mode 100644index 0000000..3f8d495--- /dev/null+++ b/src/audio/AudioEngine.ts@@ -0,0 +1,125 @@+/**+ * Main-thread side of the audio engine: AudioContext + worklet node + analyser, coalesced+ * parameter messages (at most one per animation frame per kind) and telemetry fan-out.+ */+import workletUrl from "../worklet/processor.ts?worker&url";+import type { ToWorklet, FromWorklet, TelemetryMessage, BodyName } from "../worklet/protocol.ts";+import type { HumanArtic } from "../engine/anatomy/human.ts";+import type { VoiceSource } from "../engine/voice/humanVoice.ts";++type Listener = (t: TelemetryMessage) => void;++export class AudioEngine {+ ctx: AudioContext | null = null;+ private node: AudioWorkletNode | null = null;+ analyser: AnalyserNode | null = null;+ private master: GainNode | null = null;+ latest: TelemetryMessage | null = null;+ sampleRate = 48000;+ private listeners = new Set<Listener>();+ private pendingArtic: Partial<HumanArtic> | null = null;+ private pendingTipFree: boolean | undefined;+ private pendingSource: Partial<VoiceSource> | null = null;+ private flushScheduled = false;+ private readyListeners = new Set<() => void>();+ error: string | null = null;++ get running(): boolean {+ return !!this.ctx && this.ctx.state === "running";+ }++ async start(): Promise<void> {+ if (this.ctx) {+ await this.ctx.resume();+ return;+ }+ const ctx = new AudioContext({ latencyHint: "interactive" });+ this.ctx = ctx;+ this.sampleRate = ctx.sampleRate;+ await ctx.audioWorklet.addModule(workletUrl);+ const node = new AudioWorkletNode(ctx, "chimera", { numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [2] });+ this.node = node;+ const master = ctx.createGain();+ master.gain.value = 0.8;+ this.master = master;+ const analyser = ctx.createAnalyser();+ analyser.fftSize = 4096;+ analyser.smoothingTimeConstant = 0.6;+ this.analyser = analyser;+ node.connect(master);+ master.connect(ctx.destination);+ master.connect(analyser);+ node.port.onmessage = (e: MessageEvent<FromWorklet>) => {+ const m = e.data;+ if (m.type === "telemetry") {+ this.latest = m;+ for (const l of this.listeners) l(m);+ } else if (m.type === "ready") {+ for (const l of this.readyListeners) l();+ } else if (m.type === "error") {+ this.error = m.message;+ console.error("worklet:", m.message);+ }+ };+ await ctx.resume();+ }++ onTelemetry(l: Listener): () => void {+ this.listeners.add(l);+ return () => this.listeners.delete(l);+ }++ onReady(l: () => void): () => void {+ this.readyListeners.add(l);+ return () => this.readyListeners.delete(l);+ }++ private send(m: ToWorklet): void {+ this.node?.port.postMessage(m);+ }++ setVolume(v: number): void {+ if (this.master && this.ctx) this.master.gain.setTargetAtTime(v, this.ctx.currentTime, 0.02);+ }++ setBody(body: BodyName): void {+ this.send({ type: "body", body });+ }++ gate(level: number): void {+ this.send({ type: "gate", level });+ }++ /** Coalesced: many calls within a frame become one message. */+ setArtic(values: Partial<HumanArtic>, tipFree?: boolean): void {+ this.pendingArtic = { ...(this.pendingArtic ?? {}), ...values };+ if (tipFree !== undefined) this.pendingTipFree = tipFree;+ this.scheduleFlush();+ }++ setSource(values: Partial<VoiceSource>): void {+ this.pendingSource = { ...(this.pendingSource ?? {}), ...values };+ this.scheduleFlush();+ }++ private scheduleFlush(): void {+ if (this.flushScheduled) return;+ this.flushScheduled = true;+ const flush = () => {+ this.flushScheduled = false;+ if (this.pendingArtic || this.pendingTipFree !== undefined) {+ this.send({ type: "artic", values: this.pendingArtic ?? {}, tipFree: this.pendingTipFree });+ this.pendingArtic = null;+ this.pendingTipFree = undefined;+ }+ if (this.pendingSource) {+ this.send({ type: "source", values: this.pendingSource });+ this.pendingSource = null;+ }+ };+ if (typeof requestAnimationFrame === "function") requestAnimationFrame(flush);+ else setTimeout(flush, 16);+ }+}++export const engine = new AudioEngine();diff --git a/src/engine/anatomy/human.ts b/src/engine/anatomy/human.tsindex 26f39de..3aadeb8 100644--- a/src/engine/anatomy/human.ts+++ b/src/engine/anatomy/human.ts@@ -195,6 +195,21 @@ export class HumanVocalTract {return { x: xx * k, y: yy * k };}+ /** Inverse of P(): body coordinates → template coordinates (for direct manipulation). */+ unP(x: number, y: number): Vec {+ const k = this.k;+ const ph = this.body.pharynx;+ let xx = x / k;+ let yy = y / k;+ if (xx > 0.5) xx = 0.5 + (xx - 0.5) / 0.86;+ if (yy < 7) yy = 7 - (7 - yy) / ph;+ return { x: xx, y: yy };+ }++ get scale(): number {+ return this.k;+ }+compute(a: HumanArtic): HumanFrame {const k = this.k;const P = (x: number, y: number) => this.P(x, y);diff --git a/src/main.tsx b/src/main.tsxnew file mode 100644index 0000000..cae418c--- /dev/null+++ b/src/main.tsx@@ -0,0 +1,10 @@+import { StrictMode } from "react";+import { createRoot } from "react-dom/client";+import { App } from "./ui/App.tsx";+import "./ui/styles.css";++createRoot(document.getElementById("root")!).render(+ <StrictMode>+ <App />+ </StrictMode>,+);diff --git a/src/ui/App.tsx b/src/ui/App.tsxnew file mode 100644index 0000000..c21fb05--- /dev/null+++ b/src/ui/App.tsx@@ -0,0 +1,139 @@+import { useEffect, useState } from "react";+import { useStore } from "./store.ts";+import { engine } from "../audio/AudioEngine.ts";+import { AnatomyView } from "./components/AnatomyView.tsx";+import { TubeView } from "./components/TubeView.tsx";+import { Stroboscope } from "./components/Stroboscope.tsx";+import { SpectrumView } from "./components/SpectrumView.tsx";+import { VowelMap } from "./components/VowelMap.tsx";+import { VoicePanel } from "./components/VoicePanel.tsx";+import { ArticPanel } from "./components/ArticPanel.tsx";+import { Keys } from "./components/Keys.tsx";+import { Segmented, Toggle } from "./components/Controls.tsx";+import type { BodyName } from "../worklet/protocol.ts";++function TopBar() {+ const started = useStore((s) => s.started);+ const starting = useStore((s) => s.starting);+ const start = useStore((s) => s.start);+ const body = useStore((s) => s.body);+ const setBody = useStore((s) => s.setBody);+ const volume = useStore((s) => s.volume);+ const setVolume = useStore((s) => s.setVolume);+ const [load, setLoad] = useState(0);+ useEffect(() => {+ const id = setInterval(() => setLoad(engine.latest?.load ?? 0), 500);+ return () => clearInterval(id);+ }, []);+ return (+ <header className="topbar">+ <div className="brand">+ <span className="wordmark">Chimera</span>+ <span className="tagline">A voice grown from a simulated airway</span>+ </div>+ <Segmented<BodyName>+ label="Body"+ value={body}+ onChange={setBody}+ options={[+ { value: "male", label: "Adult male" },+ { value: "female", label: "Adult female" },+ { value: "child", label: "Child" },+ ]}+ />+ <div className="topbar-right">+ <label className="volume">+ <span>Volume</span>+ <input type="range" min={0} max={1} step={0.01} value={volume} onChange={(e) => setVolume(Number(e.target.value))} style={{ "--pos": `${volume * 100}%` } as React.CSSProperties} />+ </label>+ {started ? (+ <span className="load" title="Share of the audio thread's time budget used by the simulation">+ Engine load {Math.round(load * 100)} %+ </span>+ ) : (+ <button className="primary" onClick={() => void start()} disabled={starting}>+ {starting ? "Starting…" : "Start audio"}+ </button>+ )}+ </div>+ </header>+ );+}++function ViewToggles() {+ const view = useStore((s) => s.view);+ const setView = useStore((s) => s.setView);+ return (+ <div className="view-toggles">+ <Toggle label="Sound pressure" checked={view.pressure} onChange={(v) => setView({ pressure: v })} />+ <Toggle label="Airflow" checked={view.particles} onChange={(v) => setView({ particles: v })} />+ <Toggle label="Measurements" checked={view.calipers} onChange={(v) => setView({ calipers: v })} />+ <Toggle label="Grid" checked={view.grid} onChange={(v) => setView({ grid: v })} />+ </div>+ );+}++function StartPrompt() {+ const started = useStore((s) => s.started);+ const starting = useStore((s) => s.starting);+ const err = useStore((s) => s.startError);+ const start = useStore((s) => s.start);+ const setHold = useStore((s) => s.setHold);+ if (started) return null;+ return (+ <div className="start-prompt">+ <p>Every sound here is produced by simulating air moving through a throat, mouth and nose.</p>+ <button+ className="primary large"+ disabled={starting}+ onClick={async () => {+ await start();+ setHold(true);+ }}+ >+ {starting ? "Starting…" : "Breathe in and start"}+ </button>+ {err ? <p className="error">Audio could not start: {err}. Reload the page and try again.</p> : <p className="hint">Then drag the tongue, lips or jaw, or play the keys.</p>}+ </div>+ );+}++export function App() {+ return (+ <div className="app">+ <TopBar />+ <main className="stage">+ <section className="viewport" aria-label="Live vocal tract">+ <AnatomyView />+ <StartPrompt />+ <ViewToggles />+ </section>+ <aside className="instruments">+ <figure className="instrument">+ <figcaption>Tube, glottis to lips</figcaption>+ <TubeView />+ </figure>+ <figure className="instrument">+ <figcaption>Vocal folds, slowed down</figcaption>+ <Stroboscope />+ </figure>+ <figure className="instrument">+ <figcaption>Spectrum and resonances</figcaption>+ <SpectrumView />+ </figure>+ </aside>+ </main>+ <section className="deck">+ <div className="panel vowel-panel">+ <h2>Vowels</h2>+ <VowelMap />+ </div>+ <VoicePanel />+ <ArticPanel />+ </section>+ <footer className="keys-bar">+ <Keys />+ </footer>+ </div>+ );+}diff --git a/src/ui/analysis.ts b/src/ui/analysis.tsnew file mode 100644index 0000000..e32c1c3--- /dev/null+++ b/src/ui/analysis.ts@@ -0,0 +1,125 @@+/**+ * Main-thread acoustic model mirroring the worklet's airway (same topology & node counts):+ * geometry frames for drawing, frequency-domain transfer function and formants for display,+ * and vowel-space interpolation for the vowel map. Never runs inside the audio thread.+ */+import { HumanAirway } from "../engine/voice/humanAirway.ts";+import { BODY_MALE, BODY_FEMALE, BODY_CHILD, NEUTRAL, type HumanArtic, type HumanBody, type HumanFrame } from "../engine/anatomy/human.ts";+import { transferFunction, findPeaks } from "../engine/airway/frequency.ts";+import { ARTIC_KEYS } from "../engine/control/articulators.ts";+import { VOWELS } from "../engine/phonetics/vowelData.ts";+import targets from "../engine/phonetics/vowelTargets.generated.json";+import type { BodyName } from "../worklet/protocol.ts";++export const BODIES: Record<BodyName, HumanBody> = { male: BODY_MALE, female: BODY_FEMALE, child: BODY_CHILD };++type TargetTable = Record<string, Record<string, { artic: Partial<HumanArtic>; formants: number[] }>>;+const TARGETS = targets as unknown as TargetTable;++export interface VowelPoint {+ ipa: string;+ example: string;+ F1: number;+ F2: number;+ artic: Partial<HumanArtic>;+}++const FREQS = (() => {+ const n = 360;+ const out = new Float64Array(n);+ for (let i = 0; i < n; i++) out[i] = 60 * Math.pow(8000 / 60, i / (n - 1));+ return out;+})();++export class VoiceModel {+ readonly body: BodyName;+ readonly airway: HumanAirway;+ readonly vowels: VowelPoint[];+ private cacheKey = "";+ private cacheFrame: HumanFrame | null = null;+ private tfKey = "";+ private tf: { freqs: Float64Array; db: Float64Array; formants: number[] } | null = null;++ constructor(body: BodyName, sampleRate: number) {+ this.body = body;+ const M = sampleRate > 60000 ? 1 : 2;+ this.airway = new HumanAirway({ fs: sampleRate * M, body: BODIES[body] });+ const table = TARGETS[body] ?? {};+ this.vowels = VOWELS.filter((v) => table[v.ipa]).map((v) => ({+ ipa: v.ipa,+ example: v.example,+ F1: table[v.ipa].formants[0],+ F2: table[v.ipa].formants[1],+ artic: table[v.ipa].artic,+ }));+ }++ static articFromArray(arr: ArrayLike<number>): HumanArtic {+ const a = { ...NEUTRAL };+ ARTIC_KEYS.forEach((k, i) => (a[k] = arr[i]));+ return a;+ }++ frame(a: HumanArtic): HumanFrame {+ const key = ARTIC_KEYS.map((k) => a[k].toFixed(3)).join(",");+ if (key !== this.cacheKey || !this.cacheFrame) {+ this.cacheFrame = this.airway.tract.compute(a);+ this.cacheKey = key;+ }+ return this.cacheFrame;+ }++ /** Transfer function (dB) + formants for an articulation (cached on a coarse key). */+ transfer(a: HumanArtic): { freqs: Float64Array; db: Float64Array; formants: number[] } {+ const key = ARTIC_KEYS.map((k) => a[k].toFixed(2)).join(",");+ if (key === this.tfKey && this.tf) return this.tf;+ this.airway.apply(a);+ const el = this.airway.net.linearElements();+ const H = transferFunction(el, this.airway.pharynx.firstNode, FREQS, [this.airway.glottisPort]);+ const db = new Float64Array(FREQS.length);+ for (let i = 0; i < FREQS.length; i++) db[i] = 20 * Math.log10(H.mag[i] + 1e-12);+ const formants = findPeaks(FREQS, H.mag, 150).map((p) => p.freq).slice(0, 5);+ this.tf = { freqs: FREQS, db, formants };+ this.tfKey = key;+ return this.tf;+ }++ /** Blend calibrated vowel articulations for a point in (F1, F2) space (inverse-distance, log Hz). */+ articForFormants(F1: number, F2: number): Partial<HumanArtic> {+ const w: { v: VowelPoint; w: number }[] = this.vowels.map((v) => {+ const d1 = Math.log(F1 / v.F1) * 2.2; // F1 differences are perceptually larger+ const d2 = Math.log(F2 / v.F2);+ const d = Math.hypot(d1, d2);+ return { v, w: 1 / Math.pow(d + 0.02, 3) };+ });+ w.sort((p, q) => q.w - p.w);+ const top = w.slice(0, 4);+ const sum = top.reduce((s, x) => s + x.w, 0);+ const keys = ["tbX", "tbY", "jaw", "lipAp", "lipProt", "lipWidth", "root", "larynx", "ttCurl"] as const;+ const out: Partial<HumanArtic> = {};+ for (const k of keys) {+ let acc = 0;+ for (const { v, w: wi } of top) acc += ((v.artic[k] as number | undefined) ?? NEUTRAL[k]) * wi;+ out[k] = acc / sum;+ }+ return out;+ }++ /** s-position (cm from glottis) of each tract node in the telemetry arrays */+ nodeS(phLen: number, orLen: number): Float64Array {+ const nPh = this.airway.nPh, nOr = this.airway.nOr;+ const s = new Float64Array(nPh + nOr);+ for (let i = 0; i < nPh; i++) s[i] = ((i + 0.5) / nPh) * phLen;+ for (let i = 0; i < nOr; i++) s[nPh + i] = phLen + ((i + 0.5) / nOr) * orLen;+ return s;+ }++ /** s-position of a noise-source branch index (pharynx/oral internal branches) */+ branchS(branch: number, phLen: number, orLen: number): number {+ const ph = this.airway.pharynx, or = this.airway.oral;+ if (branch >= ph.branchBase && branch < ph.branchBase + ph.n - 1) return ((branch - ph.branchBase + 1) / ph.n) * phLen;+ if (branch >= or.branchBase && branch < or.branchBase + or.n - 1) return phLen + ((branch - or.branchBase + 1) / or.n) * orLen;+ if (branch === this.airway.glottisPort) return 0.2;+ return -1;+ }+}diff --git a/src/ui/colors.ts b/src/ui/colors.tsnew file mode 100644index 0000000..66fb599--- /dev/null+++ b/src/ui/colors.ts@@ -0,0 +1,56 @@+/** Design tokens shared by canvas renderers (CSS mirrors these as custom properties). */+export const C = {+ black: "#000000",+ console: "#2a3035",+ inset: "#20262a",+ line: "#3c444a",+ text: "#e8eaeb",+ textDim: "#9aa3a8",+ caliper: "#f2cf5b",+ caliperDim: "rgba(242, 207, 91, 0.45)",+ // MRI-like tissue intensities (T1-ish)+ fat: "#bdbdbd",+ skin: "#a8a8a8",+ muscle: "#5d5d5d",+ tongue: "#6b6b6b",+ brain: "#7c7c7c",+ marrow: "#b2b2b2",+ cortex: "#1c1c1c",+ cartilage: "#3e3e3e",+ mucosa: "#8f8f8f",+ tooth: "#101010",+};++/** fMRI-style "hot" scale for acoustic energy: black → red → orange → yellow → white. */+const HOT: [number, number, number, number][] = [+ [0.0, 0, 0, 0],+ [0.25, 138, 18, 0],+ [0.5, 240, 88, 28],+ [0.75, 255, 209, 92],+ [1.0, 255, 248, 230],+];++export function hot(t: number): [number, number, number] {+ if (!(t > 0)) return [0, 0, 0];+ if (t >= 1) return [255, 248, 230];+ for (let i = 1; i < HOT.length; i++) {+ if (t <= HOT[i][0]) {+ const a = HOT[i - 1], b = HOT[i];+ const u = (t - a[0]) / (b[0] - a[0]);+ return [a[1] + (b[1] - a[1]) * u, a[2] + (b[2] - a[2]) * u, a[3] + (b[3] - a[3]) * u];+ }+ }+ return [255, 248, 230];+}++export const hotCss = (t: number, alpha = 1): string => {+ const [r, g, b] = hot(t);+ return `rgba(${r | 0}, ${g | 0}, ${b | 0}, ${alpha})`;+};++/** Map acoustic pressure RMS (dyn/cm²) to 0..1 on a log scale. */+export const pressureLevel = (rms: number): number => {+ if (!(rms > 0)) return 0;+ const lo = Math.log10(40), hi = Math.log10(4000);+ return Math.max(0, Math.min(1, (Math.log10(rms) - lo) / (hi - lo)));+};diff --git a/src/ui/components/AnatomyView.tsx b/src/ui/components/AnatomyView.tsxnew file mode 100644index 0000000..2abfc60--- /dev/null+++ b/src/ui/components/AnatomyView.tsx@@ -0,0 +1,160 @@+import { useEffect, useRef, useState } from "react";+import { AnatomyRenderer, type HandleId } from "../render/anatomy.ts";+import { engine } from "../../audio/AudioEngine.ts";+import { useStore } from "../store.ts";+import { VoiceModel } from "../analysis.ts";+import { useModel } from "../useModel.ts";+import type { HumanArtic } from "../../engine/anatomy/human.ts";++const BODY_LABEL = { male: "Human, adult male", female: "Human, adult female", child: "Human, child" } as const;++export function AnatomyView() {+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const wrapRef = useRef<HTMLDivElement>(null);+ const model = useModel();+ const [hover, setHover] = useState<HandleId | null>(null);+ const dragRef = useRef<{ id: HandleId; start: { x: number; y: number }; artic: HumanArtic } | null>(null);+ const hoverRef = useRef<HandleId | null>(null);+ hoverRef.current = hover;+ const rendererRef = useRef<AnatomyRenderer | null>(null);++ useEffect(() => {+ const canvas = canvasRef.current!;+ const wrap = wrapRef.current!;+ const r = new AnatomyRenderer(canvas);+ rendererRef.current = r;+ const ro = new ResizeObserver(() => {+ const b = wrap.getBoundingClientRect();+ r.resize(b.width, b.height, Math.min(2, window.devicePixelRatio || 1));+ });+ ro.observe(wrap);+ let raf = 0;+ let last = performance.now();+ let fTick = 0;+ let formants: number[] = [];+ const loop = (now: number) => {+ const dt = Math.min(0.05, (now - last) / 1000);+ last = now;+ const st = useStore.getState();+ const tele = engine.latest && engine.latest.body === st.body ? engine.latest : null;+ const a = tele ? VoiceModel.articFromArray(tele.t.artic) : st.artic;+ const m = model.current;+ if (m) {+ const f = m.frame(a);+ if (++fTick % 4 === 0 || formants.length === 0) formants = m.transfer(a).formants;+ r.draw(m, f, a, tele, st.view, { hover: hoverRef.current, drag: dragRef.current?.id ?? null, dt, bodyLabel: BODY_LABEL[st.body], formants });+ }+ raf = requestAnimationFrame(loop);+ };+ raf = requestAnimationFrame(loop);+ return () => {+ cancelAnimationFrame(raf);+ ro.disconnect();+ };+ }, [model]);++ const pick = (e: React.PointerEvent): HandleId | null => {+ const r = rendererRef.current;+ const m = model.current;+ if (!r || !m) return null;+ const rect = canvasRef.current!.getBoundingClientRect();+ const p = r.toBody(e.clientX - rect.left, e.clientY - rect.top);+ const st = useStore.getState();+ const tele = engine.latest && engine.latest.body === st.body ? engine.latest : null;+ const a = tele ? VoiceModel.articFromArray(tele.t.artic) : st.artic;+ const f = m.frame(a);+ let best: HandleId | null = null;+ let bd = 22 / r.pxPerCm; // 22 px hit radius+ for (const h of r.handles(m, f, a)) {+ const d = Math.hypot(h.pos.x - p.x, h.pos.y - p.y);+ if (d < bd) {+ bd = d;+ best = h.id;+ }+ }+ return best;+ };++ const onDown = (e: React.PointerEvent) => {+ const id = pick(e);+ if (!id) return;+ const r = rendererRef.current!;+ const rect = canvasRef.current!.getBoundingClientRect();+ const p = r.toBody(e.clientX - rect.left, e.clientY - rect.top);+ (e.target as Element).setPointerCapture(e.pointerId);+ dragRef.current = { id, start: p, artic: { ...useStore.getState().artic } };+ e.preventDefault();+ };++ const onMove = (e: React.PointerEvent) => {+ const d = dragRef.current;+ const r = rendererRef.current;+ const m = model.current;+ if (!d) {+ const id = pick(e);+ if (id !== hover) setHover(id);+ return;+ }+ if (!r || !m) return;+ const rect = canvasRef.current!.getBoundingClientRect();+ const p = r.toBody(e.clientX - rect.left, e.clientY - rect.top);+ const t = m.airway.tract;+ const k = t.scale;+ const dx = (p.x - d.start.x) / k;+ const dy = (p.y - d.start.y) / k;+ const set = useStore.getState().setArtic;+ const a0 = d.artic;+ switch (d.id) {+ case "tongue": {+ const q = t.unP(p.x, p.y);+ set({ tbX: q.x, tbY: q.y });+ break;+ }+ case "tip": {+ const q = t.unP(p.x, p.y);+ set({ ttX: q.x, ttY: q.y }, false);+ break;+ }+ case "jaw":+ set({ jaw: clamp(a0.jaw - dy, -0.1, 2.6) });+ break;+ case "lips":+ if (e.shiftKey) set({ lipWidth: clamp(a0.lipWidth + dx * 0.6, 0, 1) });+ else set({ lipAp: clamp(a0.lipAp - dy * 1.2, -0.4, 2.4), lipProt: clamp(a0.lipProt + dx, -0.2, 1.5) });+ break;+ case "velum":+ set({ velum: clamp(a0.velum - dy * 0.9, 0, 1.4) });+ break;+ case "larynx":+ set({ larynx: clamp(a0.larynx + dy, -1.6, 1.6) });+ break;+ }+ };++ const onUp = (e: React.PointerEvent) => {+ if (dragRef.current) (e.target as Element).releasePointerCapture?.(e.pointerId);+ dragRef.current = null;+ };++ const onDouble = (e: React.MouseEvent) => {+ const id = pick(e as unknown as React.PointerEvent);+ if (id === "tip") useStore.getState().setArtic({}, true);+ };++ return (+ <div ref={wrapRef} className="anatomy" data-hover={hover ?? undefined}>+ <canvas+ ref={canvasRef}+ onPointerDown={onDown}+ onPointerMove={onMove}+ onPointerUp={onUp}+ onPointerCancel={onUp}+ onDoubleClick={onDouble}+ aria-label="Vocal tract cross-section. Drag the tongue, tongue tip, jaw, lips, soft palate or larynx handles."+ role="img"+ />+ </div>+ );+}++const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));diff --git a/src/ui/components/ArticPanel.tsx b/src/ui/components/ArticPanel.tsxnew file mode 100644index 0000000..aeedb6b--- /dev/null+++ b/src/ui/components/ArticPanel.tsx@@ -0,0 +1,25 @@+import { useStore } from "../store.ts";+import { Slider } from "./Controls.tsx";++/** Precision controls for articulators that have no handle (or need exact values). */+export function ArticPanel() {+ const a = useStore((s) => s.artic);+ const set = useStore((s) => s.setArtic);+ const pct = (v: number) => `${Math.round(v * 100)} %`;+ const cm = (v: number) => `${v.toFixed(2)} cm`;+ return (+ <div className="panel artic-panel">+ <h2>Throat and mouth</h2>+ <Slider label="Lip rounding" value={1 - a.lipWidth} min={0} max={1} onChange={(v) => set({ lipWidth: 1 - v })} format={pct} />+ <Slider label="Lip opening" value={a.lipAp} min={-0.3} max={2.2} onChange={(v) => set({ lipAp: v })} format={cm} />+ <Slider label="Lip protrusion" value={a.lipProt} min={-0.1} max={1.4} onChange={(v) => set({ lipProt: v })} format={cm} />+ <Slider label="Jaw opening" value={a.jaw} min={0} max={2.4} onChange={(v) => set({ jaw: v })} format={cm} />+ <Slider label="Tongue root" value={a.root} min={-0.9} max={0.9} onChange={(v) => set({ root: v })} format={(v) => (v >= 0 ? `+${v.toFixed(2)} cm` : `${v.toFixed(2)} cm`)} />+ <Slider label="Tip curl" value={a.ttCurl} min={0} max={1} onChange={(v) => set({ ttCurl: v })} format={pct} />+ <Slider label="Soft palate opening" value={a.velum} min={0} max={1.2} onChange={(v) => set({ velum: v })} format={(v) => `${v.toFixed(2)} cm²`} />+ <Slider label="Larynx height" value={a.larynx} min={-1.5} max={1.5} onChange={(v) => set({ larynx: v })} format={(v) => (v >= 0 ? `+${v.toFixed(2)} cm` : `${v.toFixed(2)} cm`)} />+ <Slider label="Twang (epilarynx)" value={a.epilarynx} min={0} max={1} onChange={(v) => set({ epilarynx: v })} format={pct} />+ <Slider label="False folds" value={a.ventricular} min={0} max={1} onChange={(v) => set({ ventricular: v })} format={pct} />+ </div>+ );+}diff --git a/src/ui/components/Controls.tsx b/src/ui/components/Controls.tsxnew file mode 100644index 0000000..12ea36b--- /dev/null+++ b/src/ui/components/Controls.tsx@@ -0,0 +1,57 @@+import { useId } from "react";++export function Slider(props: {+ label: string;+ value: number;+ min: number;+ max: number;+ step?: number;+ onChange: (v: number) => void;+ format?: (v: number) => string;+ log?: boolean;+}) {+ const id = useId();+ const { label, value, min, max, step, onChange, format, log } = props;+ const toPos = (v: number) => (log ? (Math.log(v) - Math.log(min)) / (Math.log(max) - Math.log(min)) : (v - min) / (max - min));+ const fromPos = (p: number) => (log ? Math.exp(Math.log(min) + p * (Math.log(max) - Math.log(min))) : min + p * (max - min));+ const pos = Math.min(1, Math.max(0, toPos(value)));+ return (+ <div className="slider">+ <label htmlFor={id}>+ <span>{label}</span>+ <output>{format ? format(value) : value.toFixed(2)}</output>+ </label>+ <input+ id={id}+ type="range"+ min={0}+ max={1000}+ step={step ? Math.max(1, Math.round((step / (max - min)) * 1000)) : 1}+ value={Math.round(pos * 1000)}+ onChange={(e) => onChange(fromPos(Number(e.target.value) / 1000))}+ style={{ "--pos": `${pos * 100}%` } as React.CSSProperties}+ />+ </div>+ );+}++export function Toggle(props: { label: string; checked: boolean; onChange: (v: boolean) => void }) {+ return (+ <label className="toggle">+ <input type="checkbox" checked={props.checked} onChange={(e) => props.onChange(e.target.checked)} />+ <span>{props.label}</span>+ </label>+ );+}++export function Segmented<T extends string>(props: { value: T; options: { value: T; label: string }[]; onChange: (v: T) => void; label: string }) {+ return (+ <div className="segmented" role="radiogroup" aria-label={props.label}>+ {props.options.map((o) => (+ <button key={o.value} role="radio" aria-checked={props.value === o.value} className={props.value === o.value ? "on" : ""} onClick={() => props.onChange(o.value)}>+ {o.label}+ </button>+ ))}+ </div>+ );+}diff --git a/src/ui/components/Keys.tsx b/src/ui/components/Keys.tsxnew file mode 100644index 0000000..d391830--- /dev/null+++ b/src/ui/components/Keys.tsx@@ -0,0 +1,81 @@+import { useEffect, useRef } from "react";+import { useStore } from "../store.ts";++/** Computer-keyboard layout: two rows like a piano (A W S E D F T G Y H U J K O L P ;). */+const KEYMAP: Record<string, number> = { a: 0, w: 1, s: 2, e: 3, d: 4, f: 5, t: 6, g: 7, y: 8, h: 9, u: 10, j: 11, k: 12, o: 13, l: 14, p: 15, ";": 16 };+const BASE: Record<string, number> = { male: 48, female: 57, child: 60 };++export function Keys() {+ const body = useStore((s) => s.body);+ const held = useStore((s) => s.heldNotes);+ const noteOn = useStore((s) => s.noteOn);+ const noteOff = useStore((s) => s.noteOff);+ const start = useStore((s) => s.start);+ const octave = useRef(0);+ const base = BASE[body] + octave.current * 12;++ useEffect(() => {+ const down = new Set<string>();+ const onDown = (e: KeyboardEvent) => {+ if (e.repeat || e.metaKey || e.ctrlKey || e.altKey) return;+ const target = e.target as HTMLElement;+ if (target && (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable)) {+ if ((target as HTMLInputElement).type !== "range" && (target as HTMLInputElement).type !== "checkbox") return;+ }+ const k = e.key.toLowerCase();+ if (k === "z") octave.current = Math.max(-2, octave.current - 1);+ if (k === "x") octave.current = Math.min(2, octave.current + 1);+ if (!(k in KEYMAP) || down.has(k)) return;+ down.add(k);+ void start();+ noteOn(BASE[useStore.getState().body] + octave.current * 12 + KEYMAP[k]);+ e.preventDefault();+ };+ const onUp = (e: KeyboardEvent) => {+ const k = e.key.toLowerCase();+ if (!down.has(k)) return;+ down.delete(k);+ noteOff(BASE[useStore.getState().body] + octave.current * 12 + KEYMAP[k]);+ };+ const onBlur = () => {+ for (const k of down) noteOff(BASE[useStore.getState().body] + octave.current * 12 + KEYMAP[k]);+ down.clear();+ };+ window.addEventListener("keydown", onDown);+ window.addEventListener("keyup", onUp);+ window.addEventListener("blur", onBlur);+ return () => {+ window.removeEventListener("keydown", onDown);+ window.removeEventListener("keyup", onUp);+ window.removeEventListener("blur", onBlur);+ };+ }, [noteOn, noteOff, start]);++ const notes = Array.from({ length: 25 }, (_, i) => base + i);+ const isBlack = (m: number) => [1, 3, 6, 8, 10].includes(((m % 12) + 12) % 12);+ const whites = notes.filter((m) => !isBlack(m));+ const press = (m: number) => (e: React.PointerEvent) => {+ (e.target as Element).setPointerCapture(e.pointerId);+ void start();+ noteOn(m);+ };+ const release = (m: number) => () => noteOff(m);+ return (+ <div className="keys" aria-label="Keyboard. Computer keys A to semicolon play notes; Z and X change octave.">+ <div className="white-row">+ {whites.map((m) => (+ <button key={m} className={`key white${held.includes(m) ? " down" : ""}`} onPointerDown={press(m)} onPointerUp={release(m)} onPointerCancel={release(m)} aria-label={`Note ${m}`} />+ ))}+ </div>+ <div className="black-row">+ {whites.map((m, i) => {+ const b = m + 1;+ const hasBlack = isBlack(b) && i < whites.length - 1;+ return hasBlack ? (+ <button key={b} className={`key black${held.includes(b) ? " down" : ""}`} style={{ left: `calc(${((i + 1) / whites.length) * 100}% - 1.1%)` }} onPointerDown={press(b)} onPointerUp={release(b)} onPointerCancel={release(b)} aria-label={`Note ${b}`} />+ ) : null;+ })}+ </div>+ </div>+ );+}diff --git a/src/ui/components/SpectrumView.tsx b/src/ui/components/SpectrumView.tsxnew file mode 100644index 0000000..901c2a1--- /dev/null+++ b/src/ui/components/SpectrumView.tsx@@ -0,0 +1,88 @@+import { useRef } from "react";+import { useCanvasLoop, font } from "../useCanvas.ts";+import { engine } from "../../audio/AudioEngine.ts";+import { useStore } from "../store.ts";+import { useModel } from "../useModel.ts";+import { VoiceModel } from "../analysis.ts";+import { C } from "../colors.ts";++const FMIN = 60, FMAX = 8000;++/** Live output spectrum (filled) with the vocal-tract transfer function and formant calipers. */+export function SpectrumView() {+ const model = useModel();+ const bins = useRef<Float32Array | null>(null);+ const ref = useCanvasLoop(({ ctx, w, h }) => {+ const st = useStore.getState();+ const m = model.current;+ if (!m) return;+ ctx.clearRect(0, 0, w, h);+ const left = 4, right = w - 4, top = 18, bot = h - 18;+ const fx = (f: number) => left + ((Math.log(f) - Math.log(FMIN)) / (Math.log(FMAX) - Math.log(FMIN))) * (right - left);+ // grid+ ctx.font = font(10.5);+ ctx.fillStyle = C.textDim;+ ctx.strokeStyle = "rgba(255,255,255,0.06)";+ for (const f of [100, 200, 500, 1000, 2000, 5000]) {+ const x = fx(f);+ ctx.beginPath();+ ctx.moveTo(x, top);+ ctx.lineTo(x, bot);+ ctx.stroke();+ const t = f >= 1000 ? `${f / 1000}k` : `${f}`;+ ctx.fillText(t, x - ctx.measureText(t).width / 2, h - 4);+ }+ // live FFT+ const an = engine.analyser;+ if (an && st.started) {+ if (!bins.current || bins.current.length !== an.frequencyBinCount) bins.current = new Float32Array(an.frequencyBinCount);+ an.getFloatFrequencyData(bins.current as Float32Array<ArrayBuffer>);+ const b = bins.current;+ const sr = engine.sampleRate;+ ctx.beginPath();+ ctx.moveTo(left, bot);+ for (let x = left; x <= right; x += 1.5) {+ const f = Math.exp(Math.log(FMIN) + ((x - left) / (right - left)) * (Math.log(FMAX) - Math.log(FMIN)));+ const k = Math.min(b.length - 1, Math.round((f / sr) * 2 * b.length));+ const db = Math.max(-110, b[k]);+ const y = bot - ((db + 110) / 100) * (bot - top);+ ctx.lineTo(x, y);+ }+ ctx.lineTo(right, bot);+ ctx.closePath();+ ctx.fillStyle = "rgba(154,163,168,0.28)";+ ctx.fill();+ }+ // transfer function of the current tract+ const tele = engine.latest && engine.latest.body === st.body ? engine.latest : null;+ const a = tele ? VoiceModel.articFromArray(tele.t.artic) : st.artic;+ const tf = m.transfer(a);+ let mx = -Infinity;+ for (const d of tf.db) mx = Math.max(mx, d);+ ctx.beginPath();+ for (let i = 0; i < tf.freqs.length; i++) {+ const x = fx(tf.freqs[i]);+ const y = top + ((mx - tf.db[i]) / 50) * (bot - top) * 0.9;+ if (i === 0) ctx.moveTo(x, Math.min(bot, y));+ else ctx.lineTo(x, Math.min(bot, y));+ }+ ctx.strokeStyle = "rgba(232,234,235,0.92)";+ ctx.lineWidth = 1.6;+ ctx.stroke();+ // formant calipers+ ctx.font = font(11, 550);+ tf.formants.slice(0, 4).forEach((F, i) => {+ const x = fx(F);+ ctx.strokeStyle = C.caliper;+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.moveTo(x, top - 2);+ ctx.lineTo(x, top + 8);+ ctx.stroke();+ ctx.fillStyle = C.caliper;+ const label = `F${i + 1}`;+ ctx.fillText(label, x - ctx.measureText(label).width / 2, top - 5);+ });+ });+ return <canvas ref={ref} className="instrument-canvas" aria-label="Output spectrum and vocal tract transfer function" role="img" />;+}diff --git a/src/ui/components/Stroboscope.tsx b/src/ui/components/Stroboscope.tsxnew file mode 100644index 0000000..91bcd9a--- /dev/null+++ b/src/ui/components/Stroboscope.tsx@@ -0,0 +1,113 @@+import { useRef } from "react";+import { useCanvasLoop, font } from "../useCanvas.ts";+import { engine } from "../../audio/AudioEngine.ts";+import { useStore } from "../store.ts";+import { C } from "../colors.ts";++/**+ * High-speed-video style view of the vocal folds from above, replayed slowly from the+ * phase-locked glottal area trace (two cycles), plus area/flow waveforms with a playhead.+ */+export function Stroboscope() {+ const phase = useRef(0);+ const ref = useCanvasLoop(({ ctx, w, h, dt }) => {+ const st = useStore.getState();+ ctx.clearRect(0, 0, w, h);+ const tele = engine.latest && engine.latest.body === st.body ? engine.latest : null;+ const area = tele?.t.glottalArea;+ const flow = tele?.t.glottalFlow;+ const n = area?.length ?? 0;+ // apparent strobe rate: one simulated cycle per ~0.9 s+ phase.current = (phase.current + dt / 1.8) % 1;+ const idx = n ? Math.floor(phase.current * n) % n : 0;+ let maxA = 0.02;+ if (area) for (let i = 0; i < n; i++) maxA = Math.max(maxA, area[i]);+ const a = area ? area[idx] : 0;+ // --- endoscopic circle+ const R = Math.min(h * 0.42, w * 0.2);+ const cx = R + 10, cy = h / 2;+ ctx.save();+ ctx.beginPath();+ ctx.arc(cx, cy, R, 0, Math.PI * 2);+ ctx.clip();+ const bg = ctx.createRadialGradient(cx, cy, R * 0.1, cx, cy, R);+ bg.addColorStop(0, "#9a9a9a");+ bg.addColorStop(1, "#2a2a2a");+ ctx.fillStyle = bg;+ ctx.fillRect(cx - R, cy - R, 2 * R, 2 * R);+ // glottis slit: anterior (top) to posterior (bottom); opening ∝ area+ const len = R * 1.25;+ const open = Math.min(1, a / Math.max(0.12, maxA)) * R * 0.42;+ const chink = tele ? Math.min(R * 0.06, (Math.min(...Array.from(area!)) / 0.05) * R * 0.08) : 0;+ ctx.fillStyle = "#000";+ ctx.beginPath();+ ctx.moveTo(cx, cy - len / 2);+ ctx.quadraticCurveTo(cx + open + chink, cy + len * 0.05, cx + chink * 0.8, cy + len / 2);+ ctx.lineTo(cx - chink * 0.8, cy + len / 2);+ ctx.quadraticCurveTo(cx - open - chink, cy + len * 0.05, cx, cy - len / 2);+ ctx.fill();+ // fold edges (ligament highlights)+ ctx.strokeStyle = "rgba(235,235,235,0.75)";+ ctx.lineWidth = 2;+ ctx.beginPath();+ ctx.moveTo(cx, cy - len / 2);+ ctx.quadraticCurveTo(cx + open + chink, cy + len * 0.05, cx + chink * 0.8, cy + len / 2);+ ctx.moveTo(cx, cy - len / 2);+ ctx.quadraticCurveTo(cx - open - chink, cy + len * 0.05, cx - chink * 0.8, cy + len / 2);+ ctx.stroke();+ // arytenoids+ ctx.fillStyle = "rgba(60,60,60,0.9)";+ for (const sgn of [-1, 1]) {+ ctx.beginPath();+ ctx.ellipse(cx + sgn * (R * 0.22 + chink), cy + len / 2 + R * 0.08, R * 0.2, R * 0.14, 0, 0, Math.PI * 2);+ ctx.fill();+ }+ ctx.restore();+ ctx.strokeStyle = C.line;+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.arc(cx, cy, R, 0, Math.PI * 2);+ ctx.stroke();+ // --- waveforms+ const x0 = cx + R + 16, x1 = w - 8;+ const top = 16, bot = h - 18;+ ctx.font = font(11);+ ctx.fillStyle = C.textDim;+ ctx.fillText("Glottal area", x0, 12);+ ctx.fillStyle = "rgba(232,234,235,0.85)";+ ctx.fillText("flow", x0 + 76, 12);+ if (area && flow && n > 1) {+ let maxF = 1;+ for (let i = 0; i < n; i++) maxF = Math.max(maxF, Math.abs(flow[i]));+ const plot = (arr: Float32Array, mx: number, color: string, wdt: number) => {+ ctx.beginPath();+ for (let i = 0; i < n; i++) {+ const x = x0 + ((x1 - x0) * i) / (n - 1);+ const y = bot - (arr[i] / mx) * (bot - top);+ if (i === 0) ctx.moveTo(x, y);+ else ctx.lineTo(x, y);+ }+ ctx.strokeStyle = color;+ ctx.lineWidth = wdt;+ ctx.stroke();+ };+ plot(area, maxA * 1.05, C.textDim, 1.25);+ plot(flow, maxF * 1.05, "rgba(232,234,235,0.9)", 1.6);+ const px = x0 + ((x1 - x0) * idx) / (n - 1);+ ctx.strokeStyle = C.caliper;+ ctx.beginPath();+ ctx.moveTo(px, top);+ ctx.lineTo(px, bot);+ ctx.stroke();+ ctx.fillStyle = C.textDim;+ ctx.fillText(`${(a * 100).toFixed(1)} mm²`, x0, h - 4);+ const oq = Array.from(area).filter((v) => v > Math.min(...Array.from(area)) + 0.002).length / n;+ const t = `Open ${Math.round(oq * 100)} %`;+ ctx.fillText(t, x1 - ctx.measureText(t).width, h - 4);+ } else {+ ctx.fillStyle = C.textDim;+ ctx.fillText("Start audio to see the folds vibrate", x0, h / 2);+ }+ });+ return <canvas ref={ref} className="instrument-canvas" aria-label="Vocal fold stroboscope and glottal waveforms" role="img" />;+}diff --git a/src/ui/components/TubeView.tsx b/src/ui/components/TubeView.tsxnew file mode 100644index 0000000..e09b5a1--- /dev/null+++ b/src/ui/components/TubeView.tsx@@ -0,0 +1,97 @@+import { useCanvasLoop, font } from "../useCanvas.ts";+import { engine } from "../../audio/AudioEngine.ts";+import { useStore } from "../store.ts";+import { useModel } from "../useModel.ts";+import { VoiceModel } from "../analysis.ts";+import { C, hot, pressureLevel } from "../colors.ts";++/** The simulated tube: diameter profile along the tract, lit by acoustic pressure, nasal branch above. */+export function TubeView() {+ const model = useModel();+ const ref = useCanvasLoop(({ ctx, w, h }) => {+ const st = useStore.getState();+ const m = model.current;+ if (!m) return;+ ctx.clearRect(0, 0, w, h);+ const tele = engine.latest && engine.latest.body === st.body ? engine.latest : null;+ let ph: ArrayLike<number>, or: ArrayLike<number>, phLen: number, orLen: number;+ let rms: Float32Array | null = null;+ if (tele) {+ ph = tele.t.phAreas;+ or = tele.t.orAreas;+ phLen = tele.t.phLen;+ orLen = tele.t.orLen;+ rms = tele.t.pressureRms;+ } else {+ m.airway.apply(st.artic);+ ph = m.airway.phAreas;+ or = m.airway.orAreas;+ phLen = m.airway.phLen;+ orLen = m.airway.orLen;+ }+ const nPh = ph.length, nOr = or.length;+ const total = phLen + orLen;+ const padL = 12, padR = 12;+ const axisY = h * 0.62;+ const sx = (w - padL - padR) / total;+ // diameter scale: 4 cm diameter → 34% of height+ const dScale = (h * 0.34) / 4;+ const a2d = (A: number) => 2 * Math.sqrt(Math.max(0, A) / Math.PI);+ // nasal branch (fixed profile) above, from the velum junction+ const velum = tele ? tele.t.velumPort : m.frame(st.artic).velumPort;+ const naX0 = padL + phLen * sx;+ const naY = axisY - h * 0.36;+ const naLen = 11.4 * m.airway.body.scale;+ const nasalLit = Math.min(1, velum / 0.4);+ ctx.strokeStyle = `rgba(160,170,175,${0.25 + 0.5 * nasalLit})`;+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.moveTo(naX0, axisY - a2d(ph[nPh - 1]) * dScale * 0.5);+ ctx.lineTo(naX0, naY + 6);+ ctx.stroke();+ const naW = Math.min(w - padR - naX0, naLen * sx * 0.75);+ ctx.fillStyle = `rgba(120,130,135,${0.18 + 0.35 * nasalLit})`;+ ctx.beginPath();+ ctx.roundRect(naX0, naY - 5, naW, 10, 5);+ ctx.fill();+ ctx.fillStyle = C.textDim;+ ctx.font = font(11);+ ctx.fillText(velum > 0.02 ? `Nasal, port ${velum.toFixed(2)} cm²` : "Nasal, closed", naX0 + 4, naY - 10);+ // sections+ const draw = (areas: ArrayLike<number>, s0: number, len: number, n: number, off: number) => {+ const dx = len / n;+ for (let i = 0; i < n; i++) {+ const x = padL + (s0 + i * dx) * sx;+ const ww = Math.max(1, dx * sx - 1);+ const d = a2d(areas[i]) * dScale;+ const lvl = rms ? pressureLevel(rms[off + i]) : 0;+ const [r, g, b] = hot(0.08 + 0.92 * lvl);+ ctx.fillStyle = rms ? `rgb(${r | 0},${g | 0},${b | 0})` : "#5b6368";+ ctx.fillRect(x, axisY - d / 2, ww, Math.max(0.5, d));+ }+ };+ draw(ph, 0, phLen, nPh, 0);+ draw(or, phLen, orLen, nOr, nPh);+ // landmarks+ const f = m.frame(tele ? VoiceModel.articFromArray(tele.t.artic) : st.artic);+ const marks: [number, string][] = [[0, "Glottis"], [phLen, "Velum"], [total, "Lips"]];+ if ((total - f.teethS) * sx > 46) marks.splice(2, 0, [f.teethS, "Teeth"]);+ ctx.font = font(11);+ ctx.fillStyle = C.textDim;+ ctx.strokeStyle = "rgba(154,163,168,0.4)";+ let lastRight = -Infinity;+ for (const [s, name] of marks) {+ const x = padL + s * sx;+ const twCheck = ctx.measureText(name).width;+ if (x - twCheck / 2 < lastRight + 6) continue;+ lastRight = x + twCheck / 2;+ ctx.beginPath();+ ctx.moveTo(x, h - 22);+ ctx.lineTo(x, h - 16);+ ctx.stroke();+ const tw = ctx.measureText(name).width;+ ctx.fillText(name, Math.min(w - tw - 2, Math.max(2, x - tw / 2)), h - 4);+ }+ });+ return <canvas ref={ref} className="instrument-canvas" aria-label="Area function of the simulated tube" role="img" />;+}diff --git a/src/ui/components/VoicePanel.tsx b/src/ui/components/VoicePanel.tsxnew file mode 100644index 0000000..5e94cf3--- /dev/null+++ b/src/ui/components/VoicePanel.tsx@@ -0,0 +1,32 @@+import { useStore } from "../store.ts";+import { Slider, Toggle } from "./Controls.tsx";++const NOTE = ["C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B"];+export const noteName = (f: number) => {+ const m = Math.round(69 + 12 * Math.log2(f / 440));+ return `${NOTE[((m % 12) + 12) % 12]}${Math.floor(m / 12) - 1}`;+};++export function VoicePanel() {+ const s = useStore((st) => st.source);+ const set = useStore((st) => st.setSource);+ const hold = useStore((st) => st.hold);+ const setHold = useStore((st) => st.setHold);+ return (+ <div className="panel voice-panel">+ <h2>Voice</h2>+ <Slider label="Pitch" value={s.f0} min={40} max={1100} log onChange={(v) => set({ f0: v })} format={(v) => `${v.toFixed(0)} Hz, ${noteName(v)}`} />+ <Slider label="Breath pressure" value={s.pressure} min={2} max={22} onChange={(v) => set({ pressure: v })} format={(v) => `${v.toFixed(1)} cmH₂O`} />+ <Slider label="Breathiness" value={s.breathiness} min={0} max={1} onChange={(v) => set({ breathiness: v })} format={(v) => `${Math.round(v * 100)} %`} />+ <Slider label="Lax to pressed" value={s.tension} min={0} max={1} onChange={(v) => set({ tension: v })} format={(v) => `${Math.round(v * 100)} %`} />+ <Slider label="Roughness" value={s.roughness} min={0} max={1} onChange={(v) => set({ roughness: v })} format={(v) => `${Math.round(v * 100)} %`} />+ <Slider label="Vocal fry" value={s.fry} min={0} max={1} onChange={(v) => set({ fry: v })} format={(v) => `${Math.round(v * 100)} %`} />+ <Slider label="Vibrato" value={s.vibratoDepth} min={0} max={120} onChange={(v) => set({ vibratoDepth: v })} format={(v) => `${v.toFixed(0)} cents`} />+ <Slider label="Glide" value={s.glide} min={0.005} max={0.6} log onChange={(v) => set({ glide: v })} format={(v) => `${(v * 1000).toFixed(0)} ms`} />+ <div className="row">+ <Toggle label="Hold breath" checked={hold} onChange={setHold} />+ <Toggle label="Whisper" checked={!s.voiced} onChange={(v) => set({ voiced: !v })} />+ </div>+ </div>+ );+}diff --git a/src/ui/components/VowelMap.tsx b/src/ui/components/VowelMap.tsxnew file mode 100644index 0000000..4db27ff--- /dev/null+++ b/src/ui/components/VowelMap.tsx@@ -0,0 +1,107 @@+import { useRef } from "react";+import { useCanvasLoop, font } from "../useCanvas.ts";+import { engine } from "../../audio/AudioEngine.ts";+import { useStore } from "../store.ts";+import { useModel } from "../useModel.ts";+import { VoiceModel } from "../analysis.ts";+import { C } from "../colors.ts";++/**+ * Vowel map in the phonetician's orientation: F2 decreasing left→right, F1 increasing downward.+ * Calibrated vowels are plotted where this body actually produces them; dragging morphs the+ * articulation between them; the yellow ring is the live tract's measured (F1, F2).+ */+export function VowelMap() {+ const model = useModel();+ const dragging = useRef(false);+ const range = () => {+ const b = useStore.getState().body;+ return b === "male" ? { f1: [230, 950], f2: [700, 2700] } : b === "female" ? { f1: [280, 1150], f2: [800, 3200] } : { f1: [300, 1250], f2: [900, 3500] };+ };+ const toXY = (F1: number, F2: number, w: number, h: number) => {+ const r = range();+ const pad = 18;+ const x = pad + ((Math.log(r.f2[1]) - Math.log(F2)) / (Math.log(r.f2[1]) - Math.log(r.f2[0]))) * (w - 2 * pad);+ const y = pad + ((Math.log(F1) - Math.log(r.f1[0])) / (Math.log(r.f1[1]) - Math.log(r.f1[0]))) * (h - 2 * pad);+ return { x, y };+ };+ const fromXY = (x: number, y: number, w: number, h: number) => {+ const r = range();+ const pad = 18;+ const u = Math.min(1, Math.max(0, (x - pad) / (w - 2 * pad)));+ const v = Math.min(1, Math.max(0, (y - pad) / (h - 2 * pad)));+ const F2 = Math.exp(Math.log(r.f2[1]) - u * (Math.log(r.f2[1]) - Math.log(r.f2[0])));+ const F1 = Math.exp(Math.log(r.f1[0]) + v * (Math.log(r.f1[1]) - Math.log(r.f1[0])));+ return { F1, F2 };+ };+ const ref = useCanvasLoop(({ ctx, w, h }) => {+ const m = model.current;+ if (!m) return;+ const st = useStore.getState();+ ctx.clearRect(0, 0, w, h);+ // vowel trapezoid guide+ const corners = [toXY(300, 2500, w, h), toXY(320, 850, w, h), toXY(720, 1050, w, h), toXY(780, 1650, w, h)];+ ctx.strokeStyle = "rgba(255,255,255,0.07)";+ ctx.lineWidth = 1;+ ctx.beginPath();+ corners.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));+ ctx.closePath();+ ctx.stroke();+ ctx.font = font(16, 500);+ ctx.textAlign = "center";+ ctx.textBaseline = "middle";+ for (const v of m.vowels) {+ const p = toXY(v.F1, v.F2, w, h);+ ctx.fillStyle = "rgba(232,234,235,0.82)";+ ctx.fillText(v.ipa, p.x, p.y);+ }+ // live point+ const tele = engine.latest && engine.latest.body === st.body ? engine.latest : null;+ const a = tele ? VoiceModel.articFromArray(tele.t.artic) : st.artic;+ const fm = m.transfer(a).formants;+ if (fm.length >= 2) {+ const p = toXY(fm[0], fm[1], w, h);+ ctx.strokeStyle = C.caliper;+ ctx.lineWidth = 1.5;+ ctx.beginPath();+ ctx.arc(p.x, p.y, 9, 0, Math.PI * 2);+ ctx.stroke();+ ctx.beginPath();+ ctx.arc(p.x, p.y, 2, 0, Math.PI * 2);+ ctx.fillStyle = C.caliper;+ ctx.fill();+ }+ ctx.textAlign = "left";+ ctx.textBaseline = "alphabetic";+ ctx.font = font(10.5);+ ctx.fillStyle = C.textDim;+ ctx.fillText("F2", w - 22, h - 5);+ ctx.fillText("F1", 4, h - 5);+ });++ const apply = (e: React.PointerEvent) => {+ const m = model.current;+ if (!m) return;+ const r = (e.currentTarget as HTMLCanvasElement).getBoundingClientRect();+ const { F1, F2 } = fromXY(e.clientX - r.left, e.clientY - r.top, r.width, r.height);+ useStore.getState().setArtic(m.articForFormants(F1, F2), true);+ };++ return (+ <canvas+ ref={ref}+ className="vowel-map"+ onPointerDown={(e) => {+ dragging.current = true;+ (e.target as Element).setPointerCapture(e.pointerId);+ apply(e);+ }}+ onPointerMove={(e) => dragging.current && apply(e)}+ onPointerUp={() => (dragging.current = false)}+ onPointerCancel={() => (dragging.current = false)}+ aria-label="Vowel map. Drag to morph between vowels."+ role="slider"+ aria-valuetext="vowel position"+ />+ );+}diff --git a/src/ui/render/anatomy.ts b/src/ui/render/anatomy.tsnew file mode 100644index 0000000..9e87f3e--- /dev/null+++ b/src/ui/render/anatomy.ts@@ -0,0 +1,569 @@+/**+ * Real-time-MRI style midsagittal renderer for the human model.+ * Tissue: T1-like grayscale (fat/marrow bright, muscle mid, cortical bone & teeth & air black)+ * with soft edges and film grain. Physics overlays: acoustic pressure RMS (hot scale) inside+ * the airway, airflow particles at local particle velocity u = U/A, turbulence at the active+ * noise source. Handles for direct manipulation.+ */+import type { HumanArtic, HumanFrame } from "../../engine/anatomy/human.ts";+import type { Vec } from "../../engine/anatomy/geom.ts";+import { rotateAbout, dist, catmullRom } from "../../engine/anatomy/geom.ts";+import type { TelemetryMessage } from "../../worklet/protocol.ts";+import type { VoiceModel } from "../analysis.ts";+import { C, hot, pressureLevel } from "../colors.ts";++export type HandleId = "tongue" | "tip" | "jaw" | "lips" | "velum" | "larynx";++export interface Handle {+ id: HandleId;+ pos: Vec; // body coordinates (cm)+ label: string;+}++export interface ViewFlags {+ pressure: boolean;+ particles: boolean;+ grid: boolean;+ calipers: boolean;+}++interface Particle {+ s: number;+ u: number; // lateral position −1..1+ life: number;+ px: number;+ py: number;+}++const VIEW = { x0: -7.2, x1: 12.2, y0: -4.2, y1: 15.8 };++export class AnatomyRenderer {+ private readonly canvas: HTMLCanvasElement;+ private readonly ctx: CanvasRenderingContext2D;+ private grain: CanvasPattern | null = null;+ private tissue: HTMLCanvasElement;+ private tctx: CanvasRenderingContext2D;+ private particles: Particle[] = [];+ private scale = 20;+ private ox = 0;+ private oy = 0;+ private dpr = 1;+ private sparkSeed = 1;+ private readonly canFilter: boolean;++ constructor(canvas: HTMLCanvasElement) {+ this.canvas = canvas;+ this.ctx = canvas.getContext("2d")!;+ this.tissue = document.createElement("canvas");+ this.tctx = this.tissue.getContext("2d")!;+ this.canFilter = typeof this.tctx.filter === "string";+ this.makeGrain();+ for (let i = 0; i < 170; i++) this.particles.push({ s: Math.random() * 17, u: Math.random() * 2 - 1, life: Math.random(), px: NaN, py: NaN });+ }++ private makeGrain(): void {+ const g = document.createElement("canvas");+ g.width = g.height = 192;+ const gc = g.getContext("2d")!;+ const img = gc.createImageData(192, 192);+ for (let i = 0; i < img.data.length; i += 4) {+ const v = 128 + (Math.random() + Math.random() + Math.random() - 1.5) * 90;+ img.data[i] = img.data[i + 1] = img.data[i + 2] = v;+ img.data[i + 3] = 255;+ }+ gc.putImageData(img, 0, 0);+ this.grain = this.ctx.createPattern(g, "repeat");+ }++ resize(w: number, h: number, dpr: number): void {+ this.dpr = dpr;+ this.canvas.width = Math.round(w * dpr);+ this.canvas.height = Math.round(h * dpr);+ this.tissue.width = this.canvas.width;+ this.tissue.height = this.canvas.height;+ const sx = w / (VIEW.x1 - VIEW.x0);+ const sy = h / (VIEW.y1 - VIEW.y0);+ this.scale = Math.min(sx, sy) * dpr;+ this.ox = (this.canvas.width - (VIEW.x1 - VIEW.x0) * this.scale) / 2 - VIEW.x0 * this.scale;+ this.oy = (this.canvas.height - (VIEW.y1 - VIEW.y0) * this.scale) / 2 + VIEW.y1 * this.scale;+ }++ /** body cm → canvas px */+ X(p: Vec): number {+ return this.ox + p.x * this.scale;+ }+ Y(p: Vec): number {+ return this.oy - p.y * this.scale;+ }+ /** client px → body cm */+ toBody(cx: number, cy: number): Vec {+ return { x: (cx * this.dpr - this.ox) / this.scale, y: (this.oy - cy * this.dpr) / this.scale };+ }+ get pxPerCm(): number {+ return this.scale / this.dpr;+ }++ handles(model: VoiceModel, f: HumanFrame, a: HumanArtic): Handle[] {+ const t = model.airway.tract;+ const J = this.jawFn(model, a);+ const lips = { x: (f.upperLip[6].x + f.lowerLip[6].x) / 2 + 0.15, y: (f.upperLip[6].y + f.lowerLip[6].y) / 2 };+ return [+ { id: "tongue", pos: f.tongueCenter, label: "Tongue body" },+ { id: "tip", pos: f.tip, label: "Tongue tip" },+ { id: "jaw", pos: J(7.5, 4.9), label: "Jaw" },+ { id: "lips", pos: lips, label: "Lips" },+ { id: "velum", pos: f.velum[Math.floor(f.velum.length / 2)], label: "Soft palate" },+ { id: "larynx", pos: { x: f.glottis.x + 1.2 * t.scale, y: f.glottis.y }, label: "Larynx" },+ ];+ }++ private jawFn(model: VoiceModel, a: HumanArtic): (x: number, y: number) => Vec {+ const t = model.airway.tract;+ const k = t.scale;+ const condyle = t.P(-2.5, 10.5);+ const jawRef = t.P(6.95, 7.75);+ const phi = (-Math.max(-0.2, Math.min(3, a.jaw)) * k) / dist(condyle, jawRef);+ return (x: number, y: number) => rotateAbout(t.P(x, y), condyle, phi);+ }++ // ------------------------------------------------------------------ drawing helpers+ private path(c: CanvasRenderingContext2D, pts: Vec[], close = true): void {+ c.beginPath();+ c.moveTo(this.X(pts[0]), this.Y(pts[0]));+ for (let i = 1; i < pts.length; i++) c.lineTo(this.X(pts[i]), this.Y(pts[i]));+ if (close) c.closePath();+ }++ private fill(c: CanvasRenderingContext2D, pts: Vec[], color: string): void {+ if (pts.length < 3) return;+ this.path(c, pts);+ c.fillStyle = color;+ c.fill();+ }++ private stroke(c: CanvasRenderingContext2D, pts: Vec[], color: string, w: number, close = false): void {+ if (pts.length < 2) return;+ this.path(c, pts, close);+ c.strokeStyle = color;+ c.lineWidth = w * this.dpr;+ c.lineJoin = "round";+ c.lineCap = "round";+ c.stroke();+ }++ // ------------------------------------------------------------------ main draw+ draw(model: VoiceModel, f: HumanFrame, a: HumanArtic, tele: TelemetryMessage | null, view: ViewFlags, opts: { hover: HandleId | null; drag: HandleId | null; dt: number; bodyLabel: string; formants: number[] }): void {+ const ctx = this.ctx;+ const W = this.canvas.width, H = this.canvas.height;+ this.drawTissue(model, f, a);+ ctx.globalCompositeOperation = "source-over";+ ctx.fillStyle = C.black;+ ctx.fillRect(0, 0, W, H);+ ctx.drawImage(this.tissue, 0, 0);++ // acoustic energy inside the airway (section-wise projection of the 1D simulation)+ if (view.pressure && tele) this.drawPressure(model, f, tele);+ if (view.grid) {+ for (const g of f.grid) {+ ctx.beginPath();+ ctx.moveTo(this.X(g.inner), this.Y(g.inner));+ ctx.lineTo(this.X(g.outer), this.Y(g.outer));+ ctx.strokeStyle = "rgba(150, 170, 180, 0.35)";+ ctx.lineWidth = 1 * this.dpr;+ ctx.stroke();+ }+ }+ if (view.particles && tele) this.drawParticles(model, f, tele, opts.dt);+ if (tele) this.drawTurbulence(model, f, tele);+ if (view.calipers) this.drawCalipers(f, tele);+ this.drawHandles(model, f, a, opts.hover, opts.drag);+ this.drawOverlay(f, a, tele, opts.bodyLabel, opts.formants);+ }++ private drawTissue(model: VoiceModel, f: HumanFrame, a: HumanArtic): void {+ const c = this.tctx;+ const t = model.airway.tract;+ const P = (x: number, y: number) => t.P(x, y);+ const J = this.jawFn(model, a);+ const k = t.scale;+ const lar = a.larynx * k;+ c.setTransform(1, 0, 0, 1, 0, 0);+ c.globalCompositeOperation = "source-over";+ c.clearRect(0, 0, this.tissue.width, this.tissue.height);+ if (this.canFilter) c.filter = `blur(${(0.55 * this.dpr).toFixed(2)}px)`;++ const ulOut = f.upperLip.slice(7); // edge → nose+ const llOut = f.lowerLip.slice(7); // edge → chin+ const ulEdge = f.upperLip[6];+ const llEdge = f.lowerLip[6];+ // ---- head silhouette (skin + subcutaneous fat)+ // facial profile in true body coordinates (the oral-region x compression of P() would+ // flatten the nose): subnasale → nose tip → nasion → forehead+ const ph = model.airway.body.pharynx;+ const B = (x: number, y: number): Vec => ({ x: x * k, y: (y < 7 ? 7 - (7 - y) * ph : y) * k });+ const neckFront = catmullRom([B(2.3, -4.6), B(2.38, -1.5), B(2.52, 0.4), B(3.0, 1.7), J(5.3, 3.0), J(7.25, 3.35), J(7.95, 4.6), J(7.55, 5.7)], 4);+ const face = catmullRom([ulOut[ulOut.length - 1], B(7.05, 10.6), B(7.75, 10.78), B(8.75, 11.05), B(9.25, 11.65), B(8.95, 12.6), B(8.35, 13.9), B(7.7, 15.0), B(7.95, 16.1), B(7.9, 18.1), B(6.9, 20.5)], 4);+ const cranium = catmullRom([B(6.9, 20.5), B(3.0, 22.9), B(-2.2, 22.7), B(-6.9, 19.6), B(-8.7, 15.4), B(-8.3, 11.9), B(-7.4, 8.9), B(-6.8, 4.8), B(-6.6, 0), B(-6.6, -4.6)], 4);+ const head: Vec[] = [...neckFront, ...llOut.slice().reverse(), llEdge, ulEdge, ...ulOut, ...face.slice(1), ...cranium.slice(1)];+ void B;+ this.fill(c, head, C.skin);+ // deeper soft tissue (muscle) leaving a bright fat rim under the skin+ const inset = catmullRom([B(1.85, -4.6), B(1.9, -0.8), B(2.3, 1.6), J(5.2, 3.6), J(6.9, 3.9), J(7.4, 4.9), J(7.2, 5.9), B(6.6, 9.9), B(7.6, 10.9), B(8.55, 11.5), B(8.1, 13.4), B(7.25, 15.2), B(7.45, 18.0), B(3.0, 22.2), B(-2.0, 22.0), B(-6.3, 19.2), B(-7.9, 15.3), B(-7.6, 12.0), B(-6.7, 8.7), B(-6.1, 4.6), B(-6.0, -4.6)], 3);+ this.fill(c, inset, C.muscle);+ // brain (with skull: dark cortex, bright diploë)+ const skull = catmullRom([B(7.0, 16.2), B(7.3, 18.5), B(6.0, 20.7), B(3.0, 22.1), B(-2.0, 22.0), B(-6.3, 19.2), B(-7.9, 15.3), B(-7.4, 12.6), B(-4.6, 12.2), B(-2.2, 13.3), B(1.0, 13.7), B(4.1, 14.1), B(6.2, 14.9)], 4);+ this.fill(c, skull, C.marrow);+ const brain = catmullRom([B(6.55, 16.3), B(6.75, 18.4), B(5.5, 20.1), B(2.8, 21.4), B(-1.9, 21.3), B(-5.8, 18.8), B(-7.1, 15.4), B(-6.7, 13.1), B(-4.4, 12.8), B(-2.1, 13.9), B(1.0, 14.3), B(4.0, 14.7), B(5.9, 15.4)], 4);+ this.fill(c, brain, C.brain);+ this.stroke(c, catmullRom([B(5.4, 19.4), B(2.4, 20.5), B(-1.4, 20.4), B(-4.8, 18.4)], 4), "rgba(255,255,255,0.08)", 3);+ // eye (vitreous dark)+ c.beginPath();+ c.ellipse(this.X(B(6.5, 15.4)), this.Y(B(6.5, 15.4)), 1.1 * this.scale * k, 0.95 * this.scale * k, 0, 0, Math.PI * 2);+ c.fillStyle = "#262626";+ c.fill();+ // cervical spine: vertebral bodies (marrow) with dark cortex, discs, cord+ const wallX = (y: number) => -1.2 - 0.025 * y;+ for (let i = 0; i < 9; i++) {+ const y0 = -4.4 + i * 1.75;+ if (y0 > 10.5) break;+ const x0 = wallX(y0) - 2.25;+ const p0 = P(x0, y0 + 1.4), p1 = P(x0 + 1.6, y0);+ const rr = 0.32 * this.scale * k;+ c.beginPath();+ c.roundRect(this.X(p0), this.Y(p0), this.X(p1) - this.X(p0), this.Y(p1) - this.Y(p0), rr);+ c.fillStyle = C.cortex;+ c.fill();+ const q0 = P(x0 + 0.13, y0 + 1.27), q1 = P(x0 + 1.47, y0 + 0.13);+ c.beginPath();+ c.roundRect(this.X(q0), this.Y(q0), this.X(q1) - this.X(q0), this.Y(q1) - this.Y(q0), rr * 0.7);+ c.fillStyle = C.marrow;+ c.fill();+ }+ this.fill(c, [P(-5.3, -4.6), P(-4.5, -4.6), P(-4.5, 11.8), P(-5.1, 12.4), P(-5.6, 11.6)], "#2e2e2e");+ this.fill(c, [P(-5.1, -4.6), P(-4.7, -4.6), P(-4.72, 11.4), P(-5.15, 11.6)], "#6f6f6f");+ // nasal cavity (air) with turbinates+ const pal = f.outer.slice(f.outer.length - 30); // palate region points (approx)+ void pal;+ const nasalAir = catmullRom([B(0.3, 11.2), B(1.1, 10.25), B(2.7, 10.75), B(4.6, 10.85), B(6.4, 10.65), B(7.6, 10.85), B(8.45, 11.3), B(8.0, 12.2), B(6.7, 13.4), B(4.4, 13.9), B(1.8, 13.6), B(0.2, 12.6)], 4);+ this.fill(c, nasalAir, C.black);+ for (const [cx, cy, rx, ry] of [[3.0, 11.45, 2.1, 0.32], [3.5, 12.45, 1.9, 0.3], [4.0, 13.3, 1.45, 0.22]] as const) {+ c.beginPath();+ c.ellipse(this.X(B(cx, cy)), this.Y(B(cx, cy)), rx * this.scale * k, ry * this.scale * k, -0.04, 0, Math.PI * 2);+ c.fillStyle = "#7d7d7d";+ c.fill();+ }+ // hard palate bone band+ const palOral = this.palatePoints(model);+ const palNasal = palOral.map((p) => ({ x: p.x, y: p.y + 0.55 * k }));+ this.fill(c, [...palOral, ...palNasal.slice().reverse()], C.cortex);+ this.fill(c, [...palOral.map((p) => ({ x: p.x, y: p.y + 0.14 * k })), ...palNasal.map((p) => ({ x: p.x, y: p.y - 0.14 * k })).reverse()], C.marrow);+ // mandible+ const jb = f.jawBone;+ const jbIn = jb.map((p) => ({ x: p.x - 0.0, y: p.y + 0.75 * k }));+ this.fill(c, [...jb, ...jbIn.slice().reverse()], C.cortex);+ this.fill(c, [...jb.map((p) => ({ x: p.x, y: p.y + 0.15 * k })), ...jbIn.map((p) => ({ x: p.x, y: p.y - 0.15 * k })).reverse()], C.marrow);+ // hyoid + thyroid cartilage + trachea+ c.beginPath();+ const hy = { x: P(1.6, 0).x + 0.0, y: P(0, 2.9).y + 0.6 * lar };+ c.ellipse(this.X(hy), this.Y(hy), 0.5 * this.scale * k, 0.28 * this.scale * k, 0.3, 0, Math.PI * 2);+ c.fillStyle = C.marrow;+ c.fill();+ const g = f.glottis;+ const thyroid = [{ x: g.x + 0.75 * k, y: g.y - 1.6 * k }, { x: g.x + 1.75 * k, y: g.y - 0.6 * k }, { x: g.x + 1.95 * k, y: g.y + 1.2 * k }, { x: g.x + 1.45 * k, y: g.y + 1.9 * k }, { x: g.x + 1.15 * k, y: g.y + 1.1 * k }, { x: g.x + 1.3 * k, y: g.y - 0.4 * k }];+ this.fill(c, thyroid, C.cartilage);+ // trachea (air) below the glottis+ const trachea = [{ x: g.x - 0.65 * k, y: g.y }, { x: g.x + 0.75 * k, y: g.y }, { x: g.x + 0.95 * k, y: -4.8 }, { x: g.x - 0.75 * k, y: -4.8 }];+ this.fill(c, trachea, C.black);+ for (let i = 0; i < 4; i++) {+ const y = g.y - (0.9 + i * 1.0) * k;+ if (y < -4.4) break;+ this.fill(c, [{ x: g.x + 0.8 * k, y }, { x: g.x + 1.05 * k, y: y - 0.05 }, { x: g.x + 1.05 * k, y: y - 0.5 * k }, { x: g.x + 0.82 * k, y: y - 0.45 * k }], C.cartilage);+ }+ // ---- airway (carve to black): outer wall, mouth opening, inner wall reversed, epilarynx+ const airway: Vec[] = [];+ const wallAtGlottis = { x: wallX(g.y / k) * k, y: g.y };+ airway.push(g, wallAtGlottis);+ for (const p of f.outer) if (p.y > g.y || p.x > 0) airway.push(p);+ for (let i = f.inner.length - 1; i >= 0; i--) airway.push(f.inner[i]);+ this.fill(c, airway, C.black);+ // mucosal sheen along the outer wall+ this.stroke(c, f.outer.filter((p) => p.y > g.y), "rgba(170,170,170,0.35)", 1.4);+ // ---- articulators+ // tongue with subtle intrinsic-fibre texture+ this.fill(c, f.tongue, C.tongue);+ c.save();+ this.path(c, f.tongue);+ c.clip();+ // genioglossus: fibres fan from the mental spine (behind the chin) up into the dorsum+ const origin = J(6.0, 5.45);+ const tc = f.tongueCenter;+ for (let i = 0; i <= 16; i++) {+ const ang = Math.PI * (0.18 + (0.9 * i) / 16);+ const end = { x: tc.x + Math.cos(ang) * f.tongueRadius * 1.25, y: tc.y + Math.sin(ang) * f.tongueRadius * 1.25 };+ c.beginPath();+ c.moveTo(this.X(origin), this.Y(origin));+ c.quadraticCurveTo(this.X(tc), this.Y({ x: tc.x, y: (tc.y + origin.y) / 2 }), this.X(end), this.Y(end));+ c.strokeStyle = "rgba(0,0,0,0.12)";+ c.lineWidth = 1.1 * this.dpr;+ c.stroke();+ }+ c.restore();+ this.stroke(c, f.tongue.slice(0, Math.floor(f.tongue.length * 0.78)), "rgba(200,200,200,0.28)", 1.2);+ // velum+ this.fill(c, f.velum, C.muscle);+ this.stroke(c, f.velum, "rgba(180,180,180,0.25)", 1, true);+ // lips (orbicularis) – fill between inner and outer surfaces+ this.fill(c, f.upperLip, "#7a7a7a");+ this.fill(c, f.lowerLip, "#7a7a7a");+ // teeth: no MRI signal+ this.fill(c, f.upperTeeth, C.tooth);+ this.fill(c, [...f.lowerTeeth, J(6.8, 6.0), J(6.4, 6.2)], C.tooth);+ // epiglottis cartilage+ this.stroke(c, f.epiglottis.slice(0, 2), "#9a9a9a", 3.2 * k);+ // vocal folds+ this.fill(c, [{ x: g.x - 0.62 * k, y: g.y + 0.05 }, { x: g.x - 0.1, y: g.y + 0.12 * k }, { x: g.x - 0.62 * k, y: g.y + 0.32 * k }], "#8a8a8a");+ this.fill(c, [{ x: g.x + 0.72 * k, y: g.y + 0.05 }, { x: g.x + 0.12, y: g.y + 0.12 * k }, { x: g.x + 0.72 * k, y: g.y + 0.32 * k }], "#8a8a8a");+ c.filter = "none";+ // film grain over tissue (multiplicative-ish)+ if (this.grain) {+ c.globalCompositeOperation = "overlay";+ c.globalAlpha = 0.22;+ c.fillStyle = this.grain;+ this.path(c, head);+ c.fill();+ c.globalAlpha = 1;+ c.globalCompositeOperation = "source-over";+ }+ }++ private palatePoints(model: VoiceModel): Vec[] {+ const t = model.airway.tract;+ const raw: [number, number][] = [[1.0, 9.6], [1.8, 9.92], [2.7, 10.18], [3.6, 10.3], [4.4, 10.25], [5.1, 10.05], [5.7, 9.72], [6.15, 9.36], [6.55, 9.15], [7.0, 9.6]];+ return raw.map(([x, y]) => t.P(x, y));+ }++ private gridPoint(f: HumanFrame, s: number, u: number): Vec | null {+ const g = f.grid;+ if (g.length < 2) return null;+ if (s <= g[0].s) {+ const t = Math.max(0, s / Math.max(0.01, g[0].s));+ const base = f.glottis;+ const mid = { x: (g[0].inner.x + g[0].outer.x) / 2, y: (g[0].inner.y + g[0].outer.y) / 2 };+ const half = 0.35;+ return { x: base.x + (mid.x - base.x) * t + u * half * 0.5, y: base.y + (mid.y - base.y) * t };+ }+ let lo = 0, hi = g.length - 1;+ if (s >= g[hi].s) return null;+ while (hi - lo > 1) {+ const m = (lo + hi) >> 1;+ if (g[m].s <= s) lo = m;+ else hi = m;+ }+ const t = (s - g[lo].s) / Math.max(1e-6, g[hi].s - g[lo].s);+ const ix = g[lo].inner.x + (g[hi].inner.x - g[lo].inner.x) * t;+ const iy = g[lo].inner.y + (g[hi].inner.y - g[lo].inner.y) * t;+ const ox = g[lo].outer.x + (g[hi].outer.x - g[lo].outer.x) * t;+ const oy = g[lo].outer.y + (g[hi].outer.y - g[lo].outer.y) * t;+ const w = 0.5 + 0.5 * u * 0.82;+ return { x: ix + (ox - ix) * w, y: iy + (oy - iy) * w };+ }++ private nodeValueAtS(values: Float32Array, nodeS: Float64Array, s: number): number {+ // nearest-node lookup (values are per section)+ let best = 0, bd = Infinity;+ for (let i = 0; i < nodeS.length; i++) {+ const d = Math.abs(nodeS[i] - s);+ if (d < bd) {+ bd = d;+ best = i;+ }+ }+ return values[best] ?? 0;+ }++ private drawPressure(model: VoiceModel, f: HumanFrame, tele: TelemetryMessage): void {+ const ctx = this.ctx;+ const t = tele.t;+ const nodeS = model.nodeS(t.phLen, t.orLen);+ if (nodeS.length !== t.pressureRms.length) return;+ ctx.globalCompositeOperation = "screen";+ const g = f.grid;+ // epilarynx: glottis → first grid line+ const first = g[0];+ const quads: { pts: Vec[]; s: number }[] = [{ pts: [{ x: f.glottis.x - 0.45, y: f.glottis.y }, { x: f.glottis.x + 0.55, y: f.glottis.y }, first.inner, first.outer], s: first.s * 0.5 }];+ for (let i = 0; i < g.length - 1; i++) quads.push({ pts: [g[i].inner, g[i].outer, g[i + 1].outer, g[i + 1].inner], s: (g[i].s + g[i + 1].s) / 2 });+ for (const q of quads) {+ const lvl = pressureLevel(this.nodeValueAtS(t.pressureRms, nodeS, q.s));+ if (lvl <= 0.01) continue;+ const [r, gg, b] = hot(lvl);+ this.path(ctx, q.pts);+ const col = `rgba(${r | 0},${gg | 0},${b | 0},${0.35 + 0.6 * lvl})`;+ ctx.fillStyle = col;+ ctx.fill();+ // close antialiasing seams between neighbouring sections+ ctx.strokeStyle = col;+ ctx.lineWidth = 1.2 * this.dpr;+ ctx.lineJoin = "round";+ ctx.stroke();+ }+ ctx.globalCompositeOperation = "source-over";+ }++ private drawParticles(model: VoiceModel, f: HumanFrame, tele: TelemetryMessage, dt: number): void {+ const ctx = this.ctx;+ const t = tele.t;+ const nodeS = model.nodeS(t.phLen, t.orLen);+ const areas = new Float32Array(t.phAreas.length + t.orAreas.length);+ areas.set(t.phAreas, 0);+ areas.set(t.orAreas, t.phAreas.length);+ const L = f.lipS;+ ctx.lineCap = "round";+ for (const p of this.particles) {+ const U = this.nodeValueAtS(t.flow, nodeS, p.s);+ const A = Math.max(0.05, this.nodeValueAtS(areas, nodeS, p.s));+ const u = U / A; // particle velocity cm/s+ const vis = Math.sign(u) * 2.2 * Math.log1p(Math.abs(u) / 30); // perceptual speed (cm/s on screen)+ p.s += vis * dt;+ p.life -= dt * 0.25;+ if (p.s > L || p.s < 0 || p.life <= 0 || Math.abs(u) < 3) {+ if (Math.abs(u) < 3 && p.life > 0) {+ // stalled air: keep position, fade+ } else {+ p.s = Math.random() * 0.8;+ p.u = Math.random() * 2 - 1;+ p.life = 0.6 + Math.random() * 0.8;+ p.px = NaN;+ continue;+ }+ }+ const pos = this.gridPoint(f, p.s, p.u);+ if (!pos) continue;+ const x = this.X(pos), y = this.Y(pos);+ const speedA = Math.min(1, Math.abs(vis) / 6);+ if (Number.isFinite(p.px)) {+ ctx.beginPath();+ ctx.moveTo(p.px, p.py);+ ctx.lineTo(x, y);+ ctx.strokeStyle = `rgba(220, 240, 255, ${0.1 + 0.45 * speedA * Math.min(1, p.life)})`;+ ctx.lineWidth = 1.3 * this.dpr;+ ctx.stroke();+ }+ p.px = x;+ p.py = y;+ }+ }++ private drawTurbulence(model: VoiceModel, f: HumanFrame, tele: TelemetryMessage): void {+ const t = tele.t;+ if (!(t.noiseLevel > 1) || t.noiseNode < 0) return;+ const s = model.branchS(t.noiseNode, t.phLen, t.orLen);+ if (s < 0) return;+ const intensity = Math.min(1, Math.log10(t.noiseLevel) / 3.2);+ if (intensity <= 0.05) return;+ const ctx = this.ctx;+ ctx.globalCompositeOperation = "screen";+ let seed = (this.sparkSeed = (this.sparkSeed * 16807) % 2147483647);+ const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);+ for (let i = 0; i < 26; i++) {+ const pos = this.gridPoint(f, s + 0.2 + rnd() * 1.2, rnd() * 2 - 1);+ if (!pos) continue;+ const r = (0.6 + rnd() * 1.6) * this.dpr;+ ctx.beginPath();+ ctx.arc(this.X(pos), this.Y(pos), r, 0, Math.PI * 2);+ ctx.fillStyle = `rgba(190, 230, 255, ${0.15 + 0.55 * intensity * rnd()})`;+ ctx.fill();+ }+ ctx.globalCompositeOperation = "source-over";+ }++ private drawCalipers(f: HumanFrame, tele: TelemetryMessage | null): void {+ const ctx = this.ctx;+ // narrowest constriction marker+ let mi = -1, ma = Infinity;+ for (let i = 2; i < f.grid.length - 1; i++) if (f.grid[i].area < ma) { ma = f.grid[i].area; mi = i; }+ if (mi >= 0 && ma < 1.2) {+ const g = f.grid[mi];+ ctx.beginPath();+ ctx.moveTo(this.X(g.inner), this.Y(g.inner));+ ctx.lineTo(this.X(g.outer), this.Y(g.outer));+ ctx.strokeStyle = C.caliper;+ ctx.lineWidth = 1.5 * this.dpr;+ ctx.stroke();+ for (const e of [g.inner, g.outer]) {+ ctx.beginPath();+ ctx.arc(this.X(e), this.Y(e), 2.2 * this.dpr, 0, Math.PI * 2);+ ctx.fillStyle = C.caliper;+ ctx.fill();+ }+ const label = ma <= 0.0005 ? "closed" : `${ma.toFixed(2)} cm²`;+ this.label(label, this.X(g.outer) + 8 * this.dpr, this.Y(g.outer) - 6 * this.dpr, C.caliper);+ }+ void tele;+ }++ private drawHandles(model: VoiceModel, f: HumanFrame, a: HumanArtic, hover: HandleId | null, drag: HandleId | null): void {+ const ctx = this.ctx;+ for (const h of this.handles(model, f, a)) {+ const x = this.X(h.pos), y = this.Y(h.pos);+ const active = h.id === drag || h.id === hover;+ const r = (active ? 8 : 6) * this.dpr;+ ctx.beginPath();+ ctx.arc(x, y, r, 0, Math.PI * 2);+ ctx.strokeStyle = active ? C.caliper : C.caliperDim;+ ctx.lineWidth = 1.5 * this.dpr;+ ctx.stroke();+ ctx.beginPath();+ ctx.moveTo(x - r - 3 * this.dpr, y);+ ctx.lineTo(x - r + 3 * this.dpr, y);+ ctx.moveTo(x + r - 3 * this.dpr, y);+ ctx.lineTo(x + r + 3 * this.dpr, y);+ ctx.moveTo(x, y - r - 3 * this.dpr);+ ctx.lineTo(x, y - r + 3 * this.dpr);+ ctx.moveTo(x, y + r - 3 * this.dpr);+ ctx.lineTo(x, y + r + 3 * this.dpr);+ ctx.stroke();+ if (h.id === drag) {+ ctx.beginPath();+ ctx.arc(x, y, 2.5 * this.dpr, 0, Math.PI * 2);+ ctx.fillStyle = C.caliper;+ ctx.fill();+ }+ if (active) this.label(h.label, x + r + 8 * this.dpr, y + 4 * this.dpr, C.caliper);+ }+ }++ private label(text: string, x: number, y: number, color: string): void {+ const ctx = this.ctx;+ ctx.font = `${500} ${12 * this.dpr}px Archivo, system-ui, sans-serif`;+ const w = ctx.measureText(text).width;+ ctx.fillStyle = "rgba(0,0,0,0.6)";+ ctx.fillRect(x - 4 * this.dpr, y - 12 * this.dpr, w + 8 * this.dpr, 16 * this.dpr);+ ctx.fillStyle = color;+ ctx.fillText(text, x, y);+ }++ private drawOverlay(f: HumanFrame, a: HumanArtic, tele: TelemetryMessage | null, bodyLabel: string, formants: number[]): void {+ const ctx = this.ctx;+ const d = this.dpr;+ const W = this.canvas.width, H = this.canvas.height;+ const lineH = 17 * d;+ const pad = 14 * d;+ ctx.font = `${450} ${12.5 * d}px Archivo, system-ui, sans-serif`;+ ctx.fillStyle = "rgba(232, 234, 235, 0.82)";+ ctx.textAlign = "left";+ const tl = [bodyLabel, "Midsagittal, live"];+ tl.forEach((s, i) => ctx.fillText(s, pad, pad + lineH * (i + 0.6)));+ ctx.textAlign = "right";+ const tr = tele ? [`f0 ${tele.t.f0.toFixed(1)} Hz`, `Lungs ${tele.t.pLung.toFixed(1)} cmH₂O`, `Voicing ${(tele.t.voicing * 100).toFixed(0)} %`] : ["Audio off"];+ tr.forEach((s, i) => ctx.fillText(s, W - pad, pad + lineH * (i + 0.6)));+ ctx.textAlign = "left";+ const vp = f.velumPort;+ const bl = [`Tract ${f.length.toFixed(1)} cm`, `Lip opening ${f.lipArea.toFixed(2)} cm²`, vp > 0.02 ? `Velum open ${vp.toFixed(2)} cm²` : "Velum closed"];+ bl.forEach((s, i) => ctx.fillText(s, pad, H - pad - lineH * (bl.length - 1 - i)));+ ctx.textAlign = "right";+ const br = formants.slice(0, 3).map((F, i) => `F${i + 1} ${Math.round(F)} Hz`);+ br.forEach((s, i) => ctx.fillText(s, W - pad, H - pad - lineH * (br.length - 1 - i)));+ ctx.textAlign = "left";+ void a;+ }+}diff --git a/src/ui/store.ts b/src/ui/store.tsnew file mode 100644index 0000000..f229f23--- /dev/null+++ b/src/ui/store.ts@@ -0,0 +1,108 @@+import { create } from "zustand";+import { engine } from "../audio/AudioEngine.ts";+import { DEFAULT_SOURCE, type VoiceSource } from "../engine/voice/humanVoice.ts";+import { NEUTRAL, restTip, type HumanArtic } from "../engine/anatomy/human.ts";+import type { BodyName } from "../worklet/protocol.ts";++export const DEFAULT_F0: Record<BodyName, number> = { male: 110, female: 205, child: 260 };++export interface ViewOptions {+ pressure: boolean;+ particles: boolean;+ grid: boolean;+ calipers: boolean;+}++interface State {+ started: boolean;+ starting: boolean;+ startError: string | null;+ body: BodyName;+ source: VoiceSource;+ artic: HumanArtic;+ tipFree: boolean;+ volume: number;+ /** sustained breath (drone) independent of keys */+ hold: boolean;+ heldNotes: number[];+ view: ViewOptions;+ start: () => Promise<void>;+ setBody: (b: BodyName) => void;+ setSource: (v: Partial<VoiceSource>) => void;+ setArtic: (v: Partial<HumanArtic>, tipFree?: boolean) => void;+ setVolume: (v: number) => void;+ setHold: (h: boolean) => void;+ noteOn: (midi: number) => void;+ noteOff: (midi: number) => void;+ setView: (v: Partial<ViewOptions>) => void;+}++const midiToHz = (m: number) => 440 * Math.pow(2, (m - 69) / 12);++function updateGate(s: { hold: boolean; heldNotes: number[] }) {+ engine.gate(s.hold || s.heldNotes.length > 0 ? 1 : 0);+}++export const useStore = create<State>((set, get) => ({+ started: false,+ starting: false,+ startError: null,+ body: "male",+ source: { ...DEFAULT_SOURCE },+ artic: (() => {+ const tip = restTip(NEUTRAL.jaw, NEUTRAL.tbX, NEUTRAL.tbY);+ return { ...NEUTRAL, ttX: tip.x, ttY: tip.y };+ })(),+ tipFree: true,+ volume: 0.8,+ hold: false,+ heldNotes: [],+ view: { pressure: true, particles: true, grid: false, calipers: true },+ start: async () => {+ if (get().started || get().starting) return;+ set({ starting: true, startError: null });+ try {+ await engine.start();+ const s = get();+ engine.setSource(s.source);+ engine.setVolume(s.volume);+ set({ started: true, starting: false });+ } catch (e) {+ set({ starting: false, startError: e instanceof Error ? e.message : String(e) });+ }+ },+ setBody: (b) => {+ const f0 = DEFAULT_F0[b];+ set((s) => ({ body: b, source: { ...s.source, f0 } }));+ engine.setBody(b);+ },+ setSource: (v) => {+ set((s) => ({ source: { ...s.source, ...v } }));+ engine.setSource(v);+ },+ setArtic: (v, tipFree) => {+ set((s) => ({ artic: { ...s.artic, ...v }, tipFree: tipFree ?? s.tipFree }));+ engine.setArtic(v, tipFree);+ },+ setVolume: (v) => {+ set({ volume: v });+ engine.setVolume(v);+ },+ setHold: (h) => {+ set({ hold: h });+ updateGate({ ...get(), hold: h });+ },+ noteOn: (midi) => {+ const held = get().heldNotes.filter((n) => n !== midi).concat(midi);+ set({ heldNotes: held });+ get().setSource({ f0: midiToHz(midi) });+ updateGate({ ...get(), heldNotes: held });+ },+ noteOff: (midi) => {+ const held = get().heldNotes.filter((n) => n !== midi);+ set({ heldNotes: held });+ if (held.length) get().setSource({ f0: midiToHz(held[held.length - 1]) });+ updateGate({ ...get(), heldNotes: held });+ },+ setView: (v) => set((s) => ({ view: { ...s.view, ...v } })),+}));diff --git a/src/ui/styles.css b/src/ui/styles.cssnew file mode 100644index 0000000..b6e9174--- /dev/null+++ b/src/ui/styles.css@@ -0,0 +1,526 @@+@font-face {+ font-family: "Archivo";+ src: url("/fonts/archivo-latin.woff2") format("woff2");+ font-weight: 100 900;+ font-stretch: 62% 125%;+ font-display: swap;+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;+}+@font-face {+ font-family: "Archivo";+ src: url("/fonts/archivo-latin-ext.woff2") format("woff2");+ font-weight: 100 900;+ font-stretch: 62% 125%;+ font-display: swap;+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;+}++:root {+ --black: #000000;+ --console: #2a3035;+ --inset: #20262a;+ --line: #3c444a;+ --text: #e8eaeb;+ --text-dim: #9aa3a8;+ --caliper: #f2cf5b;+ --caliper-dim: rgba(242, 207, 91, 0.45);+ --radius-s: 4px;+ --radius-m: 8px;+ --font: "Archivo", system-ui, -apple-system, "Segoe UI", "Noto Sans", sans-serif;+ color-scheme: dark;+}++* {+ box-sizing: border-box;+}++html,+body {+ margin: 0;+ background: var(--console);+ color: var(--text);+ font-family: var(--font);+ font-size: 15px;+ line-height: 1.45;+ font-variant-numeric: tabular-nums;+ -webkit-font-smoothing: antialiased;+}++button,+input {+ font: inherit;+ color: inherit;+}++:focus-visible {+ outline: 2px solid var(--caliper);+ outline-offset: 2px;+}++.app {+ display: grid;+ grid-template-rows: auto minmax(0, 1fr) auto auto;+ min-height: 100vh;+ gap: 10px;+ padding: 10px;+}++/* ---------- top bar */+.topbar {+ display: flex;+ align-items: center;+ gap: 24px;+ padding: 4px 6px;+ flex-wrap: wrap;+}++.brand {+ display: flex;+ align-items: baseline;+ gap: 14px;+ margin-right: auto;+}++.wordmark {+ font-stretch: 125%;+ font-weight: 800;+ font-size: 26px;+ letter-spacing: 0.02em;+ line-height: 1;+}++.tagline {+ color: var(--text-dim);+ font-stretch: 87%;+ font-size: 14px;+}++.topbar-right {+ display: flex;+ align-items: center;+ gap: 18px;+}++.volume {+ display: flex;+ align-items: center;+ gap: 10px;+ color: var(--text-dim);+ font-stretch: 87%;+ font-size: 13px;+}++.volume input {+ width: 110px;+}++.load {+ color: var(--text-dim);+ font-stretch: 87%;+ font-size: 13px;+ min-width: 120px;+ text-align: right;+}++button.primary {+ background: var(--caliper);+ color: #1d1a10;+ border: 0;+ border-radius: var(--radius-s);+ padding: 7px 14px;+ font-weight: 650;+ cursor: pointer;+}++button.primary:hover {+ filter: brightness(1.06);+}++button.primary:disabled {+ opacity: 0.6;+ cursor: progress;+}++button.primary.large {+ font-size: 17px;+ padding: 11px 20px;+}++.segmented {+ display: inline-flex;+ background: var(--inset);+ border: 1px solid var(--line);+ border-radius: var(--radius-m);+ padding: 2px;+}++.segmented button {+ border: 0;+ background: transparent;+ padding: 5px 12px;+ border-radius: 6px;+ color: var(--text-dim);+ font-stretch: 87%;+ font-size: 14px;+ cursor: pointer;+}++.segmented button.on {+ background: var(--console);+ color: var(--text);+ box-shadow: inset 0 0 0 1px var(--line);+}++/* ---------- stage */+.stage {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(300px, 380px);+ gap: 10px;+ min-height: 520px;+}++.viewport {+ position: relative;+ background: var(--black);+ border-radius: var(--radius-m);+ overflow: hidden;+ min-height: 420px;+}++.anatomy {+ position: absolute;+ inset: 0;+}++.anatomy canvas {+ width: 100%;+ height: 100%;+ display: block;+ touch-action: none;+}++.anatomy[data-hover] canvas {+ cursor: grab;+}++.anatomy[data-hover] canvas:active {+ cursor: grabbing;+}++.view-toggles {+ position: absolute;+ left: 14px;+ bottom: 74px;+ display: flex;+ flex-direction: column;+ gap: 4px;+ font-size: 13px;+ font-stretch: 87%;+ color: var(--text-dim);+}++.start-prompt {+ position: absolute;+ left: 50%;+ top: 50%;+ transform: translate(-50%, -50%);+ max-width: 360px;+ padding: 22px 24px;+ background: rgba(10, 12, 14, 0.82);+ border: 1px solid var(--line);+ border-radius: var(--radius-m);+ text-align: center;+ backdrop-filter: blur(3px);+}++.start-prompt p {+ margin: 0 0 14px;+}++.start-prompt .hint {+ margin: 14px 0 0;+ color: var(--text-dim);+ font-size: 14px;+}++.start-prompt .error {+ margin: 14px 0 0;+ color: #ffb4a0;+ font-size: 14px;+}++.instruments {+ display: grid;+ grid-template-rows: 1fr 1fr 1fr;+ gap: 10px;+}++.instrument {+ margin: 0;+ display: grid;+ grid-template-rows: auto minmax(0, 1fr);+ background: var(--inset);+ border-radius: var(--radius-m);+ padding: 8px 10px 6px;+ min-height: 150px;+}++.instrument figcaption,+.panel h2 {+ font-size: 13px;+ font-weight: 550;+ font-stretch: 87%;+ color: var(--text-dim);+ margin: 0 0 4px;+}++.instrument-canvas {+ width: 100%;+ height: 100%;+ display: block;+}++/* ---------- deck */+.deck {+ display: grid;+ grid-template-columns: minmax(240px, 1fr) minmax(260px, 1fr) minmax(260px, 1fr);+ gap: 10px;+}++.panel {+ background: var(--inset);+ border-radius: var(--radius-m);+ padding: 10px 14px 12px;+}++.vowel-panel {+ display: grid;+ grid-template-rows: auto minmax(0, 1fr);+}++.vowel-map {+ width: 100%;+ height: 100%;+ min-height: 220px;+ display: block;+ background: var(--black);+ border-radius: var(--radius-s);+ cursor: crosshair;+ touch-action: none;+}++.voice-panel,+.artic-panel {+ display: grid;+ grid-template-columns: 1fr 1fr;+ column-gap: 18px;+ row-gap: 4px;+ align-content: start;+}++.voice-panel h2,+.artic-panel h2,+.voice-panel .row {+ grid-column: 1 / -1;+}++.row {+ display: flex;+ gap: 18px;+ padding-top: 6px;+}++.slider label {+ display: flex;+ justify-content: space-between;+ gap: 8px;+ font-size: 13px;+ font-stretch: 87%;+}++.slider label span {+ color: var(--text-dim);+}++.slider output {+ color: var(--text);+ white-space: nowrap;+}++input[type="range"] {+ -webkit-appearance: none;+ appearance: none;+ width: 100%;+ height: 18px;+ background: transparent;+ margin: 0;+ cursor: pointer;+}++input[type="range"]::-webkit-slider-runnable-track {+ height: 3px;+ border-radius: 2px;+ background: linear-gradient(to right, var(--caliper) 0, var(--caliper) var(--pos, 0%), var(--line) var(--pos, 0%));+}++input[type="range"]::-moz-range-track {+ height: 3px;+ border-radius: 2px;+ background: var(--line);+}++input[type="range"]::-moz-range-progress {+ height: 3px;+ background: var(--caliper);+}++input[type="range"]::-webkit-slider-thumb {+ -webkit-appearance: none;+ width: 12px;+ height: 12px;+ margin-top: -4.5px;+ border-radius: 50%;+ background: var(--text);+ border: 0;+}++input[type="range"]::-moz-range-thumb {+ width: 12px;+ height: 12px;+ border-radius: 50%;+ background: var(--text);+ border: 0;+}++.toggle {+ display: inline-flex;+ align-items: center;+ gap: 7px;+ cursor: pointer;+ font-size: 13px;+ font-stretch: 87%;+}++.toggle input {+ accent-color: var(--caliper);+ margin: 0;+}++/* ---------- keys */+.keys-bar {+ background: var(--inset);+ border-radius: var(--radius-m);+ padding: 8px;+}++.keys {+ position: relative;+ height: 74px;+ user-select: none;+ touch-action: none;+}++.white-row {+ display: flex;+ height: 100%;+ gap: 2px;+}++.key {+ border: 0;+ cursor: pointer;+ padding: 0;+}++.key.white {+ flex: 1;+ background: #cfd3d5;+ border-radius: 0 0 4px 4px;+}++.key.white.down {+ background: var(--caliper);+}++.black-row {+ position: absolute;+ inset: 0 0 auto 0;+ height: 58%;+ pointer-events: none;+}++.key.black {+ position: absolute;+ top: 0;+ width: 2.2%;+ height: 100%;+ background: #15191b;+ border-radius: 0 0 3px 3px;+ pointer-events: auto;+}++.key.black.down {+ background: #b69a3e;+}++/* ---------- responsive */+@media (max-width: 1100px) {+ .stage {+ grid-template-columns: 1fr;+ }+ .instruments {+ grid-template-columns: 1fr 1fr 1fr;+ grid-template-rows: auto;+ }+ .deck {+ grid-template-columns: 1fr 1fr;+ }+ .vowel-panel {+ grid-column: 1 / -1;+ }+}++@media (max-width: 720px) {+ .app {+ padding: 8px;+ gap: 8px;+ }+ .tagline {+ display: none;+ }+ .viewport {+ min-height: 360px;+ aspect-ratio: 1 / 1;+ }+ .instruments {+ grid-template-columns: 1fr;+ }+ .deck {+ grid-template-columns: 1fr;+ }+ .voice-panel,+ .artic-panel {+ grid-template-columns: 1fr;+ }+ .view-toggles {+ top: auto;+ bottom: 8px;+ left: 8px;+ right: 8px;+ flex-direction: row;+ flex-wrap: wrap;+ gap: 4px 12px;+ padding: 6px 8px;+ background: rgba(0, 0, 0, 0.55);+ border-radius: var(--radius-s);+ }+ .keys {+ height: 64px;+ }+}++@media (prefers-reduced-motion: reduce) {+ * {+ scroll-behavior: auto !important;+ }+}diff --git a/src/ui/useCanvas.ts b/src/ui/useCanvas.tsnew file mode 100644index 0000000..ee24320--- /dev/null+++ b/src/ui/useCanvas.ts@@ -0,0 +1,52 @@+import { useEffect, useRef } from "react";++export interface CanvasFrame {+ ctx: CanvasRenderingContext2D;+ w: number; // css px+ h: number;+ dpr: number;+ dt: number;+ now: number;+}++/** Canvas with devicePixelRatio scaling, resize observer and a rAF draw loop (ctx pre-scaled to css px). */+export function useCanvasLoop(draw: (f: CanvasFrame) => void) {+ const ref = useRef<HTMLCanvasElement>(null);+ const drawRef = useRef(draw);+ drawRef.current = draw;+ useEffect(() => {+ const canvas = ref.current!;+ const ctx = canvas.getContext("2d")!;+ let w = 0, h = 0, dpr = 1;+ const ro = new ResizeObserver(() => {+ const r = canvas.getBoundingClientRect();+ dpr = Math.min(2, window.devicePixelRatio || 1);+ w = r.width;+ h = r.height;+ canvas.width = Math.max(1, Math.round(w * dpr));+ canvas.height = Math.max(1, Math.round(h * dpr));+ });+ ro.observe(canvas);+ let raf = 0;+ let last = performance.now();+ const loop = (now: number) => {+ const dt = Math.min(0.05, (now - last) / 1000);+ last = now;+ if (w > 0 && h > 0) {+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ drawRef.current({ ctx, w, h, dpr, dt, now });+ }+ raf = requestAnimationFrame(loop);+ };+ raf = requestAnimationFrame(loop);+ return () => {+ cancelAnimationFrame(raf);+ ro.disconnect();+ };+ }, []);+ return ref;+}++export function font(size: number, weight = 450, width = 100): string {+ return `${weight} ${size}px Archivo, system-ui, sans-serif`;+}diff --git a/src/ui/useModel.ts b/src/ui/useModel.tsnew file mode 100644index 0000000..c2b1da3--- /dev/null+++ b/src/ui/useModel.ts@@ -0,0 +1,28 @@+import { useEffect, useRef } from "react";+import { VoiceModel } from "./analysis.ts";+import { useStore } from "./store.ts";+import { engine } from "../audio/AudioEngine.ts";++/** Shared main-thread acoustic model for the current body (rebuilt on body / sample-rate change). */+const cache = new Map<string, VoiceModel>();++export function getModel(body: string, sampleRate: number): VoiceModel {+ const key = `${body}@${sampleRate}`;+ let m = cache.get(key);+ if (!m) {+ m = new VoiceModel(body as "male" | "female" | "child", sampleRate);+ cache.set(key, m);+ }+ return m;+}++export function useModel(): React.MutableRefObject<VoiceModel | null> {+ const body = useStore((s) => s.body);+ const started = useStore((s) => s.started);+ const ref = useRef<VoiceModel | null>(null);+ ref.current = getModel(body, started ? engine.sampleRate : 48000);+ useEffect(() => {+ ref.current = getModel(body, started ? engine.sampleRate : 48000);+ }, [body, started]);+ return ref;+}diff --git a/src/vite-env.d.ts b/src/vite-env.d.tsnew file mode 100644index 0000000..11f02fe--- /dev/null+++ b/src/vite-env.d.ts@@ -0,0 +1 @@+/// <reference types="vite/client" />diff --git a/src/worklet/processor.ts b/src/worklet/processor.tsnew file mode 100644index 0000000..32d3290--- /dev/null+++ b/src/worklet/processor.ts@@ -0,0 +1,98 @@+/**+ * CHIMERA AudioWorklet processor. Execution contract: message handlers only record state;+ * all DSP happens in process(); telemetry is fixed-size and rate-limited (~60 Hz).+ */+import { HumanVoice } from "../engine/voice/humanVoice.ts";+import { BODY_MALE, BODY_FEMALE, BODY_CHILD, type HumanBody } from "../engine/anatomy/human.ts";+import type { ToWorklet, FromWorklet, BodyName } from "./protocol.ts";++// Minimal AudioWorkletGlobalScope typings+declare const sampleRate: number;+declare function registerProcessor(name: string, ctor: unknown): void;+declare class AudioWorkletProcessor {+ readonly port: MessagePort;+ constructor(options?: unknown);+}++const BODIES: Record<BodyName, HumanBody> = { male: BODY_MALE, female: BODY_FEMALE, child: BODY_CHILD };+const DEFAULT_F0: Record<BodyName, number> = { male: 110, female: 205, child: 260 };++class ChimeraProcessor extends AudioWorkletProcessor {+ private voice: HumanVoice;+ private body: BodyName = "male";+ private telemetryOn = true;+ private blocks = 0;+ private load = 0;+ private pendingBody: BodyName | null = null;++ constructor() {+ super();+ this.voice = this.makeVoice("male");+ this.port.onmessage = (e: MessageEvent<ToWorklet>) => this.onMessage(e.data);+ this.post({ type: "ready", sampleRate, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr });+ }++ private makeVoice(body: BodyName): HumanVoice {+ const v = new HumanVoice({ fsOut: sampleRate, body: BODIES[body], oversample: sampleRate > 60000 ? 1 : 2 });+ v.setSource({ f0: DEFAULT_F0[body] });+ return v;+ }++ private post(msg: FromWorklet): void {+ this.port.postMessage(msg);+ }++ private onMessage(m: ToWorklet): void {+ switch (m.type) {+ case "body":+ this.pendingBody = m.body;+ break;+ case "artic":+ this.voice.setArticulation(m.values, m.tipFree);+ break;+ case "source":+ this.voice.setSource(m.values);+ break;+ case "gate":+ this.voice.setGate(m.level);+ break;+ case "telemetry":+ this.telemetryOn = m.enabled;+ break;+ }+ }++ process(_inputs: Float32Array[][], outputs: Float32Array[][]): boolean {+ const out = outputs[0];+ if (!out || out.length === 0) return true;+ if (this.pendingBody) {+ // carry the performer's settings across the body change+ const prev = this.voice;+ this.body = this.pendingBody;+ this.pendingBody = null;+ this.voice = this.makeVoice(this.body);+ this.voice.setSource({ ...prev.source, f0: DEFAULT_F0[this.body] });+ this.voice.setArticulation({ ...prev.artic.target }, prev.artic.tipFree);+ this.voice.setGate(prev.gate > 0.5 ? 1 : 0);+ this.post({ type: "ready", sampleRate, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr });+ }+ const ch0 = out[0];+ const t0 = Date.now();+ try {+ this.voice.render(ch0, 0, ch0.length);+ } catch (err) {+ ch0.fill(0);+ this.post({ type: "error", message: String(err) });+ }+ for (let c = 1; c < out.length; c++) out[c].set(ch0);+ const dt = Date.now() - t0;+ const budget = (ch0.length / sampleRate) * 1000;+ this.load += 0.05 * (dt / budget - this.load);+ if (this.telemetryOn && ++this.blocks % 6 === 0) {+ this.post({ type: "telemetry", t: this.voice.telemetry(), load: this.load, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr });+ }+ return true;+ }+}++registerProcessor("chimera", ChimeraProcessor);diff --git a/src/worklet/protocol.ts b/src/worklet/protocol.tsnew file mode 100644index 0000000..5d02244--- /dev/null+++ b/src/worklet/protocol.ts@@ -0,0 +1,24 @@+/** Messages between the main thread and the CHIMERA AudioWorklet. */+import type { HumanArtic } from "../engine/anatomy/human.ts";+import type { VoiceSource, VoiceTelemetry } from "../engine/voice/humanVoice.ts";++export type BodyName = "male" | "female" | "child";++export type ToWorklet =+ | { type: "body"; body: BodyName }+ | { type: "artic"; values: Partial<HumanArtic>; tipFree?: boolean }+ | { type: "source"; values: Partial<VoiceSource> }+ | { type: "gate"; level: number }+ | { type: "telemetry"; enabled: boolean };++export interface TelemetryMessage {+ type: "telemetry";+ t: VoiceTelemetry;+ /** fraction of the render-quantum budget used by the engine (smoothed) */+ load: number;+ body: BodyName;+ nPh: number;+ nOr: number;+}++export type FromWorklet = { type: "ready"; sampleRate: number; body: BodyName; nPh: number; nOr: number } | TelemetryMessage | { type: "error"; message: string };diff --git a/tools/e2e.ts b/tools/e2e.tsnew file mode 100644index 0000000..03aea17--- /dev/null+++ b/tools/e2e.ts@@ -0,0 +1,65 @@+/**+ * Headless-Chromium smoke test: loads the app, starts audio, interacts, collects console errors,+ * measures worklet load, and saves screenshots.+ * Usage: bun tools/e2e.ts [url] [outdir]+ */+import { chromium } from "playwright-core";+import { mkdirSync } from "node:fs";++const url = process.argv[2] ?? "http://127.0.0.1:5318/";+const outDir = process.argv[3] ?? "out/e2e";+mkdirSync(outDir, { recursive: true });++const browser = await chromium.launch({+ headless: true,+ args: ["--autoplay-policy=no-user-gesture-required", "--use-fake-ui-for-media-stream"],+});+const errors: string[] = [];+const logs: string[] = [];+async function run(viewport: { width: number; height: number }, tag: string) {+ const page = await browser.newPage({ viewport, deviceScaleFactor: 1 });+ page.on("console", (m) => {+ const t = `${m.type()}: ${m.text()}`;+ if (m.type() === "error") errors.push(`[${tag}] ${t}`);+ else logs.push(`[${tag}] ${t}`);+ });+ page.on("pageerror", (e) => errors.push(`[${tag}] pageerror: ${e.message}`));+ await page.goto(url, { waitUntil: "networkidle" });+ await page.waitForTimeout(400);+ await page.screenshot({ path: `${outDir}/${tag}-0-idle.png` });+ const startBtn = page.getByRole("button", { name: /breathe in and start/i });+ await startBtn.click();+ await page.waitForTimeout(1800);+ await page.screenshot({ path: `${outDir}/${tag}-1-running.png` });+ // drag the tongue body handle via the canvas: find it by probing (center-ish of viewport)+ const box = await page.locator(".anatomy canvas").boundingBox();+ if (box) {+ // move over likely tongue area and drag up/forward+ const sx = box.x + box.width * 0.47, sy = box.y + box.height * 0.42;+ await page.mouse.move(sx, sy);+ await page.mouse.down();+ await page.mouse.move(sx + 40, sy - 30, { steps: 10 });+ await page.mouse.up();+ }+ // vowel map drag+ const vm = await page.locator(".vowel-map").boundingBox();+ if (vm) {+ await page.mouse.move(vm.x + vm.width * 0.2, vm.y + vm.height * 0.2);+ await page.mouse.down();+ await page.mouse.move(vm.x + vm.width * 0.8, vm.y + vm.height * 0.8, { steps: 20 });+ await page.mouse.up();+ }+ await page.keyboard.down("d");+ await page.waitForTimeout(900);+ await page.screenshot({ path: `${outDir}/${tag}-2-played.png` });+ await page.keyboard.up("d");+ const loadText = await page.locator(".load").textContent().catch(() => null);+ logs.push(`[${tag}] load: ${loadText}`);+ await page.close();+}++await run({ width: 1440, height: 980 }, "desktop");+await run({ width: 390, height: 844 }, "mobile");+await browser.close();+console.log("console errors:", errors.length ? "\n" + errors.join("\n") : "none");+console.log(logs.filter((l) => /load|warn/i.test(l)).slice(0, 20).join("\n"));diff --git a/vite.config.ts b/vite.config.tsnew file mode 100644index 0000000..46572f3--- /dev/null+++ b/vite.config.ts@@ -0,0 +1,10 @@+import { defineConfig } from "vite";+import react from "@vitejs/plugin-react";++export default defineConfig({+ plugins: [react()],+ worker: { format: "es" },+ build: { target: "es2022", sourcemap: true },+ server: { host: "127.0.0.1", port: 5317, strictPort: true, allowedHosts: true },+ preview: { host: "127.0.0.1", port: 5318, strictPort: true, allowedHosts: true },+});